@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 515 lines 17.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, hasAlchemyLabels, toLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 backupVaultOf,
14 fieldMask,
15 fingerprint,
16 listAtLocation,
17 listLabeledPages,
18 normalizeLocation,
19 parentOf,
20 parseName,
21 replaceOnIdentity,
22 ResourceNotResolved,
23 sameText,
24 toPhysicalId,
25 userLabels,
26 waitForOperation,
27 waitUntilExists,
28 waitUntilGone,
29 waitUntilReady,
30 } from "./internal.ts";
31
32 export type BackupWindow = {
33 /**
34 * Hour of day (`0`–`23`) when the window starts.
35 */
36 startHourOfDay?: number;
37 /**
38 * Hour of day (`1`–`24`) when the window ends. Must be greater than
39 * `startHourOfDay`. The end hour is exclusive.
40 */
41 endHourOfDay?: number;
42 };
43
44 export type WeekDayOfMonth = {
45 /**
46 * Day of week.
47 */
48 dayOfWeek?: backupdr.WeekDayOfMonthDayOfWeekEnum | (string & {});
49 /**
50 * Week of month (`FIRST`, `SECOND`, `THIRD`, `FOURTH`, `LAST`).
51 */
52 weekOfMonth?: backupdr.WeekDayOfMonthWeekOfMonthEnum | (string & {});
53 };
54
55 export type StandardSchedule = {
56 /**
57 * Recurrence (`HOURLY`, `DAILY`, `WEEKLY`, `MONTHLY`, `YEARLY`).
58 */
59 recurrenceType?: backupdr.StandardScheduleRecurrenceTypeEnum | (string & {});
60 /**
61 * Days of month (`1`–`31`). `MONTHLY` and `YEARLY` only.
62 */
63 daysOfMonth?: number[];
64 /**
65 * Hourly frequency. Required for `HOURLY`. Workload-specific min/max
66 * apply (Compute Instance: 4–23).
67 */
68 hourlyFrequency?: number;
69 /**
70 * Days of week. Required for `WEEKLY`.
71 */
72 daysOfWeek?: Array<backupdr.StandardScheduleDaysOfWeekItemEnum | (string & {})>;
73 /**
74 * IANA time zone used to interpret the schedule (`UTC`, `America/New_York`).
75 */
76 timeZone?: string;
77 /**
78 * Week day of the month. `MONTHLY` and `YEARLY` only.
79 */
80 weekDayOfMonth?: WeekDayOfMonth;
81 /**
82 * Months of year. `YEARLY` only.
83 */
84 months?: Array<backupdr.StandardScheduleMonthsItemEnum | (string & {})>;
85 /**
86 * Window of day during which backup jobs may start.
87 */
88 backupWindow?: BackupWindow;
89 };
90
91 export type BackupRule = {
92 /**
93 * Unique id of this rule within the plan. RFC1035: lowercase letter
94 * followed by up to 62 letters, digits, or hyphens. Immutable.
95 */
96 ruleId?: string;
97 /**
98 * Retention in days. Must be at least the vault's minimum enforced
99 * retention. Minimum 1.
100 */
101 backupRetentionDays?: number;
102 /**
103 * Schedule that runs inside a backup window.
104 */
105 standardSchedule?: StandardSchedule;
106 };
107
108 export type DiskBackupPlanProperties = {
109 /**
110 * Whether to guest-flush before a disk backup. `false` produces a
111 * crash-consistent backup.
112 * @default false
113 */
114 guestFlush?: boolean;
115 };
116
117 export type ComputeInstanceBackupPlanProperties = {
118 /**
119 * Whether to guest-flush before a compute backup. `false` produces a
120 * crash-consistent backup.
121 * @default false
122 */
123 guestFlush?: boolean;
124 };
125
126 export type BackupPlanProps = {
127 /**
128 * Backup plan id (the `{backupPlan}` segment of
129 * `projects/{project}/locations/{location}/backupPlans/{backupPlan}`).
130 * If omitted, a unique RFC1035 name is generated from the stack, stage,
131 * and logical id. Immutable — changing it replaces the plan.
132 */
133 backupPlanId?: string;
134 /**
135 * Region (`us-central1`, `us-east1`, …). Immutable — changing it
136 * replaces the plan. `US-CENTRAL1` is accepted and normalized to
137 * `us-central1`.
138 * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
139 */
140 location?: string;
141 /**
142 * Backup vault that stores backups created by this plan. Full name
143 * `projects/{project}/locations/{location}/backupVaults/{backupvault}`
144 * or a vault id combined with `location`. Immutable — changing it
145 * replaces the plan.
146 */
147 backupVault: string;
148 /**
149 * Resource type the plan applies to, e.g. `compute.googleapis.com/Instance`,
150 * `compute.googleapis.com/Disk`, `sqladmin.googleapis.com/Instance`,
151 * `alloydb.googleapis.com/Cluster`, `file.googleapis.com/Instance`.
152 * Immutable — changing it replaces the plan.
153 */
154 resourceType: string;
155 /**
156 * Backup rules (schedule + retention). At least one rule is required
157 * in practice.
158 */
159 backupRules?: BackupRule[];
160 /**
161 * Cloud SQL only. Log retention in days. Must be at least the vault's
162 * minimum log retention.
163 */
164 logRetentionDays?: string;
165 /**
166 * Maximum days an on-demand backup with custom retention may be kept.
167 */
168 maxCustomOnDemandRetentionDays?: number;
169 /**
170 * Disk-specific options (`compute.googleapis.com/Disk`).
171 */
172 diskBackupPlanProperties?: DiskBackupPlanProperties;
173 /**
174 * Compute instance-specific options (`compute.googleapis.com/Instance`).
175 */
176 computeInstanceBackupPlanProperties?: ComputeInstanceBackupPlanProperties;
177 /**
178 * Human-readable description (2048 characters or less).
179 */
180 description?: string;
181 /**
182 * User labels. Alchemy ownership labels are merged in automatically.
183 */
184 labels?: Record<string, string>;
185 };
186
187 export type BackupPlan = Resource<
188 "GCP.BackupDR.BackupPlan",
189 BackupPlanProps,
190 {
191 /** Full resource name. */
192 name: string;
193 /** Backup plan id (last path segment). */
194 backupPlanId: string;
195 /** Project id. */
196 project: string;
197 /** Location id. */
198 location: string;
199 /** Backup vault name. */
200 backupVault: string | undefined;
201 /** Backup vault service account. */
202 backupVaultServiceAccount: string | undefined;
203 /** Resource type this plan applies to. */
204 resourceType: string | undefined;
205 /** Resource types this plan can be applied to. */
206 supportedResourceTypes: string[];
207 /** Backup rules. */
208 backupRules: BackupRule[];
209 /** Cloud SQL log retention days. */
210 logRetentionDays: string | undefined;
211 /** Max custom on-demand retention days. */
212 maxCustomOnDemandRetentionDays: number | undefined;
213 /** Disk-specific options. */
214 diskBackupPlanProperties: DiskBackupPlanProperties | undefined;
215 /** Compute instance-specific options. */
216 computeInstanceBackupPlanProperties: ComputeInstanceBackupPlanProperties | undefined;
217 /** Human-readable description. */
218 description: string | undefined;
219 /** User labels (Alchemy ownership labels stripped). */
220 labels: Record<string, string>;
221 /** Server-reported state. */
222 state: string | undefined;
223 /** Revision resource name. */
224 revisionName: string | undefined;
225 /** User-friendly revision id (`v0`, `v1`, …). */
226 revisionId: string | undefined;
227 /** RFC3339 creation timestamp. */
228 createTime: string | undefined;
229 /** RFC3339 last-update timestamp. */
230 updateTime: string | undefined;
231 },
232 never,
233 Providers
234 >;
235
236 /**
237 * A Backup and DR backup plan — schedule and retention for a workload
238 * type, stored in a Backup Vault.
239 *
240 * Changing `backupPlanId`, `location`, `backupVault`, `resourceType`, or
241 * `labels` replaces the plan. Description, rules, log retention, and
242 * workload properties update in place.
243 *
244 * ### Creating a Backup Plan
245 * **Example:** Daily compute backups
246 * ```typescript
247 * const backupRules = [
248 * {
249 * ruleId: "daily",
250 * backupRetentionDays: 7,
251 * standardSchedule: {
252 * recurrenceType: "DAILY",
253 * timeZone: "UTC",
254 * backupWindow: { startHourOfDay: 1, endHourOfDay: 5 },
255 * },
256 * },
257 * ];
258 * const plan = yield* GCP.BackupDR.BackupPlan("Nightly", {
259 * backupVault: vault.name,
260 * resourceType: "compute.googleapis.com/Instance",
261 * backupRules,
262 * });
263 * ```
264 *
265 * ### Updating a Backup Plan
266 * **Example:** Description and labels
267 * ```typescript
268 * // Same logical id, changed props: the engine updates it in place.
269 * const plan = yield* GCP.BackupDR.BackupPlan("Nightly", {
270 * backupVault: vault.name,
271 * resourceType: "compute.googleapis.com/Instance",
272 * description: "nightly backups v2",
273 * labels: { env: "prod" },
274 * backupRules,
275 * });
276 * ```
277 *
278 * @resource
279 * @category BackupDR
280 */
281 export const BackupPlan = Resource<BackupPlan>("GCP.BackupDR.BackupPlan");
282
283 const resourceName = (project: string, location: string, backupPlanId: string) =>
284 `projects/${project}/locations/${location}/backupPlans/${backupPlanId}`;
285
286 const toRule = (rule: backupdr.BackupRule | BackupRule): BackupRule => ({
287 ruleId: rule.ruleId,
288 backupRetentionDays: rule.backupRetentionDays,
289 standardSchedule: rule.standardSchedule,
290 });
291
292 const toRules = (rules: readonly (backupdr.BackupRule | BackupRule)[] | undefined): BackupRule[] =>
293 (rules ?? []).map(toRule);
294
295 const toAttrs = (item: backupdr.BackupPlan, project: string, region: string) => {
296 const name = item.name ?? "";
297 const parsed = parseName(name, "backupPlans", region);
298 return {
299 name,
300 backupPlanId: parsed.id,
301 project: parsed.project || project,
302 location: parsed.location,
303 backupVault: item.backupVault,
304 backupVaultServiceAccount: item.backupVaultServiceAccount,
305 resourceType: item.resourceType,
306 supportedResourceTypes: item.supportedResourceTypes ?? [],
307 backupRules: toRules(item.backupRules),
308 logRetentionDays: item.logRetentionDays,
309 maxCustomOnDemandRetentionDays: item.maxCustomOnDemandRetentionDays,
310 diskBackupPlanProperties: item.diskBackupPlanProperties,
311 computeInstanceBackupPlanProperties: item.computeInstanceBackupPlanProperties,
312 description: item.description,
313 labels: userLabels(item.labels),
314 state: item.state,
315 revisionName: item.revisionName,
316 revisionId: item.revisionId,
317 createTime: item.createTime,
318 updateTime: item.updateTime,
319 };
320 };
321
322 const getByName = (name: string) =>
323 backupdr
324 .getProjectsLocationsBackupPlans({ name })
325 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
326
327 const listOwned = (project: string, region: string) =>
328 listAtLocation(project, region, (parent) =>
329 listLabeledPages(
330 backupdr.listProjectsLocationsBackupPlans.pages({
331 parent,
332 pageSize: 1000,
333 }),
334 (page) => page.backupPlans,
335 (item) => item.labels,
336 ),
337 );
338
339 export const BackupPlanProvider = () =>
340 Provider.succeed(BackupPlan, {
341 stables: ["name", "backupPlanId", "project", "location", "createTime"],
342
343 diff: Effect.fn(function* ({ news, olds, output }) {
344 if (!isResolved(news)) return undefined;
345 const env = yield* GcpEnvironment.current;
346 const previousVault = olds?.backupVault ?? output?.backupVault;
347 const previousType = olds?.resourceType ?? output?.resourceType;
348 return replaceOnIdentity({
349 previousId: olds?.backupPlanId ?? output?.backupPlanId,
350 nextId: news.backupPlanId ?? olds?.backupPlanId ?? output?.backupPlanId,
351 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
352 nextLocation: normalizeLocation(
353 news.location ?? olds?.location ?? output?.location,
354 env.region,
355 ),
356 extra:
357 (previousType !== undefined &&
358 news.resourceType !== undefined &&
359 previousType !== news.resourceType) ||
360 (previousVault !== undefined &&
361 news.backupVault !== undefined &&
362 previousVault !== news.backupVault &&
363 !previousVault.endsWith(`/${news.backupVault}`)) ||
364 // Backup plan labels are immutable ("labels can not be updated").
365 (olds !== undefined && fingerprint(olds.labels ?? {}) !== fingerprint(news.labels ?? {})),
366 });
367 }),
368
369 read: Effect.fn(function* ({ id, olds, output }) {
370 const env = yield* GcpEnvironment.current;
371 const backupPlanId = yield* toPhysicalId(
372 id,
373 olds?.backupPlanId,
374 output?.backupPlanId,
375 "backupplan",
376 );
377 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
378 const name = output?.name ?? resourceName(env.project, location, backupPlanId);
379 const existing = yield* getByName(name);
380 if (existing === undefined) return undefined;
381 const attrs = toAttrs(existing, env.project, env.region);
382 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
383 }),
384
385 list: () =>
386 Effect.gen(function* () {
387 const env = yield* GcpEnvironment.current;
388 const items = yield* listOwned(env.project, env.region);
389 return items.map((item) => toAttrs(item, env.project, env.region));
390 }),
391
392 reconcile: Effect.fn(function* ({ id, news, output }) {
393 const env = yield* GcpEnvironment.current;
394 const backupPlanId = yield* toPhysicalId(
395 id,
396 news.backupPlanId,
397 output?.backupPlanId,
398 "backupplan",
399 );
400 const location = normalizeLocation(news.location ?? output?.location, env.region);
401 const name = resourceName(env.project, location, backupPlanId);
402 const backupVault = backupVaultOf(news.backupVault, env.project, location);
403 const desiredLabels = {
404 ...toLabels(news.labels),
405 ...(yield* createInternalLabels(id)),
406 };
407
408 let current = yield* getByName(output?.name ?? name);
409
410 if (current === undefined) {
411 const created = yield* backupdr
412 .createProjectsLocationsBackupPlans({
413 parent: parentOf(env.project, location),
414 backupPlanId,
415 body: {
416 backupVault,
417 resourceType: news.resourceType,
418 backupRules: news.backupRules,
419 logRetentionDays: news.logRetentionDays,
420 maxCustomOnDemandRetentionDays: news.maxCustomOnDemandRetentionDays,
421 diskBackupPlanProperties: news.diskBackupPlanProperties,
422 computeInstanceBackupPlanProperties: news.computeInstanceBackupPlanProperties,
423 description: news.description,
424 labels: desiredLabels,
425 },
426 })
427 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
428 if (created !== undefined) {
429 // ALREADY_EXISTS (6): a concurrent create won the race.
430 yield* waitForOperation(created).pipe(
431 Effect.catchTag("GCP.OperationFailed", (error) =>
432 error.code === 6 ? Effect.void : Effect.fail(error),
433 ),
434 );
435 }
436 current = yield* waitUntilExists(getByName(name), name);
437 }
438
439 if (current === undefined) {
440 return yield* new ResourceNotResolved({ resourceName: name });
441 }
442
443 current = yield* waitUntilReady(
444 getByName(current.name ?? name),
445 current.name ?? name,
446 (item) => item.state,
447 );
448
449 const mask = fieldMask([
450 !sameText(current.description, news.description) && "description",
451 fingerprint(toRules(current.backupRules)) !== fingerprint(toRules(news.backupRules)) &&
452 "backupRules",
453 news.logRetentionDays !== undefined &&
454 !sameText(current.logRetentionDays, news.logRetentionDays) &&
455 "logRetentionDays",
456 news.maxCustomOnDemandRetentionDays !== undefined &&
457 current.maxCustomOnDemandRetentionDays !== news.maxCustomOnDemandRetentionDays &&
458 "maxCustomOnDemandRetentionDays",
459 news.diskBackupPlanProperties !== undefined &&
460 fingerprint(current.diskBackupPlanProperties) !==
461 fingerprint(news.diskBackupPlanProperties) &&
462 "diskBackupPlanProperties",
463 news.computeInstanceBackupPlanProperties !== undefined &&
464 fingerprint(current.computeInstanceBackupPlanProperties) !==
465 fingerprint(news.computeInstanceBackupPlanProperties) &&
466 "computeInstanceBackupPlanProperties",
467 ]);
468
469 if (mask.length > 0) {
470 const operation = yield* backupdr.patchProjectsLocationsBackupPlans({
471 name: current.name ?? name,
472 updateMask: mask,
473 body: {
474 etag: current.etag,
475 description: news.description,
476 backupRules: news.backupRules,
477 logRetentionDays: news.logRetentionDays,
478 maxCustomOnDemandRetentionDays: news.maxCustomOnDemandRetentionDays,
479 diskBackupPlanProperties: news.diskBackupPlanProperties,
480 computeInstanceBackupPlanProperties: news.computeInstanceBackupPlanProperties,
481 },
482 });
483 yield* waitForOperation(operation);
484 current = yield* waitUntilReady(
485 getByName(current.name ?? name),
486 current.name ?? name,
487 (item) => item.state,
488 );
489 }
490
491 return toAttrs(current, env.project, env.region);
492 }),
493
494 delete: Effect.fn(function* ({ output }) {
495 const operation = yield* backupdr
496 .deleteProjectsLocationsBackupPlans({ name: output.name })
497 .pipe(
498 Effect.retry({
499 while: (error) => error._tag === "Conflict",
500 times: 8,
501 schedule: Schedule.spaced("2 seconds"),
502 }),
503 Effect.catchTag("NotFound", () => Effect.undefined),
504 );
505 if (operation !== undefined) {
506 // NOT_FOUND (5): already gone.
507 yield* waitForOperation(operation).pipe(
508 Effect.catchTag("GCP.OperationFailed", (error) =>
509 error.code === 5 ? Effect.void : Effect.fail(error),
510 ),
511 );
512 }
513 yield* waitUntilGone(getByName(output.name), output.name);
514 }),
515 });