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

main
ts 406 lines 13.3 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 Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
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_ZONE,
15 expandParent,
16 fieldMask,
17 hasAlchemyLabelMap,
18 isDeletingState,
19 lastSegment,
20 listLabeledPages,
21 normalizeLocation,
22 parseName,
23 replaceOnIdentity,
24 ResourceNotResolved,
25 toPhysicalId,
26 userLabels,
27 waitForOperation,
28 waitUntilExists,
29 waitUntilGone,
30 waitUntilReady,
31 } from "./internal.ts";
32
33 export type InstancesSnapshotProps = {
34 /**
35 * Parent Filestore instance. Full name
36 * `projects/{project}/locations/{location}/instances/{instance}` or
37 * the instance id (combined with `location`). Immutable — changing it
38 * replaces the snapshot.
39 *
40 * Snapshots require a Zonal, Regional, Enterprise, or High Scale SSD
41 * instance. Basic HDD and Basic SSD do not support snapshots.
42 */
43 instance: string;
44 /**
45 * Location of the parent instance when `instance` is a bare id.
46 * Ignored when `instance` is a full resource name. Immutable —
47 * changing it replaces the snapshot. `US-CENTRAL1-A` is accepted and
48 * normalized to `us-central1-a`.
49 * @default "us-central1-a"
50 */
51 location?: string;
52 /**
53 * Snapshot id (the `{snapshot}` segment of
54 * `.../instances/{instance}/snapshots/{snapshot}`). If omitted, a
55 * unique RFC1035 name is generated from the stack, stage, and logical
56 * id. Must start with a letter, be 1-63 characters, and end with a
57 * letter or digit. Immutable — changing it replaces the snapshot.
58 */
59 snapshotId?: string;
60 /**
61 * Human-readable description (2048 characters or less).
62 */
63 description?: string;
64 /**
65 * User labels. Alchemy ownership labels are merged in automatically.
66 */
67 labels?: Record<string, string>;
68 /**
69 * Resource Manager tags (namespaced key to short value). Input-only
70 * and immutable.
71 */
72 tags?: Record<string, string>;
73 };
74
75 export type InstancesSnapshot = Resource<
76 "GCP.Filestore.InstancesSnapshot",
77 InstancesSnapshotProps,
78 {
79 /** Full resource name `projects/{project}/locations/{location}/instances/{instance}/snapshots/{snapshot}`. */
80 name: string;
81 /** Snapshot id (last path segment). */
82 snapshotId: string;
83 /** Parent instance resource name. */
84 instance: string;
85 /** Project id. */
86 project: string;
87 /** Instance location (zone or region). */
88 location: string;
89 /** Human-readable description. */
90 description: string | undefined;
91 /** User labels (Alchemy ownership labels stripped). */
92 labels: Record<string, string>;
93 /** Bytes needed to allocate a full copy of the snapshot. */
94 filesystemUsedBytes: string | undefined;
95 /** Server-reported state (`READY`, `CREATING`, `DELETING`). */
96 state: string | undefined;
97 /** RFC3339 creation timestamp. */
98 createTime: string | undefined;
99 },
100 never,
101 Providers
102 >;
103
104 /**
105 * A Cloud Filestore snapshot of an instance.
106 *
107 * Changing `snapshotId`, `instance`, or `location` replaces the
108 * snapshot. Description and labels update in place.
109 *
110 * Snapshots are supported on Zonal, Regional, Enterprise, and High Scale
111 * SSD instances. Basic HDD and Basic SSD reject snapshot create.
112 *
113 * ### Creating a Snapshot
114 * **Example:** Generated name
115 * ```typescript
116 * const snap = yield* GCP.Filestore.InstancesSnapshot("Nightly", {
117 * instance: nfs.name,
118 * });
119 * ```
120 *
121 * **Example:** Explicit id, description, and labels
122 * ```typescript
123 * const snap = yield* GCP.Filestore.InstancesSnapshot("Nightly", {
124 * instance: nfs.name,
125 * snapshotId: "app-nightly",
126 * description: "nightly snapshot",
127 * labels: { env: "prod" },
128 * });
129 * ```
130 *
131 * ### Updating a Snapshot
132 * Re-declare the same logical id with changed props; the engine keeps the
133 * physical resource and updates it in place.
134 *
135 * **Example:** Description and labels
136 * ```typescript
137 * const snap = yield* GCP.Filestore.InstancesSnapshot("Nightly", {
138 * instance: nfs.name,
139 * description: "nightly snapshot v2",
140 * labels: { env: "prod", team: "storage" },
141 * });
142 * ```
143 *
144 * @resource
145 * @category Filestore
146 */
147 export const InstancesSnapshot = Resource<InstancesSnapshot>("GCP.Filestore.InstancesSnapshot");
148
149 const resourceName = (instance: string, snapshotId: string) =>
150 `${instance}/snapshots/${snapshotId}`;
151
152 const parseInstanceRef = (value: string, fallbackProject: string, fallbackLocation: string) => {
153 const trimmed = value.trim();
154 if (trimmed.includes("/")) {
155 const parsed = parseName(trimmed, "instances", DEFAULT_ZONE);
156 const location = normalizeLocation(parsed.location, DEFAULT_ZONE);
157 return {
158 project: parsed.project || fallbackProject,
159 location,
160 instanceId: parsed.id,
161 instanceName: expandParent(
162 parsed.id,
163 parsed.project || fallbackProject,
164 location,
165 "instances",
166 ),
167 };
168 }
169 const location = normalizeLocation(fallbackLocation, DEFAULT_ZONE);
170 const instanceId = lastSegment(trimmed);
171 return {
172 project: fallbackProject,
173 location,
174 instanceId,
175 instanceName: expandParent(instanceId, fallbackProject, location, "instances"),
176 };
177 };
178
179 const toAttrs = (snapshot: file.Snapshot, project: string) => {
180 const name = snapshot.name ?? "";
181 const parsed = parseName(name, "snapshots", DEFAULT_ZONE);
182 return {
183 name,
184 snapshotId: parsed.id,
185 instance: parsed.parent,
186 project: parsed.project || project,
187 location: parsed.location,
188 description: snapshot.description,
189 labels: userLabels(snapshot.labels),
190 filesystemUsedBytes: snapshot.filesystemUsedBytes,
191 state: snapshot.state,
192 createTime: snapshot.createTime,
193 };
194 };
195
196 const isPlaceholder = (snapshot: file.Snapshot) => {
197 const name = snapshot.name ?? "";
198 return name.length === 0 || name.endsWith("/snapshots/-") || name.endsWith("/snapshots/");
199 };
200
201 const getByName = (name: string) =>
202 Effect.gen(function* () {
203 if (name.length === 0 || name.includes("//")) return undefined;
204 return yield* file
205 .getProjectsLocationsInstancesSnapshots({ name })
206 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
207 });
208
209 const listViaInstances = (project: string) =>
210 file.listProjectsLocationsInstances
211 .pages({
212 parent: `projects/${project}/locations/-`,
213 pageSize: 1000,
214 })
215 .pipe(
216 Stream.flatMap((page) => Stream.fromIterable(page.instances ?? [])),
217 Stream.filter((instance) => (instance.name ?? "").length > 0),
218 Stream.runCollect,
219 Effect.map((chunk) => Array.from(chunk)),
220 Effect.flatMap((instances) =>
221 Effect.forEach(
222 instances,
223 (instance) =>
224 listLabeledPages(
225 file.listProjectsLocationsInstancesSnapshots.pages({
226 parent: instance.name!,
227 pageSize: 1000,
228 }),
229 (page) => page.snapshots,
230 (item) => item.labels,
231 ),
232 { concurrency: 4 },
233 ).pipe(Effect.map((groups) => groups.flat())),
234 ),
235 );
236
237 const listOwned = (project: string) =>
238 file.listProjectsLocationsInstancesSnapshots
239 .pages({
240 parent: `projects/${project}/locations/-/instances/-`,
241 pageSize: 1000,
242 returnPartialSuccess: true,
243 })
244 .pipe(
245 Stream.flatMap((page) => Stream.fromIterable(page.snapshots ?? [])),
246 Stream.filter((item) => hasAlchemyLabelMap(item.labels)),
247 Stream.runCollect,
248 Effect.map((chunk) => Array.from(chunk)),
249 Effect.catchIf(
250 () => true,
251 () => listViaInstances(project),
252 ),
253 );
254
255 export const InstancesSnapshotProvider = () =>
256 Provider.succeed(InstancesSnapshot, {
257 stables: ["name", "snapshotId", "instance", "project", "location", "createTime"],
258
259 diff: Effect.fn(function* ({ news, olds, output }) {
260 if (!isResolved(news)) return undefined;
261 const env = yield* GcpEnvironment.current;
262 const previous = parseInstanceRef(
263 olds?.instance ?? output?.instance ?? "",
264 env.project,
265 olds?.location ?? output?.location ?? DEFAULT_ZONE,
266 );
267 const next = parseInstanceRef(
268 news.instance,
269 env.project,
270 news.location ?? olds?.location ?? output?.location ?? previous.location,
271 );
272 return replaceOnIdentity({
273 previousId: olds?.snapshotId ?? output?.snapshotId,
274 nextId: news.snapshotId ?? olds?.snapshotId ?? output?.snapshotId,
275 previousLocation: previous.location,
276 nextLocation: next.location,
277 previousParent: previous.instanceName,
278 nextParent: next.instanceName,
279 });
280 }),
281
282 read: Effect.fn(function* ({ id, olds, output }) {
283 const env = yield* GcpEnvironment.current;
284 const instance = parseInstanceRef(
285 olds?.instance ?? output?.instance ?? "",
286 env.project,
287 olds?.location ?? output?.location ?? DEFAULT_ZONE,
288 );
289 const snapshotId = yield* toPhysicalId(id, olds?.snapshotId, output?.snapshotId, "snapshot");
290 const name = output?.name ?? resourceName(instance.instanceName, snapshotId);
291 const existing = yield* getByName(name);
292 if (existing === undefined || isPlaceholder(existing)) return undefined;
293 const attrs = toAttrs(existing, env.project);
294 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
295 }),
296
297 list: () =>
298 Effect.gen(function* () {
299 const env = yield* GcpEnvironment.current;
300 const items = yield* listOwned(env.project);
301 return items
302 .filter((item) => !isPlaceholder(item) && hasAlchemyLabelMap(item.labels))
303 .map((item) => toAttrs(item, env.project));
304 }),
305
306 reconcile: Effect.fn(function* ({ id, news, output }) {
307 const env = yield* GcpEnvironment.current;
308 const instance = parseInstanceRef(
309 news.instance,
310 env.project,
311 news.location ?? output?.location ?? DEFAULT_ZONE,
312 );
313 const snapshotId = yield* toPhysicalId(id, news.snapshotId, output?.snapshotId, "snapshot");
314 const name = resourceName(instance.instanceName, snapshotId);
315 const desiredLabels = {
316 ...toLabels(news.labels),
317 ...(yield* createInternalLabels(id)),
318 };
319
320 let current = yield* getByName(output?.name ?? name);
321
322 if (current !== undefined && isDeletingState(current.state)) {
323 yield* waitUntilGone(getByName(current.name ?? name), current.name ?? name);
324 current = undefined;
325 }
326
327 if (current === undefined) {
328 const created = yield* file
329 .createProjectsLocationsInstancesSnapshots({
330 parent: instance.instanceName,
331 snapshotId,
332 body: {
333 description: news.description,
334 labels: desiredLabels,
335 tags: news.tags,
336 },
337 })
338 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
339 if (created !== undefined) {
340 yield* waitForOperation(created);
341 }
342 current = yield* waitUntilExists(getByName(name), name);
343 }
344
345 if (current === undefined) {
346 return yield* new ResourceNotResolved({ resourceName: name });
347 }
348
349 current = yield* waitUntilReady(
350 getByName(current.name ?? name),
351 current.name ?? name,
352 (item) => item.state,
353 );
354 if (current === undefined) {
355 return yield* new ResourceNotResolved({ resourceName: name });
356 }
357
358 const observedLabels = tagRecord(current.labels);
359 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
360 const mask = fieldMask([
361 (upsert.length > 0 || removed.length > 0) && "labels",
362 (current.description ?? "") !== (news.description ?? "") && "description",
363 ]);
364
365 if (mask.length > 0) {
366 const operation = yield* file.patchProjectsLocationsInstancesSnapshots({
367 name: current.name ?? name,
368 updateMask: mask,
369 body: {
370 name: current.name ?? name,
371 labels: desiredLabels,
372 description: news.description,
373 },
374 });
375 yield* waitForOperation(operation);
376 current = yield* waitUntilReady(
377 getByName(current.name ?? name),
378 current.name ?? name,
379 (item) => item.state,
380 );
381 if (current === undefined) {
382 return yield* new ResourceNotResolved({ resourceName: name });
383 }
384 }
385
386 return toAttrs(current, env.project);
387 }),
388
389 delete: Effect.fn(function* ({ output }) {
390 if (!output.name || output.name.includes("//")) return;
391 const operation = yield* file
392 .deleteProjectsLocationsInstancesSnapshots({ name: output.name })
393 .pipe(
394 Effect.retry({
395 while: (error) => error._tag === "Conflict",
396 times: 8,
397 schedule: Schedule.spaced("5 seconds"),
398 }),
399 Effect.catchTag("NotFound", () => Effect.undefined),
400 );
401 if (operation !== undefined) {
402 yield* waitForOperation(operation, { notFoundOk: true });
403 }
404 yield* waitUntilGone(getByName(output.name), output.name);
405 }),
406 });