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

main
ts 448 lines 16.4 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 { waitRegionOperation } from "./operations.ts";
15 import type {
16 TargetTcpProxyLoadBalancingScheme,
17 TargetTcpProxyProxyHeader,
18 } from "./TargetTcpProxy.ts";
19
20 const DEFAULT_PROXY_HEADER: TargetTcpProxyProxyHeader = "NONE";
21
22 export type RegionTargetTcpProxyProps = {
23 /**
24 * TargetTcpProxy name (RFC1035, 1-63 characters). If omitted, a unique
25 * name is generated from the stack, stage, and logical id. Changing it
26 * replaces the resource.
27 */
28 targetTcpProxyName?: string;
29 /**
30 * Region the proxy lives in (e.g. `us-central1`). Immutable — changing
31 * it replaces the resource. `US-CENTRAL1` is accepted and normalized to
32 * `us-central1`.
33 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
34 */
35 region?: string;
36 /**
37 * Optional description. Alchemy ownership is stored in a `[alchemy …]`
38 * prefix so `list` / nuke can find resources (Compute RegionTargetTcpProxy
39 * has no labels field). The regional API cannot update this field —
40 * changing it replaces the resource.
41 */
42 description?: string;
43 /**
44 * Regional backend service this proxy routes to. Accepts a
45 * RegionBackendService self-link, a
46 * `projects/{project}/regions/{region}/backendServices/{name}` path, or
47 * the BackendService name. Changing it replaces the resource.
48 */
49 service: string;
50 /**
51 * Proxy header prepended before sending data to the backend (`NONE` or
52 * `PROXY_V1`). Changing it replaces the resource.
53 * @default "NONE"
54 */
55 proxyHeader?: TargetTcpProxyProxyHeader | (string & {});
56 /**
57 * Bind inbound traffic to the forwarding-rule address. Only applies when
58 * the referencing forwarding rule uses `INTERNAL_SELF_MANAGED`. Changing
59 * it replaces the resource.
60 * @default false
61 */
62 proxyBind?: boolean;
63 /**
64 * Load balancing scheme (`INTERNAL_MANAGED`, `EXTERNAL_MANAGED`).
65 * Changing it replaces the resource.
66 */
67 loadBalancingScheme?: TargetTcpProxyLoadBalancingScheme | (string & {});
68 };
69
70 export type RegionTargetTcpProxy = Resource<
71 "GCP.Compute.RegionTargetTcpProxy",
72 RegionTargetTcpProxyProps,
73 {
74 /** TargetTcpProxy name. */
75 targetTcpProxyName: string;
76 /** Project id. */
77 project: string;
78 /** Region short name (`us-central1`). */
79 region: string;
80 /** User description with the Alchemy ownership prefix stripped. */
81 description: string | undefined;
82 /** URL of the attached BackendService. */
83 service: string;
84 /** Proxy header prepended to backend connections. */
85 proxyHeader: string | undefined;
86 /** Whether Envoy inbound bind is enabled. */
87 proxyBind: boolean;
88 /** Load balancing scheme, if set. */
89 loadBalancingScheme: string | undefined;
90 /** Server-defined URL. */
91 selfLink: string | undefined;
92 /** Server-assigned numeric id. */
93 targetTcpProxyId: string | undefined;
94 /** RFC3339 creation timestamp. */
95 creationTimestamp: string | undefined;
96 /** Resource kind. */
97 kind: string | undefined;
98 },
99 never,
100 Providers
101 >;
102
103 /**
104 * A regional Compute Engine target TCP proxy.
105 *
106 * Regional target TCP proxies are referenced by regional forwarding rules
107 * and point at a regional backend service. They are a component of
108 * regional proxy Network Load Balancers. This resource maps to the
109 * `regionTargetTcpProxies` collection (the global `targetTcpProxies`
110 * collection is `GCP.Compute.TargetTcpProxy`). Compute RegionTargetTcpProxy
111 * has no labels field and no in-place update API (`setBackendService` exists
112 * only on the global collection). Alchemy ownership is stored in the
113 * description so nuke can find leaked proxies. Changing the backend,
114 * proxy header, description, `proxyBind`, or load-balancing scheme
115 * deletes and recreates the proxy so the observed backend always matches.
116 *
117 * ### Creating a Regional Target TCP Proxy
118 * **Example:** Generated name in front of a TCP backend service
119 * ```typescript
120 * const backend = yield* GCP.Compute.RegionBackendService("tcp", {
121 * region: "us-central1",
122 * protocol: "TCP",
123 * loadBalancingScheme: "INTERNAL_MANAGED",
124 * });
125 * const proxy = yield* GCP.Compute.RegionTargetTcpProxy("tcp", {
126 * region: "us-central1",
127 * service: backend.name,
128 * });
129 * ```
130 *
131 * @resource
132 * @category Compute
133 */
134 export const RegionTargetTcpProxy = Resource<RegionTargetTcpProxy>(
135 "GCP.Compute.RegionTargetTcpProxy",
136 );
137
138 export class RegionTargetTcpProxyNotResolved extends Data.TaggedError(
139 "GCP.Compute.RegionTargetTcpProxyNotResolved",
140 )<{
141 targetTcpProxyName: string;
142 region: string;
143 }> {}
144
145 export class RegionTargetTcpProxyStillExists extends Data.TaggedError(
146 "GCP.Compute.RegionTargetTcpProxyStillExists",
147 )<{
148 targetTcpProxyName: string;
149 region: string;
150 }> {}
151
152 const lastSegment = (value: string | undefined) => {
153 if (value === undefined || value.length === 0) return "";
154 const trimmed = value.replace(/\/+$/, "");
155 const parts = trimmed.split("/");
156 return parts[parts.length - 1] || trimmed;
157 };
158
159 const normalizeRegion = (region: string | undefined, defaultRegion: string) =>
160 lastSegment(region ?? defaultRegion).toLowerCase();
161
162 const toName = (id: string, name: string | undefined, existing?: string) =>
163 Effect.gen(function* () {
164 if (name !== undefined) return name;
165 if (existing !== undefined) return existing;
166 const generated = yield* createPhysicalName({
167 id,
168 maxLength: 63,
169 lowercase: true,
170 });
171 return /^[a-z]/.test(generated) ? generated : `t${generated}`.slice(0, 63);
172 });
173
174 const encodeDescription = (
175 labels: Record<string, string>,
176 description: string | undefined,
177 ): string => {
178 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
179 return description ? `${marker}\n${description}` : marker;
180 };
181
182 const parseDescription = (
183 description: string | undefined,
184 ): {
185 labels: Record<string, string>;
186 description: string | undefined;
187 } => {
188 if (!description?.startsWith("[alchemy ")) {
189 return { labels: {}, description };
190 }
191 const end = description.indexOf("]");
192 if (end < 0) return { labels: {}, description };
193 const labels: Record<string, string> = {};
194 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
195 const eq = part.indexOf("=");
196 if (eq > 0) {
197 labels[part.slice(0, eq)] = part.slice(eq + 1);
198 }
199 }
200 const rest = description.slice(end + 1).replace(/^\n/, "");
201 return { labels, description: rest.length > 0 ? rest : undefined };
202 };
203
204 const resourceTail = (value: string | undefined): string => lastSegment(value);
205
206 const toBackendServiceRef = (project: string, region: string, service: string): string => {
207 if (service.includes("/")) return service;
208 return `projects/${project}/regions/${region}/backendServices/${service}`;
209 };
210
211 const toAttrs = (proxy: compute.TargetTcpProxy, project: string) => {
212 const parsed = parseDescription(proxy.description);
213 return {
214 targetTcpProxyName: proxy.name ?? proxy.id ?? "",
215 project,
216 region: lastSegment(proxy.region).toLowerCase(),
217 description: parsed.description,
218 service: proxy.service ?? "",
219 proxyHeader: proxy.proxyHeader,
220 proxyBind: proxy.proxyBind === true,
221 loadBalancingScheme: proxy.loadBalancingScheme,
222 selfLink: proxy.selfLink,
223 targetTcpProxyId: proxy.id,
224 creationTimestamp: proxy.creationTimestamp,
225 kind: proxy.kind,
226 };
227 };
228
229 const getByName = (project: string, region: string, targetTcpProxy: string) =>
230 compute
231 .getRegionTargetTcpProxies({ project, region, targetTcpProxy })
232 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
233
234 const waitUntilGone = (project: string, region: string, targetTcpProxyName: string) =>
235 getByName(project, region, targetTcpProxyName).pipe(
236 Effect.flatMap((proxy) =>
237 proxy === undefined
238 ? Effect.void
239 : Effect.fail(
240 new RegionTargetTcpProxyStillExists({
241 targetTcpProxyName,
242 region,
243 }),
244 ),
245 ),
246 Effect.retry({
247 while: (error) => error._tag === "GCP.Compute.RegionTargetTcpProxyStillExists",
248 times: 18,
249 schedule: Schedule.spaced("2 seconds"),
250 }),
251 );
252
253 const immutableChanged = (
254 news: RegionTargetTcpProxyProps,
255 olds: RegionTargetTcpProxyProps | undefined,
256 output: RegionTargetTcpProxy["Attributes"] | undefined,
257 ) => {
258 const previousDescription = olds?.description ?? output?.description ?? "";
259 if ((news.description ?? "") !== previousDescription) return true;
260 const previousService = resourceTail(olds?.service ?? output?.service);
261 const nextService = resourceTail(news.service);
262 if (previousService.length > 0 && nextService.length > 0 && previousService !== nextService) {
263 return true;
264 }
265 const previousHeader = olds?.proxyHeader ?? output?.proxyHeader ?? DEFAULT_PROXY_HEADER;
266 const nextHeader = news.proxyHeader ?? DEFAULT_PROXY_HEADER;
267 if (previousHeader !== nextHeader) return true;
268 const previousBind = olds?.proxyBind ?? output?.proxyBind ?? false;
269 if ((news.proxyBind ?? false) !== previousBind) return true;
270 const previousScheme = olds?.loadBalancingScheme ?? output?.loadBalancingScheme ?? "";
271 if ((news.loadBalancingScheme ?? "") !== previousScheme) return true;
272 return false;
273 };
274
275 export const RegionTargetTcpProxyProvider = () =>
276 Provider.succeed(RegionTargetTcpProxy, {
277 stables: [
278 "targetTcpProxyName",
279 "project",
280 "region",
281 "targetTcpProxyId",
282 "selfLink",
283 "creationTimestamp",
284 ],
285
286 diff: Effect.fn(function* ({ news, olds, output }) {
287 if (!isResolved(news)) return undefined;
288 const env = yield* GcpEnvironment.current;
289 const previous = olds?.targetTcpProxyName ?? output?.targetTcpProxyName;
290 const next = news.targetTcpProxyName ?? previous;
291 const previousRegion = normalizeRegion(olds?.region ?? output?.region, env.region);
292 const nextRegion = normalizeRegion(news.region ?? output?.region, env.region);
293 const regionChanged = previousRegion !== nextRegion;
294 const nameChanged = previous !== undefined && next !== undefined && previous !== next;
295 if (nameChanged || regionChanged || immutableChanged(news, olds, output)) {
296 return {
297 action: "replace" as const,
298 deleteFirst: !regionChanged,
299 };
300 }
301 return undefined;
302 }),
303
304 read: Effect.fn(function* ({ id, olds, output }) {
305 const env = yield* GcpEnvironment.current;
306 const targetTcpProxyName = yield* toName(
307 id,
308 olds?.targetTcpProxyName,
309 output?.targetTcpProxyName,
310 );
311 const region = normalizeRegion(olds?.region ?? output?.region, env.region);
312 const existing = yield* getByName(env.project, region, targetTcpProxyName);
313 if (existing === undefined) return undefined;
314 const attrs = toAttrs(existing, env.project);
315 const { labels } = parseDescription(existing.description);
316 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
317 }),
318
319 list: () =>
320 Effect.gen(function* () {
321 const env = yield* GcpEnvironment.current;
322 const pages = yield* compute.aggregatedListTargetTcpProxies
323 .pages({
324 project: env.project,
325 returnPartialSuccess: true,
326 maxResults: 500,
327 })
328 .pipe(Stream.runCollect);
329 return Array.from(pages).flatMap((page) =>
330 Object.values(page.items ?? {}).flatMap((scoped) =>
331 (scoped?.targetTcpProxies ?? [])
332 .filter((proxy) => (proxy.region ?? "").length > 0)
333 .filter((proxy) => {
334 const { labels } = parseDescription(proxy.description);
335 return Object.keys(labels).some((key) => key.startsWith("alchemy-"));
336 })
337 .map((proxy) => toAttrs(proxy, env.project)),
338 ),
339 );
340 }),
341
342 reconcile: Effect.fn(function* ({ id, news, output }) {
343 const env = yield* GcpEnvironment.current;
344 const targetTcpProxyName = yield* toName(
345 id,
346 news.targetTcpProxyName,
347 output?.targetTcpProxyName,
348 );
349 const region = normalizeRegion(news.region ?? output?.region, env.region);
350 const ownership = yield* createInternalLabels(id);
351 const desiredDescription = encodeDescription(ownership, news.description);
352 const desiredService = toBackendServiceRef(env.project, region, news.service);
353 const desiredHeader = news.proxyHeader ?? DEFAULT_PROXY_HEADER;
354 const desiredBind = news.proxyBind ?? false;
355 const desiredScheme = news.loadBalancingScheme ?? "";
356
357 const insertProxy = () => {
358 const body: compute.TargetTcpProxy = {
359 name: targetTcpProxyName,
360 description: desiredDescription,
361 service: desiredService,
362 proxyHeader: desiredHeader,
363 };
364 if (news.proxyBind !== undefined) {
365 body.proxyBind = news.proxyBind;
366 }
367 if (news.loadBalancingScheme !== undefined) {
368 body.loadBalancingScheme = news.loadBalancingScheme;
369 }
370 return compute
371 .insertRegionTargetTcpProxies({
372 project: env.project,
373 region,
374 body,
375 })
376 .pipe(
377 Effect.flatMap((operation) =>
378 waitRegionOperation(env.project, region, operation, {
379 ignore: ["RESOURCE_ALREADY_EXISTS"],
380 }),
381 ),
382 Effect.catchTag("Conflict", () => Effect.undefined),
383 );
384 };
385
386 const deleteProxy = () =>
387 compute
388 .deleteRegionTargetTcpProxies({
389 project: env.project,
390 region,
391 targetTcpProxy: targetTcpProxyName,
392 })
393 .pipe(
394 Effect.flatMap((operation) => waitRegionOperation(env.project, region, operation)),
395 Effect.catchTag("NotFound", () => Effect.void),
396 );
397
398 let current = yield* getByName(env.project, region, targetTcpProxyName);
399
400 // Regional target TCP proxies have no setBackendService API. If the
401 // observed backend (or other immutable fields) drifted, delete then
402 // insert so update-as-well-as-replace converges.
403 if (current !== undefined) {
404 const serviceChanged = resourceTail(current.service) !== resourceTail(desiredService);
405 const headerChanged = (current.proxyHeader ?? DEFAULT_PROXY_HEADER) !== desiredHeader;
406 const descriptionChanged = (current.description ?? "") !== desiredDescription;
407 const bindChanged = (current.proxyBind === true) !== desiredBind;
408 const schemeChanged = (current.loadBalancingScheme ?? "") !== desiredScheme;
409 if (serviceChanged || headerChanged || descriptionChanged || bindChanged || schemeChanged) {
410 yield* deleteProxy();
411 yield* waitUntilGone(env.project, region, targetTcpProxyName);
412 current = undefined;
413 }
414 }
415
416 if (current === undefined) {
417 yield* insertProxy();
418 current = yield* getByName(env.project, region, targetTcpProxyName);
419 }
420
421 if (current === undefined) {
422 return yield* new RegionTargetTcpProxyNotResolved({
423 targetTcpProxyName,
424 region,
425 });
426 }
427
428 return toAttrs(current, env.project);
429 }),
430
431 delete: Effect.fn(function* ({ output }) {
432 const env = yield* GcpEnvironment.current;
433 const region = normalizeRegion(output.region, env.region);
434 const operation = yield* compute
435 .deleteRegionTargetTcpProxies({
436 project: env.project,
437 region,
438 targetTcpProxy: output.targetTcpProxyName,
439 })
440 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
441 if (operation !== undefined) {
442 yield* waitRegionOperation(env.project, region, operation).pipe(
443 Effect.catchTag("NotFound", () => Effect.void),
444 );
445 }
446 yield* waitUntilGone(env.project, region, output.targetTcpProxyName);
447 }),
448 });