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

main
ts 642 lines 22.2 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 { 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 hasAlchemyLabels,
16 stripInternalLabels,
17 toLabels,
18 } from "../Labels.ts";
19 import type { Providers } from "../Providers.ts";
20 import { waitGlobalOperation } from "./operations.ts";
21
22 const DEFAULT_PROTOCOL = "HTTP";
23 const DEFAULT_SCHEME = "EXTERNAL";
24 const DEFAULT_TIMEOUT_SEC = 30;
25
26 export type BackendServiceBackend = {
27 /** Fully-qualified instance group or NEG URL. */
28 group: string;
29 /** Optional backend description. */
30 description?: string;
31 /** Balancing mode (`UTILIZATION`, `RATE`, `CONNECTION`, …). */
32 balancingMode?: string;
33 /** Capacity scaler in `[0.0, 1.0]`. */
34 capacityScaler?: number;
35 /** Max requests per second (RATE mode). */
36 maxRate?: number;
37 /** Max RPS per instance. */
38 maxRatePerInstance?: number;
39 /** Target utilization in `[0.0, 1.0]`. */
40 maxUtilization?: number;
41 /** Whether this backend is a failover group. */
42 failover?: boolean;
43 };
44
45 export type BackendServiceLogConfigProps = {
46 /**
47 * Export load-balancer logs to Cloud Logging.
48 * @default false
49 */
50 enable?: boolean;
51 /**
52 * Sampling rate in `[0, 1]` when logging is enabled.
53 * @default 1.0
54 */
55 sampleRate?: number;
56 };
57
58 export type BackendServiceProps = {
59 /**
60 * Name of the backend service. If omitted, a unique RFC1035 name is
61 * generated from the stack, stage, and logical id. Must be 1-63
62 * characters and match `[a-z]([-a-z0-9]*[a-z0-9])?`. Immutable —
63 * changing it replaces the resource.
64 */
65 name?: string;
66 /**
67 * User-facing description. Alchemy ownership is stamped into the stored
68 * description (`[alchemy alchemy-stack=… alchemy-stage=… alchemy-id=…]`);
69 * global backend services have no labels API.
70 */
71 description?: string;
72 /**
73 * Protocol used to talk to backends (`HTTP`, `HTTPS`, `HTTP2`, `TCP`,
74 * `SSL`, `UDP`, `GRPC`, `H2C`).
75 * @default "HTTP"
76 */
77 protocol?: string;
78 /**
79 * Load balancer type. Immutable — changing it replaces the resource.
80 * @default "EXTERNAL"
81 */
82 loadBalancingScheme?: string;
83 /**
84 * Backend timeout in seconds.
85 * @default 30
86 */
87 timeoutSec?: number;
88 /**
89 * Named port on instance-group backends. Ignored for NEGs and for
90 * passthrough Network Load Balancers.
91 */
92 portName?: string;
93 /**
94 * Enable Cloud CDN (global external Application / classic HTTP(S) LB).
95 * @default false
96 */
97 enableCDN?: boolean;
98 /**
99 * Session affinity (`NONE`, `CLIENT_IP`, `GENERATED_COOKIE`, …).
100 * @default "NONE"
101 */
102 sessionAffinity?: string;
103 /**
104 * Cookie lifetime in seconds for `GENERATED_COOKIE` / `HTTP_COOKIE`
105 * affinity. `0` is a session cookie.
106 */
107 affinityCookieTtlSec?: number;
108 /**
109 * Fully-qualified health-check URLs. At most one is typically allowed.
110 * Required for instance-group / zonal NEG backends; forbidden for
111 * internet and serverless NEGs.
112 */
113 healthChecks?: string[];
114 /**
115 * Backends (instance groups or NEGs) that serve this service.
116 */
117 backends?: BackendServiceBackend[];
118 /**
119 * Connection-draining timeout in seconds. GCP defaults this to `300`
120 * when omitted.
121 */
122 connectionDrainingTimeoutSec?: number;
123 /**
124 * Compress text responses (`AUTOMATIC` or `DISABLED`).
125 */
126 compressionMode?: string;
127 /**
128 * Headers the load balancer adds to proxied requests.
129 */
130 customRequestHeaders?: string[];
131 /**
132 * Headers the load balancer adds to proxied responses.
133 */
134 customResponseHeaders?: string[];
135 /**
136 * Cloud Logging options for traffic served by this backend service.
137 */
138 logConfig?: BackendServiceLogConfigProps;
139 /**
140 * User labels. Encoded into the description marker alongside Alchemy
141 * ownership labels (the API has no `labels` field).
142 */
143 labels?: Record<string, string>;
144 };
145
146 export type BackendService = Resource<
147 "GCP.Compute.BackendService",
148 BackendServiceProps,
149 {
150 /** RFC1035 resource name. */
151 name: string;
152 /** Project id. */
153 project: string;
154 /** Server-assigned numeric id. */
155 backendServiceId: string | undefined;
156 /** Compute self-link. */
157 selfLink: string | undefined;
158 /** RFC3339 creation timestamp. */
159 creationTimestamp: string | undefined;
160 /** Optimistic-locking fingerprint. */
161 fingerprint: string | undefined;
162 /** User-facing description (ownership marker stripped). */
163 description: string | undefined;
164 /** Protocol used to talk to backends. */
165 protocol: string | undefined;
166 /** Load balancer type. */
167 loadBalancingScheme: string | undefined;
168 /** Backend timeout in seconds. */
169 timeoutSec: number | undefined;
170 /** Named port on instance-group backends. */
171 portName: string | undefined;
172 /** Whether Cloud CDN is enabled. */
173 enableCDN: boolean;
174 /** Session affinity mode. */
175 sessionAffinity: string | undefined;
176 /** Cookie TTL in seconds, if set. */
177 affinityCookieTtlSec: number | undefined;
178 /** Fully-qualified health-check URLs. */
179 healthChecks: string[];
180 /** Attached backends. */
181 backends: BackendServiceBackend[];
182 /** Connection-draining timeout in seconds. */
183 connectionDrainingTimeoutSec: number | undefined;
184 /** Response compression mode. */
185 compressionMode: string | undefined;
186 /** Custom request headers. */
187 customRequestHeaders: string[];
188 /** Custom response headers. */
189 customResponseHeaders: string[];
190 /** Logging configuration. */
191 logConfig: BackendServiceLogConfigProps | undefined;
192 /** User labels (Alchemy ownership labels stripped). */
193 labels: Record<string, string>;
194 /** Resource kind (`compute#backendService`). */
195 kind: string | undefined;
196 },
197 never,
198 Providers
199 >;
200
201 /**
202 * A global Compute Engine backend service. Backend services define how
203 * Google Cloud load balancers distribute traffic — protocol, timeout,
204 * session affinity, health checks, and the backends themselves.
205 *
206 * Compute Engine backend services have no labels field, so Alchemy stamps
207 * ownership into the description (`[alchemy alchemy-stack=… alchemy-stage=…
208 * alchemy-id=…]`) so `list` / `pnpm nuke:gcp` can find them.
209 *
210 * ### Creating a Backend Service
211 * **Example:** Generated name
212 * ```typescript
213 * const backend = yield* GCP.Compute.BackendService("web", {
214 * protocol: "HTTP",
215 * });
216 * ```
217 *
218 * **Example:** Explicit name, timeout, and labels
219 * ```typescript
220 * const backend = yield* GCP.Compute.BackendService("web", {
221 * name: "web-backend",
222 * protocol: "HTTP",
223 * loadBalancingScheme: "EXTERNAL",
224 * timeoutSec: 30,
225 * enableCDN: true,
226 * labels: { env: "prod" },
227 * });
228 * ```
229 *
230 * ### Updating a Backend Service
231 * **Example:** Raise the timeout and enable CDN
232 * ```typescript
233 * const backend = yield* GCP.Compute.BackendService("web", {
234 * name: "web-backend",
235 * timeoutSec: 60,
236 * enableCDN: true,
237 * });
238 * ```
239 *
240 * @resource
241 * @category Compute
242 */
243 export const BackendService = Resource<BackendService>("GCP.Compute.BackendService");
244
245 export class BackendServiceNotResolved extends Data.TaggedError(
246 "GCP.Compute.BackendServiceNotResolved",
247 )<{
248 resourceName: string;
249 }> {}
250
251 const rfc1035 = (name: string): string => {
252 let next = name
253 .toLowerCase()
254 .replace(/[^a-z0-9-]/g, "-")
255 .replace(/-+/g, "-")
256 .replace(/^-+/, "")
257 .replace(/-+$/, "");
258 if (!/^[a-z]/.test(next)) {
259 next = `b${next}`;
260 }
261 next = next.slice(0, 63).replace(/-+$/, "");
262 return next.length > 0 ? next : "backend";
263 };
264
265 const toName = (id: string, name: string | undefined, existing?: string) =>
266 Effect.gen(function* () {
267 if (name !== undefined) return name;
268 if (existing !== undefined) return existing;
269 return rfc1035(
270 yield* createPhysicalName({
271 id,
272 maxLength: 63,
273 lowercase: true,
274 }),
275 );
276 });
277
278 const encodeDescription = (user: string | undefined, labels: Record<string, string>): string => {
279 const packed = Object.entries(labels)
280 .sort(([a], [b]) => a.localeCompare(b))
281 .map(([key, value]) => `${key}=${value}`)
282 .join(" ");
283 const marker = `[alchemy ${packed}]`;
284 return user ? `${marker}\n${user}` : marker;
285 };
286
287 const parseDescription = (
288 description: string | undefined,
289 ): { labels: Record<string, string>; user: string | undefined } => {
290 if (!description?.startsWith("[alchemy ")) {
291 return { labels: {}, user: description };
292 }
293 const end = description.indexOf("]");
294 if (end < 0) return { labels: {}, user: description };
295 const labels: Record<string, string> = {};
296 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
297 const eq = part.indexOf("=");
298 if (eq > 0) {
299 labels[part.slice(0, eq)] = part.slice(eq + 1);
300 }
301 }
302 const rest = description.slice(end + 1).replace(/^\n/, "");
303 return { labels, user: rest.length > 0 ? rest : undefined };
304 };
305
306 const hasOwnershipMarker = (description: string | undefined): boolean =>
307 (description ?? "").startsWith("[alchemy ");
308
309 const userLabels = (
310 labels: Record<string, string | undefined> | null | undefined,
311 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
312
313 const toBackend = (backend: compute.Backend): BackendServiceBackend => ({
314 group: backend.group ?? "",
315 description: backend.description,
316 balancingMode: backend.balancingMode,
317 capacityScaler: backend.capacityScaler,
318 maxRate: backend.maxRate,
319 maxRatePerInstance: backend.maxRatePerInstance,
320 maxUtilization: backend.maxUtilization,
321 failover: backend.failover,
322 });
323
324 const toLogConfig = (
325 logConfig: compute.BackendServiceLogConfig | undefined,
326 ): BackendServiceLogConfigProps | undefined => {
327 if (logConfig === undefined) return undefined;
328 return {
329 enable: logConfig.enable,
330 sampleRate: logConfig.sampleRate,
331 };
332 };
333
334 const toAttrs = (service: compute.BackendService, project: string) => {
335 const decoded = parseDescription(service.description);
336 return {
337 name: service.name ?? "",
338 project,
339 backendServiceId: service.id,
340 selfLink: service.selfLink,
341 creationTimestamp: service.creationTimestamp,
342 fingerprint: service.fingerprint,
343 description: decoded.user,
344 protocol: service.protocol,
345 loadBalancingScheme: service.loadBalancingScheme,
346 timeoutSec: service.timeoutSec,
347 portName: service.portName,
348 enableCDN: service.enableCDN === true,
349 sessionAffinity: service.sessionAffinity,
350 affinityCookieTtlSec: service.affinityCookieTtlSec,
351 healthChecks: [...(service.healthChecks ?? [])],
352 backends: (service.backends ?? []).map(toBackend),
353 connectionDrainingTimeoutSec: service.connectionDraining?.drainingTimeoutSec,
354 compressionMode: service.compressionMode,
355 customRequestHeaders: [...(service.customRequestHeaders ?? [])],
356 customResponseHeaders: [...(service.customResponseHeaders ?? [])],
357 logConfig: toLogConfig(service.logConfig),
358 labels: userLabels(decoded.labels),
359 kind: service.kind,
360 };
361 };
362
363 const sameStringList = (
364 left: readonly string[] | undefined,
365 right: readonly string[] | undefined,
366 ) => JSON.stringify([...(left ?? [])].sort()) === JSON.stringify([...(right ?? [])].sort());
367
368 const backendKey = (backend: BackendServiceBackend) =>
369 JSON.stringify({
370 group: backend.group,
371 description: backend.description ?? "",
372 balancingMode: backend.balancingMode ?? "",
373 capacityScaler: backend.capacityScaler ?? null,
374 maxRate: backend.maxRate ?? null,
375 maxRatePerInstance: backend.maxRatePerInstance ?? null,
376 maxUtilization: backend.maxUtilization ?? null,
377 failover: backend.failover ?? false,
378 });
379
380 const sameBackends = (
381 left: readonly BackendServiceBackend[] | undefined,
382 right: readonly BackendServiceBackend[] | undefined,
383 ) =>
384 JSON.stringify([...(left ?? [])].map(backendKey).sort()) ===
385 JSON.stringify([...(right ?? [])].map(backendKey).sort());
386
387 const sameLogConfig = (
388 left: BackendServiceLogConfigProps | undefined,
389 right: compute.BackendServiceLogConfig | undefined,
390 ) =>
391 (left?.enable ?? false) === (right?.enable ?? false) &&
392 (left?.sampleRate === undefined || left.sampleRate === right?.sampleRate);
393
394 const getByName = (project: string, name: string) =>
395 compute
396 .getBackendServices({ project, backendService: name })
397 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
398
399 const awaitResource = (project: string, name: string) =>
400 getByName(project, name).pipe(
401 Effect.repeat({
402 schedule: Schedule.spaced("1 second"),
403 until: (service) => service !== undefined,
404 times: 8,
405 }),
406 );
407
408 export const BackendServiceProvider = () =>
409 Provider.succeed(BackendService, {
410 stables: [
411 "name",
412 "project",
413 "backendServiceId",
414 "selfLink",
415 "creationTimestamp",
416 "loadBalancingScheme",
417 ],
418
419 diff: Effect.fn(function* ({ news, olds, output }) {
420 if (!isResolved(news)) return undefined;
421 const previousName = olds?.name ?? output?.name;
422 const nextName = news.name ?? previousName;
423 if (news.name !== undefined && previousName !== undefined && news.name !== previousName) {
424 return { action: "replace" as const };
425 }
426 const previousScheme =
427 olds?.loadBalancingScheme ?? output?.loadBalancingScheme ?? DEFAULT_SCHEME;
428 const nextScheme = news.loadBalancingScheme ?? DEFAULT_SCHEME;
429 if (previousScheme !== nextScheme) {
430 return {
431 action: "replace" as const,
432 deleteFirst:
433 previousName !== undefined && (nextName === undefined || nextName === previousName),
434 };
435 }
436 return undefined;
437 }),
438
439 read: Effect.fn(function* ({ id, olds, output }) {
440 const env = yield* GcpEnvironment.current;
441 const name = yield* toName(id, olds?.name, output?.name);
442 const existing = yield* getByName(env.project, name);
443 if (existing === undefined) return undefined;
444 const attrs = toAttrs(existing, env.project);
445 const parsed = parseDescription(existing.description);
446 return (yield* hasAlchemyLabels(id, parsed.labels)) ? attrs : Unowned(attrs);
447 }),
448
449 list: () =>
450 Effect.gen(function* () {
451 const env = yield* GcpEnvironment.current;
452 return yield* compute.listBackendServices
453 .items({ project: env.project, maxResults: 500 })
454 .pipe(
455 Stream.filter((service) => hasOwnershipMarker(service.description)),
456 Stream.map((service) => toAttrs(service, env.project)),
457 Stream.runCollect,
458 Effect.map((chunk) => Array.from(chunk)),
459 );
460 }),
461
462 reconcile: Effect.fn(function* ({ id, news, output }) {
463 const env = yield* GcpEnvironment.current;
464 const name = yield* toName(id, news.name, output?.name);
465 const desiredLabels = {
466 ...toLabels(news.labels),
467 ...(yield* createInternalLabels(id)),
468 };
469 const desiredDescription = encodeDescription(news.description, desiredLabels);
470 const protocol = news.protocol ?? DEFAULT_PROTOCOL;
471 const loadBalancingScheme = news.loadBalancingScheme ?? DEFAULT_SCHEME;
472 const timeoutSec = news.timeoutSec ?? DEFAULT_TIMEOUT_SEC;
473 const enableCDN = news.enableCDN === true;
474 const desiredBackends = (news.backends ?? []).map((backend) => ({
475 group: backend.group,
476 description: backend.description,
477 balancingMode: backend.balancingMode,
478 capacityScaler: backend.capacityScaler,
479 maxRate: backend.maxRate,
480 maxRatePerInstance: backend.maxRatePerInstance,
481 maxUtilization: backend.maxUtilization,
482 failover: backend.failover,
483 }));
484
485 let current = yield* getByName(env.project, name);
486
487 if (current === undefined) {
488 const inserted = yield* compute
489 .insertBackendServices({
490 project: env.project,
491 body: {
492 name,
493 description: desiredDescription,
494 protocol,
495 loadBalancingScheme,
496 timeoutSec,
497 portName: news.portName,
498 enableCDN,
499 sessionAffinity: news.sessionAffinity,
500 affinityCookieTtlSec: news.affinityCookieTtlSec,
501 healthChecks: (news.healthChecks?.length ?? 0) > 0 ? news.healthChecks : undefined,
502 backends: desiredBackends.length > 0 ? desiredBackends : undefined,
503 connectionDraining:
504 news.connectionDrainingTimeoutSec !== undefined
505 ? {
506 drainingTimeoutSec: news.connectionDrainingTimeoutSec,
507 }
508 : undefined,
509 compressionMode: news.compressionMode,
510 customRequestHeaders:
511 (news.customRequestHeaders?.length ?? 0) > 0
512 ? news.customRequestHeaders
513 : undefined,
514 customResponseHeaders:
515 (news.customResponseHeaders?.length ?? 0) > 0
516 ? news.customResponseHeaders
517 : undefined,
518 logConfig: news.logConfig,
519 },
520 })
521 .pipe(
522 Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)),
523 Effect.catchTag("Conflict", () => Effect.undefined),
524 );
525 current =
526 inserted !== undefined
527 ? yield* awaitResource(env.project, name)
528 : yield* getByName(env.project, name);
529 }
530
531 if (current === undefined) {
532 return yield* new BackendServiceNotResolved({ resourceName: name });
533 }
534
535 const timeoutChanged = (current.timeoutSec ?? DEFAULT_TIMEOUT_SEC) !== timeoutSec;
536 const protocolChanged = (current.protocol ?? DEFAULT_PROTOCOL) !== protocol;
537 const descriptionChanged = (current.description ?? "") !== desiredDescription;
538 const enableCDNChanged = (current.enableCDN === true) !== enableCDN;
539 const sessionAffinityChanged =
540 (current.sessionAffinity ?? "NONE") !== (news.sessionAffinity ?? "NONE");
541 const affinityCookieChanged =
542 news.affinityCookieTtlSec !== undefined &&
543 current.affinityCookieTtlSec !== news.affinityCookieTtlSec;
544 const portNameChanged = news.portName !== undefined && current.portName !== news.portName;
545 const healthChecksChanged = !sameStringList(current.healthChecks, news.healthChecks);
546 const backendsChanged = !sameBackends((current.backends ?? []).map(toBackend), news.backends);
547 const drainingChanged =
548 news.connectionDrainingTimeoutSec !== undefined &&
549 current.connectionDraining?.drainingTimeoutSec !== news.connectionDrainingTimeoutSec;
550 const compressionChanged =
551 news.compressionMode !== undefined && current.compressionMode !== news.compressionMode;
552 const requestHeadersChanged =
553 news.customRequestHeaders !== undefined &&
554 !sameStringList(current.customRequestHeaders, news.customRequestHeaders);
555 const responseHeadersChanged =
556 news.customResponseHeaders !== undefined &&
557 !sameStringList(current.customResponseHeaders, news.customResponseHeaders);
558 const logConfigChanged =
559 news.logConfig !== undefined && !sameLogConfig(news.logConfig, current.logConfig);
560
561 if (
562 timeoutChanged ||
563 protocolChanged ||
564 descriptionChanged ||
565 enableCDNChanged ||
566 sessionAffinityChanged ||
567 affinityCookieChanged ||
568 portNameChanged ||
569 healthChecksChanged ||
570 backendsChanged ||
571 drainingChanged ||
572 compressionChanged ||
573 requestHeadersChanged ||
574 responseHeadersChanged ||
575 logConfigChanged
576 ) {
577 const patch: compute.BackendService = {
578 fingerprint: current.fingerprint,
579 };
580 if (timeoutChanged) patch.timeoutSec = timeoutSec;
581 if (protocolChanged) patch.protocol = protocol;
582 if (descriptionChanged) patch.description = desiredDescription;
583 if (enableCDNChanged) patch.enableCDN = enableCDN;
584 if (sessionAffinityChanged) {
585 patch.sessionAffinity = news.sessionAffinity ?? "NONE";
586 }
587 if (affinityCookieChanged) {
588 patch.affinityCookieTtlSec = news.affinityCookieTtlSec;
589 }
590 if (portNameChanged) patch.portName = news.portName;
591 if (healthChecksChanged) patch.healthChecks = news.healthChecks ?? [];
592 if (backendsChanged) patch.backends = desiredBackends;
593 if (drainingChanged) {
594 patch.connectionDraining = {
595 drainingTimeoutSec: news.connectionDrainingTimeoutSec,
596 };
597 }
598 if (compressionChanged) patch.compressionMode = news.compressionMode;
599 if (requestHeadersChanged) {
600 patch.customRequestHeaders = news.customRequestHeaders;
601 }
602 if (responseHeadersChanged) {
603 patch.customResponseHeaders = news.customResponseHeaders;
604 }
605 if (logConfigChanged) patch.logConfig = news.logConfig;
606
607 yield* compute
608 .patchBackendServices({
609 project: env.project,
610 backendService: name,
611 body: patch,
612 })
613 .pipe(Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)));
614 current = yield* awaitResource(env.project, name);
615 if (current === undefined) {
616 return yield* new BackendServiceNotResolved({ resourceName: name });
617 }
618 }
619
620 return toAttrs(current, env.project);
621 }),
622
623 delete: Effect.fn(function* ({ output }) {
624 const env = yield* GcpEnvironment.current;
625 yield* compute
626 .deleteBackendServices({
627 project: env.project,
628 backendService: output.name,
629 })
630 .pipe(
631 // Compute rejects the delete while another operation is still in
632 // flight on the backend service (a just-applied update).
633 Effect.retry({
634 while: (error) => error._tag === "ResourceNotReady",
635 times: 20,
636 schedule: Schedule.spaced("10 seconds"),
637 }),
638 Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)),
639 Effect.catchTag("NotFound", () => Effect.void),
640 );
641 }),
642 });