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

main
ts 375 lines 13.3 KB
Raw
1 import * as compute from "@distilled.cloud/gcp/compute_v1";
2 import { unownedUnlessPrevious } 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 Stream from "effect/Stream";
10 import { GcpEnvironment } from "../Environment.ts";
11 import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
12 import type { Providers } from "../Providers.ts";
13 import { waitGlobalOperation } from "./operations.ts";
14
15 export type TargetTcpProxyProxyHeader = compute.TargetTcpProxyProxyHeaderEnum;
16 export type TargetTcpProxyLoadBalancingScheme = compute.TargetTcpProxyLoadBalancingSchemeEnum;
17
18 const DEFAULT_PROXY_HEADER: TargetTcpProxyProxyHeader = "NONE";
19
20 export type TargetTcpProxyProps = {
21 /**
22 * TargetTcpProxy name (RFC1035, 1-63 characters). If omitted, a unique
23 * name is generated from the stack, stage, and logical id. Changing it
24 * replaces the resource.
25 */
26 targetTcpProxyName?: string;
27 /**
28 * Optional description. Alchemy ownership is stored in a `[alchemy …]`
29 * prefix so `list` / nuke can find resources (Compute TargetTcpProxy has
30 * no labels field). The API cannot update this field — changing it
31 * replaces the resource.
32 */
33 description?: string;
34 /**
35 * Backend service this proxy routes to. Accepts a BackendService
36 * self-link, a `projects/{project}/global/backendServices/{name}` path,
37 * or the BackendService name.
38 */
39 service: string;
40 /**
41 * Proxy header prepended before sending data to the backend (`NONE` or
42 * `PROXY_V1`).
43 * @default "NONE"
44 */
45 proxyHeader?: TargetTcpProxyProxyHeader | (string & {});
46 /**
47 * Bind inbound traffic to the forwarding-rule address. Only applies when
48 * the referencing forwarding rule uses `INTERNAL_SELF_MANAGED`. Changing
49 * it replaces the resource.
50 * @default false
51 */
52 proxyBind?: boolean;
53 /**
54 * Load balancing scheme (`EXTERNAL`, `EXTERNAL_MANAGED`,
55 * `INTERNAL_MANAGED`). Changing it replaces the resource.
56 */
57 loadBalancingScheme?: TargetTcpProxyLoadBalancingScheme | (string & {});
58 };
59
60 export type TargetTcpProxy = Resource<
61 "GCP.Compute.TargetTcpProxy",
62 TargetTcpProxyProps,
63 {
64 /** TargetTcpProxy name. */
65 targetTcpProxyName: string;
66 /** Project id. */
67 project: string;
68 /** User description with the Alchemy ownership prefix stripped. */
69 description: string | undefined;
70 /** URL of the attached BackendService. */
71 service: string;
72 /** Proxy header prepended to backend connections. */
73 proxyHeader: string | undefined;
74 /** Whether Envoy inbound bind is enabled. */
75 proxyBind: boolean;
76 /** Load balancing scheme, if set. */
77 loadBalancingScheme: string | undefined;
78 /** Server-defined URL. */
79 selfLink: string | undefined;
80 /** Server-assigned numeric id. */
81 targetTcpProxyId: string | undefined;
82 /** RFC3339 creation timestamp. */
83 creationTimestamp: string | undefined;
84 /** Resource kind. */
85 kind: string | undefined;
86 },
87 never,
88 Providers
89 >;
90
91 /**
92 * A global Compute Engine target TCP proxy.
93 *
94 * Target TCP proxies are referenced by global forwarding rules and point
95 * at a backend service. They are a component of Proxy Network Load
96 * Balancers (classic and global external). This resource maps to the
97 * global `targetTcpProxies` collection (`regionTargetTcpProxies` is a
98 * separate resource). Compute TargetTcpProxy has no labels field —
99 * Alchemy ownership is stored in the description so nuke can find leaked
100 * proxies.
101 *
102 * The API can update the backend service and proxy header in place.
103 * `targetTcpProxyName`, `description`, `proxyBind`, and
104 * `loadBalancingScheme` replace the resource.
105 *
106 * ### Creating a Target TCP Proxy
107 * **Example:** Generated name in front of a TCP backend service
108 * ```typescript
109 * const backend = yield* GCP.Compute.BackendService("tcp", {
110 * protocol: "TCP",
111 * loadBalancingScheme: "EXTERNAL",
112 * });
113 * const proxy = yield* GCP.Compute.TargetTcpProxy("tcp", {
114 * service: backend.name,
115 * });
116 * ```
117 *
118 * **Example:** Explicit name, PROXY protocol, and description
119 * ```typescript
120 * const proxy = yield* GCP.Compute.TargetTcpProxy("tcp", {
121 * targetTcpProxyName: "app-tcp",
122 * description: "public tcp frontend",
123 * service: backend.selfLink,
124 * proxyHeader: "PROXY_V1",
125 * });
126 * ```
127 *
128 * ### Updating a Target TCP Proxy
129 * **Example:** Swap the backend service and enable PROXY protocol
130 * ```typescript
131 * const proxy = yield* GCP.Compute.TargetTcpProxy("tcp", {
132 * targetTcpProxyName: "app-tcp",
133 * service: otherBackend.name,
134 * proxyHeader: "PROXY_V1",
135 * });
136 * ```
137 *
138 * @resource
139 * @category Compute
140 */
141 export const TargetTcpProxy = Resource<TargetTcpProxy>("GCP.Compute.TargetTcpProxy");
142
143 export class TargetTcpProxyNotResolved extends Data.TaggedError(
144 "GCP.Compute.TargetTcpProxyNotResolved",
145 )<{
146 targetTcpProxyName: string;
147 }> {}
148
149 const toName = (id: string, name: string | undefined, existing?: string) =>
150 Effect.gen(function* () {
151 if (name !== undefined) return name;
152 if (existing !== undefined) return existing;
153 const generated = yield* createPhysicalName({
154 id,
155 maxLength: 63,
156 lowercase: true,
157 });
158 return /^[a-z]/.test(generated) ? generated : `t${generated}`.slice(0, 63);
159 });
160
161 const encodeDescription = (
162 labels: Record<string, string>,
163 description: string | undefined,
164 ): string => {
165 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
166 return description ? `${marker}\n${description}` : marker;
167 };
168
169 const parseDescription = (
170 description: string | undefined,
171 ): {
172 labels: Record<string, string>;
173 description: string | undefined;
174 } => {
175 if (!description?.startsWith("[alchemy ")) {
176 return { labels: {}, description };
177 }
178 const end = description.indexOf("]");
179 if (end < 0) return { labels: {}, description };
180 const labels: Record<string, string> = {};
181 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
182 const eq = part.indexOf("=");
183 if (eq > 0) {
184 labels[part.slice(0, eq)] = part.slice(eq + 1);
185 }
186 }
187 const rest = description.slice(end + 1).replace(/^\n/, "");
188 return { labels, description: rest.length > 0 ? rest : undefined };
189 };
190
191 const resourceTail = (value: string | undefined): string => {
192 if (value === undefined || value.length === 0) return "";
193 const parts = value.split("/").filter((part) => part.length > 0);
194 return parts[parts.length - 1] ?? "";
195 };
196
197 const toBackendServiceRef = (project: string, service: string): string => {
198 if (service.includes("/")) return service;
199 return `projects/${project}/global/backendServices/${service}`;
200 };
201
202 const toAttrs = (proxy: compute.TargetTcpProxy, project: string) => {
203 const parsed = parseDescription(proxy.description);
204 return {
205 targetTcpProxyName: proxy.name ?? proxy.id ?? "",
206 project,
207 description: parsed.description,
208 service: proxy.service ?? "",
209 proxyHeader: proxy.proxyHeader,
210 proxyBind: proxy.proxyBind === true,
211 loadBalancingScheme: proxy.loadBalancingScheme,
212 selfLink: proxy.selfLink,
213 targetTcpProxyId: proxy.id,
214 creationTimestamp: proxy.creationTimestamp,
215 kind: proxy.kind,
216 };
217 };
218
219 const getByName = (project: string, targetTcpProxy: string) =>
220 compute
221 .getTargetTcpProxies({ project, targetTcpProxy })
222 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
223
224 export const TargetTcpProxyProvider = () =>
225 Provider.succeed(TargetTcpProxy, {
226 stables: ["targetTcpProxyName", "project", "targetTcpProxyId", "selfLink", "creationTimestamp"],
227
228 diff: Effect.fn(function* ({ news, olds, output }) {
229 if (!isResolved(news)) return undefined;
230 const previous = olds?.targetTcpProxyName ?? output?.targetTcpProxyName;
231 const next = news.targetTcpProxyName;
232 if (previous !== undefined && next !== undefined && previous !== next) {
233 return { action: "replace" as const, deleteFirst: true };
234 }
235 if (olds !== undefined) {
236 if ((olds.description ?? "") !== (news.description ?? "")) {
237 return { action: "replace" as const, deleteFirst: true };
238 }
239 if ((olds.proxyBind ?? false) !== (news.proxyBind ?? false)) {
240 return { action: "replace" as const, deleteFirst: true };
241 }
242 if ((olds.loadBalancingScheme ?? "") !== (news.loadBalancingScheme ?? "")) {
243 return { action: "replace" as const, deleteFirst: true };
244 }
245 }
246 return undefined;
247 }),
248
249 read: Effect.fn(function* ({ id, olds, output, previous }) {
250 const env = yield* GcpEnvironment.current;
251 const targetTcpProxyName = yield* toName(
252 id,
253 olds?.targetTcpProxyName,
254 output?.targetTcpProxyName,
255 );
256 const existing = yield* getByName(env.project, targetTcpProxyName);
257 if (existing === undefined) return undefined;
258 const attrs = toAttrs(existing, env.project);
259 const { labels } = parseDescription(existing.description);
260 return (yield* hasAlchemyLabels(id, labels))
261 ? attrs
262 : unownedUnlessPrevious(attrs, previous, "targetTcpProxyName");
263 }),
264
265 list: () =>
266 Effect.gen(function* () {
267 const env = yield* GcpEnvironment.current;
268 return yield* compute.listTargetTcpProxies
269 .items({ project: env.project, maxResults: 500 })
270 .pipe(
271 Stream.filter((proxy) => {
272 const { labels } = parseDescription(proxy.description);
273 return Object.keys(labels).some((key) => key.startsWith("alchemy-"));
274 }),
275 Stream.map((proxy) => toAttrs(proxy, env.project)),
276 Stream.runCollect,
277 Effect.map((chunk) => Array.from(chunk)),
278 );
279 }),
280
281 reconcile: Effect.fn(function* ({ id, news, output }) {
282 const env = yield* GcpEnvironment.current;
283 const targetTcpProxyName = yield* toName(
284 id,
285 news.targetTcpProxyName,
286 output?.targetTcpProxyName,
287 );
288 const ownership = yield* createInternalLabels(id);
289 const desiredDescription = encodeDescription(ownership, news.description);
290 const desiredService = toBackendServiceRef(env.project, news.service);
291 const desiredProxyHeader = news.proxyHeader ?? DEFAULT_PROXY_HEADER;
292
293 let current = yield* getByName(env.project, targetTcpProxyName);
294
295 if (current === undefined) {
296 const body: compute.TargetTcpProxy = {
297 name: targetTcpProxyName,
298 description: desiredDescription,
299 service: desiredService,
300 };
301 if (news.proxyHeader !== undefined) {
302 body.proxyHeader = news.proxyHeader;
303 }
304 if (news.proxyBind !== undefined) {
305 body.proxyBind = news.proxyBind;
306 }
307 if (news.loadBalancingScheme !== undefined) {
308 body.loadBalancingScheme = news.loadBalancingScheme;
309 }
310 yield* compute
311 .insertTargetTcpProxies({
312 project: env.project,
313 body,
314 })
315 .pipe(
316 Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)),
317 Effect.catchTag("Conflict", () => Effect.undefined),
318 );
319 current = yield* getByName(env.project, targetTcpProxyName);
320 }
321
322 if (current === undefined) {
323 return yield* new TargetTcpProxyNotResolved({ targetTcpProxyName });
324 }
325
326 if (resourceTail(current.service) !== resourceTail(desiredService)) {
327 yield* compute
328 .setBackendServiceTargetTcpProxies({
329 project: env.project,
330 targetTcpProxy: targetTcpProxyName,
331 body: { service: desiredService },
332 })
333 .pipe(Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)));
334 current = yield* getByName(env.project, targetTcpProxyName);
335 if (current === undefined) {
336 return yield* new TargetTcpProxyNotResolved({
337 targetTcpProxyName,
338 });
339 }
340 }
341
342 if ((current.proxyHeader ?? DEFAULT_PROXY_HEADER) !== desiredProxyHeader) {
343 yield* compute
344 .setProxyHeaderTargetTcpProxies({
345 project: env.project,
346 targetTcpProxy: targetTcpProxyName,
347 body: { proxyHeader: desiredProxyHeader },
348 })
349 .pipe(Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)));
350 current = yield* getByName(env.project, targetTcpProxyName);
351 if (current === undefined) {
352 return yield* new TargetTcpProxyNotResolved({
353 targetTcpProxyName,
354 });
355 }
356 }
357
358 return toAttrs(current, env.project);
359 }),
360
361 delete: Effect.fn(function* ({ output }) {
362 const env = yield* GcpEnvironment.current;
363 const operation = yield* compute
364 .deleteTargetTcpProxies({
365 project: env.project,
366 targetTcpProxy: output.targetTcpProxyName,
367 })
368 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
369 if (operation !== undefined) {
370 yield* waitGlobalOperation(env.project, operation).pipe(
371 Effect.catchTag("NotFound", () => Effect.void),
372 );
373 }
374 }),
375 });