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

main
ts 410 lines 14.4 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, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
12 import type { Providers } from "../Providers.ts";
13 import {
14 fieldMask,
15 fingerprint,
16 hasAlchemyLabelMap,
17 locationParent,
18 normalizeLocation,
19 parseName,
20 replaceOnIdentity,
21 ResourceNotResolved,
22 toPhysicalId,
23 userLabels,
24 waitForOperation,
25 waitUntilExists,
26 waitUntilGone,
27 } from "./internal.ts";
28
29 export type AwsSourceDetails = vm.AwsSourceDetails;
30 export type AzureSourceDetails = vm.AzureSourceDetails;
31 export type VmwareSourceDetails = vm.VmwareSourceDetails;
32 export type Encryption = vm.Encryption;
33
34 export type SourceProps = {
35 /**
36 * Source id (the `{source}` segment of
37 * `projects/{project}/locations/{location}/sources/{source}`). If
38 * omitted, a unique RFC1035 name is generated. Immutable — changing it
39 * replaces the source.
40 */
41 sourceId?: string;
42 /**
43 * Region (`us-central1`, …). Immutable — changing it replaces the
44 * source. `US-CENTRAL1` is accepted and normalized to `us-central1`.
45 * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
46 */
47 location?: string;
48 /**
49 * User-provided description of the source.
50 */
51 description?: string;
52 /**
53 * User labels. Alchemy ownership labels are merged in automatically.
54 */
55 labels?: Record<string, string>;
56 /**
57 * Encryption of source data stored by the service. Immutable —
58 * changing it replaces the source.
59 */
60 encryption?: Encryption;
61 /**
62 * AWS source environment. Mutually exclusive with `azure` and
63 * `vmware`. Switching source kinds replaces the source.
64 */
65 aws?: AwsSourceDetails;
66 /**
67 * Azure source environment. Mutually exclusive with `aws` and
68 * `vmware`. Switching source kinds replaces the source.
69 */
70 azure?: AzureSourceDetails;
71 /**
72 * VMware vCenter source environment. Mutually exclusive with `aws`
73 * and `azure`. Switching source kinds replaces the source.
74 */
75 vmware?: VmwareSourceDetails;
76 };
77
78 export type Source = Resource<
79 "GCP.VMMigration.Source",
80 SourceProps,
81 {
82 /** Full resource name. */
83 name: string;
84 /** Source id (last path segment). */
85 sourceId: string;
86 /** Project id. */
87 project: string;
88 /** Location id. */
89 location: string;
90 /** User-provided description. */
91 description: string | undefined;
92 /** User labels (Alchemy ownership labels stripped). */
93 labels: Record<string, string>;
94 /** Encryption of stored source data. */
95 encryption: Encryption | undefined;
96 /** AWS source details as reported by the API. */
97 aws: AwsSourceDetails | undefined;
98 /** Azure source details as reported by the API. */
99 azure: AzureSourceDetails | undefined;
100 /** VMware source details as reported by the API. */
101 vmware: VmwareSourceDetails | undefined;
102 /** RFC3339 creation timestamp. */
103 createTime: string | undefined;
104 /** RFC3339 last-update timestamp. */
105 updateTime: string | undefined;
106 },
107 never,
108 Providers
109 >;
110
111 /**
112 * A VM Migration source environment (AWS, Azure, or VMware vCenter)
113 * that inventories VMs and disks for migration.
114 *
115 * `sourceId`, `location`, `encryption`, and the source kind
116 * (`aws` / `azure` / `vmware`) plus immutable region/subscription
117 * fields are replacement triggers. Description, labels, and credential
118 * fields update in place.
119 *
120 * ### Creating a Source
121 * **Example:** AWS source
122 * ```typescript
123 * const source = yield* GCP.VMMigration.Source("Aws", {
124 * aws: {
125 * awsRegion: "us-east-1",
126 * accessKeyCreds: {
127 * accessKeyId: process.env.AWS_ACCESS_KEY_ID,
128 * secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
129 * },
130 * },
131 * labels: { env: "test" },
132 * });
133 * ```
134 *
135 * **Example:** VMware source
136 * ```typescript
137 * const source = yield* GCP.VMMigration.Source("Vcenter", {
138 * vmware: {
139 * vcenterIp: "10.0.0.4",
140 * username: "admin",
141 * password: process.env.VCENTER_PASSWORD,
142 * thumbprint: process.env.VCENTER_THUMBPRINT,
143 * },
144 * });
145 * ```
146 *
147 * @resource
148 * @category VMMigration
149 */
150 export const Source = Resource<Source>("GCP.VMMigration.Source");
151
152 const resourceName = (project: string, location: string, sourceId: string) =>
153 `${locationParent(project, location)}/sources/${sourceId}`;
154
155 const kindOf = (value: { aws?: unknown; azure?: unknown; vmware?: unknown }) =>
156 value.aws ? "aws" : value.azure ? "azure" : value.vmware ? "vmware" : "";
157
158 const toAttrs = (source: vm.Source, project: string, region: string) => {
159 const name = source.name ?? "";
160 const parsed = parseName(name, "sources", region);
161 return {
162 name,
163 sourceId: parsed.id,
164 project: parsed.project || project,
165 location: parsed.location,
166 description: source.description,
167 labels: userLabels(source.labels),
168 encryption: source.encryption,
169 aws: source.aws,
170 azure: source.azure,
171 vmware: source.vmware,
172 createTime: source.createTime,
173 updateTime: source.updateTime,
174 };
175 };
176
177 const getByName = (name: string) =>
178 name.length === 0
179 ? Effect.undefined
180 : vm
181 .getProjectsLocationsSources({ name })
182 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
183
184 const listOwned = (project: string, region: string) =>
185 vm.listProjectsLocationsSources
186 .pages({
187 parent: `projects/${project}/locations/-`,
188 pageSize: 1000,
189 })
190 .pipe(
191 Stream.flatMap((page) => Stream.fromIterable(page.sources ?? [])),
192 Stream.filter((item) => hasAlchemyLabelMap(item.labels)),
193 Stream.runCollect,
194 Effect.map((chunk) => Array.from(chunk)),
195 Effect.catchTag("NotFound", () =>
196 vm.listProjectsLocationsSources
197 .pages({
198 parent: locationParent(project, region),
199 pageSize: 1000,
200 })
201 .pipe(
202 Stream.flatMap((page) => Stream.fromIterable(page.sources ?? [])),
203 Stream.filter((item) => hasAlchemyLabelMap(item.labels)),
204 Stream.runCollect,
205 Effect.map((chunk) => Array.from(chunk)),
206 Effect.catchTag("NotFound", () => Effect.succeed([] as vm.Source[])),
207 ),
208 ),
209 );
210
211 const publicAws = (aws: AwsSourceDetails | undefined) =>
212 aws === undefined
213 ? undefined
214 : {
215 awsRegion: aws.awsRegion,
216 inventorySecurityGroupNames: aws.inventorySecurityGroupNames,
217 inventoryTagList: aws.inventoryTagList,
218 migrationResourcesUserTags: aws.migrationResourcesUserTags,
219 accessKeyCreds: aws.accessKeyCreds
220 ? { accessKeyId: aws.accessKeyCreds.accessKeyId }
221 : undefined,
222 };
223
224 const publicAzure = (azure: AzureSourceDetails | undefined) =>
225 azure === undefined
226 ? undefined
227 : {
228 azureLocation: azure.azureLocation,
229 subscriptionId: azure.subscriptionId,
230 migrationResourcesUserTags: azure.migrationResourcesUserTags,
231 clientSecretCreds: azure.clientSecretCreds
232 ? {
233 tenantId: azure.clientSecretCreds.tenantId,
234 clientId: azure.clientSecretCreds.clientId,
235 }
236 : undefined,
237 };
238
239 const publicVmware = (vmware: VmwareSourceDetails | undefined) =>
240 vmware === undefined
241 ? undefined
242 : {
243 vcenterIp: vmware.vcenterIp,
244 username: vmware.username,
245 thumbprint: vmware.thumbprint,
246 resolvedVcenterHost: vmware.resolvedVcenterHost,
247 };
248
249 export const SourceProvider = () =>
250 Provider.succeed(Source, {
251 stables: ["name", "sourceId", "project", "location", "createTime"],
252
253 diff: Effect.fn(function* ({ news, olds, output }) {
254 if (!isResolved(news)) return undefined;
255 const env = yield* GcpEnvironment.current;
256 const previousKind = kindOf({
257 aws: olds?.aws ?? output?.aws,
258 azure: olds?.azure ?? output?.azure,
259 vmware: olds?.vmware ?? output?.vmware,
260 });
261 const nextKind = kindOf(news) || previousKind;
262 const previousEncryption = olds?.encryption?.kmsKey ?? output?.encryption?.kmsKey;
263 const nextEncryption = news.encryption?.kmsKey ?? previousEncryption;
264 const previousAwsRegion = olds?.aws?.awsRegion ?? output?.aws?.awsRegion;
265 const nextAwsRegion = news.aws?.awsRegion ?? previousAwsRegion;
266 const previousAzureLocation = olds?.azure?.azureLocation ?? output?.azure?.azureLocation;
267 const nextAzureLocation = news.azure?.azureLocation ?? previousAzureLocation;
268 const previousSubscription = olds?.azure?.subscriptionId ?? output?.azure?.subscriptionId;
269 const nextSubscription = news.azure?.subscriptionId ?? previousSubscription;
270 return replaceOnIdentity({
271 previousId: olds?.sourceId ?? output?.sourceId,
272 nextId: news.sourceId ?? olds?.sourceId ?? output?.sourceId,
273 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
274 nextLocation: normalizeLocation(
275 news.location ?? olds?.location ?? output?.location,
276 env.region,
277 ),
278 extra:
279 previousKind !== nextKind ||
280 previousEncryption !== nextEncryption ||
281 previousAwsRegion !== nextAwsRegion ||
282 previousAzureLocation !== nextAzureLocation ||
283 previousSubscription !== nextSubscription,
284 });
285 }),
286
287 read: Effect.fn(function* ({ id, olds, output }) {
288 const env = yield* GcpEnvironment.current;
289 const sourceId = yield* toPhysicalId(id, olds?.sourceId, output?.sourceId, "source");
290 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
291 const name = output?.name ?? resourceName(env.project, location, sourceId);
292 const existing = yield* getByName(name);
293 if (existing === undefined) return undefined;
294 const attrs = toAttrs(existing, env.project, env.region);
295 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
296 }),
297
298 list: () =>
299 Effect.gen(function* () {
300 const env = yield* GcpEnvironment.current;
301 const items = yield* listOwned(env.project, env.region);
302 return items.map((item) => toAttrs(item, env.project, env.region));
303 }),
304
305 reconcile: Effect.fn(function* ({ id, news, output }) {
306 const env = yield* GcpEnvironment.current;
307 const sourceId = yield* toPhysicalId(id, news.sourceId, output?.sourceId, "source");
308 const location = normalizeLocation(news.location ?? output?.location, env.region);
309 const name = resourceName(env.project, location, sourceId);
310 const desiredLabels = {
311 ...toLabels(news.labels),
312 ...(yield* createInternalLabels(id)),
313 };
314
315 let current = yield* getByName(output?.name ?? name);
316
317 if (current === undefined) {
318 const created = yield* vm
319 .createProjectsLocationsSources({
320 parent: locationParent(env.project, location),
321 sourceId,
322 body: {
323 description: news.description,
324 labels: desiredLabels,
325 encryption: news.encryption,
326 aws: news.aws,
327 azure: news.azure,
328 vmware: news.vmware,
329 },
330 })
331 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
332 if (created !== undefined) {
333 // ALREADY_EXISTS (6): a concurrent create won the race.
334 yield* waitForOperation(created).pipe(
335 Effect.catchTag("GCP.OperationFailed", (error) =>
336 error.code === 6 ? Effect.void : Effect.fail(error),
337 ),
338 );
339 }
340 current = yield* waitUntilExists(getByName(name), name);
341 }
342
343 if (current === undefined) {
344 return yield* new ResourceNotResolved({ resourceName: name });
345 }
346
347 const observedLabels = tagRecord(current.labels);
348 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
349 const labelsChanged = upsert.length > 0 || removed.length > 0;
350 const descriptionChanged = (current.description ?? "") !== (news.description ?? "");
351 const awsChanged =
352 news.aws !== undefined &&
353 (fingerprint(publicAws(current.aws)) !== fingerprint(publicAws(news.aws)) ||
354 news.aws.accessKeyCreds?.secretAccessKey !== undefined);
355 const azureChanged =
356 news.azure !== undefined &&
357 (fingerprint(publicAzure(current.azure)) !== fingerprint(publicAzure(news.azure)) ||
358 news.azure.clientSecretCreds?.clientSecret !== undefined);
359 const vmwareChanged =
360 news.vmware !== undefined &&
361 (fingerprint(publicVmware(current.vmware)) !== fingerprint(publicVmware(news.vmware)) ||
362 news.vmware.password !== undefined);
363 const mask = fieldMask([
364 labelsChanged && "labels",
365 descriptionChanged && "description",
366 awsChanged && "aws",
367 azureChanged && "azure",
368 vmwareChanged && "vmware",
369 ]);
370
371 if (mask.length > 0) {
372 const operation = yield* vm.patchProjectsLocationsSources({
373 name: current.name ?? name,
374 updateMask: mask,
375 body: {
376 name: current.name ?? name,
377 description: news.description,
378 labels: desiredLabels,
379 aws: news.aws,
380 azure: news.azure,
381 vmware: news.vmware,
382 },
383 });
384 yield* waitForOperation(operation);
385 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
386 }
387
388 return toAttrs(current, env.project, env.region);
389 }),
390
391 delete: Effect.fn(function* ({ output }) {
392 const operation = yield* vm.deleteProjectsLocationsSources({ name: output.name }).pipe(
393 Effect.retry({
394 while: (error) => error._tag === "Conflict",
395 times: 8,
396 schedule: Schedule.spaced("2 seconds"),
397 }),
398 Effect.catchTag("NotFound", () => Effect.undefined),
399 );
400 if (operation !== undefined) {
401 // NOT_FOUND (5): already gone.
402 yield* waitForOperation(operation).pipe(
403 Effect.catchTag("GCP.OperationFailed", (error) =>
404 error.code === 5 ? Effect.void : Effect.fail(error),
405 ),
406 );
407 }
408 yield* waitUntilGone(getByName(output.name), output.name);
409 }),
410 });