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

main
ts 719 lines 24.7 KB
Raw
1 import * as memcache from "@distilled.cloud/gcp/memcache_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 { tagRecord } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12 import { GcpEnvironment } from "../Environment.ts";
13 import {
14 createInternalLabels,
15 diffLabels,
16 hasAlchemyLabels,
17 stripInternalLabels,
18 toLabels,
19 } from "../Labels.ts";
20 import { waitForOperation as waitForGcpOperation } from "../Operation.ts";
21 import type { Providers } from "../Providers.ts";
22
23 const DEFAULT_NODE_COUNT = 1;
24 const DEFAULT_CPU_COUNT = 1;
25 const DEFAULT_MEMORY_SIZE_MB = 1024;
26 const MAX_NAME_LENGTH = 40;
27
28 export type TimeOfDay = {
29 /** Hours of day in 24-hour format (`0`–`23`). */
30 hours?: number;
31 /** Minutes of hour (`0`–`59`). */
32 minutes?: number;
33 /** Seconds of minute (`0`–`59`). */
34 seconds?: number;
35 /** Fractional seconds, in nanoseconds. */
36 nanos?: number;
37 };
38
39 export type WeeklyMaintenanceWindow = {
40 /** Day of week that maintenance occurs (`MONDAY` … `SUNDAY`). */
41 day?: memcache.WeeklyMaintenanceWindowDayEnum | (string & {});
42 /** Start time of the window in UTC. */
43 startTime?: TimeOfDay;
44 /** Window length as a duration string (e.g. `"10800s"` for 3 hours). */
45 duration?: string;
46 };
47
48 export type MaintenancePolicy = {
49 /** Description of the policy. Max 512 characters. */
50 description?: string;
51 /** Weekly windows. Current API maximum is one window. */
52 weeklyMaintenanceWindow?: WeeklyMaintenanceWindow[];
53 };
54
55 export type NodeConfig = {
56 /**
57 * vCPUs per Memcached node.
58 * @default 1
59 */
60 cpuCount?: number;
61 /**
62 * Memory per node in MiB.
63 * @default 1024
64 */
65 memorySizeMb?: number;
66 };
67
68 export type InstanceProps = {
69 /**
70 * Instance id (the `{instance}` segment of
71 * `projects/{project}/locations/{location}/instances/{instance}`).
72 * If omitted, a unique name is generated from the stack, stage, and
73 * logical id. Must match `^[a-z][a-z0-9-]{0,38}[a-z0-9]$` (1-40
74 * characters). Immutable — changing it replaces the instance.
75 */
76 instanceId?: string;
77 /**
78 * Region (`us-central1`, `us-east1`, …). Immutable — changing it
79 * replaces the instance. `US-CENTRAL1` is accepted and normalized to
80 * `us-central1`.
81 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
82 */
83 location?: string;
84 /**
85 * User-facing display name. Max 80 characters.
86 */
87 displayName?: string;
88 /**
89 * User labels. Alchemy ownership labels are merged in automatically.
90 */
91 labels?: Record<string, string>;
92 /**
93 * VPC network
94 * (`projects/{project}/global/networks/{network}`). Immutable. Defaults
95 * to the project `default` network.
96 */
97 authorizedNetwork?: string;
98 /**
99 * Zones to place nodes in. Nodes are spread evenly. Immutable. If
100 * omitted, Memorystore uses every zone in the region.
101 */
102 zones?: string[];
103 /**
104 * Number of Memcached nodes.
105 * @default 1
106 */
107 nodeCount?: number;
108 /**
109 * Per-node CPU and memory. Immutable — changing it replaces the
110 * instance.
111 */
112 nodeConfig?: NodeConfig;
113 /**
114 * Memcached software version (`MEMCACHE_1_5`, `MEMCACHE_1_6_15`).
115 * Upgrading uses `instances.upgrade`; downgrading replaces the instance.
116 */
117 memcacheVersion?: memcache.InstanceMemcacheVersionEnum | (string & {});
118 /**
119 * User-defined memcached process parameters (`max_item_size`, …).
120 * Staged with `updateParameters` and applied with `applyParameters`.
121 */
122 parameters?: Record<string, string>;
123 /**
124 * Maintenance policy. If omitted, Memorystore may perform maintenance
125 * at any time.
126 */
127 maintenancePolicy?: MaintenancePolicy;
128 /**
129 * Allocated private-service-access range ids (e.g. `"default"`).
130 * Immutable.
131 */
132 reservedIpRangeId?: string[];
133 /**
134 * Self-service maintenance version (e.g. `"20210712_00_00"`).
135 */
136 maintenanceVersion?: string;
137 };
138
139 export type Instance = Resource<
140 "GCP.Memcache.Instance",
141 InstanceProps,
142 {
143 /** Full resource name `projects/{project}/locations/{location}/instances/{instance}`. */
144 name: string;
145 /** Instance id (last path segment). */
146 instanceId: string;
147 /** Project id. */
148 project: string;
149 /** Region id (`us-central1`, …). */
150 location: string;
151 /** User-facing display name. */
152 displayName: string | undefined;
153 /** User labels (Alchemy ownership labels stripped). */
154 labels: Record<string, string>;
155 /** Authorized VPC network. */
156 authorizedNetwork: string | undefined;
157 /** Zones nodes were provisioned in. */
158 zones: string[];
159 /** Number of Memcached nodes. */
160 nodeCount: number;
161 /** Per-node CPU and memory currently applied. */
162 nodeConfig: NodeConfig;
163 /** Memcached software version. */
164 memcacheVersion: string | undefined;
165 /** Full memcached version string (e.g. `memcached-1.5.16`). */
166 memcacheFullVersion: string | undefined;
167 /** User-defined memcached process parameters currently staged. */
168 parameters: Record<string, string>;
169 /** Server-assigned parameter-set id. */
170 parameterId: string | undefined;
171 /** Per-node info. */
172 memcacheNodes: memcache.Node[];
173 /** Server-reported state (`READY`, `CREATING`, …). */
174 state: string | undefined;
175 /** Discovery API endpoint. */
176 discoveryEndpoint: string | undefined;
177 /** Allocated private-service-access range ids. */
178 reservedIpRangeId: string[];
179 /** Self-service maintenance version. */
180 maintenanceVersion: string | undefined;
181 /** Effective maintenance version. */
182 effectiveMaintenanceVersion: string | undefined;
183 /** RFC3339 creation timestamp. */
184 createTime: string | undefined;
185 /** RFC3339 last-update timestamp. */
186 updateTime: string | undefined;
187 },
188 never,
189 Providers
190 >;
191
192 /**
193 * A Memorystore for Memcached instance.
194 *
195 * Changing `instanceId`, `location`, `authorizedNetwork`, `zones`,
196 * `nodeConfig`, or `reservedIpRangeId` replaces the instance. Memcached
197 * version upgrades use `instances.upgrade`; a downgrade replaces the
198 * instance.
199 *
200 * Provisioning typically takes several minutes.
201 *
202 * ### Creating an Instance
203 * **Example:** Generated name, 1 node
204 * ```typescript
205 * const cache = yield* GCP.Memcache.Instance("Cache", {
206 * nodeCount: 1,
207 * nodeConfig: { cpuCount: 1, memorySizeMb: 1024 },
208 * });
209 * ```
210 *
211 * **Example:** Explicit id, labels, and display name
212 * ```typescript
213 * const cache = yield* GCP.Memcache.Instance("Cache", {
214 * instanceId: "app-memcache",
215 * location: "us-central1",
216 * displayName: "app cache",
217 * labels: { env: "prod" },
218 * nodeCount: 1,
219 * nodeConfig: { cpuCount: 1, memorySizeMb: 1024 },
220 * });
221 * ```
222 *
223 * ### Scaling Nodes
224 * **Example:** Increase node count in place
225 * ```typescript
226 * const cache = yield* GCP.Memcache.Instance("Cache", {
227 * nodeCount: 2,
228 * nodeConfig: { cpuCount: 1, memorySizeMb: 1024 },
229 * });
230 * ```
231 *
232 * @resource
233 * @category Memcache
234 */
235 export const Instance = Resource<Instance>("GCP.Memcache.Instance");
236
237 export class InstanceNotResolved extends Data.TaggedError("GCP.Memcache.InstanceNotResolved")<{
238 resourceName: string;
239 }> {}
240
241 export class InstanceNotReady extends Data.TaggedError("GCP.Memcache.InstanceNotReady")<{
242 resourceName: string;
243 state: string;
244 }> {}
245
246 export class InstanceStillExists extends Data.TaggedError("GCP.Memcache.InstanceStillExists")<{
247 resourceName: string;
248 }> {}
249
250 const lastSegment = (value: string) => {
251 const trimmed = value.replace(/\/+$/, "");
252 const parts = trimmed.split("/");
253 return parts[parts.length - 1] || trimmed;
254 };
255
256 const normalizeLocation = (location: string | undefined, defaultLocation: string) =>
257 lastSegment(location ?? defaultLocation).toLowerCase();
258
259 const rfc1035 = (name: string): string => {
260 let next = name
261 .toLowerCase()
262 .replace(/[^a-z0-9-]/g, "-")
263 .replace(/-+/g, "-")
264 .replace(/^-+|-+$/g, "");
265 if (!/^[a-z]/.test(next)) next = `m${next}`;
266 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, "");
267 if (next.length === 0) return "instance";
268 if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`;
269 return next.slice(0, MAX_NAME_LENGTH);
270 };
271
272 const resourceName = (project: string, location: string, instanceId: string) =>
273 `projects/${project}/locations/${location}/instances/${instanceId}`;
274
275 const parseName = (name: string, defaultLocation: string) => {
276 const parts = name.split("/").filter((part) => part.length > 0);
277 const instancesAt = parts.lastIndexOf("instances");
278 const locationsAt = parts.lastIndexOf("locations");
279 const projectsAt = parts.lastIndexOf("projects");
280 return {
281 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
282 location:
283 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : defaultLocation,
284 instanceId:
285 instancesAt >= 0 && parts[instancesAt + 1] ? parts[instancesAt + 1]! : lastSegment(name),
286 };
287 };
288
289 const userLabels = (
290 labels: Record<string, string | undefined> | null | undefined,
291 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
292
293 const toId = (id: string, instanceId: string | undefined, existing?: string) =>
294 Effect.gen(function* () {
295 return (
296 instanceId ??
297 existing ??
298 rfc1035(
299 yield* createPhysicalName({
300 id,
301 maxLength: MAX_NAME_LENGTH,
302 lowercase: true,
303 }),
304 )
305 );
306 });
307
308 const paramsOf = (
309 params: Record<string, string | undefined> | null | undefined,
310 ): Record<string, string> =>
311 Object.fromEntries(
312 Object.entries(params ?? {}).filter(
313 (entry): entry is [string, string] => entry[1] !== undefined,
314 ),
315 );
316
317 const paramsKey = (params: Record<string, string | undefined> | null | undefined) =>
318 JSON.stringify(
319 Object.fromEntries(Object.entries(paramsOf(params)).sort(([a], [b]) => a.localeCompare(b))),
320 );
321
322 const listKey = (values: readonly string[] | undefined) =>
323 JSON.stringify([...(values ?? [])].map((value) => value.toLowerCase()).sort());
324
325 const nodeConfigOf = (config: NodeConfig | undefined): NodeConfig => ({
326 cpuCount: config?.cpuCount ?? DEFAULT_CPU_COUNT,
327 memorySizeMb: config?.memorySizeMb ?? DEFAULT_MEMORY_SIZE_MB,
328 });
329
330 const nodeConfigKey = (config: NodeConfig | undefined) => {
331 const value = nodeConfigOf(config);
332 return JSON.stringify({
333 cpuCount: value.cpuCount,
334 memorySizeMb: value.memorySizeMb,
335 });
336 };
337
338 const windowKey = (window: WeeklyMaintenanceWindow) =>
339 JSON.stringify({
340 day: (window.day ?? "").toUpperCase(),
341 hours: window.startTime?.hours ?? 0,
342 minutes: window.startTime?.minutes ?? 0,
343 seconds: window.startTime?.seconds ?? 0,
344 nanos: window.startTime?.nanos ?? 0,
345 duration: window.duration ?? "",
346 });
347
348 const maintenanceOf = (
349 policy: memcache.GoogleCloudMemcacheV1MaintenancePolicy | MaintenancePolicy | undefined,
350 ): MaintenancePolicy | undefined => {
351 if (policy === undefined) return undefined;
352 return {
353 description: policy.description,
354 weeklyMaintenanceWindow: policy.weeklyMaintenanceWindow,
355 };
356 };
357
358 const maintenanceKey = (policy: MaintenancePolicy | undefined) =>
359 JSON.stringify({
360 description: policy?.description ?? "",
361 windows: (policy?.weeklyMaintenanceWindow ?? []).map(windowKey),
362 });
363
364 const parseMemcacheVersion = (version: string | undefined) => {
365 if (version === undefined) return undefined;
366 const match = version.toUpperCase().match(/^MEMCACHE_(\d+)_(\d+)(?:_(\d+))?$/);
367 if (!match) return undefined;
368 return Number(match[1]) * 10_000 + Number(match[2]) * 100 + Number(match[3] ?? 0);
369 };
370
371 const versionDecreasing = (previous: string | undefined, next: string) => {
372 const oldN = parseMemcacheVersion(previous);
373 const newN = parseMemcacheVersion(next);
374 if (oldN === undefined || newN === undefined) return previous !== next;
375 return newN < oldN;
376 };
377
378 const toAttrs = (instance: memcache.Instance, project: string, region: string) => {
379 const name = instance.name ?? "";
380 const parsed = parseName(name, region);
381 return {
382 name,
383 instanceId: parsed.instanceId,
384 project: parsed.project || project,
385 location: parsed.location,
386 displayName: instance.displayName,
387 labels: userLabels(instance.labels),
388 authorizedNetwork: instance.authorizedNetwork,
389 zones: instance.zones ?? [],
390 nodeCount: instance.nodeCount ?? DEFAULT_NODE_COUNT,
391 nodeConfig: nodeConfigOf(instance.nodeConfig),
392 memcacheVersion: instance.memcacheVersion,
393 memcacheFullVersion: instance.memcacheFullVersion,
394 parameters: paramsOf(instance.parameters?.params),
395 parameterId: instance.parameters?.id,
396 memcacheNodes: instance.memcacheNodes ?? [],
397 state: instance.state,
398 discoveryEndpoint: instance.discoveryEndpoint,
399 reservedIpRangeId: instance.reservedIpRangeId ?? [],
400 maintenanceVersion: instance.maintenanceVersion,
401 effectiveMaintenanceVersion: instance.effectiveMaintenanceVersion,
402 createTime: instance.createTime,
403 updateTime: instance.updateTime,
404 };
405 };
406
407 const isPlaceholder = (instance: memcache.Instance) => {
408 const name = instance.name ?? "";
409 return name.endsWith("/instances/-") || name.endsWith("/instances/");
410 };
411
412 const getByName = (name: string) =>
413 memcache
414 .getProjectsLocationsInstances({ name })
415 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
416
417 /**
418 * Wait for a Memorystore for Memcached operation; instance create,
419 * resize, and upgrade take 10–20 minutes. With `notFoundOk`, NOT_FOUND
420 * (code 5) and an operation that is already gone count as success
421 * (delete race).
422 */
423 const waitForOperation = (operation: memcache.Operation, options?: { notFoundOk?: boolean }) =>
424 waitForGcpOperation(operation, (name) => memcache.getProjectsLocationsOperations({ name }), {
425 budget: "30 minutes",
426 interval: "10 seconds",
427 }).pipe(
428 Effect.catchIf(
429 (error) =>
430 options?.notFoundOk === true &&
431 (error._tag === "NotFound" || (error._tag === "GCP.OperationFailed" && error.code === 5)),
432 () => Effect.succeed(operation),
433 ),
434 );
435
436 const waitUntilExists = (name: string) =>
437 getByName(name).pipe(
438 Effect.flatMap((instance) =>
439 instance
440 ? Effect.succeed(instance)
441 : Effect.fail(new InstanceNotResolved({ resourceName: name })),
442 ),
443 Effect.retry({
444 while: (error) => error._tag === "GCP.Memcache.InstanceNotResolved",
445 times: 8,
446 schedule: Schedule.spaced("1 second"),
447 }),
448 );
449
450 const waitUntilReady = (name: string) =>
451 getByName(name).pipe(
452 Effect.filterOrFail(
453 (instance): instance is memcache.Instance => instance !== undefined,
454 () => new InstanceNotResolved({ resourceName: name }),
455 ),
456 Effect.filterOrFail(
457 (instance) => (instance.state ?? "STATE_UNSPECIFIED") === "READY",
458 (instance) =>
459 new InstanceNotReady({
460 resourceName: name,
461 state: instance.state ?? "STATE_UNSPECIFIED",
462 }),
463 ),
464 Effect.retry({
465 while: (error) =>
466 error._tag === "GCP.Memcache.InstanceNotReady" ||
467 error._tag === "GCP.Memcache.InstanceNotResolved",
468 times: 10,
469 schedule: Schedule.spaced("8 seconds"),
470 }),
471 );
472
473 const waitUntilGone = (name: string) =>
474 getByName(name).pipe(
475 Effect.flatMap((instance) =>
476 instance === undefined
477 ? Effect.void
478 : Effect.fail(new InstanceStillExists({ resourceName: name })),
479 ),
480 Effect.retry({
481 while: (error) => error._tag === "GCP.Memcache.InstanceStillExists",
482 times: 10,
483 schedule: Schedule.spaced("8 seconds"),
484 }),
485 );
486
487 const toCreateBody = (
488 news: InstanceProps,
489 desiredLabels: Record<string, string>,
490 nodeCount: number,
491 nodeConfig: NodeConfig,
492 ): memcache.Instance => ({
493 displayName: news.displayName,
494 labels: desiredLabels,
495 authorizedNetwork: news.authorizedNetwork,
496 zones: news.zones,
497 nodeCount,
498 nodeConfig,
499 memcacheVersion: news.memcacheVersion,
500 parameters: news.parameters === undefined ? undefined : { params: news.parameters },
501 maintenancePolicy: news.maintenancePolicy,
502 reservedIpRangeId: news.reservedIpRangeId,
503 });
504
505 export const InstanceProvider = () =>
506 Provider.succeed(Instance, {
507 stables: ["name", "instanceId", "project", "location", "createTime"],
508
509 diff: Effect.fn(function* ({ news, olds, output }) {
510 if (!isResolved(news)) return undefined;
511 const env = yield* GcpEnvironment.current;
512
513 const previousId = olds?.instanceId ?? output?.instanceId;
514 const nextId = news.instanceId ?? previousId;
515 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
516 const nextLocation = normalizeLocation(news.location ?? output?.location, env.region);
517 const previousNetwork = olds?.authorizedNetwork ?? output?.authorizedNetwork ?? "";
518 const nextNetwork = news.authorizedNetwork ?? previousNetwork;
519 const previousZones = listKey(olds?.zones ?? output?.zones);
520 const nextZones = news.zones !== undefined ? listKey(news.zones) : previousZones;
521 const previousNodeConfig = nodeConfigKey(olds?.nodeConfig ?? output?.nodeConfig);
522 const nextNodeConfig = nodeConfigKey(news.nodeConfig ?? output?.nodeConfig);
523 const previousRanges = listKey(olds?.reservedIpRangeId ?? output?.reservedIpRangeId);
524 const nextRanges =
525 news.reservedIpRangeId !== undefined ? listKey(news.reservedIpRangeId) : previousRanges;
526 const previousVersion = olds?.memcacheVersion ?? output?.memcacheVersion;
527 const nextVersion = news.memcacheVersion;
528 const downgrade =
529 nextVersion !== undefined &&
530 previousVersion !== undefined &&
531 versionDecreasing(previousVersion, nextVersion);
532
533 const replace =
534 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
535 previousLocation !== nextLocation ||
536 previousNetwork !== nextNetwork ||
537 previousZones !== nextZones ||
538 previousNodeConfig !== nextNodeConfig ||
539 previousRanges !== nextRanges ||
540 downgrade;
541
542 if (!replace) return undefined;
543 return {
544 action: "replace" as const,
545 deleteFirst:
546 previousLocation === nextLocation && previousId !== undefined && nextId === previousId,
547 };
548 }),
549
550 read: Effect.fn(function* ({ id, olds, output }) {
551 const env = yield* GcpEnvironment.current;
552 const instanceId = yield* toId(id, olds?.instanceId, output?.instanceId);
553 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
554 const name = output?.name ?? resourceName(env.project, location, instanceId);
555 const existing = yield* getByName(name);
556 if (existing === undefined) return undefined;
557 const attrs = toAttrs(existing, env.project, env.region);
558 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
559 }),
560
561 list: () =>
562 Effect.gen(function* () {
563 const env = yield* GcpEnvironment.current;
564 return yield* memcache.listProjectsLocationsInstances
565 .pages({
566 parent: `projects/${env.project}/locations/-`,
567 pageSize: 1000,
568 })
569 .pipe(
570 Stream.flatMap((page) => Stream.fromIterable(page.instances ?? [])),
571 Stream.filter(
572 (instance) =>
573 !isPlaceholder(instance) &&
574 Object.keys(instance.labels ?? {}).some((key) => key.startsWith("alchemy-")),
575 ),
576 Stream.map((instance) => toAttrs(instance, env.project, env.region)),
577 Stream.runCollect,
578 Effect.map((chunk) => Array.from(chunk)),
579 Effect.catchTag("NotFound", () => Effect.succeed([])),
580 );
581 }),
582
583 reconcile: Effect.fn(function* ({ id, news, output }) {
584 const env = yield* GcpEnvironment.current;
585 const instanceId = yield* toId(id, news.instanceId, output?.instanceId);
586 const location = normalizeLocation(news.location ?? output?.location, env.region);
587 const name = resourceName(env.project, location, instanceId);
588 const nodeCount = news.nodeCount ?? DEFAULT_NODE_COUNT;
589 const nodeConfig = nodeConfigOf(news.nodeConfig);
590 const desiredLabels = {
591 ...toLabels(news.labels),
592 ...(yield* createInternalLabels(id)),
593 };
594
595 let current = yield* getByName(output?.name ?? name);
596
597 if (current === undefined) {
598 const created = yield* memcache
599 .createProjectsLocationsInstances({
600 parent: `projects/${env.project}/locations/${location}`,
601 instanceId,
602 body: toCreateBody(news, desiredLabels, nodeCount, nodeConfig),
603 })
604 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
605 if (created !== undefined) {
606 yield* waitForOperation(created);
607 }
608 current = yield* waitUntilExists(name);
609 }
610
611 if (current === undefined) {
612 return yield* new InstanceNotResolved({ resourceName: name });
613 }
614
615 if ((current.state ?? "") !== "READY") {
616 current = yield* waitUntilReady(name);
617 }
618
619 const desiredVersion = news.memcacheVersion;
620 const currentVersion = current.memcacheVersion;
621 if (
622 desiredVersion !== undefined &&
623 currentVersion !== undefined &&
624 desiredVersion !== currentVersion &&
625 !versionDecreasing(currentVersion, desiredVersion)
626 ) {
627 const upgraded = yield* memcache.upgradeProjectsLocationsInstances({
628 name,
629 body: { memcacheVersion: desiredVersion },
630 });
631 yield* waitForOperation(upgraded);
632 current = yield* waitUntilReady(name);
633 }
634
635 const observedLabels = tagRecord(current.labels);
636 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
637 const labelsChanged = upsert.length > 0 || removed.length > 0;
638 const displayNameChanged = (current.displayName ?? "") !== (news.displayName ?? "");
639 const desiredNodeCount = news.nodeCount ?? current.nodeCount ?? nodeCount;
640 const nodeCountChanged = (current.nodeCount ?? DEFAULT_NODE_COUNT) !== desiredNodeCount;
641 const maintenanceChanged =
642 news.maintenancePolicy !== undefined &&
643 maintenanceKey(maintenanceOf(current.maintenancePolicy)) !==
644 maintenanceKey(news.maintenancePolicy);
645 const maintenanceVersionChanged =
646 news.maintenanceVersion !== undefined &&
647 (current.maintenanceVersion ?? "") !== news.maintenanceVersion;
648
649 if (
650 labelsChanged ||
651 displayNameChanged ||
652 nodeCountChanged ||
653 maintenanceChanged ||
654 maintenanceVersionChanged
655 ) {
656 const updateMask = [
657 labelsChanged ? "labels" : undefined,
658 displayNameChanged ? "displayName" : undefined,
659 nodeCountChanged ? "nodeCount" : undefined,
660 maintenanceChanged ? "maintenancePolicy" : undefined,
661 maintenanceVersionChanged ? "maintenanceVersion" : undefined,
662 ].filter((field): field is string => field !== undefined);
663
664 const patched = yield* memcache.patchProjectsLocationsInstances({
665 name,
666 updateMask: updateMask.join(","),
667 body: {
668 name,
669 labels: desiredLabels,
670 displayName: news.displayName,
671 nodeCount: desiredNodeCount,
672 maintenancePolicy: news.maintenancePolicy,
673 maintenanceVersion: news.maintenanceVersion,
674 },
675 });
676 yield* waitForOperation(patched);
677 current = yield* waitUntilReady(name);
678 }
679
680 const parametersChanged =
681 news.parameters !== undefined &&
682 paramsKey(current.parameters?.params) !== paramsKey(news.parameters);
683 if (parametersChanged) {
684 const updated = yield* memcache.updateParametersProjectsLocationsInstances({
685 name,
686 body: {
687 updateMask: "parameters",
688 parameters: { params: news.parameters },
689 },
690 });
691 yield* waitForOperation(updated);
692 const applied = yield* memcache.applyParametersProjectsLocationsInstances({
693 name,
694 body: { applyAll: true },
695 });
696 yield* waitForOperation(applied);
697 current = yield* waitUntilReady(name);
698 }
699
700 return toAttrs(current, env.project, env.region);
701 }),
702
703 delete: Effect.fn(function* ({ output }) {
704 const operation = yield* memcache
705 .deleteProjectsLocationsInstances({ name: output.name })
706 .pipe(
707 Effect.catchTag("NotFound", () => Effect.undefined),
708 Effect.retry({
709 while: (error) => error._tag === "Conflict",
710 times: 8,
711 schedule: Schedule.spaced("5 seconds"),
712 }),
713 );
714 if (operation !== undefined) {
715 yield* waitForOperation(operation, { notFoundOk: true });
716 }
717 yield* waitUntilGone(output.name);
718 }),
719 });