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

main
ts 449 lines 15 KB
Raw
1 import * as file from "@distilled.cloud/gcp/file_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 Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import { GcpEnvironment } from "../Environment.ts";
11 import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
12 import type { Providers } from "../Providers.ts";
13 import {
14 DEFAULT_SHARE_NAME,
15 DEFAULT_ZONE,
16 expandParent,
17 fieldMask,
18 isDeletingState,
19 lastSegment,
20 listLabeledPages,
21 normalizeLocation,
22 parseName,
23 regionOf,
24 replaceOnIdentity,
25 ResourceNotResolved,
26 toPhysicalId,
27 userLabels,
28 waitForOperation,
29 waitUntilExists,
30 waitUntilGone,
31 waitUntilReady,
32 } from "./internal.ts";
33
34 export type BackupProps = {
35 /**
36 * Source Filestore instance. Full name
37 * `projects/{project}/locations/{location}/instances/{instance}` or
38 * the instance id (combined with `instanceLocation`). Immutable —
39 * changing it replaces the backup.
40 */
41 sourceInstance: string;
42 /**
43 * File share on the source instance to back up. Immutable — changing
44 * it replaces the backup.
45 * @default "share1"
46 */
47 sourceFileShare?: string;
48 /**
49 * Zone of the source instance when `sourceInstance` is a bare id.
50 * Ignored when `sourceInstance` is a full resource name.
51 * @default "us-central1-a"
52 */
53 instanceLocation?: string;
54 /**
55 * Region that stores the backup (`us-central1`, …). Backups are
56 * regional and may live in a different region than the instance.
57 * Immutable — changing it replaces the backup. `US-CENTRAL1` is
58 * accepted and normalized to `us-central1`.
59 * @default the region of the source instance
60 */
61 location?: string;
62 /**
63 * Backup id (the `{backup}` segment of
64 * `projects/{project}/locations/{location}/backups/{backup}`). If
65 * omitted, a unique RFC1035 name is generated from the stack, stage,
66 * and logical id. Must start with a letter, be 1-63 characters, and
67 * end with a letter or digit. Immutable — changing it replaces the
68 * backup.
69 */
70 backupId?: string;
71 /**
72 * Human-readable description (2048 characters or less).
73 */
74 description?: string;
75 /**
76 * User labels. Alchemy ownership labels are merged in automatically.
77 */
78 labels?: Record<string, string>;
79 /**
80 * Customer-managed KMS key for backup encryption
81 * (`projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey}`).
82 * Immutable — changing it replaces the backup.
83 */
84 kmsKey?: string;
85 /**
86 * Resource Manager tags (namespaced key to short value). Input-only
87 * and immutable.
88 */
89 tags?: Record<string, string>;
90 };
91
92 export type Backup = Resource<
93 "GCP.Filestore.Backup",
94 BackupProps,
95 {
96 /** Full resource name `projects/{project}/locations/{location}/backups/{backup}`. */
97 name: string;
98 /** Backup id (last path segment). */
99 backupId: string;
100 /** Project id. */
101 project: string;
102 /** Backup region. */
103 location: string;
104 /** Source instance resource name. */
105 sourceInstance: string | undefined;
106 /** Source file share name. */
107 sourceFileShare: string | undefined;
108 /** Source instance service tier. */
109 sourceInstanceTier: string | undefined;
110 /** File protocol of the source instance. */
111 fileSystemProtocol: string | undefined;
112 /** Source share capacity in GiB when the backup was taken. */
113 capacityGb: string | undefined;
114 /** Bytes occupied by this backup (shared storage; can change). */
115 storageBytes: string | undefined;
116 /** Bytes downloaded when restoring this backup. */
117 downloadBytes: string | undefined;
118 /** Customer-managed KMS key, if any. */
119 kmsKey: string | undefined;
120 /** Human-readable description. */
121 description: string | undefined;
122 /** User labels (Alchemy ownership labels stripped). */
123 labels: Record<string, string>;
124 /** Server-reported state (`READY`, `CREATING`, `FINALIZING`, …). */
125 state: string | undefined;
126 /** RFC3339 creation timestamp. */
127 createTime: string | undefined;
128 },
129 never,
130 Providers
131 >;
132
133 /**
134 * A Cloud Filestore backup of an instance file share.
135 *
136 * Changing `backupId`, `location`, `sourceInstance`, `sourceFileShare`,
137 * or `kmsKey` replaces the backup. Description and labels update in
138 * place.
139 *
140 * Backups are regional. Creating a backup of a Basic HDD share typically
141 * takes several minutes.
142 *
143 * ### Creating a Backup
144 * **Example:** Backup the default share
145 * ```typescript
146 * const nfs = yield* GCP.Filestore.Instance("Nfs", {});
147 * const backup = yield* GCP.Filestore.Backup("Nightly", {
148 * sourceInstance: nfs.name,
149 * });
150 * ```
151 *
152 * **Example:** Explicit id, share, labels, and description
153 * ```typescript
154 * const backup = yield* GCP.Filestore.Backup("Nightly", {
155 * sourceInstance: nfs.name,
156 * sourceFileShare: "share1",
157 * backupId: "app-nfs-nightly",
158 * location: "us-central1",
159 * description: "nightly backup",
160 * labels: { env: "prod" },
161 * });
162 * ```
163 *
164 * ### Updating a Backup
165 * Re-declare the same logical id with changed props; the engine keeps the
166 * physical resource and updates it in place.
167 *
168 * **Example:** Description and labels
169 * ```typescript
170 * const backup = yield* GCP.Filestore.Backup("Nightly", {
171 * sourceInstance: nfs.name,
172 * description: "nightly backup v2",
173 * labels: { env: "prod", team: "storage" },
174 * });
175 * ```
176 *
177 * @resource
178 * @category Filestore
179 */
180 export const Backup = Resource<Backup>("GCP.Filestore.Backup");
181
182 export class BackupSourceMissing extends Data.TaggedError("GCP.Filestore.BackupSourceMissing")<{
183 message: string;
184 }> {}
185
186 const resourceName = (project: string, location: string, backupId: string) =>
187 `projects/${project}/locations/${location}/backups/${backupId}`;
188
189 const parseInstanceRef = (value: string, fallbackProject: string, fallbackLocation: string) => {
190 const trimmed = value.trim();
191 if (trimmed.includes("/")) {
192 const parsed = parseName(trimmed, "instances", DEFAULT_ZONE);
193 const instanceLocation = normalizeLocation(parsed.location, DEFAULT_ZONE);
194 return {
195 project: parsed.project || fallbackProject,
196 location: instanceLocation,
197 instanceId: parsed.id,
198 instanceName: expandParent(
199 parsed.id,
200 parsed.project || fallbackProject,
201 instanceLocation,
202 "instances",
203 ),
204 };
205 }
206 const location = normalizeLocation(fallbackLocation, DEFAULT_ZONE);
207 const instanceId = lastSegment(trimmed);
208 return {
209 project: fallbackProject,
210 location,
211 instanceId,
212 instanceName: expandParent(instanceId, fallbackProject, location, "instances"),
213 };
214 };
215
216 const backupLocationOf = (
217 newsLocation: string | undefined,
218 outputLocation: string | undefined,
219 instanceLocation: string,
220 ) => normalizeLocation(newsLocation ?? outputLocation, regionOf(instanceLocation));
221
222 const toAttrs = (backup: file.Backup, project: string, region: string) => {
223 const name = backup.name ?? "";
224 const parsed = parseName(name, "backups", region);
225 return {
226 name,
227 backupId: parsed.id,
228 project: parsed.project || project,
229 location: parsed.location,
230 sourceInstance: backup.sourceInstance,
231 sourceFileShare: backup.sourceFileShare,
232 sourceInstanceTier: backup.sourceInstanceTier,
233 fileSystemProtocol: backup.fileSystemProtocol,
234 capacityGb: backup.capacityGb,
235 storageBytes: backup.storageBytes,
236 downloadBytes: backup.downloadBytes,
237 kmsKey: backup.kmsKey,
238 description: backup.description,
239 labels: userLabels(backup.labels),
240 state: backup.state,
241 createTime: backup.createTime,
242 };
243 };
244
245 const isPlaceholder = (backup: file.Backup) => {
246 const name = backup.name ?? "";
247 return name.length === 0 || name.endsWith("/backups/-") || name.endsWith("/backups/");
248 };
249
250 const getByName = (name: string) =>
251 Effect.gen(function* () {
252 if (name.length === 0 || name.includes("//")) return undefined;
253 return yield* file
254 .getProjectsLocationsBackups({ name })
255 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
256 });
257
258 export const BackupProvider = () =>
259 Provider.succeed(Backup, {
260 stables: [
261 "name",
262 "backupId",
263 "project",
264 "location",
265 "sourceInstance",
266 "sourceFileShare",
267 "kmsKey",
268 "createTime",
269 ],
270
271 diff: Effect.fn(function* ({ news, olds, output }) {
272 if (!isResolved(news)) return undefined;
273 const env = yield* GcpEnvironment.current;
274 const previousInstance = parseInstanceRef(
275 olds?.sourceInstance ?? output?.sourceInstance ?? "",
276 env.project,
277 olds?.instanceLocation ?? output?.location ?? DEFAULT_ZONE,
278 );
279 const nextInstance = parseInstanceRef(
280 news.sourceInstance,
281 env.project,
282 news.instanceLocation ?? olds?.instanceLocation ?? previousInstance.location,
283 );
284 const previousLocation = normalizeLocation(
285 olds?.location ?? output?.location,
286 regionOf(previousInstance.location),
287 );
288 const nextLocation = backupLocationOf(
289 news.location,
290 olds?.location ?? output?.location,
291 nextInstance.location,
292 );
293 const previousShare = olds?.sourceFileShare ?? output?.sourceFileShare ?? DEFAULT_SHARE_NAME;
294 const nextShare = news.sourceFileShare ?? previousShare;
295 const previousKey = olds?.kmsKey ?? output?.kmsKey ?? "";
296 const nextKey = news.kmsKey ?? previousKey;
297 return replaceOnIdentity({
298 previousId: olds?.backupId ?? output?.backupId,
299 nextId: news.backupId ?? olds?.backupId ?? output?.backupId,
300 previousLocation,
301 nextLocation,
302 extra:
303 previousInstance.instanceName !== nextInstance.instanceName ||
304 previousShare !== nextShare ||
305 previousKey !== nextKey,
306 });
307 }),
308
309 read: Effect.fn(function* ({ id, olds, output }) {
310 const env = yield* GcpEnvironment.current;
311 const instance = parseInstanceRef(
312 olds?.sourceInstance ?? output?.sourceInstance ?? "",
313 env.project,
314 olds?.instanceLocation ?? output?.location ?? DEFAULT_ZONE,
315 );
316 const location = backupLocationOf(olds?.location, output?.location, instance.location);
317 const backupId = yield* toPhysicalId(id, olds?.backupId, output?.backupId, "backup");
318 const name = output?.name ?? resourceName(env.project, location, backupId);
319 const existing = yield* getByName(name);
320 if (existing === undefined || isPlaceholder(existing)) return undefined;
321 const attrs = toAttrs(existing, env.project, env.region);
322 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
323 }),
324
325 list: () =>
326 Effect.gen(function* () {
327 const env = yield* GcpEnvironment.current;
328 const items = yield* listLabeledPages(
329 file.listProjectsLocationsBackups.pages({
330 parent: `projects/${env.project}/locations/-`,
331 pageSize: 1000,
332 }),
333 (page) => page.backups,
334 (item) => item.labels,
335 );
336 return items
337 .filter((item) => !isPlaceholder(item))
338 .map((item) => toAttrs(item, env.project, env.region));
339 }),
340
341 reconcile: Effect.fn(function* ({ id, news, output }) {
342 const env = yield* GcpEnvironment.current;
343 if (news.sourceInstance.trim().length === 0) {
344 return yield* new BackupSourceMissing({
345 message: "sourceInstance is required",
346 });
347 }
348 const instance = parseInstanceRef(
349 news.sourceInstance,
350 env.project,
351 news.instanceLocation ?? DEFAULT_ZONE,
352 );
353 const location = backupLocationOf(news.location, output?.location, instance.location);
354 const backupId = yield* toPhysicalId(id, news.backupId, output?.backupId, "backup");
355 const name = resourceName(env.project, location, backupId);
356 const sourceFileShare = news.sourceFileShare ?? DEFAULT_SHARE_NAME;
357 const desiredLabels = {
358 ...toLabels(news.labels),
359 ...(yield* createInternalLabels(id)),
360 };
361
362 let current = yield* getByName(output?.name ?? name);
363
364 if (current !== undefined && isDeletingState(current.state)) {
365 yield* waitUntilGone(getByName(current.name ?? name), current.name ?? name);
366 current = undefined;
367 }
368
369 if (current === undefined) {
370 const created = yield* file
371 .createProjectsLocationsBackups({
372 parent: `projects/${env.project}/locations/${location}`,
373 backupId,
374 body: {
375 sourceInstance: instance.instanceName,
376 sourceFileShare,
377 description: news.description,
378 labels: desiredLabels,
379 kmsKey: news.kmsKey,
380 tags: news.tags,
381 },
382 })
383 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
384 if (created !== undefined) {
385 yield* waitForOperation(created);
386 }
387 current = yield* waitUntilExists(getByName(name), name);
388 }
389
390 if (current === undefined) {
391 return yield* new ResourceNotResolved({ resourceName: name });
392 }
393
394 current = yield* waitUntilReady(
395 getByName(current.name ?? name),
396 current.name ?? name,
397 (item) => item.state,
398 );
399 if (current === undefined) {
400 return yield* new ResourceNotResolved({ resourceName: name });
401 }
402
403 const observedLabels = tagRecord(current.labels);
404 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
405 const mask = fieldMask([
406 (upsert.length > 0 || removed.length > 0) && "labels",
407 (current.description ?? "") !== (news.description ?? "") && "description",
408 ]);
409
410 if (mask.length > 0) {
411 const operation = yield* file.patchProjectsLocationsBackups({
412 name: current.name ?? name,
413 updateMask: mask,
414 body: {
415 name: current.name ?? name,
416 labels: desiredLabels,
417 description: news.description,
418 },
419 });
420 yield* waitForOperation(operation);
421 current = yield* waitUntilReady(
422 getByName(current.name ?? name),
423 current.name ?? name,
424 (item) => item.state,
425 );
426 if (current === undefined) {
427 return yield* new ResourceNotResolved({ resourceName: name });
428 }
429 }
430
431 return toAttrs(current, env.project, env.region);
432 }),
433
434 delete: Effect.fn(function* ({ output }) {
435 if (!output.name || output.name.includes("//")) return;
436 const operation = yield* file.deleteProjectsLocationsBackups({ name: output.name }).pipe(
437 Effect.retry({
438 while: (error) => error._tag === "Conflict",
439 times: 8,
440 schedule: Schedule.spaced("5 seconds"),
441 }),
442 Effect.catchTag("NotFound", () => Effect.undefined),
443 );
444 if (operation !== undefined) {
445 yield* waitForOperation(operation, { notFoundOk: true });
446 }
447 yield* waitUntilGone(getByName(output.name), output.name);
448 }),
449 });