@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 549 lines 17.2 KB
Raw
1 import * as gkebackup from "@distilled.cloud/gcp/gkebackup_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 clusterName,
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 waitForDeleteOperation,
27 waitForOperation,
28 waitUntilExists,
29 waitUntilGone,
30 waitUntilReady,
31 } from "./internal.ts";
32
33 export type RetentionPolicy = {
34 /**
35 * Default maximum age of a Backup created via this plan, in days
36 * (`0`–`365`). `0` disables automatic deletion.
37 */
38 backupRetainDays?: number;
39 /**
40 * When true, the retention policy cannot be updated further.
41 */
42 locked?: boolean;
43 /**
44 * Minimum age before a Backup can be deleted, in days (`0`–`90`).
45 */
46 backupDeleteLockDays?: number;
47 };
48
49 export type TimeOfDay = {
50 /** Hours of day in 24-hour format (`0`–`23`). */
51 hours?: number;
52 /** Minutes of hour (`0`–`59`). */
53 minutes?: number;
54 /** Seconds of minute (`0`–`59`). */
55 seconds?: number;
56 /** Fractional seconds, in nanoseconds. */
57 nanos?: number;
58 };
59
60 export type CalendarDate = {
61 /** Year (`1`–`9999`), or `0` to omit. */
62 year?: number;
63 /** Month (`1`–`12`), or `0` to omit. */
64 month?: number;
65 /** Day (`1`–`31`), or `0` to omit. */
66 day?: number;
67 };
68
69 export type DayOfWeekList = {
70 /** Days of week in UTC. */
71 daysOfWeek?: Array<gkebackup.DayOfWeekListDaysOfWeekItemEnum | (string & {})>;
72 };
73
74 export type ExclusionWindow = {
75 /** Weekly recurrence days in UTC. */
76 daysOfWeek?: DayOfWeekList;
77 /** Start time of the window in UTC. */
78 startTime?: TimeOfDay;
79 /** When true, the window recurs every day. */
80 daily?: boolean;
81 /** Window duration (at least 5 minutes). */
82 duration?: string;
83 /** Single-occurrence date in UTC (no recurrence). */
84 singleOccurrenceDate?: CalendarDate;
85 };
86
87 export type RpoConfig = {
88 /**
89 * Target RPO in minutes (`60`–`86400`).
90 */
91 targetRpoMinutes?: number;
92 /**
93 * Windows during which backups must not run.
94 */
95 exclusionWindows?: ExclusionWindow[];
96 };
97
98 export type BackupSchedule = {
99 /**
100 * When true, automatic Backup creation is paused.
101 */
102 paused?: boolean;
103 /**
104 * Cron schedule for creating Backups. Mutually exclusive with
105 * `rpoConfig`.
106 */
107 cronSchedule?: string;
108 /**
109 * RPO schedule. Mutually exclusive with `cronSchedule`.
110 */
111 rpoConfig?: RpoConfig;
112 };
113
114 export type NamespacedName = {
115 /** Kubernetes namespace. */
116 namespace?: string;
117 /** Kubernetes resource name. */
118 name?: string;
119 };
120
121 export type EncryptionKey = {
122 /**
123 * Cloud KMS key used to encrypt config backup artifacts.
124 * Format: `projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey}`.
125 */
126 gcpKmsEncryptionKey?: string;
127 };
128
129 export type ResourceLabels = {
130 /** Kubernetes label-value pairs. */
131 resourceLabels?: Array<{
132 /** Label key. */
133 key?: string;
134 /** Label value. */
135 value?: string;
136 }>;
137 };
138
139 export type BackupConfig = {
140 /** When true, include all namespaced resources. */
141 allNamespaces?: boolean;
142 /** Include namespaces matching these Kubernetes labels. */
143 selectedNamespaceLabels?: ResourceLabels;
144 /**
145 * Whether Kubernetes Secret resources are included.
146 * @default false
147 */
148 includeSecrets?: boolean;
149 /**
150 * Whether volume data is backed up when PVCs are in scope.
151 * @default false
152 */
153 includeVolumeData?: boolean;
154 /**
155 * When false, backups fail on non-standard Kubernetes configuration.
156 * @default false
157 */
158 permissiveMode?: boolean;
159 /** Include only resources in these namespaces. */
160 selectedNamespaces?: { namespaces?: string[] };
161 /** Include only resources referenced by these ProtectedApplications. */
162 selectedApplications?: { namespacedNames?: NamespacedName[] };
163 /** Customer-managed key that encrypts config backup artifacts. */
164 encryptionKey?: EncryptionKey;
165 };
166
167 export type BackupPlanProps = {
168 /**
169 * Backup plan id (the `{backupPlan}` segment of
170 * `projects/{project}/locations/{location}/backupPlans/{backupPlan}`).
171 * If omitted, a unique RFC1035 name is generated from the stack, stage,
172 * and logical id. Immutable — changing it replaces the plan.
173 */
174 backupPlanId?: string;
175 /**
176 * Region (`us-central1`, `us-east1`, …). Immutable — changing it
177 * replaces the plan. `US-CENTRAL1` is accepted and normalized to
178 * `us-central1`. Must match the source cluster region.
179 * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
180 */
181 location?: string;
182 /**
183 * Source GKE cluster. Full name
184 * `projects/{project}/locations/{location}/clusters/{cluster}` (or the
185 * zonal `zones/{zone}` form) or a cluster id combined with `location`.
186 * Immutable — changing it replaces the plan.
187 */
188 cluster: string;
189 /**
190 * Retention policy for Backups created via this plan.
191 */
192 retentionPolicy?: RetentionPolicy;
193 /**
194 * Schedule for automatic Backup creation.
195 */
196 backupSchedule?: BackupSchedule;
197 /**
198 * Configuration of Backups created via this plan.
199 */
200 backupConfig?: BackupConfig;
201 /**
202 * When true, the plan is locked and no further Backups are created.
203 * @default false
204 */
205 deactivated?: boolean;
206 /**
207 * Human-readable description.
208 */
209 description?: string;
210 /**
211 * User labels. Alchemy ownership labels are merged in automatically.
212 */
213 labels?: Record<string, string>;
214 };
215
216 export type BackupPlan = Resource<
217 "GCP.GKEBackup.BackupPlan",
218 BackupPlanProps,
219 {
220 /** Full resource name. */
221 name: string;
222 /** Backup plan id (last path segment). */
223 backupPlanId: string;
224 /** Project id. */
225 project: string;
226 /** Location id. */
227 location: string;
228 /** Source cluster name. */
229 cluster: string | undefined;
230 /** Cross-project backup channel, if any. */
231 backupChannel: string | undefined;
232 /** Retention policy. */
233 retentionPolicy: RetentionPolicy | undefined;
234 /** Automatic backup schedule. */
235 backupSchedule: BackupSchedule | undefined;
236 /** Backup configuration. */
237 backupConfig: BackupConfig | undefined;
238 /** Whether the plan is deactivated. */
239 deactivated: boolean;
240 /** Human-readable description. */
241 description: string | undefined;
242 /** User labels (Alchemy ownership labels stripped). */
243 labels: Record<string, string>;
244 /** Server-reported state. */
245 state: string | undefined;
246 /** Human-readable state reason. */
247 stateReason: string | undefined;
248 /** Server-generated resource uid. */
249 uid: string | undefined;
250 /** RFC3339 creation timestamp. */
251 createTime: string | undefined;
252 /** RFC3339 last-update timestamp. */
253 updateTime: string | undefined;
254 /** Last successful Backup completion time. */
255 lastSuccessfulBackupTime: string | undefined;
256 },
257 never,
258 Providers
259 >;
260
261 /**
262 * A Backup for GKE backup plan — the configuration and schedule for a
263 * line of cluster backups.
264 *
265 * Changing `backupPlanId`, `location`, or `cluster` replaces the plan.
266 * Description, labels, retention, schedule, backup config, and
267 * `deactivated` update in place.
268 *
269 * ### Creating a Backup Plan
270 * **Example:** Generated name
271 * ```typescript
272 * const plan = yield* GCP.GKEBackup.BackupPlan("Nightly", {
273 * cluster: cluster.name,
274 * backupConfig: { allNamespaces: true },
275 * });
276 * ```
277 *
278 * **Example:** Cron schedule and retention
279 * ```typescript
280 * const plan = yield* GCP.GKEBackup.BackupPlan("Nightly", {
281 * cluster: cluster.name,
282 * backupSchedule: { cronSchedule: "0 2 * * *" },
283 * retentionPolicy: { backupRetainDays: 14, backupDeleteLockDays: 1 },
284 * labels: { env: "prod" },
285 * });
286 * ```
287 *
288 * ### Updating a Backup Plan
289 * **Example:** Description and labels
290 * ```typescript
291 * const plan = yield* GCP.GKEBackup.BackupPlan("Nightly", {
292 * cluster: cluster.name,
293 * description: "nightly backups v2",
294 * labels: { env: "prod", team: "platform" },
295 * });
296 * ```
297 *
298 * @resource
299 * @category GKEBackup
300 */
301 export const BackupPlan = Resource<BackupPlan>("GCP.GKEBackup.BackupPlan");
302
303 const resourceName = (project: string, location: string, backupPlanId: string) =>
304 `projects/${project}/locations/${location}/backupPlans/${backupPlanId}`;
305
306 const toRetention = (policy: gkebackup.RetentionPolicy | undefined): RetentionPolicy | undefined =>
307 policy === undefined
308 ? undefined
309 : {
310 backupRetainDays: policy.backupRetainDays,
311 locked: policy.locked,
312 backupDeleteLockDays: policy.backupDeleteLockDays,
313 };
314
315 const toSchedule = (schedule: gkebackup.Schedule | undefined): BackupSchedule | undefined =>
316 schedule === undefined
317 ? undefined
318 : {
319 paused: schedule.paused,
320 cronSchedule: schedule.cronSchedule,
321 rpoConfig: schedule.rpoConfig,
322 };
323
324 const toBackupConfig = (config: gkebackup.BackupConfig | undefined): BackupConfig | undefined =>
325 config === undefined
326 ? undefined
327 : {
328 allNamespaces: config.allNamespaces,
329 selectedNamespaceLabels: config.selectedNamespaceLabels,
330 includeSecrets: config.includeSecrets,
331 includeVolumeData: config.includeVolumeData,
332 permissiveMode: config.permissiveMode,
333 selectedNamespaces: config.selectedNamespaces,
334 selectedApplications: config.selectedApplications,
335 encryptionKey: config.encryptionKey,
336 };
337
338 const desiredSchedule = (schedule: BackupSchedule | undefined) =>
339 schedule === undefined
340 ? undefined
341 : {
342 paused: schedule.paused,
343 cronSchedule: schedule.cronSchedule,
344 rpoConfig: schedule.rpoConfig,
345 };
346
347 const toAttrs = (item: gkebackup.BackupPlan, project: string, region: string) => {
348 const name = item.name ?? "";
349 const parsed = parseName(name, "backupPlans", region);
350 return {
351 name,
352 backupPlanId: parsed.id,
353 project: parsed.project || project,
354 location: parsed.location,
355 cluster: item.cluster,
356 backupChannel: item.backupChannel,
357 retentionPolicy: toRetention(item.retentionPolicy),
358 backupSchedule: toSchedule(item.backupSchedule),
359 backupConfig: toBackupConfig(item.backupConfig),
360 deactivated: item.deactivated === true,
361 description: item.description,
362 labels: userLabels(item.labels),
363 state: item.state,
364 stateReason: item.stateReason,
365 uid: item.uid,
366 createTime: item.createTime,
367 updateTime: item.updateTime,
368 lastSuccessfulBackupTime: item.lastSuccessfulBackupTime,
369 };
370 };
371
372 const getByName = (name: string) =>
373 gkebackup
374 .getProjectsLocationsBackupPlans({ name })
375 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
376
377 const listOwned = (project: string) =>
378 listAtLocation(project, (parent) =>
379 listLabeledPages(
380 gkebackup.listProjectsLocationsBackupPlans.pages({
381 parent,
382 pageSize: 1000,
383 }),
384 (page) => page.backupPlans,
385 (item) => item.labels,
386 ),
387 );
388
389 export const BackupPlanProvider = () =>
390 Provider.succeed(BackupPlan, {
391 stables: ["name", "backupPlanId", "project", "location", "uid", "createTime"],
392
393 diff: Effect.fn(function* ({ news, olds, output }) {
394 if (!isResolved(news)) return undefined;
395 const env = yield* GcpEnvironment.current;
396 const previousCluster = olds?.cluster ?? output?.cluster;
397 return replaceOnIdentity({
398 previousId: olds?.backupPlanId ?? output?.backupPlanId,
399 nextId: news.backupPlanId ?? olds?.backupPlanId ?? output?.backupPlanId,
400 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
401 nextLocation: normalizeLocation(
402 news.location ?? olds?.location ?? output?.location,
403 env.region,
404 ),
405 extra:
406 previousCluster !== undefined &&
407 news.cluster !== undefined &&
408 previousCluster !== news.cluster &&
409 !previousCluster.endsWith(`/${news.cluster}`),
410 });
411 }),
412
413 read: Effect.fn(function* ({ id, olds, output }) {
414 const env = yield* GcpEnvironment.current;
415 const backupPlanId = yield* toPhysicalId(
416 id,
417 olds?.backupPlanId,
418 output?.backupPlanId,
419 "backupplan",
420 );
421 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
422 const name = output?.name ?? resourceName(env.project, location, backupPlanId);
423 const existing = yield* getByName(name);
424 if (existing === undefined) return undefined;
425 const attrs = toAttrs(existing, env.project, env.region);
426 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
427 }),
428
429 list: () =>
430 Effect.gen(function* () {
431 const env = yield* GcpEnvironment.current;
432 const items = yield* listOwned(env.project);
433 return items.map((item) => toAttrs(item, env.project, env.region));
434 }),
435
436 reconcile: Effect.fn(function* ({ id, news, output }) {
437 const env = yield* GcpEnvironment.current;
438 const backupPlanId = yield* toPhysicalId(
439 id,
440 news.backupPlanId,
441 output?.backupPlanId,
442 "backupplan",
443 );
444 const location = normalizeLocation(news.location ?? output?.location, env.region);
445 const name = resourceName(env.project, location, backupPlanId);
446 const cluster = clusterName(news.cluster, env.project, location);
447 const desiredLabels = {
448 ...toLabels(news.labels),
449 ...(yield* createInternalLabels(id)),
450 };
451
452 let current = yield* getByName(output?.name ?? name);
453
454 if (current === undefined) {
455 const created = yield* gkebackup
456 .createProjectsLocationsBackupPlans({
457 parent: parentOf(env.project, location),
458 backupPlanId,
459 body: {
460 cluster,
461 retentionPolicy: news.retentionPolicy,
462 backupSchedule: news.backupSchedule,
463 backupConfig: news.backupConfig,
464 deactivated: news.deactivated,
465 description: news.description,
466 labels: desiredLabels,
467 },
468 })
469 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
470 if (created !== undefined) {
471 yield* waitForOperation(created);
472 }
473 current = yield* waitUntilExists(getByName(name), name);
474 }
475
476 if (current === undefined) {
477 return yield* new ResourceNotResolved({ resourceName: name });
478 }
479
480 current = yield* waitUntilReady(
481 getByName(current.name ?? name),
482 current.name ?? name,
483 (item) => item.state,
484 (item) => item.stateReason,
485 );
486 if (current === undefined) {
487 return yield* new ResourceNotResolved({ resourceName: name });
488 }
489
490 const observedLabels = tagRecord(current.labels);
491 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
492 const mask = fieldMask([
493 (upsert.length > 0 || removed.length > 0) && "labels",
494 !sameText(current.description, news.description) && "description",
495 fingerprint(toRetention(current.retentionPolicy)) !== fingerprint(news.retentionPolicy) &&
496 "retentionPolicy",
497 fingerprint(desiredSchedule(toSchedule(current.backupSchedule))) !==
498 fingerprint(desiredSchedule(news.backupSchedule)) && "backupSchedule",
499 fingerprint(toBackupConfig(current.backupConfig)) !== fingerprint(news.backupConfig) &&
500 "backupConfig",
501 (current.deactivated === true) !== (news.deactivated === true) && "deactivated",
502 ]);
503
504 if (mask.length > 0) {
505 const operation = yield* gkebackup.patchProjectsLocationsBackupPlans({
506 name: current.name ?? name,
507 updateMask: mask,
508 body: {
509 etag: current.etag,
510 labels: desiredLabels,
511 description: news.description,
512 retentionPolicy: news.retentionPolicy,
513 backupSchedule: news.backupSchedule,
514 backupConfig: news.backupConfig,
515 deactivated: news.deactivated,
516 },
517 });
518 yield* waitForOperation(operation);
519 current = yield* waitUntilReady(
520 getByName(current.name ?? name),
521 current.name ?? name,
522 (item) => item.state,
523 (item) => item.stateReason,
524 );
525 if (current === undefined) {
526 return yield* new ResourceNotResolved({ resourceName: name });
527 }
528 }
529
530 return toAttrs(current, env.project, env.region);
531 }),
532
533 delete: Effect.fn(function* ({ output }) {
534 const operation = yield* gkebackup
535 .deleteProjectsLocationsBackupPlans({ name: output.name })
536 .pipe(
537 Effect.retry({
538 while: (error) => error._tag === "Conflict",
539 times: 8,
540 schedule: Schedule.spaced("2 seconds"),
541 }),
542 Effect.catchTag("NotFound", () => Effect.undefined),
543 );
544 if (operation !== undefined) {
545 yield* waitForDeleteOperation(operation);
546 }
547 yield* waitUntilGone(getByName(output.name), output.name);
548 }),
549 });