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

main
ts 334 lines 11 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 expandParent,
14 fieldMask,
15 listAtNested,
16 listLabeledPages,
17 normalizeLocation,
18 parseName,
19 replaceOnIdentity,
20 ResourceNotResolved,
21 sameText,
22 toPhysicalId,
23 userLabels,
24 waitForDeleteOperation,
25 waitForOperation,
26 waitUntilExists,
27 waitUntilGone,
28 } from "./internal.ts";
29
30 export type BackupPlansBackupProps = {
31 /**
32 * Parent BackupPlan. Full name
33 * `projects/{project}/locations/{location}/backupPlans/{backupPlan}`
34 * or the plan id (combined with `location`). Immutable — changing it
35 * replaces the backup.
36 */
37 backupPlan: string;
38 /**
39 * Region used when `backupPlan` is a bare id.
40 * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
41 */
42 location?: string;
43 /**
44 * Backup id (the `{backup}` segment). If omitted, a unique RFC1035 name
45 * is generated from the stack, stage, and logical id. Immutable —
46 * changing it replaces the backup.
47 */
48 backupId?: string;
49 /**
50 * Minimum age in days before this Backup can be deleted (`0`–`90`).
51 * May only be increased after create. Defaults to the parent plan's
52 * `backupDeleteLockDays`.
53 */
54 deleteLockDays?: number;
55 /**
56 * Age in days after which this Backup is automatically deleted. `0`
57 * disables automatic deletion. May only be increased after create.
58 * Defaults to the parent plan's `backupRetainDays`.
59 */
60 retainDays?: number;
61 /**
62 * Human-readable description.
63 */
64 description?: string;
65 /**
66 * User labels. Alchemy ownership labels are merged in automatically.
67 */
68 labels?: Record<string, string>;
69 };
70
71 export type BackupPlansBackup = Resource<
72 "GCP.GKEBackup.BackupPlansBackup",
73 BackupPlansBackupProps,
74 {
75 /** Full resource name. */
76 name: string;
77 /** Backup id (last path segment). */
78 backupId: string;
79 /** Parent BackupPlan name. */
80 backupPlan: string;
81 /** Project id. */
82 project: string;
83 /** Location id. */
84 location: string;
85 /** Whether all namespaces were included. */
86 allNamespaces: boolean | undefined;
87 /** Delete-lock duration in days. */
88 deleteLockDays: number | undefined;
89 /** Automatic-deletion age in days. */
90 retainDays: number | undefined;
91 /** Whether this Backup was created manually. */
92 manual: boolean | undefined;
93 /** Whether the Backup contains volume data. */
94 containsVolumeData: boolean | undefined;
95 /** Whether the Backup contains Kubernetes Secrets. */
96 containsSecrets: boolean | undefined;
97 /** Size of the Backup in bytes. */
98 sizeBytes: string | undefined;
99 /** Human-readable description. */
100 description: string | undefined;
101 /** User labels (Alchemy ownership labels stripped). */
102 labels: Record<string, string>;
103 /** Server-reported state. */
104 state: string | undefined;
105 /** Human-readable state reason. */
106 stateReason: string | undefined;
107 /** Server-generated resource uid. */
108 uid: string | undefined;
109 /** RFC3339 creation timestamp. */
110 createTime: string | undefined;
111 /** RFC3339 completion timestamp. */
112 completeTime: string | undefined;
113 },
114 never,
115 Providers
116 >;
117
118 /**
119 * A Backup for GKE backup — a point-in-time capture of a cluster under
120 * a BackupPlan.
121 *
122 * Changing `backupId`, `backupPlan`, or `location` replaces the backup.
123 * Description, labels, `deleteLockDays`, and `retainDays` update in
124 * place (`deleteLockDays` and `retainDays` may only increase).
125 *
126 * ### Creating a Backup
127 * **Example:** Manual backup
128 * ```typescript
129 * const backup = yield* GCP.GKEBackup.BackupPlansBackup("Nightly", {
130 * backupPlan: plan.name,
131 * });
132 * ```
133 *
134 * **Example:** Retention overrides
135 * ```typescript
136 * const backup = yield* GCP.GKEBackup.BackupPlansBackup("Nightly", {
137 * backupPlan: plan.name,
138 * deleteLockDays: 7,
139 * retainDays: 30,
140 * description: "pre-release",
141 * labels: { env: "prod" },
142 * });
143 * ```
144 *
145 * ### Updating a Backup
146 * **Example:** Description and labels
147 * ```typescript
148 * const backup = yield* GCP.GKEBackup.BackupPlansBackup("Nightly", {
149 * backupPlan: plan.name,
150 * description: "pre-release v2",
151 * labels: { env: "prod", team: "platform" },
152 * });
153 * ```
154 *
155 * @resource
156 * @category GKEBackup
157 */
158 export const BackupPlansBackup = Resource<BackupPlansBackup>("GCP.GKEBackup.BackupPlansBackup");
159
160 const resourceName = (plan: string, backupId: string) => `${plan}/backups/${backupId}`;
161
162 const toAttrs = (item: gkebackup.Backup, project: string, region: string) => {
163 const name = item.name ?? "";
164 const parsed = parseName(name, "backups", region);
165 return {
166 name,
167 backupId: parsed.id,
168 backupPlan: parsed.parent,
169 project: parsed.project || project,
170 location: parsed.location,
171 allNamespaces: item.allNamespaces,
172 deleteLockDays: item.deleteLockDays,
173 retainDays: item.retainDays,
174 manual: item.manual,
175 containsVolumeData: item.containsVolumeData,
176 containsSecrets: item.containsSecrets,
177 sizeBytes: item.sizeBytes,
178 description: item.description,
179 labels: userLabels(item.labels),
180 state: item.state,
181 stateReason: item.stateReason,
182 uid: item.uid,
183 createTime: item.createTime,
184 completeTime: item.completeTime,
185 };
186 };
187
188 const getByName = (name: string) =>
189 gkebackup
190 .getProjectsLocationsBackupPlansBackups({ name })
191 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
192
193 const listOwned = (project: string) =>
194 listAtNested(project, "backupPlans/-", (parent) =>
195 listLabeledPages(
196 gkebackup.listProjectsLocationsBackupPlansBackups.pages({
197 parent,
198 pageSize: 1000,
199 }),
200 (page) => page.backups,
201 (item) => item.labels,
202 ),
203 );
204
205 export const BackupPlansBackupProvider = () =>
206 Provider.succeed(BackupPlansBackup, {
207 stables: ["name", "backupId", "backupPlan", "project", "location", "uid", "createTime"],
208
209 diff: Effect.fn(function* ({ news, olds, output }) {
210 if (!isResolved(news)) return undefined;
211 const env = yield* GcpEnvironment.current;
212 return replaceOnIdentity({
213 previousId: olds?.backupId ?? output?.backupId,
214 nextId: news.backupId ?? olds?.backupId ?? output?.backupId,
215 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
216 nextLocation: normalizeLocation(
217 news.location ?? olds?.location ?? output?.location,
218 env.region,
219 ),
220 previousParent: olds?.backupPlan ?? output?.backupPlan,
221 nextParent: news.backupPlan,
222 });
223 }),
224
225 read: Effect.fn(function* ({ id, olds, output }) {
226 const env = yield* GcpEnvironment.current;
227 const backupId = yield* toPhysicalId(id, olds?.backupId, output?.backupId, "backup");
228 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
229 const plan = expandParent(
230 olds?.backupPlan ?? output?.backupPlan ?? "",
231 env.project,
232 location,
233 "backupPlans",
234 );
235 const name = output?.name ?? resourceName(plan, backupId);
236 const existing = yield* getByName(name);
237 if (existing === undefined) return undefined;
238 const attrs = toAttrs(existing, env.project, env.region);
239 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
240 }),
241
242 list: () =>
243 Effect.gen(function* () {
244 const env = yield* GcpEnvironment.current;
245 const items = yield* listOwned(env.project);
246 return items.map((item) => toAttrs(item, env.project, env.region));
247 }),
248
249 reconcile: Effect.fn(function* ({ id, news, output }) {
250 const env = yield* GcpEnvironment.current;
251 const backupId = yield* toPhysicalId(id, news.backupId, output?.backupId, "backup");
252 const location = normalizeLocation(news.location ?? output?.location, env.region);
253 const plan = expandParent(news.backupPlan, env.project, location, "backupPlans");
254 const name = resourceName(plan, backupId);
255 const desiredLabels = {
256 ...toLabels(news.labels),
257 ...(yield* createInternalLabels(id)),
258 };
259
260 let current = yield* getByName(output?.name ?? name);
261
262 if (current === undefined) {
263 const created = yield* gkebackup
264 .createProjectsLocationsBackupPlansBackups({
265 parent: plan,
266 backupId,
267 body: {
268 deleteLockDays: news.deleteLockDays,
269 retainDays: news.retainDays,
270 description: news.description,
271 labels: desiredLabels,
272 },
273 })
274 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
275 if (created !== undefined) {
276 yield* waitForOperation(created);
277 }
278 current = yield* waitUntilExists(getByName(name), name);
279 }
280
281 if (current === undefined) {
282 return yield* new ResourceNotResolved({ resourceName: name });
283 }
284
285 const observedLabels = tagRecord(current.labels);
286 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
287 const mask = fieldMask([
288 (upsert.length > 0 || removed.length > 0) && "labels",
289 !sameText(current.description, news.description) && "description",
290 news.deleteLockDays !== undefined &&
291 news.deleteLockDays !== current.deleteLockDays &&
292 "deleteLockDays",
293 news.retainDays !== undefined && news.retainDays !== current.retainDays && "retainDays",
294 ]);
295
296 if (mask.length > 0) {
297 const operation = yield* gkebackup.patchProjectsLocationsBackupPlansBackups({
298 name: current.name ?? name,
299 updateMask: mask,
300 body: {
301 etag: current.etag,
302 labels: desiredLabels,
303 description: news.description,
304 deleteLockDays: news.deleteLockDays,
305 retainDays: news.retainDays,
306 },
307 });
308 yield* waitForOperation(operation);
309 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
310 }
311
312 return toAttrs(current, env.project, env.region);
313 }),
314
315 delete: Effect.fn(function* ({ output }) {
316 const operation = yield* gkebackup
317 .deleteProjectsLocationsBackupPlansBackups({
318 name: output.name,
319 force: true,
320 })
321 .pipe(
322 Effect.retry({
323 while: (error) => error._tag === "Conflict",
324 times: 8,
325 schedule: Schedule.spaced("2 seconds"),
326 }),
327 Effect.catchTag("NotFound", () => Effect.undefined),
328 );
329 if (operation !== undefined) {
330 yield* waitForDeleteOperation(operation);
331 }
332 yield* waitUntilGone(getByName(output.name), output.name);
333 }),
334 });