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

main
ts 691 lines 23.5 KB
Raw
1 import * as compute from "@distilled.cloud/gcp/compute_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import { GcpEnvironment } from "../Environment.ts";
12 import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
13 import type { Providers } from "../Providers.ts";
14 import { waitZoneOperation } from "./operations.ts";
15
16 export type InstanceGroupManagerNamedPort = {
17 /** RFC1035 name for this port mapping (e.g. `"http"`). */
18 name: string;
19 /** TCP port number (`1`–`65535`). */
20 port: number;
21 };
22
23 export type InstanceGroupManagerAutoHealingPolicy = {
24 /**
25 * Health check URL or name. Names expand to
26 * `projects/{project}/global/healthChecks/{name}`.
27 */
28 healthCheck: string;
29 /**
30 * Seconds to ignore failed health checks after a VM is created
31 * (`0`–`3600`).
32 * @default 0
33 */
34 initialDelaySec?: number;
35 };
36
37 export type InstanceGroupManagerUpdatePolicy = compute.InstanceGroupManagerUpdatePolicy;
38
39 export type InstanceGroupManagerProps = {
40 /**
41 * Name of the managed instance group. Must be 1–63 characters and comply
42 * with RFC1035. If omitted, a unique name is generated from the stack,
43 * stage, and logical id. Changing this replaces the group.
44 */
45 managerName?: string;
46 /**
47 * Zone of the group (e.g. `"us-central1-a"`). Immutable — changing it
48 * replaces the group.
49 * @default "us-central1-a"
50 */
51 zone?: string;
52 /**
53 * Instance template URL or name used to create VMs. Names expand to
54 * `projects/{project}/global/instanceTemplates/{name}`.
55 */
56 instanceTemplate: string;
57 /**
58 * Target number of running VMs. `0` creates an empty group.
59 * @default 0
60 */
61 targetSize?: number;
62 /**
63 * Prefix for VM names (RFC1035, max 58 characters). Defaults to the
64 * manager name. Immutable — changing it replaces the group.
65 */
66 baseInstanceName?: string;
67 /**
68 * Optional description. Managed instance groups have no labels API, so
69 * Alchemy stamps ownership (`alchemy-stack` / `alchemy-stage` /
70 * `alchemy-id`) into this field for `list` / nuke.
71 */
72 description?: string;
73 /**
74 * Named ports applied to the complementary instance group (the manager
75 * field is output-only; updates use `instanceGroups.setNamedPorts`).
76 */
77 namedPorts?: InstanceGroupManagerNamedPort[];
78 /**
79 * Autohealing policy (one health check). Omit to leave the observed
80 * policy unchanged.
81 */
82 autoHealingPolicies?: InstanceGroupManagerAutoHealingPolicy[];
83 /**
84 * Rolling-update policy. Omit to leave the observed policy unchanged.
85 */
86 updatePolicy?: InstanceGroupManagerUpdatePolicy;
87 /**
88 * Target-pool URLs or names that receive the group's VMs. Omit to leave
89 * observed pools unchanged.
90 */
91 targetPools?: string[];
92 /**
93 * Repair / failure policy for managed VMs (e.g.
94 * `{ defaultActionOnFailure: "DO_NOTHING" }`, which resize requests
95 * require). Omit to leave the observed policy unchanged.
96 */
97 instanceLifecyclePolicy?: compute.InstanceGroupManagerInstanceLifecyclePolicy;
98 };
99
100 export type InstanceGroupManager = Resource<
101 "GCP.Compute.InstanceGroupManager",
102 InstanceGroupManagerProps,
103 {
104 /** Managed instance group name. */
105 managerName: string;
106 /** Zone (short name, e.g. `"us-central1-a"`). */
107 zone: string;
108 /** Project id. */
109 project: string;
110 /** Instance template URL. */
111 instanceTemplate: string | undefined;
112 /** Target number of running VMs. */
113 targetSize: number;
114 /** Prefix used for VM names. */
115 baseInstanceName: string | undefined;
116 /** User-facing description (ownership marker stripped). */
117 description: string | undefined;
118 /** Named ports currently configured on the group. */
119 namedPorts: InstanceGroupManagerNamedPort[];
120 /** Complementary unmanaged instance group URL. */
121 instanceGroup: string | undefined;
122 /** Whether the group is currently stable. */
123 isStable: boolean | undefined;
124 /** Server-generated resource URL. */
125 selfLink: string | undefined;
126 /** Server-generated numeric id. */
127 id: string | undefined;
128 /** RFC3339 creation timestamp. */
129 creationTimestamp: string | undefined;
130 },
131 never,
132 Providers
133 >;
134
135 /**
136 * A zonal Compute Engine managed instance group (MIG).
137 *
138 * The group creates VMs from an instance template and maintains
139 * `targetSize`. Alchemy records ownership in the description so
140 * `list` / `pnpm nuke:gcp` can find groups (MIGs have no labels API).
141 * Changing `managerName`, `zone`, or `baseInstanceName` replaces the
142 * group.
143 *
144 * ### Creating a Managed Instance Group
145 * **Example:** Generated name, empty group
146 * ```typescript
147 * const template = yield* GCP.Compute.InstanceTemplate("web", {});
148 * const group = yield* GCP.Compute.InstanceGroupManager("web", {
149 * instanceTemplate: template.templateName,
150 * });
151 * ```
152 *
153 * **Example:** Named ports and target size
154 * ```typescript
155 * const template = yield* GCP.Compute.InstanceTemplate("web", {});
156 * const group = yield* GCP.Compute.InstanceGroupManager("web", {
157 * managerName: "web-mig",
158 * zone: "us-central1-a",
159 * instanceTemplate: template.templateName,
160 * targetSize: 2,
161 * namedPorts: [{ name: "http", port: 80 }],
162 * });
163 * ```
164 *
165 * @resource
166 * @category Compute
167 */
168 export const InstanceGroupManager = Resource<InstanceGroupManager>(
169 "GCP.Compute.InstanceGroupManager",
170 );
171
172 export class InstanceGroupManagerNotResolved extends Data.TaggedError(
173 "GCP.Compute.InstanceGroupManagerNotResolved",
174 )<{
175 managerName: string;
176 zone: string;
177 }> {}
178
179 export class InstanceGroupManagerStillExists extends Data.TaggedError(
180 "GCP.Compute.InstanceGroupManagerStillExists",
181 )<{
182 managerName: string;
183 zone: string;
184 }> {}
185
186 const DEFAULT_ZONE = "us-central1-a";
187 const DEFAULT_TARGET_SIZE = 0;
188 const MAX_NAME_LENGTH = 63;
189 const MAX_BASE_NAME_LENGTH = 58;
190
191 const lastSegment = (value: string | undefined) => {
192 if (value === undefined || value.length === 0) return "";
193 const parts = value.split("/").filter((part) => part.length > 0);
194 return parts[parts.length - 1] ?? value;
195 };
196
197 const rfc1035Name = (name: string, maxLength = MAX_NAME_LENGTH) => {
198 let next = name
199 .toLowerCase()
200 .replace(/[^a-z0-9-]/g, "-")
201 .replace(/-+/g, "-")
202 .replace(/^-+|-+$/g, "");
203 if (!/^[a-z]/.test(next)) {
204 next = `m${next}`;
205 }
206 next = next.slice(0, maxLength).replace(/-+$/g, "");
207 return next.length > 0 ? next : "mig";
208 };
209
210 const toName = (id: string, name: string | undefined, existing?: string) =>
211 Effect.gen(function* () {
212 return rfc1035Name(
213 name ??
214 existing ??
215 (yield* createPhysicalName({
216 id,
217 maxLength: MAX_NAME_LENGTH,
218 lowercase: true,
219 })),
220 );
221 });
222
223 const toBaseInstanceName = (managerName: string, explicit?: string) =>
224 rfc1035Name(explicit ?? managerName, MAX_BASE_NAME_LENGTH);
225
226 const encodeDescription = (user: string | undefined, labels: Record<string, string>) => {
227 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
228 const trimmed = user?.trim();
229 return trimmed && trimmed.length > 0 ? `${marker}\n${trimmed}` : marker;
230 };
231
232 const parseDescription = (description: string | undefined) => {
233 if (!description?.startsWith("[alchemy ")) {
234 return { user: description, labels: {} as Record<string, string> };
235 }
236 const end = description.indexOf("]");
237 if (end < 0) {
238 return { user: description, labels: {} as Record<string, string> };
239 }
240 const labels: Record<string, string> = {};
241 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
242 const eq = part.indexOf("=");
243 if (eq > 0) {
244 labels[part.slice(0, eq)] = part.slice(eq + 1);
245 }
246 }
247 const rest = description
248 .slice(end + 1)
249 .replace(/^\n/, "")
250 .trim();
251 return {
252 user: rest.length > 0 ? rest : undefined,
253 labels,
254 };
255 };
256
257 const hasOwnershipMarker = (description: string | undefined) =>
258 Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-"));
259
260 const toTemplateUrl = (project: string, template: string) =>
261 template.includes("/") ? template : `projects/${project}/global/instanceTemplates/${template}`;
262
263 const toHealthCheckUrl = (project: string, healthCheck: string) =>
264 healthCheck.includes("/")
265 ? healthCheck
266 : `projects/${project}/global/healthChecks/${healthCheck}`;
267
268 const toTargetPoolUrl = (project: string, zone: string, pool: string) => {
269 if (pool.includes("/")) return pool;
270 const region = zone.slice(0, zone.lastIndexOf("-"));
271 return `projects/${project}/regions/${region}/targetPools/${pool}`;
272 };
273
274 const canonPorts = (
275 ports: readonly InstanceGroupManagerNamedPort[] | undefined,
276 ): InstanceGroupManagerNamedPort[] =>
277 [...(ports ?? [])]
278 .map((port) => ({ name: port.name, port: port.port }))
279 .sort((a, b) => a.name.localeCompare(b.name) || a.port - b.port);
280
281 const samePorts = (
282 left: readonly InstanceGroupManagerNamedPort[] | undefined,
283 right: readonly InstanceGroupManagerNamedPort[] | undefined,
284 ) => JSON.stringify(canonPorts(left)) === JSON.stringify(canonPorts(right));
285
286 const fromApiPorts = (
287 ports: readonly compute.NamedPort[] | undefined,
288 ): InstanceGroupManagerNamedPort[] =>
289 canonPorts(
290 (ports ?? [])
291 .filter(
292 (port): port is { name: string; port: number } =>
293 typeof port.name === "string" && typeof port.port === "number",
294 )
295 .map((port) => ({ name: port.name, port: port.port })),
296 );
297
298 const sameSegments = (
299 left: readonly string[] | undefined,
300 right: readonly string[] | undefined,
301 ) => {
302 const a = [...(left ?? [])].map(lastSegment).sort();
303 const b = [...(right ?? [])].map(lastSegment).sort();
304 return a.length === b.length && a.every((value, index) => value === b[index]);
305 };
306
307 const toHealing = (
308 project: string,
309 policies: readonly InstanceGroupManagerAutoHealingPolicy[],
310 ): compute.InstanceGroupManagerAutoHealingPolicy[] =>
311 policies.map((policy) => ({
312 healthCheck: toHealthCheckUrl(project, policy.healthCheck),
313 initialDelaySec: policy.initialDelaySec,
314 }));
315
316 const fromApiHealing = (
317 policies: readonly compute.InstanceGroupManagerAutoHealingPolicy[] | undefined,
318 ): InstanceGroupManagerAutoHealingPolicy[] =>
319 (policies ?? [])
320 .filter(
321 (policy): policy is { healthCheck: string } & typeof policy =>
322 typeof policy.healthCheck === "string",
323 )
324 .map((policy) => ({
325 healthCheck: policy.healthCheck,
326 initialDelaySec: policy.initialDelaySec,
327 }));
328
329 const sameHealing = (
330 left: readonly { healthCheck?: string; initialDelaySec?: number }[] | undefined,
331 right: readonly { healthCheck?: string; initialDelaySec?: number }[] | undefined,
332 ) => {
333 const canon = (policies: readonly { healthCheck?: string; initialDelaySec?: number }[]) =>
334 [...policies]
335 .map((policy) => ({
336 healthCheck: lastSegment(policy.healthCheck ?? ""),
337 initialDelaySec: policy.initialDelaySec ?? 0,
338 }))
339 .sort((a, b) => a.healthCheck.localeCompare(b.healthCheck));
340 return JSON.stringify(canon(left ?? [])) === JSON.stringify(canon(right ?? []));
341 };
342
343 const sameUpdatePolicy = (
344 left: compute.InstanceGroupManagerUpdatePolicy | undefined,
345 right: compute.InstanceGroupManagerUpdatePolicy | undefined,
346 ) => JSON.stringify(left ?? {}) === JSON.stringify(right ?? {});
347
348 const toAttrs = (manager: compute.InstanceGroupManager, project: string) => {
349 const { user } = parseDescription(manager.description);
350 return {
351 managerName: manager.name ?? lastSegment(manager.selfLink),
352 zone: lastSegment(manager.zone) || DEFAULT_ZONE,
353 project,
354 instanceTemplate: manager.instanceTemplate,
355 targetSize: manager.targetSize ?? DEFAULT_TARGET_SIZE,
356 baseInstanceName: manager.baseInstanceName,
357 description: user,
358 namedPorts: fromApiPorts(manager.namedPorts),
359 instanceGroup: manager.instanceGroup,
360 isStable: manager.status?.isStable,
361 selfLink: manager.selfLink,
362 id: manager.id,
363 creationTimestamp: manager.creationTimestamp,
364 };
365 };
366
367 const getByName = (project: string, zone: string, instanceGroupManager: string) =>
368 compute
369 .getInstanceGroupManagers({ project, zone, instanceGroupManager })
370 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
371
372 const waitGone = (project: string, zone: string, managerName: string) =>
373 getByName(project, zone, managerName).pipe(
374 Effect.flatMap((manager) =>
375 manager === undefined
376 ? Effect.void
377 : Effect.fail(new InstanceGroupManagerStillExists({ managerName, zone })),
378 ),
379 Effect.retry({
380 while: (error) => error._tag === "GCP.Compute.InstanceGroupManagerStillExists",
381 times: 10,
382 schedule: Schedule.spaced("2 seconds"),
383 }),
384 );
385
386 const waitPresent = (project: string, zone: string, managerName: string) =>
387 getByName(project, zone, managerName).pipe(
388 Effect.flatMap((manager) =>
389 manager === undefined
390 ? Effect.fail(new InstanceGroupManagerNotResolved({ managerName, zone }))
391 : Effect.succeed(manager),
392 ),
393 Effect.retry({
394 while: (error) => error._tag === "GCP.Compute.InstanceGroupManagerNotResolved",
395 times: 8,
396 schedule: Schedule.exponential("250 millis"),
397 }),
398 Effect.catchTag("GCP.Compute.InstanceGroupManagerNotResolved", () => Effect.undefined),
399 );
400
401 const runOp = <E, R>(
402 project: string,
403 zone: string,
404 start: Effect.Effect<compute.Operation, E, R>,
405 ) =>
406 start.pipe(
407 Effect.flatMap((operation) =>
408 waitZoneOperation(project, zone, operation, {
409 ignore: ["RESOURCE_ALREADY_EXISTS"],
410 }),
411 ),
412 );
413
414 const syncNamedPorts = (
415 project: string,
416 zone: string,
417 instanceGroupUrl: string | undefined,
418 namedPorts: InstanceGroupManagerNamedPort[],
419 ) =>
420 Effect.gen(function* () {
421 const instanceGroup = lastSegment(instanceGroupUrl);
422 if (instanceGroup.length === 0) return;
423 const group = yield* compute
424 .getInstanceGroups({ project, zone, instanceGroup })
425 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
426 if (group === undefined) return;
427 if (samePorts(fromApiPorts(group.namedPorts), namedPorts)) return;
428 yield* runOp(
429 project,
430 zone,
431 compute.setNamedPortsInstanceGroups({
432 project,
433 zone,
434 instanceGroup,
435 body: {
436 namedPorts,
437 fingerprint: group.fingerprint,
438 },
439 }),
440 ).pipe(
441 Effect.retry({
442 while: (error) => error._tag === "Conflict",
443 times: 5,
444 schedule: Schedule.exponential("250 millis"),
445 }),
446 );
447 });
448
449 export const InstanceGroupManagerProvider = () =>
450 Provider.succeed(InstanceGroupManager, {
451 stables: [
452 "managerName",
453 "zone",
454 "project",
455 "baseInstanceName",
456 "id",
457 "selfLink",
458 "instanceGroup",
459 "creationTimestamp",
460 ],
461
462 diff: Effect.fn(function* ({ news, olds, output }) {
463 if (!isResolved(news)) return undefined;
464 const previousName = olds?.managerName ?? output?.managerName;
465 const nextName = news.managerName ?? previousName;
466 const previousZone = lastSegment(olds?.zone ?? output?.zone);
467 const nextZone = lastSegment(news.zone ?? DEFAULT_ZONE);
468 const previousBase = olds?.baseInstanceName ?? output?.baseInstanceName;
469 const nextBase =
470 news.baseInstanceName !== undefined
471 ? toBaseInstanceName(nextName ?? news.baseInstanceName, news.baseInstanceName)
472 : previousBase;
473 const nameChanged =
474 previousName !== undefined && nextName !== undefined && previousName !== nextName;
475 const zoneChanged = previousZone.length > 0 && previousZone !== nextZone;
476 const baseChanged =
477 previousBase !== undefined &&
478 nextBase !== undefined &&
479 lastSegment(previousBase) !== lastSegment(nextBase);
480 if (!nameChanged && !zoneChanged && !baseChanged) {
481 return undefined;
482 }
483 return {
484 action: "replace" as const,
485 deleteFirst:
486 previousName !== undefined &&
487 nextName !== undefined &&
488 previousName === nextName &&
489 previousZone === nextZone,
490 };
491 }),
492
493 read: Effect.fn(function* ({ id, olds, output }) {
494 const env = yield* GcpEnvironment.current;
495 const managerName = yield* toName(id, olds?.managerName, output?.managerName);
496 const zone = lastSegment(olds?.zone ?? output?.zone ?? DEFAULT_ZONE);
497 const existing = yield* getByName(env.project, zone, managerName);
498 if (existing === undefined) return undefined;
499 const attrs = toAttrs(existing, env.project);
500 const { labels } = parseDescription(existing.description);
501 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
502 }),
503
504 list: () =>
505 Effect.gen(function* () {
506 const env = yield* GcpEnvironment.current;
507 const pages = yield* compute.aggregatedListInstanceGroupManagers
508 .pages({
509 project: env.project,
510 maxResults: 500,
511 returnPartialSuccess: true,
512 })
513 .pipe(Stream.runCollect);
514 return Array.from(pages).flatMap((page) =>
515 Object.entries(page.items ?? {}).flatMap(([scope, scoped]) => {
516 if (!scope.startsWith("zones/")) return [];
517 return (scoped?.instanceGroupManagers ?? [])
518 .filter((manager) => hasOwnershipMarker(manager.description))
519 .map((manager) => toAttrs(manager, env.project));
520 }),
521 );
522 }),
523
524 reconcile: Effect.fn(function* ({ id, news, output }) {
525 const env = yield* GcpEnvironment.current;
526 const managerName = yield* toName(id, news.managerName, output?.managerName);
527 const zone = lastSegment(news.zone ?? output?.zone ?? DEFAULT_ZONE);
528 const instanceTemplate = toTemplateUrl(env.project, news.instanceTemplate);
529 const targetSize = news.targetSize ?? DEFAULT_TARGET_SIZE;
530 const baseInstanceName = toBaseInstanceName(
531 managerName,
532 news.baseInstanceName ?? output?.baseInstanceName,
533 );
534 const namedPorts = canonPorts(news.namedPorts);
535 const desiredLabels = yield* createInternalLabels(id);
536 const description = encodeDescription(news.description, desiredLabels);
537
538 let current = yield* getByName(env.project, zone, managerName);
539
540 if (current === undefined) {
541 yield* compute
542 .insertInstanceGroupManagers({
543 project: env.project,
544 zone,
545 body: {
546 name: managerName,
547 description,
548 instanceTemplate,
549 baseInstanceName,
550 targetSize,
551 namedPorts: namedPorts.length > 0 ? namedPorts : undefined,
552 autoHealingPolicies:
553 news.autoHealingPolicies !== undefined
554 ? toHealing(env.project, news.autoHealingPolicies)
555 : undefined,
556 updatePolicy: news.updatePolicy,
557 targetPools:
558 news.targetPools !== undefined
559 ? news.targetPools.map((pool) => toTargetPoolUrl(env.project, zone, pool))
560 : undefined,
561 instanceLifecyclePolicy: news.instanceLifecyclePolicy,
562 },
563 })
564 .pipe(
565 Effect.catchTag("Conflict", () => Effect.undefined),
566 Effect.flatMap((operation) =>
567 operation === undefined
568 ? Effect.void
569 : waitZoneOperation(env.project, zone, operation, {
570 ignore: ["RESOURCE_ALREADY_EXISTS"],
571 }).pipe(Effect.asVoid),
572 ),
573 );
574 current = yield* waitPresent(env.project, zone, managerName);
575 }
576
577 if (current === undefined) {
578 return yield* new InstanceGroupManagerNotResolved({
579 managerName,
580 zone,
581 });
582 }
583
584 const patch: compute.InstanceGroupManager = {
585 fingerprint: current.fingerprint,
586 };
587 let dirty = false;
588
589 if ((current.description ?? "") !== description) {
590 patch.description = description;
591 dirty = true;
592 }
593 if ((current.targetSize ?? DEFAULT_TARGET_SIZE) !== targetSize) {
594 patch.targetSize = targetSize;
595 dirty = true;
596 }
597 if (lastSegment(current.instanceTemplate) !== lastSegment(instanceTemplate)) {
598 patch.instanceTemplate = instanceTemplate;
599 dirty = true;
600 }
601 if (news.autoHealingPolicies !== undefined) {
602 const desiredHealing = toHealing(env.project, news.autoHealingPolicies);
603 if (!sameHealing(fromApiHealing(current.autoHealingPolicies), desiredHealing)) {
604 patch.autoHealingPolicies = desiredHealing;
605 dirty = true;
606 }
607 }
608 if (
609 news.updatePolicy !== undefined &&
610 !sameUpdatePolicy(current.updatePolicy, news.updatePolicy)
611 ) {
612 patch.updatePolicy = news.updatePolicy;
613 dirty = true;
614 }
615 if (news.targetPools !== undefined) {
616 const desiredPools = news.targetPools.map((pool) =>
617 toTargetPoolUrl(env.project, zone, pool),
618 );
619 if (!sameSegments(current.targetPools, desiredPools)) {
620 patch.targetPools = desiredPools;
621 dirty = true;
622 }
623 }
624 const observedLifecycle: Record<string, unknown> = {
625 ...current.instanceLifecyclePolicy,
626 };
627 if (
628 news.instanceLifecyclePolicy !== undefined &&
629 Object.entries(news.instanceLifecyclePolicy).some(
630 ([key, value]) =>
631 JSON.stringify(observedLifecycle[key] ?? null) !== JSON.stringify(value ?? null),
632 )
633 ) {
634 patch.instanceLifecyclePolicy = news.instanceLifecyclePolicy;
635 dirty = true;
636 }
637
638 if (dirty) {
639 yield* runOp(
640 env.project,
641 zone,
642 compute.patchInstanceGroupManagers({
643 project: env.project,
644 zone,
645 instanceGroupManager: managerName,
646 body: patch,
647 }),
648 ).pipe(
649 Effect.retry({
650 while: (error) => error._tag === "Conflict",
651 times: 5,
652 schedule: Schedule.exponential("250 millis"),
653 }),
654 );
655 current = (yield* getByName(env.project, zone, managerName)) ?? current;
656 }
657
658 if (!samePorts(fromApiPorts(current.namedPorts), namedPorts)) {
659 yield* syncNamedPorts(env.project, zone, current.instanceGroup, namedPorts);
660 current = (yield* getByName(env.project, zone, managerName)) ?? current;
661 }
662
663 return toAttrs(current, env.project);
664 }),
665
666 delete: Effect.fn(function* ({ output }) {
667 yield* compute
668 .deleteInstanceGroupManagers({
669 project: output.project,
670 zone: output.zone,
671 instanceGroupManager: output.managerName,
672 })
673 .pipe(
674 Effect.retry({
675 while: (error) => error._tag === "Conflict",
676 times: 8,
677 schedule: Schedule.spaced("2 seconds"),
678 }),
679 Effect.catchTag("NotFound", () => Effect.undefined),
680 Effect.flatMap((operation) =>
681 operation === undefined
682 ? Effect.void
683 : waitZoneOperation(output.project, output.zone, operation, {
684 ignore: ["RESOURCE_NOT_FOUND"],
685 }).pipe(Effect.asVoid),
686 ),
687 Effect.catchTag("NotFound", () => Effect.void),
688 );
689 yield* waitGone(output.project, output.zone, output.managerName);
690 }),
691 });