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

main
ts 482 lines 16.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 const DEFAULT_ZONE = "us-central1-a";
17 const DEFAULT_PRIORITY = 1000;
18 const MAX_NAME_LENGTH = 63;
19
20 export type ZoneVmExtensionPolicyExtensionPolicy = compute.VmExtensionPolicyExtensionPolicy;
21 export type ZoneVmExtensionPolicyInstanceSelector = compute.VmExtensionPolicyInstanceSelector;
22 export type ZoneVmExtensionPolicyExtensionPolicyMap = compute.VmExtensionPolicyExtensionPolicyMap;
23
24 export type ZoneVmExtensionPolicyProps = {
25 /**
26 * Policy name (RFC1035, 1-63 characters). If omitted, a unique name is
27 * generated from the stack, stage, and logical id. Changing the name
28 * replaces the policy.
29 */
30 vmExtensionPolicyName?: string;
31 /**
32 * Zone the policy lives in (e.g. `us-central1-a`). Immutable — changing
33 * it replaces the policy.
34 * @default "us-central1-a"
35 */
36 zone?: string;
37 /**
38 * Optional description. Zone VM extension policies have no labels
39 * field, so Alchemy ownership (`alchemy-stack` / `alchemy-stage` /
40 * `alchemy-id`) is stored in a `[alchemy …]` prefix for `list` / nuke.
41 */
42 description?: string;
43 /**
44 * Policy priority (0-65535, lower is higher priority).
45 * @default 1000
46 */
47 priority?: number;
48 /**
49 * Selectors that target VMs. A VM matches if it matches any selector.
50 * Empty applies the policy to every VM in the zone.
51 */
52 instanceSelectors?: ReadonlyArray<ZoneVmExtensionPolicyInstanceSelector>;
53 /**
54 * Map of extension name (`ops-agent`, `google-cloud-sap-extension`,
55 * `google-cloud-workload-extension`) to configuration.
56 */
57 extensionPolicies?: ZoneVmExtensionPolicyExtensionPolicyMap;
58 };
59
60 export type ZoneVmExtensionPolicy = Resource<
61 "GCP.Compute.ZoneVmExtensionPolicy",
62 ZoneVmExtensionPolicyProps,
63 {
64 /** Policy name. */
65 vmExtensionPolicyName: string;
66 /** Server-assigned numeric id. */
67 vmExtensionPolicyId: string | undefined;
68 /** Project id. */
69 project: string;
70 /** Zone short name (`us-central1-a`). */
71 zone: string;
72 /** User description with the Alchemy ownership prefix stripped. */
73 description: string | undefined;
74 /** Policy priority. */
75 priority: number | undefined;
76 /** VM selectors. */
77 instanceSelectors: ReadonlyArray<ZoneVmExtensionPolicyInstanceSelector>;
78 /** Extension configurations. */
79 extensionPolicies: ZoneVmExtensionPolicyExtensionPolicyMap | undefined;
80 /** Server-reported state (`ACTIVE`, `DELETING`, …). */
81 state: string | undefined;
82 /** Whether a global policy manages this zonal policy. */
83 managedByGlobal: boolean;
84 /** Link to the managing global policy, if any. */
85 globalResourceLink: string | undefined;
86 /** Compute Engine self-link. */
87 selfLink: string | undefined;
88 /** RFC3339 creation timestamp. */
89 creationTimestamp: string | undefined;
90 },
91 never,
92 Providers
93 >;
94
95 /**
96 * A zonal Compute Engine VM extension policy.
97 *
98 * Zone VM extension policies install Google-provided extensions (Ops
99 * Agent, SAP, workload) on VMs that match label selectors. Compute Engine
100 * has no labels on this resource, so Alchemy stamps ownership into the
101 * description so `list` / `pnpm nuke:gcp` can find them.
102 *
103 * Name and zone are immutable — changing them replaces the policy.
104 * Description, priority, selectors, and extension configurations update
105 * in place via `zoneVmExtensionPolicies.patch`.
106 *
107 * ### Creating a Zone VM Extension Policy
108 * **Example:** Install Ops Agent on labeled VMs
109 * ```typescript
110 * const policy = yield* GCP.Compute.ZoneVmExtensionPolicy("Ops", {
111 * zone: "us-central1-a",
112 * extensionPolicies: {
113 * "ops-agent": { pinnedVersion: "2.58.0" },
114 * },
115 * instanceSelectors: [
116 * { labelSelector: { inclusionLabels: { env: "prod" } } },
117 * ],
118 * });
119 * ```
120 *
121 * **Example:** Named policy with a description
122 * ```typescript
123 * const policy = yield* GCP.Compute.ZoneVmExtensionPolicy("Ops", {
124 * vmExtensionPolicyName: "ops-agent-prod",
125 * description: "ops-agent for prod VMs",
126 * priority: 500,
127 * extensionPolicies: { "ops-agent": {} },
128 * instanceSelectors: [
129 * { labelSelector: { inclusionLabels: { role: "app" } } },
130 * ],
131 * });
132 * ```
133 *
134 * @resource
135 * @category Compute
136 */
137 export const ZoneVmExtensionPolicy = Resource<ZoneVmExtensionPolicy>(
138 "GCP.Compute.ZoneVmExtensionPolicy",
139 );
140
141 export class ZoneVmExtensionPolicyNotResolved extends Data.TaggedError(
142 "GCP.Compute.ZoneVmExtensionPolicyNotResolved",
143 )<{
144 vmExtensionPolicyName: string;
145 zone: string;
146 }> {}
147
148 export class ZoneVmExtensionPolicyNotReady extends Data.TaggedError(
149 "GCP.Compute.ZoneVmExtensionPolicyNotReady",
150 )<{
151 vmExtensionPolicyName: string;
152 status: string;
153 }> {}
154
155 export class ZoneVmExtensionPolicyStillExists extends Data.TaggedError(
156 "GCP.Compute.ZoneVmExtensionPolicyStillExists",
157 )<{
158 vmExtensionPolicyName: string;
159 status: string;
160 }> {}
161
162 const lastSegment = (value: string | undefined): string => {
163 if (value === undefined || value.length === 0) return "";
164 const trimmed = value.replace(/\/+$/, "");
165 const parts = trimmed.split("/");
166 return parts[parts.length - 1] || trimmed;
167 };
168
169 const normalizeZone = (zone: string | undefined) => lastSegment(zone ?? DEFAULT_ZONE).toLowerCase();
170
171 const toName = (id: string, name: string | undefined, existing?: string) =>
172 Effect.gen(function* () {
173 if (name !== undefined) return name;
174 if (existing !== undefined) return existing;
175 const generated = yield* createPhysicalName({
176 id,
177 maxLength: MAX_NAME_LENGTH,
178 lowercase: true,
179 });
180 return /^[a-z]/.test(generated) ? generated : `v${generated}`.slice(0, MAX_NAME_LENGTH);
181 });
182
183 const encodeDescription = (
184 labels: Record<string, string>,
185 description: string | undefined,
186 ): string => {
187 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
188 return description ? `${marker}\n${description}` : marker;
189 };
190
191 const parseDescription = (
192 description: string | undefined,
193 ): {
194 labels: Record<string, string>;
195 description: string | undefined;
196 } => {
197 if (!description?.startsWith("[alchemy ")) {
198 return { labels: {}, description };
199 }
200 const end = description.indexOf("]");
201 if (end < 0) return { labels: {}, description };
202 const labels: Record<string, string> = {};
203 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
204 const eq = part.indexOf("=");
205 if (eq > 0) {
206 labels[part.slice(0, eq)] = part.slice(eq + 1);
207 }
208 }
209 const rest = description.slice(end + 1).replace(/^\n/, "");
210 return { labels, description: rest.length > 0 ? rest : undefined };
211 };
212
213 const hasOwnershipMarker = (description: string | undefined) =>
214 Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-"));
215
216 const sameJson = (left: unknown, right: unknown) =>
217 JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
218
219 const defaultExtensions = (): compute.VmExtensionPolicyExtensionPolicyMap => ({
220 "ops-agent": {},
221 });
222
223 const toBody = (
224 vmExtensionPolicyName: string,
225 props: ZoneVmExtensionPolicyProps,
226 ownership: Record<string, string>,
227 ): compute.VmExtensionPolicy => ({
228 name: vmExtensionPolicyName,
229 description: encodeDescription(ownership, props.description),
230 priority: props.priority ?? DEFAULT_PRIORITY,
231 instanceSelectors: props.instanceSelectors ? [...props.instanceSelectors] : undefined,
232 extensionPolicies: props.extensionPolicies ?? defaultExtensions(),
233 });
234
235 const toAttrs = (
236 policy: compute.VmExtensionPolicy,
237 project: string,
238 zone: string,
239 ): ZoneVmExtensionPolicy["Attributes"] => {
240 const parsed = parseDescription(policy.description);
241 return {
242 vmExtensionPolicyName: policy.name ?? policy.id ?? "",
243 vmExtensionPolicyId: policy.id,
244 project,
245 zone: normalizeZone(zone),
246 description: parsed.description,
247 priority: policy.priority,
248 instanceSelectors: policy.instanceSelectors ?? [],
249 extensionPolicies: policy.extensionPolicies,
250 state: policy.state,
251 managedByGlobal: policy.managedByGlobal === true,
252 globalResourceLink: policy.globalResourceLink,
253 selfLink: policy.selfLink,
254 creationTimestamp: policy.creationTimestamp,
255 };
256 };
257
258 const getByName = (project: string, zone: string, vmExtensionPolicy: string) =>
259 compute
260 .getZoneVmExtensionPolicies({ project, zone, vmExtensionPolicy })
261 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
262
263 const waitPolicyReady = (project: string, zone: string, vmExtensionPolicyName: string) =>
264 getByName(project, zone, vmExtensionPolicyName).pipe(
265 Effect.filterOrFail(
266 (policy): policy is compute.VmExtensionPolicy =>
267 policy !== undefined && (policy.state === "ACTIVE" || policy.state === undefined),
268 (policy) =>
269 new ZoneVmExtensionPolicyNotReady({
270 vmExtensionPolicyName,
271 status: policy?.state ?? "MISSING",
272 }),
273 ),
274 Effect.retry({
275 while: (error) => error._tag === "GCP.Compute.ZoneVmExtensionPolicyNotReady",
276 times: 10,
277 schedule: Schedule.spaced("2 seconds"),
278 }),
279 );
280
281 const waitPolicyGone = (project: string, zone: string, vmExtensionPolicyName: string) =>
282 getByName(project, zone, vmExtensionPolicyName).pipe(
283 Effect.flatMap((policy) =>
284 policy === undefined
285 ? Effect.void
286 : Effect.fail(
287 new ZoneVmExtensionPolicyStillExists({
288 vmExtensionPolicyName,
289 status: policy.state ?? "UNKNOWN",
290 }),
291 ),
292 ),
293 Effect.retry({
294 while: (error) => error instanceof ZoneVmExtensionPolicyStillExists,
295 times: 10,
296 schedule: Schedule.spaced("2 seconds"),
297 }),
298 );
299
300 export const ZoneVmExtensionPolicyProvider = () =>
301 Provider.succeed(ZoneVmExtensionPolicy, {
302 stables: [
303 "vmExtensionPolicyName",
304 "vmExtensionPolicyId",
305 "project",
306 "zone",
307 "selfLink",
308 "creationTimestamp",
309 ],
310
311 diff: Effect.fn(function* ({ news, olds, output }) {
312 if (!isResolved(news)) return undefined;
313
314 const previousName = olds?.vmExtensionPolicyName ?? output?.vmExtensionPolicyName;
315 const nextName = news.vmExtensionPolicyName ?? previousName;
316 const nameChanged =
317 previousName !== undefined && nextName !== undefined && previousName !== nextName;
318
319 const previousZone = normalizeZone(olds?.zone ?? output?.zone);
320 const nextZone = normalizeZone(news.zone ?? output?.zone);
321
322 if (nameChanged || previousZone !== nextZone) {
323 return {
324 action: "replace" as const,
325 deleteFirst:
326 previousName !== undefined && nextName === previousName && previousZone === nextZone,
327 };
328 }
329 return undefined;
330 }),
331
332 read: Effect.fn(function* ({ id, olds, output }) {
333 const env = yield* GcpEnvironment.current;
334 const vmExtensionPolicyName = yield* toName(
335 id,
336 olds?.vmExtensionPolicyName,
337 output?.vmExtensionPolicyName,
338 );
339 const zone = normalizeZone(olds?.zone ?? output?.zone);
340 const existing = yield* getByName(env.project, zone, vmExtensionPolicyName);
341 if (existing === undefined) return undefined;
342 const attrs = toAttrs(existing, env.project, zone);
343 const { labels } = parseDescription(existing.description);
344 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
345 }),
346
347 list: () =>
348 Effect.gen(function* () {
349 const env = yield* GcpEnvironment.current;
350 const zones = yield* compute.listZones
351 .items({
352 project: env.project,
353 maxResults: 500,
354 })
355 .pipe(
356 Stream.filter((zone) => zone.status === "UP" && !!zone.name),
357 Stream.runCollect,
358 Effect.map((chunk) => Array.from(chunk)),
359 );
360 const pages = yield* Effect.forEach(
361 zones,
362 (zone) =>
363 compute.listZoneVmExtensionPolicies
364 .items({
365 project: env.project,
366 zone: zone.name!,
367 maxResults: 500,
368 returnPartialSuccess: true,
369 })
370 .pipe(
371 Stream.filter((policy) => hasOwnershipMarker(policy.description)),
372 Stream.map((policy) => toAttrs(policy, env.project, zone.name!)),
373 Stream.runCollect,
374 Effect.map((chunk) => Array.from(chunk)),
375 Effect.catchTag("NotFound", () => Effect.succeed([])),
376 ),
377 { concurrency: 8 },
378 );
379 return pages.flat();
380 }),
381
382 reconcile: Effect.fn(function* ({ id, news, output }) {
383 const env = yield* GcpEnvironment.current;
384 const vmExtensionPolicyName = yield* toName(
385 id,
386 news.vmExtensionPolicyName,
387 output?.vmExtensionPolicyName,
388 );
389 const zone = normalizeZone(news.zone ?? output?.zone);
390 const ownership = yield* createInternalLabels(id);
391 const desired = toBody(vmExtensionPolicyName, news, ownership);
392
393 let current = yield* getByName(env.project, zone, vmExtensionPolicyName);
394 if (current?.state === "DELETING") {
395 yield* waitPolicyGone(env.project, zone, vmExtensionPolicyName);
396 current = undefined;
397 }
398
399 if (current === undefined) {
400 const inserted = yield* compute
401 .insertZoneVmExtensionPolicies({
402 project: env.project,
403 zone,
404 body: desired,
405 })
406 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
407 if (inserted !== undefined) {
408 yield* waitZoneOperation(env.project, zone, inserted, {
409 ignore: ["RESOURCE_ALREADY_EXISTS"],
410 });
411 }
412 current = yield* waitPolicyReady(env.project, zone, vmExtensionPolicyName);
413 }
414
415 if (current === undefined) {
416 return yield* new ZoneVmExtensionPolicyNotResolved({
417 vmExtensionPolicyName,
418 zone,
419 });
420 }
421
422 const descriptionChanged = (current.description ?? "") !== (desired.description ?? "");
423 const priorityChanged =
424 (current.priority ?? DEFAULT_PRIORITY) !== (desired.priority ?? DEFAULT_PRIORITY);
425 const selectorsChanged = !sameJson(
426 current.instanceSelectors ?? [],
427 desired.instanceSelectors ?? [],
428 );
429 const extensionsChanged = !sameJson(current.extensionPolicies, desired.extensionPolicies);
430
431 if (
432 !current.managedByGlobal &&
433 (descriptionChanged || priorityChanged || selectorsChanged || extensionsChanged)
434 ) {
435 const patched = yield* compute.updateZoneVmExtensionPolicies({
436 project: env.project,
437 zone,
438 vmExtensionPolicy: vmExtensionPolicyName,
439 body: desired,
440 });
441 yield* waitZoneOperation(env.project, zone, patched);
442 current =
443 (yield* getByName(env.project, zone, vmExtensionPolicyName)) ??
444 (yield* waitPolicyReady(env.project, zone, vmExtensionPolicyName));
445 }
446
447 if (current === undefined) {
448 return yield* new ZoneVmExtensionPolicyNotResolved({
449 vmExtensionPolicyName,
450 zone,
451 });
452 }
453
454 return toAttrs(current, env.project, zone);
455 }),
456
457 delete: Effect.fn(function* ({ output }) {
458 const env = yield* GcpEnvironment.current;
459 const project = output.project || env.project;
460 const zone = normalizeZone(output.zone);
461 const deleted = yield* compute
462 .deleteZoneVmExtensionPolicies({
463 project,
464 zone,
465 vmExtensionPolicy: output.vmExtensionPolicyName,
466 })
467 .pipe(
468 Effect.catchTag("NotFound", () => Effect.undefined),
469 Effect.retry({
470 while: (error) => error._tag === "Conflict",
471 times: 8,
472 schedule: Schedule.spaced("2 seconds"),
473 }),
474 );
475 if (deleted !== undefined) {
476 yield* waitZoneOperation(project, zone, deleted, {
477 ignore: ["RESOURCE_NOT_FOUND"],
478 });
479 }
480 yield* waitPolicyGone(project, zone, output.vmExtensionPolicyName);
481 }),
482 });