@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 413 lines 14.3 KB
Raw
1 import * as backupdr from "@distilled.cloud/gcp/backupdr_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { tagRecord } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import { GcpEnvironment } from "../Environment.ts";
10 import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 DEFAULT_RETENTION,
14 fieldMask,
15 listAtLocation,
16 listLabeledPages,
17 normalizeLocation,
18 parentOf,
19 parseName,
20 replaceOnIdentity,
21 ResourceNotResolved,
22 sameText,
23 toPhysicalId,
24 userLabels,
25 waitForOperation,
26 waitUntilExists,
27 waitUntilGone,
28 waitUntilReady,
29 } from "./internal.ts";
30
31 export type EncryptionConfig = {
32 /**
33 * Cloud KMS key used to encrypt backups in this vault. Must be in the
34 * same region. Format:
35 * `projects/{project}/locations/{location}/keyRings/{ring}/cryptoKeys/{key}`.
36 * Immutable after create.
37 */
38 kmsKeyName?: string;
39 };
40
41 export type BackupVaultProps = {
42 /**
43 * Backup vault id (the `{backupvault}` segment of
44 * `projects/{project}/locations/{location}/backupVaults/{backupvault}`).
45 * If omitted, a unique RFC1035 name is generated from the stack, stage,
46 * and logical id. 3-63 characters. Immutable — changing it replaces the
47 * vault.
48 */
49 backupVaultId?: string;
50 /**
51 * Region (`us-central1`, `us-east1`, …). Immutable — changing it
52 * replaces the vault. `US-CENTRAL1` is accepted and normalized to
53 * `us-central1`.
54 * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
55 */
56 location?: string;
57 /**
58 * Default and minimum enforced retention for each backup. Duration
59 * string (`86400s`, `259200s`, …). Longer values raise storage cost.
60 * @default "86400s"
61 */
62 backupMinimumEnforcedRetentionDuration?: string;
63 /**
64 * How a backup's enforced retention end time is inherited.
65 */
66 backupRetentionInheritance?: backupdr.BackupVaultBackupRetentionInheritanceEnum | (string & {});
67 /**
68 * Access restriction for restores. Default is `WITHIN_ORGANIZATION`
69 * when omitted at create.
70 */
71 accessRestriction?: backupdr.BackupVaultAccessRestrictionEnum | (string & {});
72 /**
73 * Customer-managed encryption. Immutable after create.
74 */
75 encryptionConfig?: EncryptionConfig;
76 /**
77 * Time after which the vault is locked (RFC3339).
78 */
79 effectiveTime?: string;
80 /**
81 * Human-readable description (2048 characters or less).
82 */
83 description?: string;
84 /**
85 * User labels. Alchemy ownership labels are merged in automatically.
86 */
87 labels?: Record<string, string>;
88 /**
89 * User annotations (AIP-128).
90 */
91 annotations?: Record<string, string>;
92 };
93
94 export type BackupVault = Resource<
95 "GCP.BackupDR.BackupVault",
96 BackupVaultProps,
97 {
98 /** Full resource name. */
99 name: string;
100 /** Backup vault id (last path segment). */
101 backupVaultId: string;
102 /** Project id. */
103 project: string;
104 /** Location id. */
105 location: string;
106 /** Minimum enforced retention duration. */
107 backupMinimumEnforcedRetentionDuration: string | undefined;
108 /** Retention inheritance setting. */
109 backupRetentionInheritance: string | undefined;
110 /** Access restriction. */
111 accessRestriction: string | undefined;
112 /** Encryption config. */
113 encryptionConfig: EncryptionConfig | undefined;
114 /** Lock time. */
115 effectiveTime: string | undefined;
116 /** Human-readable description. */
117 description: string | undefined;
118 /** User labels (Alchemy ownership labels stripped). */
119 labels: Record<string, string>;
120 /** User annotations. */
121 annotations: Record<string, string>;
122 /** Service account used by the vault. */
123 serviceAccount: string | undefined;
124 /** Number of backups in the vault. */
125 backupCount: string | undefined;
126 /** Total stored bytes. */
127 totalStoredBytes: string | undefined;
128 /** Whether the vault has no nested backups. */
129 deletable: boolean | undefined;
130 /** Server-reported state. */
131 state: string | undefined;
132 /** Server-generated resource uid. */
133 uid: string | undefined;
134 /** RFC3339 creation timestamp. */
135 createTime: string | undefined;
136 /** RFC3339 last-update timestamp. */
137 updateTime: string | undefined;
138 },
139 never,
140 Providers
141 >;
142
143 /**
144 * A Backup and DR backup vault — the storage location for backups created
145 * by Backup Plans.
146 *
147 * Changing `backupVaultId`, `location`, or `encryptionConfig` replaces
148 * the vault. Description, labels, annotations, retention, access
149 * restriction, and inheritance update in place.
150 *
151 * ### Creating a Backup Vault
152 * **Example:** Generated name
153 * ```typescript
154 * const vault = yield* GCP.BackupDR.BackupVault("Vault", {});
155 * ```
156 *
157 * **Example:** Explicit id, retention, and labels
158 * ```typescript
159 * const vault = yield* GCP.BackupDR.BackupVault("Vault", {
160 * backupVaultId: "app-backups",
161 * backupMinimumEnforcedRetentionDuration: "86400s",
162 * description: "nightly backups",
163 * labels: { env: "prod" },
164 * });
165 * ```
166 *
167 * ### Updating a Backup Vault
168 * **Example:** Description and labels
169 * ```typescript
170 * // Same logical id, changed props: the engine updates it in place.
171 * const vault = yield* GCP.BackupDR.BackupVault("Vault", {
172 * description: "nightly backups v2",
173 * labels: { env: "prod", team: "platform" },
174 * });
175 * ```
176 *
177 * @resource
178 * @category BackupDR
179 */
180 export const BackupVault = Resource<BackupVault>("GCP.BackupDR.BackupVault");
181
182 const resourceName = (project: string, location: string, backupVaultId: string) =>
183 `projects/${project}/locations/${location}/backupVaults/${backupVaultId}`;
184
185 const toEncryption = (
186 config: backupdr.EncryptionConfig | EncryptionConfig | undefined,
187 ): EncryptionConfig | undefined =>
188 config === undefined ? undefined : { kmsKeyName: config.kmsKeyName };
189
190 const toAttrs = (item: backupdr.BackupVault, project: string, region: string) => {
191 const name = item.name ?? "";
192 const parsed = parseName(name, "backupVaults", region);
193 return {
194 name,
195 backupVaultId: parsed.id,
196 project: parsed.project || project,
197 location: parsed.location,
198 backupMinimumEnforcedRetentionDuration: item.backupMinimumEnforcedRetentionDuration,
199 backupRetentionInheritance: item.backupRetentionInheritance,
200 accessRestriction: item.accessRestriction,
201 encryptionConfig: toEncryption(item.encryptionConfig),
202 effectiveTime: item.effectiveTime,
203 description: item.description,
204 labels: userLabels(item.labels),
205 annotations: tagRecord(item.annotations),
206 serviceAccount: item.serviceAccount,
207 backupCount: item.backupCount,
208 totalStoredBytes: item.totalStoredBytes,
209 deletable: item.deletable,
210 state: item.state,
211 uid: item.uid,
212 createTime: item.createTime,
213 updateTime: item.updateTime,
214 };
215 };
216
217 const getByName = (name: string) =>
218 backupdr
219 .getProjectsLocationsBackupVaults({ name })
220 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
221
222 const listOwned = (project: string, region: string) =>
223 listAtLocation(project, region, (parent) =>
224 listLabeledPages(
225 backupdr.listProjectsLocationsBackupVaults.pages({
226 parent,
227 pageSize: 1000,
228 }),
229 (page) => page.backupVaults,
230 (item) => item.labels,
231 ),
232 );
233
234 export const BackupVaultProvider = () =>
235 Provider.succeed(BackupVault, {
236 stables: ["name", "backupVaultId", "project", "location", "uid", "createTime"],
237
238 diff: Effect.fn(function* ({ news, olds, output }) {
239 if (!isResolved(news)) return undefined;
240 const env = yield* GcpEnvironment.current;
241 const previousKey =
242 olds?.encryptionConfig?.kmsKeyName ?? output?.encryptionConfig?.kmsKeyName;
243 const nextKey = news.encryptionConfig?.kmsKeyName;
244 return replaceOnIdentity({
245 previousId: olds?.backupVaultId ?? output?.backupVaultId,
246 nextId: news.backupVaultId ?? olds?.backupVaultId ?? output?.backupVaultId,
247 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
248 nextLocation: normalizeLocation(
249 news.location ?? olds?.location ?? output?.location,
250 env.region,
251 ),
252 extra: previousKey !== undefined && nextKey !== undefined && previousKey !== nextKey,
253 });
254 }),
255
256 read: Effect.fn(function* ({ id, olds, output }) {
257 const env = yield* GcpEnvironment.current;
258 const backupVaultId = yield* toPhysicalId(
259 id,
260 olds?.backupVaultId,
261 output?.backupVaultId,
262 "backupvault",
263 );
264 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
265 const name = output?.name ?? resourceName(env.project, location, backupVaultId);
266 const existing = yield* getByName(name);
267 if (existing === undefined) return undefined;
268 const attrs = toAttrs(existing, env.project, env.region);
269 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
270 }),
271
272 list: () =>
273 Effect.gen(function* () {
274 const env = yield* GcpEnvironment.current;
275 const items = yield* listOwned(env.project, env.region);
276 return items.map((item) => toAttrs(item, env.project, env.region));
277 }),
278
279 reconcile: Effect.fn(function* ({ id, news, output }) {
280 const env = yield* GcpEnvironment.current;
281 const backupVaultId = yield* toPhysicalId(
282 id,
283 news.backupVaultId,
284 output?.backupVaultId,
285 "backupvault",
286 );
287 const location = normalizeLocation(news.location ?? output?.location, env.region);
288 const name = resourceName(env.project, location, backupVaultId);
289 const desiredLabels = {
290 ...toLabels(news.labels),
291 ...(yield* createInternalLabels(id)),
292 };
293 const retention = news.backupMinimumEnforcedRetentionDuration ?? DEFAULT_RETENTION;
294 const annotations = news.annotations;
295
296 let current = yield* getByName(output?.name ?? name);
297
298 if (current === undefined) {
299 const created = yield* backupdr
300 .createProjectsLocationsBackupVaults({
301 parent: parentOf(env.project, location),
302 backupVaultId,
303 body: {
304 backupMinimumEnforcedRetentionDuration: retention,
305 backupRetentionInheritance: news.backupRetentionInheritance,
306 accessRestriction: news.accessRestriction,
307 encryptionConfig: news.encryptionConfig,
308 effectiveTime: news.effectiveTime,
309 description: news.description,
310 labels: desiredLabels,
311 annotations,
312 },
313 })
314 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
315 if (created !== undefined) {
316 // ALREADY_EXISTS (6): a concurrent create won the race.
317 yield* waitForOperation(created).pipe(
318 Effect.catchTag("GCP.OperationFailed", (error) =>
319 error.code === 6 ? Effect.void : Effect.fail(error),
320 ),
321 );
322 }
323 current = yield* waitUntilExists(getByName(name), name);
324 }
325
326 if (current === undefined) {
327 return yield* new ResourceNotResolved({ resourceName: name });
328 }
329
330 current = yield* waitUntilReady(
331 getByName(current.name ?? name),
332 current.name ?? name,
333 (item) => item.state,
334 );
335
336 const observedLabels = tagRecord(current.labels);
337 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
338 const observedAnnotations = tagRecord(current.annotations);
339 const desiredAnnotations = annotations ?? {};
340 const annotationDiff = diffLabels(observedAnnotations, desiredAnnotations);
341 const mask = fieldMask([
342 (upsert.length > 0 || removed.length > 0) && "labels",
343 (annotationDiff.upsert.length > 0 || annotationDiff.removed.length > 0) &&
344 news.annotations !== undefined &&
345 "annotations",
346 !sameText(current.description, news.description) && "description",
347 !sameText(current.backupMinimumEnforcedRetentionDuration, retention) &&
348 "backupMinimumEnforcedRetentionDuration",
349 news.backupRetentionInheritance !== undefined &&
350 current.backupRetentionInheritance !== news.backupRetentionInheritance &&
351 "backupRetentionInheritance",
352 news.accessRestriction !== undefined &&
353 current.accessRestriction !== news.accessRestriction &&
354 "accessRestriction",
355 news.effectiveTime !== undefined &&
356 !sameText(current.effectiveTime, news.effectiveTime) &&
357 "effectiveTime",
358 ]);
359
360 if (mask.length > 0) {
361 const operation = yield* backupdr.patchProjectsLocationsBackupVaults({
362 name: current.name ?? name,
363 updateMask: mask,
364 force: true,
365 body: {
366 name: current.name ?? name,
367 etag: current.etag,
368 labels: desiredLabels,
369 annotations: annotations ?? current.annotations,
370 description: news.description,
371 backupMinimumEnforcedRetentionDuration: retention,
372 backupRetentionInheritance: news.backupRetentionInheritance,
373 accessRestriction: news.accessRestriction,
374 effectiveTime: news.effectiveTime,
375 },
376 });
377 yield* waitForOperation(operation);
378 current = yield* waitUntilReady(
379 getByName(current.name ?? name),
380 current.name ?? name,
381 (item) => item.state,
382 );
383 }
384
385 return toAttrs(current, env.project, env.region);
386 }),
387
388 delete: Effect.fn(function* ({ output }) {
389 const operation = yield* backupdr
390 .deleteProjectsLocationsBackupVaults({
391 name: output.name,
392 force: true,
393 ignoreBackupPlanReferences: true,
394 })
395 .pipe(
396 Effect.retry({
397 while: (error) => error._tag === "Conflict",
398 times: 8,
399 schedule: Schedule.spaced("2 seconds"),
400 }),
401 Effect.catchTag("NotFound", () => Effect.undefined),
402 );
403 if (operation !== undefined) {
404 // NOT_FOUND (5): already gone.
405 yield* waitForOperation(operation).pipe(
406 Effect.catchTag("GCP.OperationFailed", (error) =>
407 error.code === 5 ? Effect.void : Effect.fail(error),
408 ),
409 );
410 }
411 yield* waitUntilGone(getByName(output.name), output.name);
412 }),
413 });