@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, 04:45 UTC

main
ts 341 lines 11.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 { GcpEnvironment } from "../Environment.ts";
10 import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 collectPages,
14 fieldMask,
15 fingerprint,
16 forEachSource,
17 hasAlchemyLabelMap,
18 normalizeLocation,
19 parseName,
20 replaceOnIdentity,
21 ResourceNotResolved,
22 sourceOf,
23 toPhysicalId,
24 userLabels,
25 waitForOperation,
26 waitUntilExists,
27 waitUntilGone,
28 } from "./internal.ts";
29
30 export type DiskMigrationJobTargetDetails = vm.DiskMigrationJobTargetDetails;
31 export type AwsSourceDiskDetails = vm.AwsSourceDiskDetails;
32 export type DiskMigrationJobState = vm.DiskMigrationJobStateEnum | (string & {});
33
34 export type SourcesDiskMigrationJobProps = {
35 /**
36 * Parent source. Full name
37 * `projects/{project}/locations/{location}/sources/{source}` or the
38 * source id (combined with `location`). Immutable — changing it
39 * replaces the job.
40 */
41 source: string;
42 /**
43 * Region used when `source` is a bare id.
44 * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
45 */
46 location?: string;
47 /**
48 * Disk migration job id. If omitted, a unique RFC1035 name is
49 * generated. Immutable — changing it replaces the job.
50 */
51 diskMigrationJobId?: string;
52 /**
53 * Target disk in Compute Engine. Alchemy ownership labels are merged
54 * into `targetDetails.labels` (the job itself has no labels field).
55 */
56 targetDetails: DiskMigrationJobTargetDetails;
57 /**
58 * Unattached AWS source disk. Immutable volume id — changing it
59 * replaces the job.
60 */
61 awsSourceDiskDetails?: AwsSourceDiskDetails;
62 };
63
64 export type SourcesDiskMigrationJob = Resource<
65 "GCP.VMMigration.SourcesDiskMigrationJob",
66 SourcesDiskMigrationJobProps,
67 {
68 /** Full resource name. */
69 name: string;
70 /** Disk migration job id (last path segment). */
71 diskMigrationJobId: string;
72 /** Parent source resource name. */
73 source: string;
74 /** Project id. */
75 project: string;
76 /** Location id. */
77 location: string;
78 /** Target disk details with Alchemy labels stripped. */
79 targetDetails: DiskMigrationJobTargetDetails | undefined;
80 /** AWS source disk details. */
81 awsSourceDiskDetails: AwsSourceDiskDetails | undefined;
82 /** Job state. */
83 state: string | undefined;
84 /** Progress steps. */
85 steps: vm.DiskMigrationStepList | undefined;
86 /** Errors that led to a failed state. */
87 errors: vm.StatusList | undefined;
88 /** RFC3339 creation timestamp. */
89 createTime: string | undefined;
90 /** RFC3339 last-update timestamp. */
91 updateTime: string | undefined;
92 },
93 never,
94 Providers
95 >;
96
97 /**
98 * A VM Migration disk migration job that copies an unattached source
99 * disk into a Compute Engine persistent disk.
100 *
101 * The job has no labels field — Alchemy stamps ownership into
102 * `targetDetails.labels` so `list` / nuke can find them. Source, job
103 * id, and AWS volume id are immutable. Target details update in place.
104 *
105 * ### Creating a Disk Migration Job
106 * **Example:** AWS volume to Compute Engine
107 * ```typescript
108 * const job = yield* GCP.VMMigration.SourcesDiskMigrationJob("Boot", {
109 * source: source.name,
110 * awsSourceDiskDetails: { volumeId: "vol-123" },
111 * targetDetails: {
112 * targetProject: target.name,
113 * targetDisk: {
114 * zone: "projects/my-project/locations/us-central1-a",
115 * diskType: "COMPUTE_ENGINE_DISK_TYPE_STANDARD",
116 * diskId: "imported-boot",
117 * },
118 * },
119 * });
120 * ```
121 *
122 * @resource
123 * @category VMMigration
124 */
125 export const SourcesDiskMigrationJob = Resource<SourcesDiskMigrationJob>(
126 "GCP.VMMigration.SourcesDiskMigrationJob",
127 );
128
129 const resourceName = (source: string, diskMigrationJobId: string) =>
130 `${source}/diskMigrationJobs/${diskMigrationJobId}`;
131
132 const stampTarget = (
133 target: DiskMigrationJobTargetDetails,
134 ownership: Record<string, string>,
135 ): DiskMigrationJobTargetDetails => ({
136 ...target,
137 labels: {
138 ...toLabels(tagRecord(target.labels)),
139 ...ownership,
140 },
141 });
142
143 const stripTarget = (
144 target: DiskMigrationJobTargetDetails | undefined,
145 ): DiskMigrationJobTargetDetails | undefined => {
146 if (target === undefined) return undefined;
147 return {
148 ...target,
149 labels: userLabels(target.labels),
150 };
151 };
152
153 const toAttrs = (job: vm.DiskMigrationJob, project: string, region: string) => {
154 const name = job.name ?? "";
155 const parsed = parseName(name, "diskMigrationJobs", region);
156 return {
157 name,
158 diskMigrationJobId: parsed.id,
159 source: parsed.parent,
160 project: parsed.project || project,
161 location: parsed.location,
162 targetDetails: stripTarget(job.targetDetails),
163 awsSourceDiskDetails: job.awsSourceDiskDetails,
164 state: job.state,
165 steps: job.steps,
166 errors: job.errors,
167 createTime: job.createTime,
168 updateTime: job.updateTime,
169 };
170 };
171
172 const getByName = (name: string) =>
173 name.length === 0
174 ? Effect.undefined
175 : vm
176 .getProjectsLocationsSourcesDiskMigrationJobs({ name })
177 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
178
179 const listChildren = (parent: string) =>
180 collectPages(
181 vm.listProjectsLocationsSourcesDiskMigrationJobs.pages({
182 parent,
183 pageSize: 1000,
184 }),
185 (page) => page.diskMigrationJobs,
186 ).pipe(Effect.catchTag("NotFound", () => Effect.succeed([] as vm.DiskMigrationJob[])));
187
188 export const SourcesDiskMigrationJobProvider = () =>
189 Provider.succeed(SourcesDiskMigrationJob, {
190 stables: ["name", "diskMigrationJobId", "source", "project", "location", "createTime"],
191
192 diff: Effect.fn(function* ({ news, olds, output }) {
193 if (!isResolved(news)) return undefined;
194 const env = yield* GcpEnvironment.current;
195 const previousVolume =
196 olds?.awsSourceDiskDetails?.volumeId ?? output?.awsSourceDiskDetails?.volumeId;
197 const nextVolume = news.awsSourceDiskDetails?.volumeId ?? previousVolume;
198 const previousSource = olds?.source ?? output?.source;
199 return replaceOnIdentity({
200 previousId: olds?.diskMigrationJobId ?? output?.diskMigrationJobId,
201 nextId: news.diskMigrationJobId ?? olds?.diskMigrationJobId ?? output?.diskMigrationJobId,
202 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
203 nextLocation: normalizeLocation(
204 news.location ?? olds?.location ?? output?.location,
205 env.region,
206 ),
207 previousParent: previousSource,
208 nextParent: news.source ?? previousSource,
209 extra: previousVolume !== nextVolume,
210 });
211 }),
212
213 read: Effect.fn(function* ({ id, olds, output }) {
214 const env = yield* GcpEnvironment.current;
215 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
216 const diskMigrationJobId = yield* toPhysicalId(
217 id,
218 olds?.diskMigrationJobId,
219 output?.diskMigrationJobId,
220 "diskmigration",
221 );
222 const source =
223 olds?.source !== undefined
224 ? sourceOf(olds.source, env.project, location)
225 : (output?.source ?? "");
226 const name =
227 output?.name ?? (source.length > 0 ? resourceName(source, diskMigrationJobId) : "");
228 const existing = yield* getByName(name);
229 if (existing === undefined) return undefined;
230 const attrs = toAttrs(existing, env.project, env.region);
231 return (yield* hasAlchemyLabels(id, tagRecord(existing.targetDetails?.labels)))
232 ? attrs
233 : Unowned(attrs);
234 }),
235
236 list: () =>
237 Effect.gen(function* () {
238 const env = yield* GcpEnvironment.current;
239 const items = yield* forEachSource(env.project, listChildren, env.region);
240 return items
241 .filter((item) => hasAlchemyLabelMap(item.targetDetails?.labels))
242 .map((item) => toAttrs(item, env.project, env.region));
243 }),
244
245 reconcile: Effect.fn(function* ({ id, news, output }) {
246 const env = yield* GcpEnvironment.current;
247 const location = normalizeLocation(news.location ?? output?.location, env.region);
248 const source = sourceOf(news.source, env.project, location);
249 const diskMigrationJobId = yield* toPhysicalId(
250 id,
251 news.diskMigrationJobId,
252 output?.diskMigrationJobId,
253 "diskmigration",
254 );
255 const name = resourceName(source, diskMigrationJobId);
256 const ownership = yield* createInternalLabels(id);
257 const targetDetails = stampTarget(news.targetDetails, ownership);
258
259 let current = yield* getByName(output?.name ?? name);
260
261 if (current === undefined) {
262 const created = yield* vm
263 .createProjectsLocationsSourcesDiskMigrationJobs({
264 parent: source,
265 diskMigrationJobId,
266 body: {
267 targetDetails,
268 awsSourceDiskDetails: news.awsSourceDiskDetails,
269 },
270 })
271 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
272 if (created !== undefined) {
273 // ALREADY_EXISTS (6): a concurrent create won the race.
274 yield* waitForOperation(created).pipe(
275 Effect.catchTag("GCP.OperationFailed", (error) =>
276 error.code === 6 ? Effect.void : Effect.fail(error),
277 ),
278 );
279 }
280 current = yield* waitUntilExists(getByName(name), name);
281 }
282
283 if (current === undefined) {
284 return yield* new ResourceNotResolved({ resourceName: name });
285 }
286
287 const observedLabels = tagRecord(current.targetDetails?.labels);
288 const desiredLabels = tagRecord(targetDetails.labels);
289 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
290 const labelsChanged = upsert.length > 0 || removed.length > 0;
291 const targetChanged =
292 fingerprint({
293 ...current.targetDetails,
294 labels: undefined,
295 }) !==
296 fingerprint({
297 ...targetDetails,
298 labels: undefined,
299 });
300 const mask = fieldMask([(labelsChanged || targetChanged) && "targetDetails"]);
301
302 if (mask.length > 0) {
303 const operation = yield* vm.patchProjectsLocationsSourcesDiskMigrationJobs({
304 name: current.name ?? name,
305 updateMask: mask,
306 body: {
307 name: current.name ?? name,
308 targetDetails,
309 },
310 });
311 yield* waitForOperation(operation);
312 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
313 }
314
315 return toAttrs(current, env.project, env.region);
316 }),
317
318 delete: Effect.fn(function* ({ output }) {
319 const operation = yield* vm
320 .deleteProjectsLocationsSourcesDiskMigrationJobs({
321 name: output.name,
322 })
323 .pipe(
324 Effect.retry({
325 while: (error) => error._tag === "Conflict",
326 times: 8,
327 schedule: Schedule.spaced("2 seconds"),
328 }),
329 Effect.catchTag("NotFound", () => Effect.undefined),
330 );
331 if (operation !== undefined) {
332 // NOT_FOUND (5): already gone.
333 yield* waitForOperation(operation).pipe(
334 Effect.catchTag("GCP.OperationFailed", (error) =>
335 error.code === 5 ? Effect.void : Effect.fail(error),
336 ),
337 );
338 }
339 yield* waitUntilGone(getByName(output.name), output.name);
340 }),
341 });