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

main
ts 355 lines 12.5 KB
Raw
1 import * as vm from "@distilled.cloud/gcp/vmmigration_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, hasAlchemyLabels, toLabels } from "../Labels.ts";
12 import type { Providers } from "../Providers.ts";
13 import {
14 encodeOwnership,
15 fingerprint,
16 hasAlchemyLabelMap,
17 hasOwnershipMarker,
18 locationParent,
19 normalizeLocation,
20 ownedByAlchemy,
21 parseName,
22 parseOwnership,
23 replaceOnIdentity,
24 ResourceNotResolved,
25 toPhysicalId,
26 userLabels,
27 waitForOperation,
28 waitUntilExists,
29 waitUntilGone,
30 } from "./internal.ts";
31
32 export type DiskImageTargetDetails = vm.DiskImageTargetDetails;
33 export type MachineImageTargetDetails = vm.MachineImageTargetDetails;
34
35 export type ImageImportProps = {
36 /**
37 * Image import id (the `{imageImport}` segment of
38 * `projects/{project}/locations/{location}/imageImports/{imageImport}`).
39 * If omitted, a unique RFC1035 name is generated. Immutable — changing
40 * it replaces the import.
41 */
42 imageImportId?: string;
43 /**
44 * Region (`us-central1`, …). Immutable — changing it replaces the
45 * import. `US-CENTRAL1` is accepted and normalized to `us-central1`.
46 * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
47 */
48 location?: string;
49 /**
50 * Cloud Storage URI of the image to import. Immutable — changing it
51 * replaces the import.
52 */
53 cloudStorageUri: string;
54 /**
55 * Target details for a disk image. Mutually exclusive with
56 * `machineImageTargetDefaults`. Alchemy ownership labels are merged
57 * into `labels` (the import itself has no labels field). Immutable.
58 */
59 diskImageTargetDefaults?: DiskImageTargetDetails;
60 /**
61 * Target details for a machine image. Mutually exclusive with
62 * `diskImageTargetDefaults`. Alchemy ownership labels are merged into
63 * `labels`. Immutable.
64 */
65 machineImageTargetDefaults?: MachineImageTargetDetails;
66 /**
67 * Encryption used during image adaptation. Immutable — changing it
68 * replaces the import.
69 */
70 encryption?: vm.Encryption;
71 };
72
73 export type ImageImport = Resource<
74 "GCP.VMMigration.ImageImport",
75 ImageImportProps,
76 {
77 /** Full resource name. */
78 name: string;
79 /** Image import id (last path segment). */
80 imageImportId: string;
81 /** Project id. */
82 project: string;
83 /** Location id. */
84 location: string;
85 /** Cloud Storage URI of the imported image. */
86 cloudStorageUri: string | undefined;
87 /** Disk image target details with Alchemy labels stripped. */
88 diskImageTargetDefaults: DiskImageTargetDetails | undefined;
89 /** Machine image target details with Alchemy labels stripped. */
90 machineImageTargetDefaults: MachineImageTargetDetails | undefined;
91 /** Encryption used during adaptation. */
92 encryption: vm.Encryption | undefined;
93 /** Most recent import jobs. */
94 recentImageImportJobs: vm.ImageImportJobList | undefined;
95 /** RFC3339 creation timestamp. */
96 createTime: string | undefined;
97 },
98 never,
99 Providers
100 >;
101
102 /**
103 * A VM Migration image import from a Cloud Storage file into a Compute
104 * Engine disk or machine image.
105 *
106 * Image imports are immutable — every field is a replacement trigger.
107 * The resource has no labels field; Alchemy stamps ownership into the
108 * target details' `labels` and `description` so `list` / nuke can find
109 * them.
110 *
111 * ### Creating an Image Import
112 * **Example:** Disk image
113 * ```typescript
114 * const target = yield* GCP.VMMigration.Target("Landing");
115 * const image = yield* GCP.VMMigration.ImageImport("Disk", {
116 * cloudStorageUri: "gs://bucket/disk.vmdk",
117 * diskImageTargetDefaults: {
118 * imageName: "imported-disk",
119 * targetProject: target.name,
120 * },
121 * });
122 * ```
123 *
124 * **Example:** Machine image
125 * ```typescript
126 * const image = yield* GCP.VMMigration.ImageImport("Machine", {
127 * cloudStorageUri: "gs://bucket/machine.ova",
128 * machineImageTargetDefaults: {
129 * machineImageName: "imported-machine",
130 * targetProject: target.name,
131 * },
132 * });
133 * ```
134 *
135 * @resource
136 * @category VMMigration
137 */
138 export const ImageImport = Resource<ImageImport>("GCP.VMMigration.ImageImport");
139
140 const resourceName = (project: string, location: string, imageImportId: string) =>
141 `${locationParent(project, location)}/imageImports/${imageImportId}`;
142
143 const stripTarget = <T extends { labels?: vm.StringMap; description?: string }>(
144 target: T | undefined,
145 ): T | undefined => {
146 if (target === undefined) return undefined;
147 return {
148 ...target,
149 labels: userLabels(target.labels),
150 description: parseOwnership(target.description).text,
151 };
152 };
153
154 const toAttrs = (image: vm.ImageImport, project: string, region: string) => {
155 const name = image.name ?? "";
156 const parsed = parseName(name, "imageImports", region);
157 return {
158 name,
159 imageImportId: parsed.id,
160 project: parsed.project || project,
161 location: parsed.location,
162 cloudStorageUri: image.cloudStorageUri,
163 diskImageTargetDefaults: stripTarget(image.diskImageTargetDefaults),
164 machineImageTargetDefaults: stripTarget(image.machineImageTargetDefaults),
165 encryption: image.encryption,
166 recentImageImportJobs: image.recentImageImportJobs,
167 createTime: image.createTime,
168 };
169 };
170
171 const isOwned = (image: vm.ImageImport) =>
172 hasAlchemyLabelMap(image.diskImageTargetDefaults?.labels) ||
173 hasAlchemyLabelMap(image.machineImageTargetDefaults?.labels) ||
174 hasOwnershipMarker(image.diskImageTargetDefaults?.description) ||
175 hasOwnershipMarker(image.machineImageTargetDefaults?.description);
176
177 const ownedById = (id: string, image: vm.ImageImport) =>
178 Effect.gen(function* () {
179 const disk = image.diskImageTargetDefaults;
180 const machine = image.machineImageTargetDefaults;
181 if (disk && (yield* hasAlchemyLabels(id, tagRecord(disk.labels)))) {
182 return true;
183 }
184 if (machine && (yield* hasAlchemyLabels(id, tagRecord(machine.labels)))) {
185 return true;
186 }
187 if (yield* ownedByAlchemy(id, disk?.description)) return true;
188 if (yield* ownedByAlchemy(id, machine?.description)) return true;
189 return false;
190 });
191
192 const stampTarget = <T extends { labels?: vm.StringMap; description?: string }>(
193 target: T | undefined,
194 ownership: Record<string, string>,
195 ): T | undefined => {
196 if (target === undefined) return undefined;
197 return {
198 ...target,
199 labels: { ...toLabels(tagRecord(target.labels)), ...ownership },
200 description: encodeOwnership(ownership, target.description),
201 };
202 };
203
204 const getByName = (name: string) =>
205 name.length === 0
206 ? Effect.undefined
207 : vm
208 .getProjectsLocationsImageImports({ name })
209 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
210
211 const listOwned = (project: string, region: string) =>
212 vm.listProjectsLocationsImageImports
213 .pages({
214 parent: `projects/${project}/locations/-`,
215 pageSize: 1000,
216 })
217 .pipe(
218 Stream.flatMap((page) => Stream.fromIterable(page.imageImports ?? [])),
219 Stream.filter(isOwned),
220 Stream.runCollect,
221 Effect.map((chunk) => Array.from(chunk)),
222 Effect.catchTag("NotFound", () =>
223 vm.listProjectsLocationsImageImports
224 .pages({
225 parent: locationParent(project, region),
226 pageSize: 1000,
227 })
228 .pipe(
229 Stream.flatMap((page) => Stream.fromIterable(page.imageImports ?? [])),
230 Stream.filter(isOwned),
231 Stream.runCollect,
232 Effect.map((chunk) => Array.from(chunk)),
233 Effect.catchTag("NotFound", () => Effect.succeed([] as vm.ImageImport[])),
234 ),
235 ),
236 );
237
238 export const ImageImportProvider = () =>
239 Provider.succeed(ImageImport, {
240 stables: ["name", "imageImportId", "project", "location", "createTime"],
241
242 diff: Effect.fn(function* ({ news, olds, output }) {
243 if (!isResolved(news)) return undefined;
244 const env = yield* GcpEnvironment.current;
245 const extra =
246 (news.cloudStorageUri !== undefined &&
247 (olds?.cloudStorageUri ?? output?.cloudStorageUri) !== undefined &&
248 news.cloudStorageUri !== (olds?.cloudStorageUri ?? output?.cloudStorageUri)) ||
249 fingerprint(news.encryption) !== fingerprint(olds?.encryption ?? output?.encryption) ||
250 fingerprint(news.diskImageTargetDefaults) !==
251 fingerprint(olds?.diskImageTargetDefaults ?? output?.diskImageTargetDefaults) ||
252 fingerprint(news.machineImageTargetDefaults) !==
253 fingerprint(olds?.machineImageTargetDefaults ?? output?.machineImageTargetDefaults);
254 return replaceOnIdentity({
255 previousId: olds?.imageImportId ?? output?.imageImportId,
256 nextId: news.imageImportId ?? olds?.imageImportId ?? output?.imageImportId,
257 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
258 nextLocation: normalizeLocation(
259 news.location ?? olds?.location ?? output?.location,
260 env.region,
261 ),
262 extra,
263 });
264 }),
265
266 read: Effect.fn(function* ({ id, olds, output }) {
267 const env = yield* GcpEnvironment.current;
268 const imageImportId = yield* toPhysicalId(
269 id,
270 olds?.imageImportId,
271 output?.imageImportId,
272 "imageimport",
273 );
274 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
275 const name = output?.name ?? resourceName(env.project, location, imageImportId);
276 const existing = yield* getByName(name);
277 if (existing === undefined) return undefined;
278 const attrs = toAttrs(existing, env.project, env.region);
279 return (yield* ownedById(id, existing)) ? attrs : Unowned(attrs);
280 }),
281
282 list: () =>
283 Effect.gen(function* () {
284 const env = yield* GcpEnvironment.current;
285 const items = yield* listOwned(env.project, env.region);
286 return items.map((item) => toAttrs(item, env.project, env.region));
287 }),
288
289 reconcile: Effect.fn(function* ({ id, news, output }) {
290 const env = yield* GcpEnvironment.current;
291 const imageImportId = yield* toPhysicalId(
292 id,
293 news.imageImportId,
294 output?.imageImportId,
295 "imageimport",
296 );
297 const location = normalizeLocation(news.location ?? output?.location, env.region);
298 const name = resourceName(env.project, location, imageImportId);
299 const ownership = yield* createInternalLabels(id);
300 const diskImageTargetDefaults = stampTarget(news.diskImageTargetDefaults, ownership);
301 const machineImageTargetDefaults = stampTarget(news.machineImageTargetDefaults, ownership);
302
303 let current = yield* getByName(output?.name ?? name);
304
305 if (current === undefined) {
306 const created = yield* vm
307 .createProjectsLocationsImageImports({
308 parent: locationParent(env.project, location),
309 imageImportId,
310 body: {
311 cloudStorageUri: news.cloudStorageUri,
312 diskImageTargetDefaults,
313 machineImageTargetDefaults,
314 encryption: news.encryption,
315 },
316 })
317 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
318 if (created !== undefined) {
319 // ALREADY_EXISTS (6): a concurrent create won the race.
320 yield* waitForOperation(created).pipe(
321 Effect.catchTag("GCP.OperationFailed", (error) =>
322 error.code === 6 ? Effect.void : Effect.fail(error),
323 ),
324 );
325 }
326 current = yield* waitUntilExists(getByName(name), name);
327 }
328
329 if (current === undefined) {
330 return yield* new ResourceNotResolved({ resourceName: name });
331 }
332
333 return toAttrs(current, env.project, env.region);
334 }),
335
336 delete: Effect.fn(function* ({ output }) {
337 const operation = yield* vm.deleteProjectsLocationsImageImports({ name: output.name }).pipe(
338 Effect.retry({
339 while: (error) => error._tag === "Conflict",
340 times: 8,
341 schedule: Schedule.spaced("2 seconds"),
342 }),
343 Effect.catchTag("NotFound", () => Effect.undefined),
344 );
345 if (operation !== undefined) {
346 // NOT_FOUND (5): already gone.
347 yield* waitForOperation(operation).pipe(
348 Effect.catchTag("GCP.OperationFailed", (error) =>
349 error.code === 5 ? Effect.void : Effect.fail(error),
350 ),
351 );
352 }
353 yield* waitUntilGone(getByName(output.name), output.name);
354 }),
355 });