@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, 06:00 UTC

main
ts 741 lines 24.6 KB
Raw
1 import * as tpu from "@distilled.cloud/gcp/tpu_v2";
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 DEFAULT_ACCELERATOR,
14 DEFAULT_NETWORK,
15 DEFAULT_RUNTIME,
16 fieldMask,
17 lastSegment,
18 listLabeledPages,
19 mapKey,
20 normalizeLocation,
21 parseName,
22 replaceOnIdentity,
23 ResourceNotResolved,
24 stringMapOf,
25 stringsKey,
26 stringsOf,
27 toPhysicalId,
28 userLabels,
29 waitForOperation,
30 waitUntilExists,
31 waitUntilGone,
32 waitUntilReady,
33 } from "./internal.ts";
34
35 export type NetworkConfig = {
36 /**
37 * Associate external IPs with TPU workers. When false, the network or
38 * subnetwork must have Private Google Access.
39 * @default true
40 */
41 enableExternalIps?: boolean;
42 /**
43 * Subnetwork name or path. Defaults to `default`.
44 */
45 subnetwork?: string;
46 /**
47 * VPC network name or path. Defaults to `default`.
48 * @default "default"
49 */
50 network?: string;
51 /**
52 * Allow the TPU to send/receive packets with non-matching IPs (required
53 * to forward routes).
54 */
55 canIpForward?: boolean;
56 /**
57 * Networking queue count for the TPU VM NIC.
58 */
59 queueCount?: number;
60 };
61
62 export type AcceleratorConfig = {
63 /**
64 * TPU generation (`V2`, `V3`, `V4`, `V5LITE_POD`, `V5P`, `V6E`).
65 */
66 type?: tpu.AcceleratorConfigTypeEnum | (string & {});
67 /**
68 * Chip topology (e.g. `2x2` for v2-8).
69 */
70 topology?: string;
71 };
72
73 export type ServiceAccount = {
74 /**
75 * Service account email. Omit to use the default Compute service
76 * account.
77 */
78 email?: string;
79 /**
80 * OAuth scopes. Omit to allow all Cloud APIs.
81 */
82 scope?: string[];
83 };
84
85 export type SchedulingConfig = {
86 /** Provision under a reservation. */
87 reserved?: boolean;
88 /** Provision as a Spot VM. Immutable. */
89 spot?: boolean;
90 /** Provision as preemptible. Immutable. */
91 preemptible?: boolean;
92 };
93
94 export type AttachedDisk = {
95 /**
96 * Existing disk path
97 * (`projects/{project}/zones/{zone}/disks/{disk}`).
98 */
99 sourceDisk?: string;
100 /**
101 * Attach mode. Defaults to `READ_WRITE`.
102 */
103 mode?: tpu.AttachedDiskModeEnum | (string & {});
104 };
105
106 export type BootDiskConfig = {
107 /** Customer-managed KMS key for the boot disk. */
108 customerEncryptionKey?: {
109 /** Cloud KMS crypto key resource name. */
110 kmsKeyName?: string;
111 };
112 };
113
114 export type ShieldedInstanceConfig = {
115 /** Enable Secure Boot. */
116 enableSecureBoot?: boolean;
117 };
118
119 export type NodeProps = {
120 /**
121 * Node id (the `{node}` segment of
122 * `projects/{project}/locations/{location}/nodes/{node}`).
123 * If omitted, a unique RFC1035 name is generated from the stack, stage,
124 * and logical id. Must be 1-63 characters, start with a letter, and end
125 * with a letter or digit. Immutable — changing it replaces the node.
126 */
127 nodeId?: string;
128 /**
129 * Zone (`us-central1-c`, `us-central1-b`, …). TPU nodes are zonal.
130 * Immutable — changing it replaces the node. `US-CENTRAL1-C` is
131 * accepted and normalized to `us-central1-c`.
132 * @default "us-central1-c"
133 */
134 location?: string;
135 /**
136 * Runtime version running on the node (e.g. `tpu-ubuntu2204-base`).
137 * Immutable — changing it replaces the node.
138 * @default "tpu-ubuntu2204-base"
139 */
140 runtimeVersion?: string;
141 /**
142 * Accelerator type (`v2-8`, `v3-8`, `v5litepod-8`, …). Mutually
143 * exclusive with `acceleratorConfig`. Immutable. If neither is set,
144 * defaults to `v2-8`.
145 */
146 acceleratorType?: string;
147 /**
148 * Accelerator generation and chip topology. Mutually exclusive with
149 * `acceleratorType`. Immutable.
150 */
151 acceleratorConfig?: AcceleratorConfig;
152 /**
153 * Human-readable description (512 characters or less).
154 */
155 description?: string;
156 /**
157 * User labels. Alchemy ownership labels are merged in automatically.
158 */
159 labels?: Record<string, string>;
160 /**
161 * Custom VM metadata (`startup-script`, `shutdown-script`, …).
162 */
163 metadata?: Record<string, string>;
164 /**
165 * Network tags applied to the TPU VM (firewall source/target tags).
166 */
167 networkTags?: string[];
168 /**
169 * CIDR `/29` the node uses when picking an IP. Immutable.
170 */
171 cidrBlock?: string;
172 /**
173 * Service account the TPU VMs run as. Immutable.
174 */
175 serviceAccount?: ServiceAccount;
176 /**
177 * Single-NIC network configuration. Mutually exclusive with
178 * `networkConfigs`. `enableExternalIps` updates in place; the rest is
179 * immutable.
180 */
181 networkConfig?: NetworkConfig;
182 /**
183 * Multi-NIC network configurations. Mutually exclusive with
184 * `networkConfig`. Immutable.
185 */
186 networkConfigs?: NetworkConfig[];
187 /**
188 * Boot disk encryption. Immutable.
189 */
190 bootDiskConfig?: BootDiskConfig;
191 /**
192 * Additional data disks. Immutable.
193 */
194 dataDisks?: AttachedDisk[];
195 /**
196 * Scheduling (reservation, Spot, preemptible). Immutable.
197 */
198 schedulingConfig?: SchedulingConfig;
199 /**
200 * Shielded VM options. Immutable.
201 */
202 shieldedInstanceConfig?: ShieldedInstanceConfig;
203 };
204
205 export type Node = Resource<
206 "GCP.TPU.Node",
207 NodeProps,
208 {
209 /** Full resource name `projects/{project}/locations/{location}/nodes/{node}`. */
210 name: string;
211 /** Node id (last path segment). */
212 nodeId: string;
213 /** Project id. */
214 project: string;
215 /** Zone id (`us-central1-c`, …). */
216 location: string;
217 /** Server-assigned numeric id. */
218 tpuId: string | undefined;
219 /** Human-readable description. */
220 description: string | undefined;
221 /** User labels (Alchemy ownership labels stripped). */
222 labels: Record<string, string>;
223 /** Custom VM metadata. */
224 metadata: Record<string, string>;
225 /** Network tags. */
226 networkTags: string[];
227 /** Accelerator type (`v2-8`, …). */
228 acceleratorType: string | undefined;
229 /** Accelerator config currently applied. */
230 acceleratorConfig: AcceleratorConfig | undefined;
231 /** Runtime version. */
232 runtimeVersion: string | undefined;
233 /** Server-reported state (`READY`, `CREATING`, …). */
234 state: string | undefined;
235 /** Health (`HEALTHY`, `TIMEOUT`, …). */
236 health: string | undefined;
237 /** Why the node is unhealthy, if populated. */
238 healthDescription: string | undefined;
239 /** CIDR `/29` in use. */
240 cidrBlock: string | undefined;
241 /** Service account. */
242 serviceAccount: ServiceAccount | undefined;
243 /** Single-NIC network configuration. */
244 networkConfig: NetworkConfig | undefined;
245 /** Multi-NIC network configurations. */
246 networkConfigs: NetworkConfig[];
247 /** Worker network endpoints. */
248 networkEndpoints: tpu.NetworkEndpoint[];
249 /** Boot disk configuration. */
250 bootDiskConfig: BootDiskConfig | undefined;
251 /** Attached data disks. */
252 dataDisks: AttachedDisk[];
253 /** Scheduling options. */
254 schedulingConfig: SchedulingConfig | undefined;
255 /** Shielded VM options. */
256 shieldedInstanceConfig: ShieldedInstanceConfig | undefined;
257 /** Whether this node is part of a Multislice group. */
258 multisliceNode: boolean | undefined;
259 /** QueuedResource that requested this node, if any. */
260 queuedResource: string | undefined;
261 /** API version that created the node. */
262 apiVersion: string | undefined;
263 /** Symptoms reported on the node. */
264 symptoms: tpu.Symptom[];
265 /** Upcoming maintenance, if any. */
266 upcomingMaintenance: tpu.UpcomingMaintenance | undefined;
267 /** RFC3339 creation timestamp. */
268 createTime: string | undefined;
269 },
270 never,
271 Providers
272 >;
273
274 /**
275 * A Cloud TPU node (TPU VM).
276 *
277 * Changing `nodeId`, `location`, `runtimeVersion`, `acceleratorType`,
278 * `acceleratorConfig`, `cidrBlock`, `serviceAccount`, scheduling,
279 * boot/data disks, shielded config, or network identity (other than
280 * `enableExternalIps`) replaces the node. Description, labels, metadata,
281 * network tags, and `networkConfig.enableExternalIps` update in place.
282 *
283 * Provisioning typically takes several minutes and requires Cloud TPU
284 * quota in the zone.
285 *
286 * ### Creating a Node
287 * **Example:** Generated name, v2-8
288 * ```typescript
289 * const tpu = yield* GCP.TPU.Node("Trainer", {});
290 * ```
291 *
292 * **Example:** Explicit id, labels, and description
293 * ```typescript
294 * const tpu = yield* GCP.TPU.Node("Trainer", {
295 * nodeId: "app-tpu",
296 * location: "us-central1-c",
297 * acceleratorType: "v2-8",
298 * runtimeVersion: "tpu-ubuntu2204-base",
299 * description: "training node",
300 * labels: { env: "prod" },
301 * });
302 * ```
303 *
304 * ### Spot scheduling
305 * **Example:** Preemptible Spot TPU
306 * ```typescript
307 * const tpu = yield* GCP.TPU.Node("Trainer", {
308 * acceleratorType: "v2-8",
309 * schedulingConfig: { spot: true, preemptible: true },
310 * });
311 * ```
312 *
313 * @resource
314 * @category TPU
315 */
316 export const Node = Resource<Node>("GCP.TPU.Node");
317
318 const resourceName = (project: string, location: string, nodeId: string) =>
319 `projects/${project}/locations/${location}/nodes/${nodeId}`;
320
321 const networkOf = (
322 config: tpu.NetworkConfig | NetworkConfig | undefined,
323 ): NetworkConfig | undefined => {
324 if (config === undefined) return undefined;
325 return {
326 enableExternalIps: config.enableExternalIps,
327 subnetwork: config.subnetwork,
328 network: config.network,
329 canIpForward: config.canIpForward,
330 queueCount: config.queueCount,
331 };
332 };
333
334 const networksOf = (
335 configs: ReadonlyArray<tpu.NetworkConfig | NetworkConfig> | undefined,
336 ): NetworkConfig[] => (configs ?? []).map((config) => networkOf(config)!);
337
338 const networkIdentityKey = (config: NetworkConfig | undefined) =>
339 JSON.stringify({
340 network: lastSegment(config?.network ?? DEFAULT_NETWORK),
341 subnetwork: lastSegment(config?.subnetwork ?? ""),
342 canIpForward: config?.canIpForward === true,
343 queueCount: config?.queueCount ?? "",
344 });
345
346 const networksIdentityKey = (configs: readonly NetworkConfig[] | undefined) =>
347 JSON.stringify((configs ?? []).map(networkIdentityKey));
348
349 const acceleratorOf = (
350 config: tpu.AcceleratorConfig | AcceleratorConfig | undefined,
351 ): AcceleratorConfig | undefined => {
352 if (config === undefined) return undefined;
353 if (config.type === undefined && config.topology === undefined) {
354 return undefined;
355 }
356 return { type: config.type, topology: config.topology };
357 };
358
359 const acceleratorKey = (type: string | undefined, config: AcceleratorConfig | undefined) =>
360 JSON.stringify({
361 type: (type ?? "").toLowerCase(),
362 configType: (config?.type ?? "").toUpperCase(),
363 topology: config?.topology ?? "",
364 });
365
366 const serviceAccountOf = (
367 account: tpu.ServiceAccount | ServiceAccount | undefined,
368 ): ServiceAccount | undefined => {
369 if (account === undefined) return undefined;
370 return {
371 email: account.email,
372 scope: account.scope ? [...account.scope] : undefined,
373 };
374 };
375
376 const serviceAccountKey = (account: tpu.ServiceAccount | ServiceAccount | undefined) =>
377 JSON.stringify({
378 email: serviceAccountOf(account)?.email ?? "",
379 scope: [...(serviceAccountOf(account)?.scope ?? [])].sort(),
380 });
381
382 const schedulingOf = (
383 config: tpu.SchedulingConfig | SchedulingConfig | undefined,
384 ): SchedulingConfig | undefined => {
385 if (config === undefined) return undefined;
386 return {
387 reserved: config.reserved,
388 spot: config.spot,
389 preemptible: config.preemptible,
390 };
391 };
392
393 const schedulingKey = (config: tpu.SchedulingConfig | SchedulingConfig | undefined) =>
394 JSON.stringify({
395 reserved: schedulingOf(config)?.reserved === true,
396 spot: schedulingOf(config)?.spot === true,
397 preemptible: schedulingOf(config)?.preemptible === true,
398 });
399
400 const diskOf = (disk: tpu.AttachedDisk | AttachedDisk): AttachedDisk => ({
401 sourceDisk: disk.sourceDisk,
402 mode: disk.mode,
403 });
404
405 const disksKey = (disks: ReadonlyArray<tpu.AttachedDisk | AttachedDisk> | undefined) =>
406 JSON.stringify(
407 (disks ?? []).map((disk) => ({
408 sourceDisk: disk.sourceDisk ?? "",
409 mode: (disk.mode ?? "READ_WRITE").toUpperCase(),
410 })),
411 );
412
413 const bootOf = (
414 config: tpu.BootDiskConfig | BootDiskConfig | undefined,
415 ): BootDiskConfig | undefined => {
416 if (config === undefined) return undefined;
417 const key = config.customerEncryptionKey?.kmsKeyName;
418 if (key === undefined) return undefined;
419 return { customerEncryptionKey: { kmsKeyName: key } };
420 };
421
422 const bootKey = (config: tpu.BootDiskConfig | BootDiskConfig | undefined) =>
423 bootOf(config)?.customerEncryptionKey?.kmsKeyName ?? "";
424
425 const shieldedOf = (
426 config: tpu.ShieldedInstanceConfig | ShieldedInstanceConfig | undefined,
427 ): ShieldedInstanceConfig | undefined => {
428 if (config === undefined) return undefined;
429 return { enableSecureBoot: config.enableSecureBoot };
430 };
431
432 const shieldedKey = (config: tpu.ShieldedInstanceConfig | ShieldedInstanceConfig | undefined) =>
433 JSON.stringify(shieldedOf(config)?.enableSecureBoot === true);
434
435 const runtimeOf = (version: string | undefined) => version ?? DEFAULT_RUNTIME;
436
437 const desiredAcceleratorType = (news: NodeProps) =>
438 news.acceleratorConfig === undefined
439 ? (news.acceleratorType ?? DEFAULT_ACCELERATOR)
440 : news.acceleratorType;
441
442 export const toNodeBody = (
443 news: NodeProps,
444 desiredLabels: Record<string, string>,
445 options?: { description?: string },
446 ): tpu.Node => {
447 const runtimeVersion = runtimeOf(news.runtimeVersion);
448 const acceleratorType = desiredAcceleratorType(news);
449 const networkConfigs = news.networkConfigs;
450 const networkConfig =
451 networkConfigs === undefined
452 ? (news.networkConfig ?? {
453 enableExternalIps: true,
454 network: DEFAULT_NETWORK,
455 })
456 : undefined;
457 return {
458 description: options?.description ?? news.description,
459 labels: desiredLabels,
460 metadata: news.metadata,
461 tags: news.networkTags,
462 runtimeVersion,
463 acceleratorType,
464 acceleratorConfig: news.acceleratorConfig,
465 cidrBlock: news.cidrBlock,
466 serviceAccount: news.serviceAccount,
467 networkConfig,
468 networkConfigs,
469 bootDiskConfig: news.bootDiskConfig,
470 dataDisks: news.dataDisks,
471 schedulingConfig: news.schedulingConfig,
472 shieldedInstanceConfig: news.shieldedInstanceConfig,
473 };
474 };
475
476 const toAttrs = (node: tpu.Node, project: string) => {
477 const name = node.name ?? "";
478 const parsed = parseName(name, "nodes");
479 return {
480 name,
481 nodeId: parsed.id,
482 project: parsed.project || project,
483 location: parsed.location,
484 tpuId: node.id,
485 description: node.description,
486 labels: userLabels(node.labels),
487 metadata: stringMapOf(node.metadata),
488 networkTags: stringsOf(node.tags),
489 acceleratorType: node.acceleratorType,
490 acceleratorConfig: acceleratorOf(node.acceleratorConfig),
491 runtimeVersion: node.runtimeVersion,
492 state: node.state,
493 health: node.health,
494 healthDescription: node.healthDescription,
495 cidrBlock: node.cidrBlock,
496 serviceAccount: serviceAccountOf(node.serviceAccount),
497 networkConfig: networkOf(node.networkConfig),
498 networkConfigs: networksOf(node.networkConfigs),
499 networkEndpoints: node.networkEndpoints ?? [],
500 bootDiskConfig: bootOf(node.bootDiskConfig),
501 dataDisks: (node.dataDisks ?? []).map(diskOf),
502 schedulingConfig: schedulingOf(node.schedulingConfig),
503 shieldedInstanceConfig: shieldedOf(node.shieldedInstanceConfig),
504 multisliceNode: node.multisliceNode,
505 queuedResource: node.queuedResource,
506 apiVersion: node.apiVersion,
507 symptoms: node.symptoms ?? [],
508 upcomingMaintenance: node.upcomingMaintenance,
509 createTime: node.createTime,
510 };
511 };
512
513 const isPlaceholder = (node: tpu.Node) => {
514 const name = node.name ?? "";
515 return name.length === 0 || name.endsWith("/nodes/-") || name.endsWith("/nodes/");
516 };
517
518 const getByName = (name: string) =>
519 tpu.getProjectsLocationsNodes({ name }).pipe(Effect.catchTag("NotFound", () => Effect.undefined));
520
521 export const NodeProvider = () =>
522 Provider.succeed(Node, {
523 stables: ["name", "nodeId", "project", "location", "tpuId", "createTime"],
524
525 diff: Effect.fn(function* ({ news, olds, output }) {
526 if (!isResolved(news)) return undefined;
527
528 const previousId = olds?.nodeId ?? output?.nodeId;
529 const nextId = news.nodeId ?? previousId;
530 const previousLocation = normalizeLocation(olds?.location ?? output?.location);
531 const nextLocation = normalizeLocation(news.location ?? output?.location);
532 const previousRuntime = runtimeOf(olds?.runtimeVersion ?? output?.runtimeVersion);
533 const nextRuntime = runtimeOf(
534 news.runtimeVersion ?? olds?.runtimeVersion ?? output?.runtimeVersion,
535 );
536 const previousAccelerator = acceleratorKey(
537 olds?.acceleratorType ?? output?.acceleratorType,
538 acceleratorOf(olds?.acceleratorConfig ?? output?.acceleratorConfig),
539 );
540 const nextAccelerator = acceleratorKey(
541 news.acceleratorType ?? olds?.acceleratorType ?? output?.acceleratorType,
542 acceleratorOf(
543 news.acceleratorConfig ?? olds?.acceleratorConfig ?? output?.acceleratorConfig,
544 ),
545 );
546 const previousCidr = olds?.cidrBlock ?? output?.cidrBlock ?? "";
547 const nextCidr = news.cidrBlock ?? previousCidr;
548 const previousAccount = serviceAccountKey(olds?.serviceAccount ?? output?.serviceAccount);
549 const nextAccount = serviceAccountKey(
550 news.serviceAccount ?? olds?.serviceAccount ?? output?.serviceAccount,
551 );
552 const previousScheduling = schedulingKey(olds?.schedulingConfig ?? output?.schedulingConfig);
553 const nextScheduling = schedulingKey(
554 news.schedulingConfig ?? olds?.schedulingConfig ?? output?.schedulingConfig,
555 );
556 const previousBoot = bootKey(olds?.bootDiskConfig ?? output?.bootDiskConfig);
557 const nextBoot = bootKey(
558 news.bootDiskConfig ?? olds?.bootDiskConfig ?? output?.bootDiskConfig,
559 );
560 const previousDisks = disksKey(olds?.dataDisks ?? output?.dataDisks);
561 const nextDisks = disksKey(news.dataDisks ?? olds?.dataDisks ?? output?.dataDisks);
562 const previousShielded = shieldedKey(
563 olds?.shieldedInstanceConfig ?? output?.shieldedInstanceConfig,
564 );
565 const nextShielded = shieldedKey(
566 news.shieldedInstanceConfig ??
567 olds?.shieldedInstanceConfig ??
568 output?.shieldedInstanceConfig,
569 );
570 const previousMulti = networksIdentityKey(olds?.networkConfigs ?? output?.networkConfigs);
571 const nextMulti = networksIdentityKey(
572 news.networkConfigs ?? olds?.networkConfigs ?? output?.networkConfigs,
573 );
574 const previousNet = networkIdentityKey(olds?.networkConfig ?? output?.networkConfig);
575 const nextNet = networkIdentityKey(
576 news.networkConfig ?? olds?.networkConfig ?? output?.networkConfig,
577 );
578 const usedMulti =
579 (news.networkConfigs ?? olds?.networkConfigs ?? output?.networkConfigs)?.length ?? 0;
580
581 return replaceOnIdentity({
582 previousId,
583 nextId,
584 previousLocation,
585 nextLocation,
586 extra:
587 previousRuntime !== nextRuntime ||
588 previousAccelerator !== nextAccelerator ||
589 previousCidr !== nextCidr ||
590 previousAccount !== nextAccount ||
591 previousScheduling !== nextScheduling ||
592 previousBoot !== nextBoot ||
593 previousDisks !== nextDisks ||
594 previousShielded !== nextShielded ||
595 previousMulti !== nextMulti ||
596 (usedMulti === 0 && previousNet !== nextNet),
597 });
598 }),
599
600 read: Effect.fn(function* ({ id, olds, output }) {
601 const env = yield* GcpEnvironment.current;
602 const nodeId = yield* toPhysicalId(id, olds?.nodeId, output?.nodeId);
603 const location = normalizeLocation(olds?.location ?? output?.location);
604 const name = output?.name ?? resourceName(env.project, location, nodeId);
605 const existing = yield* getByName(name);
606 if (existing === undefined) return undefined;
607 const attrs = toAttrs(existing, env.project);
608 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
609 }),
610
611 list: () =>
612 Effect.gen(function* () {
613 const env = yield* GcpEnvironment.current;
614 const nodes = yield* listLabeledPages(
615 tpu.listProjectsLocationsNodes.pages({
616 parent: `projects/${env.project}/locations/-`,
617 pageSize: 1000,
618 }),
619 (page) => page.nodes,
620 (node) => node.labels,
621 );
622 return nodes
623 .filter((node) => !isPlaceholder(node))
624 .map((node) => toAttrs(node, env.project));
625 }),
626
627 reconcile: Effect.fn(function* ({ id, news, output }) {
628 const env = yield* GcpEnvironment.current;
629 const nodeId = yield* toPhysicalId(id, news.nodeId, output?.nodeId);
630 const location = normalizeLocation(news.location ?? output?.location);
631 const name = resourceName(env.project, location, nodeId);
632 const desiredLabels = {
633 ...toLabels(news.labels),
634 ...(yield* createInternalLabels(id)),
635 };
636
637 let current = yield* getByName(output?.name ?? name);
638
639 if (current === undefined) {
640 const created = yield* tpu
641 .createProjectsLocationsNodes({
642 parent: `projects/${env.project}/locations/${location}`,
643 nodeId,
644 body: toNodeBody(news, desiredLabels),
645 })
646 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
647 if (created !== undefined) {
648 yield* waitForOperation(created);
649 }
650 current = yield* waitUntilExists(getByName(name), name);
651 }
652
653 if (current === undefined) {
654 return yield* new ResourceNotResolved({ resourceName: name });
655 }
656
657 const state = (current.state ?? "").toUpperCase();
658 if (state !== "READY" && state !== "STOPPED" && state.length > 0) {
659 current = yield* waitUntilReady(
660 getByName(name),
661 name,
662 (node) => node.state,
663 (node) => node.healthDescription,
664 );
665 }
666
667 if (current === undefined) {
668 return yield* new ResourceNotResolved({ resourceName: name });
669 }
670
671 const observedLabels = tagRecord(current.labels);
672 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
673 const labelsChanged = upsert.length > 0 || removed.length > 0;
674 const descriptionChanged = (current.description ?? "") !== (news.description ?? "");
675 const metadataChanged =
676 news.metadata !== undefined && mapKey(current.metadata) !== mapKey(news.metadata);
677 const tagsChanged =
678 news.networkTags !== undefined && stringsKey(current.tags) !== stringsKey(news.networkTags);
679 const desiredExternal = news.networkConfig?.enableExternalIps !== false;
680 const observedExternal = current.networkConfig?.enableExternalIps !== false;
681 const usingMulti = (news.networkConfigs ?? current.networkConfigs ?? []).length > 0;
682 const externalChanged =
683 !usingMulti && news.networkConfig !== undefined && desiredExternal !== observedExternal;
684
685 if (
686 labelsChanged ||
687 descriptionChanged ||
688 metadataChanged ||
689 tagsChanged ||
690 externalChanged
691 ) {
692 const updateMask = fieldMask([
693 labelsChanged && "labels",
694 descriptionChanged && "description",
695 metadataChanged && "metadata",
696 tagsChanged && "tags",
697 externalChanged && "network_config.enable_external_ips",
698 ]);
699 const patched = yield* tpu.patchProjectsLocationsNodes({
700 name,
701 updateMask,
702 body: {
703 name,
704 labels: desiredLabels,
705 description: news.description,
706 metadata: news.metadata ?? stringMapOf(current.metadata),
707 tags: news.networkTags ?? stringsOf(current.tags),
708 networkConfig: externalChanged
709 ? {
710 ...networkOf(current.networkConfig),
711 enableExternalIps: desiredExternal,
712 }
713 : undefined,
714 },
715 });
716 yield* waitForOperation(patched);
717 current = yield* waitUntilExists(getByName(name), name);
718 }
719
720 if (current === undefined) {
721 return yield* new ResourceNotResolved({ resourceName: name });
722 }
723
724 return toAttrs(current, env.project);
725 }),
726
727 delete: Effect.fn(function* ({ output }) {
728 const operation = yield* tpu.deleteProjectsLocationsNodes({ name: output.name }).pipe(
729 Effect.catchTag("NotFound", () => Effect.undefined),
730 Effect.retry({
731 while: (error) => error._tag === "Conflict",
732 times: 8,
733 schedule: Schedule.spaced("5 seconds"),
734 }),
735 );
736 if (operation !== undefined) {
737 yield* waitForOperation(operation, { notFoundOk: true });
738 }
739 yield* waitUntilGone(getByName(output.name), output.name);
740 }),
741 });