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

main
ts 507 lines 18 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 { waitRegionOperation } from "./operations.ts";
14
15 export type RegionTargetHttpsProxyProps = {
16 /**
17 * TargetHttpsProxy name (RFC1035, 1-63 characters). If omitted, a unique
18 * name is generated from the stack, stage, and logical id. Changing it
19 * replaces the resource.
20 */
21 targetHttpsProxyName?: string;
22 /**
23 * Region the proxy lives in (e.g. `us-central1`). Immutable — changing
24 * it replaces the resource. `US-CENTRAL1` is accepted and normalized to
25 * `us-central1`.
26 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
27 */
28 region?: string;
29 /**
30 * Optional description. Alchemy ownership is stored in a `[alchemy …]`
31 * prefix so `list` / nuke can find resources (Compute
32 * RegionTargetHttpsProxy has no labels field).
33 */
34 description?: string;
35 /**
36 * Regional URL map this proxy routes to. Accepts a RegionUrlMap
37 * self-link, a `projects/{project}/regions/{region}/urlMaps/{name}`
38 * path, or the UrlMap name.
39 */
40 urlMap: string;
41 /**
42 * Regional SslCertificate URLs used to terminate HTTPS. Accepts
43 * self-links, `projects/{project}/regions/{region}/sslCertificates/{name}`
44 * paths, or certificate names. At least one is required.
45 */
46 sslCertificates?: string[];
47 /**
48 * Regional SslPolicy URL applied to client TLS. Empty string clears the
49 * policy. Accepts a self-link, path, or policy name.
50 */
51 sslPolicy?: string;
52 /**
53 * HTTP keep-alive timeout in seconds after a response while idle.
54 * Regional Application Load Balancers allow 5–600 (default 610).
55 */
56 httpKeepAliveTimeoutSec?: number;
57 /**
58 * Bind inbound traffic to the forwarding-rule address. Only applies when
59 * the referencing forwarding rule uses `INTERNAL_SELF_MANAGED`.
60 * @default false
61 */
62 proxyBind?: boolean;
63 /**
64 * networksecurity.ServerTlsPolicy URL used to authenticate inbound
65 * traffic.
66 */
67 serverTlsPolicy?: string;
68 };
69
70 export type RegionTargetHttpsProxy = Resource<
71 "GCP.Compute.RegionTargetHttpsProxy",
72 RegionTargetHttpsProxyProps,
73 {
74 /** TargetHttpsProxy name. */
75 targetHttpsProxyName: 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 regional UrlMap. */
83 urlMap: string;
84 /** SslCertificate URLs. */
85 sslCertificates: string[];
86 /** SslPolicy URL, if set. */
87 sslPolicy: string | undefined;
88 /** HTTP keep-alive timeout in seconds, if set. */
89 httpKeepAliveTimeoutSec: number | undefined;
90 /** Whether Envoy inbound bind is enabled. */
91 proxyBind: boolean;
92 /** Server TLS policy URL, if set. */
93 serverTlsPolicy: string | undefined;
94 /** Server-defined URL. */
95 selfLink: string | undefined;
96 /** Server-assigned numeric id. */
97 targetHttpsProxyId: string | undefined;
98 /** Optimistic-locking fingerprint. */
99 fingerprint: string | undefined;
100 /** RFC3339 creation timestamp. */
101 creationTimestamp: string | undefined;
102 /** Resource kind. */
103 kind: string | undefined;
104 },
105 never,
106 Providers
107 >;
108
109 /**
110 * A regional Compute Engine target HTTPS proxy.
111 *
112 * Regional target HTTPS proxies terminate HTTPS for regional Application
113 * Load Balancers. A forwarding rule points at the proxy; the proxy points
114 * at a regional URL map and one or more regional SSL certificates.
115 *
116 * This resource maps to the `regionTargetHttpsProxies` collection (the
117 * global `targetHttpsProxies` collection is `GCP.Compute.TargetHttpsProxy`).
118 * Compute RegionTargetHttpsProxy has no labels field — Alchemy ownership
119 * is stored in the description so nuke can find leaked proxies. Url map
120 * and certificates update in place; name and region replace.
121 *
122 * ### Creating a Regional Target HTTPS Proxy
123 * **Example:** Generated name in front of a regional URL map
124 * ```typescript
125 * const map = yield* GCP.Compute.RegionUrlMap("web", {
126 * region: "us-central1",
127 * defaultUrlRedirect: {
128 * httpsRedirect: true,
129 * hostRedirect: "example.com",
130 * stripQuery: false,
131 * },
132 * });
133 * const cert = yield* GCP.Compute.RegionSslCertificate("tls", {
134 * region: "us-central1",
135 * certificate: pemCertificate,
136 * privateKey: pemPrivateKey,
137 * });
138 * const proxy = yield* GCP.Compute.RegionTargetHttpsProxy("https", {
139 * region: "us-central1",
140 * urlMap: map.urlMapName,
141 * sslCertificates: [cert.sslCertificateName],
142 * });
143 * ```
144 *
145 * @resource
146 * @category Compute
147 */
148 export const RegionTargetHttpsProxy = Resource<RegionTargetHttpsProxy>(
149 "GCP.Compute.RegionTargetHttpsProxy",
150 );
151
152 export class RegionTargetHttpsProxyNotResolved extends Data.TaggedError(
153 "GCP.Compute.RegionTargetHttpsProxyNotResolved",
154 )<{
155 targetHttpsProxyName: string;
156 region: string;
157 }> {}
158
159 const lastSegment = (value: string | undefined) => {
160 if (value === undefined || value.length === 0) return "";
161 const trimmed = value.replace(/\/+$/, "");
162 const parts = trimmed.split("/");
163 return parts[parts.length - 1] || trimmed;
164 };
165
166 const normalizeRegion = (region: string | undefined, defaultRegion: string) =>
167 lastSegment(region ?? defaultRegion).toLowerCase();
168
169 const toName = (id: string, name: string | undefined, existing?: string) =>
170 Effect.gen(function* () {
171 if (name !== undefined) return name;
172 if (existing !== undefined) return existing;
173 const generated = yield* createPhysicalName({
174 id,
175 maxLength: 63,
176 lowercase: true,
177 });
178 return /^[a-z]/.test(generated) ? generated : `h${generated}`.slice(0, 63);
179 });
180
181 const encodeDescription = (
182 labels: Record<string, string>,
183 description: string | undefined,
184 ): string => {
185 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
186 return description ? `${marker}\n${description}` : marker;
187 };
188
189 const parseDescription = (
190 description: string | undefined,
191 ): {
192 labels: Record<string, string>;
193 description: string | undefined;
194 } => {
195 if (!description?.startsWith("[alchemy ")) {
196 return { labels: {}, description };
197 }
198 const end = description.indexOf("]");
199 if (end < 0) return { labels: {}, description };
200 const labels: Record<string, string> = {};
201 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
202 const eq = part.indexOf("=");
203 if (eq > 0) {
204 labels[part.slice(0, eq)] = part.slice(eq + 1);
205 }
206 }
207 const rest = description.slice(end + 1).replace(/^\n/, "");
208 return { labels, description: rest.length > 0 ? rest : undefined };
209 };
210
211 const resourceTail = (value: string | undefined): string => lastSegment(value);
212
213 const toUrlMapRef = (project: string, region: string, urlMap: string): string => {
214 if (urlMap.includes("/")) return urlMap;
215 return `projects/${project}/regions/${region}/urlMaps/${urlMap}`;
216 };
217
218 const toSslCertRef = (project: string, region: string, cert: string): string => {
219 if (cert.includes("/")) return cert;
220 return `projects/${project}/regions/${region}/sslCertificates/${cert}`;
221 };
222
223 const toSslPolicyRef = (project: string, region: string, policy: string): string => {
224 if (policy.length === 0 || policy.includes("/")) return policy;
225 return `projects/${project}/regions/${region}/sslPolicies/${policy}`;
226 };
227
228 const sameResourceList = (
229 left: readonly string[] | undefined,
230 right: readonly string[] | undefined,
231 ) => {
232 const a = [...(left ?? [])].map(resourceTail).sort();
233 const b = [...(right ?? [])].map(resourceTail).sort();
234 return a.length === b.length && a.every((value, i) => value === b[i]);
235 };
236
237 const toAttrs = (proxy: compute.TargetHttpsProxy, project: string) => {
238 const parsed = parseDescription(proxy.description);
239 return {
240 targetHttpsProxyName: proxy.name ?? proxy.id ?? "",
241 project,
242 region: lastSegment(proxy.region).toLowerCase(),
243 description: parsed.description,
244 urlMap: proxy.urlMap ?? "",
245 sslCertificates: [...(proxy.sslCertificates ?? [])],
246 sslPolicy: proxy.sslPolicy,
247 httpKeepAliveTimeoutSec: proxy.httpKeepAliveTimeoutSec,
248 proxyBind: proxy.proxyBind === true,
249 serverTlsPolicy: proxy.serverTlsPolicy,
250 selfLink: proxy.selfLink,
251 targetHttpsProxyId: proxy.id,
252 fingerprint: proxy.fingerprint,
253 creationTimestamp: proxy.creationTimestamp,
254 kind: proxy.kind,
255 };
256 };
257
258 const getByName = (project: string, region: string, targetHttpsProxy: string) =>
259 compute
260 .getRegionTargetHttpsProxies({ project, region, targetHttpsProxy })
261 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
262
263 export const RegionTargetHttpsProxyProvider = () =>
264 Provider.succeed(RegionTargetHttpsProxy, {
265 stables: [
266 "targetHttpsProxyName",
267 "project",
268 "region",
269 "targetHttpsProxyId",
270 "selfLink",
271 "creationTimestamp",
272 ],
273
274 diff: Effect.fn(function* ({ news, olds, output }) {
275 if (!isResolved(news)) return undefined;
276 const env = yield* GcpEnvironment.current;
277 const previous = olds?.targetHttpsProxyName ?? output?.targetHttpsProxyName;
278 const next = news.targetHttpsProxyName;
279 const previousRegion = normalizeRegion(olds?.region ?? output?.region, env.region);
280 const nextRegion = normalizeRegion(news.region ?? output?.region, env.region);
281 if (previousRegion !== nextRegion) {
282 return { action: "replace" as const, deleteFirst: false };
283 }
284 if (previous !== undefined && next !== undefined && previous !== next) {
285 return { action: "replace" as const, deleteFirst: true };
286 }
287 return undefined;
288 }),
289
290 read: Effect.fn(function* ({ id, olds, output, previous }) {
291 const env = yield* GcpEnvironment.current;
292 const targetHttpsProxyName = yield* toName(
293 id,
294 olds?.targetHttpsProxyName,
295 output?.targetHttpsProxyName,
296 );
297 const region = normalizeRegion(olds?.region ?? output?.region, env.region);
298 const existing = yield* getByName(env.project, region, targetHttpsProxyName);
299 if (existing === undefined) return undefined;
300 const attrs = toAttrs(existing, env.project);
301 const { labels } = parseDescription(existing.description);
302 return (yield* hasAlchemyLabels(id, labels))
303 ? attrs
304 : unownedUnlessPrevious(attrs, previous, "targetHttpsProxyName");
305 }),
306
307 list: () =>
308 Effect.gen(function* () {
309 const env = yield* GcpEnvironment.current;
310 const pages = yield* compute.aggregatedListTargetHttpsProxies
311 .pages({
312 project: env.project,
313 returnPartialSuccess: true,
314 maxResults: 500,
315 })
316 .pipe(Stream.runCollect);
317 return Array.from(pages).flatMap((page) =>
318 Object.values(page.items ?? {}).flatMap((scoped) =>
319 (scoped?.targetHttpsProxies ?? [])
320 .filter((proxy) => (proxy.region ?? "").length > 0)
321 .filter((proxy) => {
322 const { labels } = parseDescription(proxy.description);
323 return Object.keys(labels).some((key) => key.startsWith("alchemy-"));
324 })
325 .map((proxy) => toAttrs(proxy, env.project)),
326 ),
327 );
328 }),
329
330 reconcile: Effect.fn(function* ({ id, news, output }) {
331 const env = yield* GcpEnvironment.current;
332 const targetHttpsProxyName = yield* toName(
333 id,
334 news.targetHttpsProxyName,
335 output?.targetHttpsProxyName,
336 );
337 const region = normalizeRegion(news.region ?? output?.region, env.region);
338 const ownership = yield* createInternalLabels(id);
339 const desiredDescription = encodeDescription(ownership, news.description);
340 const desiredUrlMap = toUrlMapRef(env.project, region, news.urlMap);
341 const desiredCerts = (news.sslCertificates ?? []).map((cert) =>
342 toSslCertRef(env.project, region, cert),
343 );
344 const desiredSslPolicy =
345 news.sslPolicy !== undefined
346 ? toSslPolicyRef(env.project, region, news.sslPolicy)
347 : undefined;
348
349 let current = yield* getByName(env.project, region, targetHttpsProxyName);
350
351 if (current === undefined) {
352 const body: compute.TargetHttpsProxy = {
353 name: targetHttpsProxyName,
354 description: desiredDescription,
355 urlMap: desiredUrlMap,
356 };
357 if (desiredCerts.length > 0) {
358 body.sslCertificates = desiredCerts;
359 }
360 if (desiredSslPolicy !== undefined) {
361 body.sslPolicy = desiredSslPolicy;
362 }
363 if (news.httpKeepAliveTimeoutSec !== undefined) {
364 body.httpKeepAliveTimeoutSec = news.httpKeepAliveTimeoutSec;
365 }
366 if (news.proxyBind !== undefined) {
367 body.proxyBind = news.proxyBind;
368 }
369 if (news.serverTlsPolicy !== undefined) {
370 body.serverTlsPolicy = news.serverTlsPolicy;
371 }
372 yield* compute
373 .insertRegionTargetHttpsProxies({
374 project: env.project,
375 region,
376 body,
377 })
378 .pipe(
379 Effect.flatMap((operation) =>
380 waitRegionOperation(env.project, region, operation, {
381 ignore: ["RESOURCE_ALREADY_EXISTS"],
382 }),
383 ),
384 Effect.catchTag("Conflict", () => Effect.undefined),
385 );
386 current = yield* getByName(env.project, region, targetHttpsProxyName);
387 }
388
389 if (current === undefined) {
390 return yield* new RegionTargetHttpsProxyNotResolved({
391 targetHttpsProxyName,
392 region,
393 });
394 }
395
396 if (resourceTail(current.urlMap) !== resourceTail(desiredUrlMap)) {
397 yield* compute
398 .setUrlMapRegionTargetHttpsProxies({
399 project: env.project,
400 region,
401 targetHttpsProxy: targetHttpsProxyName,
402 body: { urlMap: desiredUrlMap },
403 })
404 .pipe(Effect.flatMap((operation) => waitRegionOperation(env.project, region, operation)));
405 current = yield* getByName(env.project, region, targetHttpsProxyName);
406 if (current === undefined) {
407 return yield* new RegionTargetHttpsProxyNotResolved({
408 targetHttpsProxyName,
409 region,
410 });
411 }
412 }
413
414 if (
415 news.sslCertificates !== undefined &&
416 !sameResourceList(current.sslCertificates, desiredCerts)
417 ) {
418 yield* compute
419 .setSslCertificatesRegionTargetHttpsProxies({
420 project: env.project,
421 region,
422 targetHttpsProxy: targetHttpsProxyName,
423 body: { sslCertificates: desiredCerts },
424 })
425 .pipe(Effect.flatMap((operation) => waitRegionOperation(env.project, region, operation)));
426 current = yield* getByName(env.project, region, targetHttpsProxyName);
427 if (current === undefined) {
428 return yield* new RegionTargetHttpsProxyNotResolved({
429 targetHttpsProxyName,
430 region,
431 });
432 }
433 }
434
435 const descriptionChanged = (current.description ?? "") !== desiredDescription;
436 const keepAliveChanged =
437 news.httpKeepAliveTimeoutSec !== undefined &&
438 current.httpKeepAliveTimeoutSec !== news.httpKeepAliveTimeoutSec;
439 const proxyBindChanged =
440 news.proxyBind !== undefined && (current.proxyBind === true) !== news.proxyBind;
441 const serverTlsChanged =
442 news.serverTlsPolicy !== undefined &&
443 (current.serverTlsPolicy ?? "") !== news.serverTlsPolicy;
444 const sslPolicyChanged =
445 desiredSslPolicy !== undefined &&
446 resourceTail(current.sslPolicy) !== resourceTail(desiredSslPolicy);
447
448 if (
449 descriptionChanged ||
450 keepAliveChanged ||
451 proxyBindChanged ||
452 serverTlsChanged ||
453 sslPolicyChanged
454 ) {
455 const body: compute.TargetHttpsProxy = {
456 fingerprint: current.fingerprint,
457 description: desiredDescription,
458 };
459 if (news.httpKeepAliveTimeoutSec !== undefined) {
460 body.httpKeepAliveTimeoutSec = news.httpKeepAliveTimeoutSec;
461 }
462 if (news.proxyBind !== undefined) {
463 body.proxyBind = news.proxyBind;
464 }
465 if (news.serverTlsPolicy !== undefined) {
466 body.serverTlsPolicy = news.serverTlsPolicy;
467 }
468 if (desiredSslPolicy !== undefined) {
469 body.sslPolicy = desiredSslPolicy;
470 }
471 yield* compute
472 .patchRegionTargetHttpsProxies({
473 project: env.project,
474 region,
475 targetHttpsProxy: targetHttpsProxyName,
476 body,
477 })
478 .pipe(Effect.flatMap((operation) => waitRegionOperation(env.project, region, operation)));
479 current = yield* getByName(env.project, region, targetHttpsProxyName);
480 if (current === undefined) {
481 return yield* new RegionTargetHttpsProxyNotResolved({
482 targetHttpsProxyName,
483 region,
484 });
485 }
486 }
487
488 return toAttrs(current, env.project);
489 }),
490
491 delete: Effect.fn(function* ({ output }) {
492 const env = yield* GcpEnvironment.current;
493 const region = normalizeRegion(output.region, env.region);
494 const operation = yield* compute
495 .deleteRegionTargetHttpsProxies({
496 project: env.project,
497 region,
498 targetHttpsProxy: output.targetHttpsProxyName,
499 })
500 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
501 if (operation !== undefined) {
502 yield* waitRegionOperation(env.project, region, operation).pipe(
503 Effect.catchTag("NotFound", () => Effect.void),
504 );
505 }
506 }),
507 });