@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 474 lines 16.6 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 TargetInstanceNatPolicy = compute.TargetInstanceNatPolicyEnum;
17
18 const DEFAULT_ZONE = "us-central1-a";
19 const DEFAULT_NAT_POLICY: TargetInstanceNatPolicy = "NO_NAT";
20
21 export type TargetInstanceProps = {
22 /**
23 * TargetInstance name (RFC1035, 1-63 characters). If omitted, a unique
24 * name is generated from the stack, stage, and logical id. Changing it
25 * replaces the resource.
26 */
27 targetInstanceName?: string;
28 /**
29 * Zone the target instance lives in (e.g. `us-central1-a`). Must match
30 * the backend VM's zone. Immutable — changing it replaces the resource.
31 * When omitted, Alchemy uses the zone from `instance` if that value is a
32 * URL, otherwise `us-central1-a`.
33 * @default "us-central1-a"
34 */
35 zone?: string;
36 /**
37 * Backend VM that terminates traffic. Accepts an instance name, a
38 * `projects/{project}/zones/{zone}/instances/{instance}` path, or a
39 * self-link. Immutable — changing it replaces the resource.
40 */
41 instance: string;
42 /**
43 * Optional description. Alchemy ownership is stored in a `[alchemy …]`
44 * prefix so `list` / nuke can find resources (Compute TargetInstance has
45 * no labels field). Immutable — changing it replaces the resource.
46 */
47 description?: string;
48 /**
49 * Network used to forward traffic. Accepts a network name
50 * (`default`), a partial URL (`global/networks/default`), or a full
51 * self-link. When omitted, traffic is forwarded on the VM's default
52 * network interface. Immutable — changing it replaces the resource.
53 */
54 network?: string;
55 /**
56 * NAT policy applied to forwarded packets. Must be `NO_NAT` — protocol
57 * forwarding preserves the destination IP of the forwarding rule.
58 * Immutable — changing it replaces the resource.
59 * @default "NO_NAT"
60 */
61 natPolicy?: TargetInstanceNatPolicy | (string & {});
62 /**
63 * Cloud Armor security policy URL. Updated in place via
64 * `setSecurityPolicy`. Pass an empty string to detach.
65 */
66 securityPolicy?: string;
67 };
68
69 export type TargetInstance = Resource<
70 "GCP.Compute.TargetInstance",
71 TargetInstanceProps,
72 {
73 /** TargetInstance name. */
74 targetInstanceName: string;
75 /** Project id. */
76 project: string;
77 /** Zone short name (e.g. `us-central1-a`). */
78 zone: string;
79 /** User description with the Alchemy ownership prefix stripped. */
80 description: string | undefined;
81 /** URL of the backend VM. */
82 instance: string;
83 /** Network URL used for forwarding, if set. */
84 network: string | undefined;
85 /** NAT policy (`NO_NAT`). */
86 natPolicy: string | undefined;
87 /** Attached Cloud Armor security policy URL, if any. */
88 securityPolicy: string | undefined;
89 /** Server-defined URL. */
90 selfLink: string | undefined;
91 /** Server-assigned numeric id. */
92 targetInstanceId: string | undefined;
93 /** RFC3339 creation timestamp. */
94 creationTimestamp: string | undefined;
95 /** Resource kind. */
96 kind: string | undefined;
97 },
98 never,
99 Providers
100 >;
101
102 /**
103 * A zonal Compute Engine target instance.
104 *
105 * Target instances terminate protocol-forwarding traffic (ESP, AH, TCP,
106 * UDP) for one or more forwarding rules. The backend VM should enable IP
107 * forwarding (`canIpForward`). Compute TargetInstance has no labels field —
108 * Alchemy ownership is stored in the description so nuke can find leaked
109 * resources. Name, zone, instance, network, NAT policy, and description are
110 * immutable; only `securityPolicy` updates in place.
111 *
112 * ### Creating a Target Instance
113 * **Example:** Generated name in front of a VM
114 * ```typescript
115 * const vm = yield* GCP.Compute.Instance("web", {
116 * zone: "us-central1-a",
117 * canIpForward: true,
118 * });
119 * const target = yield* GCP.Compute.TargetInstance("protocol", {
120 * instance: vm.instanceName,
121 * zone: vm.zone,
122 * });
123 * ```
124 *
125 * **Example:** Explicit name, description, and network
126 * ```typescript
127 * const target = yield* GCP.Compute.TargetInstance("protocol", {
128 * targetInstanceName: "app-protocol",
129 * description: "esp frontend",
130 * instance: vm.selfLink,
131 * zone: "us-central1-a",
132 * network: "default",
133 * natPolicy: "NO_NAT",
134 * });
135 * ```
136 *
137 * @resource
138 * @category Compute
139 */
140 export const TargetInstance = Resource<TargetInstance>("GCP.Compute.TargetInstance");
141
142 export class TargetInstanceNotResolved extends Data.TaggedError(
143 "GCP.Compute.TargetInstanceNotResolved",
144 )<{
145 targetInstanceName: string;
146 zone: string;
147 }> {}
148
149 export class TargetInstanceStillExists extends Data.TaggedError(
150 "GCP.Compute.TargetInstanceStillExists",
151 )<{
152 targetInstanceName: string;
153 zone: string;
154 }> {}
155
156 const lastSegment = (value: string | undefined): string => {
157 if (value === undefined || value.length === 0) return "";
158 const parts = value.split("/").filter((part) => part.length > 0);
159 return parts[parts.length - 1] ?? "";
160 };
161
162 const zoneFromUrl = (value: string | undefined): string | undefined => {
163 if (value === undefined || value.length === 0) return undefined;
164 const parts = value.split("/").filter((part) => part.length > 0);
165 const index = parts.indexOf("zones");
166 if (index >= 0 && parts[index + 1] !== undefined) {
167 return parts[index + 1];
168 }
169 return undefined;
170 };
171
172 const rfc1035 = (name: string): string => {
173 let next = name
174 .toLowerCase()
175 .replace(/[^a-z0-9-]/g, "-")
176 .replace(/-+/g, "-")
177 .replace(/^-+|-+$/g, "");
178 if (!/^[a-z]/.test(next)) next = `t${next}`;
179 next = next.slice(0, 63).replace(/-+$/g, "");
180 return next.length > 0 ? next : "target";
181 };
182
183 const toName = (id: string, name: string | undefined, existing?: string) =>
184 Effect.gen(function* () {
185 if (name !== undefined) return name;
186 if (existing !== undefined) return existing;
187 return rfc1035(
188 yield* createPhysicalName({
189 id,
190 maxLength: 63,
191 lowercase: true,
192 }),
193 );
194 });
195
196 const encodeDescription = (
197 labels: Record<string, string>,
198 description: string | undefined,
199 ): string => {
200 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
201 return description ? `${marker}\n${description}` : marker;
202 };
203
204 const parseDescription = (
205 description: string | undefined,
206 ): {
207 labels: Record<string, string>;
208 description: string | undefined;
209 } => {
210 if (!description?.startsWith("[alchemy ")) {
211 return { labels: {}, description };
212 }
213 const end = description.indexOf("]");
214 if (end < 0) return { labels: {}, description };
215 const labels: Record<string, string> = {};
216 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
217 const eq = part.indexOf("=");
218 if (eq > 0) {
219 labels[part.slice(0, eq)] = part.slice(eq + 1);
220 }
221 }
222 const rest = description.slice(end + 1).replace(/^\n/, "");
223 return { labels, description: rest.length > 0 ? rest : undefined };
224 };
225
226 const toInstanceRef = (project: string, zone: string, instance: string) => {
227 if (instance.includes("/")) return instance;
228 return `projects/${project}/zones/${zone}/instances/${instance}`;
229 };
230
231 const toNetworkRef = (project: string, network: string | undefined) => {
232 if (network === undefined || network.length === 0) return undefined;
233 if (network.includes("/")) {
234 return network.startsWith("projects/") || network.startsWith("http")
235 ? network
236 : `projects/${project}/${network.replace(/^\//, "")}`;
237 }
238 return `projects/${project}/global/networks/${network}`;
239 };
240
241 const resolveZone = (news: { zone?: string; instance?: string }, fallback?: string) =>
242 lastSegment(news.zone) || zoneFromUrl(news.instance) || lastSegment(fallback) || DEFAULT_ZONE;
243
244 const toAttrs = (target: compute.TargetInstance, project: string) => {
245 const parsed = parseDescription(target.description);
246 return {
247 targetInstanceName: target.name ?? target.id ?? "",
248 project,
249 zone: lastSegment(target.zone) || zoneFromUrl(target.selfLink) || "",
250 description: parsed.description,
251 instance: target.instance ?? "",
252 network: target.network,
253 natPolicy: target.natPolicy,
254 securityPolicy: target.securityPolicy,
255 selfLink: target.selfLink,
256 targetInstanceId: target.id,
257 creationTimestamp: target.creationTimestamp,
258 kind: target.kind,
259 };
260 };
261
262 const getByName = (project: string, zone: string, targetInstance: string) =>
263 compute
264 .getTargetInstances({ project, zone, targetInstance })
265 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
266
267 const waitTargetGone = (project: string, zone: string, targetInstanceName: string) =>
268 getByName(project, zone, targetInstanceName).pipe(
269 Effect.flatMap((existing) =>
270 existing === undefined
271 ? Effect.void
272 : Effect.fail(new TargetInstanceStillExists({ targetInstanceName, zone })),
273 ),
274 Effect.retry({
275 while: (error) => error._tag === "GCP.Compute.TargetInstanceStillExists",
276 times: 8,
277 schedule: Schedule.spaced("1 second"),
278 }),
279 );
280
281 const requireTarget = (project: string, zone: string, targetInstanceName: string) =>
282 getByName(project, zone, targetInstanceName).pipe(
283 Effect.flatMap((existing) =>
284 existing !== undefined
285 ? Effect.succeed(existing)
286 : Effect.fail(new TargetInstanceNotResolved({ targetInstanceName, zone })),
287 ),
288 Effect.retry({
289 while: (error) => error._tag === "GCP.Compute.TargetInstanceNotResolved",
290 schedule: Schedule.spaced("1 second"),
291 times: 8,
292 }),
293 );
294
295 export const TargetInstanceProvider = () =>
296 Provider.succeed(TargetInstance, {
297 stables: [
298 "targetInstanceName",
299 "project",
300 "zone",
301 "instance",
302 "network",
303 "natPolicy",
304 "targetInstanceId",
305 "selfLink",
306 "creationTimestamp",
307 ],
308
309 diff: Effect.fn(function* ({ news, olds, output }) {
310 if (!isResolved(news)) return undefined;
311 const previousName = olds?.targetInstanceName ?? output?.targetInstanceName;
312 const nextName = news.targetInstanceName ?? previousName;
313 const previousZone = resolveZone(
314 { zone: olds?.zone ?? output?.zone, instance: olds?.instance },
315 output?.zone,
316 );
317 const nextZone = resolveZone(news, previousZone);
318 const previousInstance = lastSegment(olds?.instance ?? output?.instance);
319 const nextInstance = lastSegment(news.instance);
320 const previousNetwork = lastSegment(olds?.network ?? output?.network);
321 const nextNetwork = news.network !== undefined ? lastSegment(news.network) : previousNetwork;
322 const previousNat = olds?.natPolicy ?? output?.natPolicy ?? DEFAULT_NAT_POLICY;
323 const nextNat = news.natPolicy ?? DEFAULT_NAT_POLICY;
324 const previousDescription = olds?.description ?? output?.description ?? "";
325 const nextDescription = news.description ?? "";
326
327 const replace =
328 (previousName !== undefined && nextName !== undefined && previousName !== nextName) ||
329 previousZone !== nextZone ||
330 (previousInstance.length > 0 &&
331 nextInstance.length > 0 &&
332 previousInstance !== nextInstance) ||
333 (news.network !== undefined && previousNetwork !== nextNetwork) ||
334 previousNat !== nextNat ||
335 previousDescription !== nextDescription;
336
337 if (!replace) return undefined;
338 return {
339 action: "replace" as const,
340 deleteFirst:
341 previousName !== undefined && nextName !== undefined && previousName === nextName,
342 };
343 }),
344
345 read: Effect.fn(function* ({ id, olds, output }) {
346 const env = yield* GcpEnvironment.current;
347 const targetInstanceName = yield* toName(
348 id,
349 olds?.targetInstanceName,
350 output?.targetInstanceName,
351 );
352 const zone = resolveZone(
353 { zone: olds?.zone ?? output?.zone, instance: olds?.instance },
354 output?.zone,
355 );
356 const existing = yield* getByName(env.project, zone, targetInstanceName);
357 if (existing === undefined) return undefined;
358 const attrs = toAttrs(existing, env.project);
359 const { labels } = parseDescription(existing.description);
360 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
361 }),
362
363 list: () =>
364 Effect.gen(function* () {
365 const env = yield* GcpEnvironment.current;
366 const pages = yield* compute.aggregatedListTargetInstances
367 .pages({
368 project: env.project,
369 returnPartialSuccess: true,
370 maxResults: 500,
371 })
372 .pipe(Stream.runCollect);
373 return Array.from(pages).flatMap((page) =>
374 Object.values(page.items ?? {}).flatMap((scoped) =>
375 (scoped?.targetInstances ?? [])
376 .filter((item) => {
377 const { labels } = parseDescription(item.description);
378 return Object.keys(labels).some((key) => key.startsWith("alchemy-"));
379 })
380 .map((item) => toAttrs(item, env.project)),
381 ),
382 );
383 }),
384
385 reconcile: Effect.fn(function* ({ id, news, output }) {
386 const env = yield* GcpEnvironment.current;
387 const targetInstanceName = yield* toName(
388 id,
389 news.targetInstanceName,
390 output?.targetInstanceName,
391 );
392 const zone = resolveZone(news, output?.zone);
393 const ownership = yield* createInternalLabels(id);
394 const desiredDescription = encodeDescription(ownership, news.description);
395 const desiredInstance = toInstanceRef(env.project, zone, news.instance);
396 const desiredNetwork = toNetworkRef(env.project, news.network);
397 const desiredNat = news.natPolicy ?? DEFAULT_NAT_POLICY;
398
399 let current = yield* getByName(env.project, zone, targetInstanceName);
400
401 if (current === undefined) {
402 const body: compute.TargetInstance = {
403 name: targetInstanceName,
404 description: desiredDescription,
405 instance: desiredInstance,
406 natPolicy: desiredNat,
407 };
408 if (desiredNetwork !== undefined) {
409 body.network = desiredNetwork;
410 }
411 yield* compute
412 .insertTargetInstances({
413 project: env.project,
414 zone,
415 body,
416 })
417 .pipe(
418 Effect.flatMap((operation) => waitZoneOperation(env.project, zone, operation)),
419 Effect.catchTag("Conflict", () => Effect.undefined),
420 );
421 current = yield* requireTarget(env.project, zone, targetInstanceName);
422 }
423
424 if (current === undefined) {
425 return yield* new TargetInstanceNotResolved({
426 targetInstanceName,
427 zone,
428 });
429 }
430
431 if (news.securityPolicy !== undefined) {
432 const observedPolicy = lastSegment(current.securityPolicy);
433 const desiredPolicy = lastSegment(news.securityPolicy);
434 if (observedPolicy !== desiredPolicy) {
435 yield* compute
436 .setSecurityPolicyTargetInstances({
437 project: env.project,
438 zone,
439 targetInstance: targetInstanceName,
440 body: { securityPolicy: news.securityPolicy },
441 })
442 .pipe(Effect.flatMap((operation) => waitZoneOperation(env.project, zone, operation)));
443 current = yield* requireTarget(env.project, zone, targetInstanceName);
444 }
445 }
446
447 return toAttrs(current, env.project);
448 }),
449
450 delete: Effect.fn(function* ({ output }) {
451 const env = yield* GcpEnvironment.current;
452 const zone = lastSegment(output.zone) || DEFAULT_ZONE;
453 const operation = yield* compute
454 .deleteTargetInstances({
455 project: env.project,
456 zone,
457 targetInstance: output.targetInstanceName,
458 })
459 .pipe(
460 Effect.retry({
461 while: (error) => error._tag === "Conflict",
462 times: 8,
463 schedule: Schedule.spaced("2 seconds"),
464 }),
465 Effect.catchTag("NotFound", () => Effect.undefined),
466 );
467 if (operation !== undefined) {
468 yield* waitZoneOperation(env.project, zone, operation, {
469 ignore: ["RESOURCE_NOT_FOUND"],
470 }).pipe(Effect.catchTag("NotFound", () => Effect.void));
471 }
472 yield* waitTargetGone(env.project, zone, output.targetInstanceName);
473 }),
474 });