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

main
ts 582 lines 20.4 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 TargetHttpsProxyQuicOverride = compute.TargetHttpsProxyQuicOverrideEnum;
16 export type TargetHttpsProxyTlsEarlyData = compute.TargetHttpsProxyTlsEarlyDataEnum;
17
18 const DEFAULT_QUIC: TargetHttpsProxyQuicOverride = "NONE";
19
20 export type TargetHttpsProxyProps = {
21 /**
22 * TargetHttpsProxy 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 targetHttpsProxyName?: string;
27 /**
28 * Optional description. Alchemy ownership is stored in a `[alchemy …]`
29 * prefix so `list` / nuke can find resources (Compute TargetHttpsProxy
30 * has no labels field).
31 */
32 description?: string;
33 /**
34 * URL map this proxy routes to. Accepts a UrlMap self-link, a
35 * `projects/{project}/global/urlMaps/{name}` path, or the UrlMap name.
36 */
37 urlMap: string;
38 /**
39 * SslCertificate URLs used to terminate HTTPS. Accepts self-links,
40 * `projects/{project}/global/sslCertificates/{name}` paths, or
41 * certificate names. At least one is required unless `certificateMap`
42 * is set. Up to 15 classic certificates.
43 */
44 sslCertificates?: string[];
45 /**
46 * Certificate Manager map URL
47 * (`//certificatemanager.googleapis.com/projects/{project}/locations/{location}/certificateMaps/{name}`).
48 * When set, `sslCertificates` is ignored. Global external / classic
49 * Application Load Balancers only.
50 */
51 certificateMap?: string;
52 /**
53 * SslPolicy URL applied to client TLS. Empty string clears the policy.
54 */
55 sslPolicy?: string;
56 /**
57 * QUIC override (`NONE`, `ENABLE`, `DISABLE`).
58 * @default "NONE"
59 */
60 quicOverride?: TargetHttpsProxyQuicOverride | (string & {});
61 /**
62 * HTTP keep-alive timeout in seconds after a response while idle.
63 * Global external Application Load Balancers: 5–1200. Not supported
64 * on classic Application Load Balancers.
65 */
66 httpKeepAliveTimeoutSec?: number;
67 /**
68 * Whether TLS 1.3 0-RTT early data is accepted (`DISABLED`,
69 * `PERMISSIVE`, `STRICT`, `UNRESTRICTED`).
70 * @default "DISABLED"
71 */
72 tlsEarlyData?: TargetHttpsProxyTlsEarlyData | (string & {});
73 /**
74 * Bind inbound traffic to the forwarding-rule address. Only applies when
75 * the referencing forwarding rule uses `INTERNAL_SELF_MANAGED`.
76 * @default false
77 */
78 proxyBind?: boolean;
79 /**
80 * networksecurity.ServerTlsPolicy URL used to authenticate inbound
81 * traffic.
82 */
83 serverTlsPolicy?: string;
84 /**
85 * networksecurity.AuthorizationPolicy URL. Currently has no impact.
86 */
87 authorizationPolicy?: string;
88 };
89
90 export type TargetHttpsProxy = Resource<
91 "GCP.Compute.TargetHttpsProxy",
92 TargetHttpsProxyProps,
93 {
94 /** TargetHttpsProxy name. */
95 targetHttpsProxyName: string;
96 /** Project id. */
97 project: string;
98 /** User description with the Alchemy ownership prefix stripped. */
99 description: string | undefined;
100 /** URL of the attached UrlMap. */
101 urlMap: string;
102 /** SslCertificate URLs. */
103 sslCertificates: string[];
104 /** Certificate Manager map URL, if set. */
105 certificateMap: string | undefined;
106 /** SslPolicy URL, if set. */
107 sslPolicy: string | undefined;
108 /** QUIC override policy. */
109 quicOverride: string | undefined;
110 /** HTTP keep-alive timeout in seconds, if set. */
111 httpKeepAliveTimeoutSec: number | undefined;
112 /** TLS 1.3 early-data mode, if set. */
113 tlsEarlyData: string | undefined;
114 /** Whether Envoy inbound bind is enabled. */
115 proxyBind: boolean;
116 /** Server TLS policy URL, if set. */
117 serverTlsPolicy: string | undefined;
118 /** Authorization policy URL, if set. */
119 authorizationPolicy: string | undefined;
120 /** Server-defined URL. */
121 selfLink: string | undefined;
122 /** Server-assigned numeric id. */
123 targetHttpsProxyId: string | undefined;
124 /** Optimistic-locking fingerprint. */
125 fingerprint: string | undefined;
126 /** RFC3339 creation timestamp. */
127 creationTimestamp: string | undefined;
128 /** Resource kind. */
129 kind: string | undefined;
130 },
131 never,
132 Providers
133 >;
134
135 /**
136 * A global Compute Engine target HTTPS proxy.
137 *
138 * Target HTTPS proxies terminate HTTPS for global external Application
139 * Load Balancers, classic Application Load Balancers, cross-region
140 * internal Application Load Balancers, and Traffic Director. A forwarding
141 * rule points at the proxy; the proxy points at a URL map and one or more
142 * SSL certificates (or a Certificate Manager map).
143 *
144 * This resource maps to the global `targetHttpsProxies` collection
145 * (`regionTargetHttpsProxies` is a separate resource). Compute
146 * TargetHttpsProxy has no labels field — Alchemy ownership is stored in
147 * the description so nuke can find leaked proxies.
148 *
149 * ### Creating a Target HTTPS Proxy
150 * **Example:** Generated name in front of a URL map
151 * ```typescript
152 * const map = yield* GCP.Compute.UrlMap("web", {
153 * defaultUrlRedirect: {
154 * httpsRedirect: true,
155 * hostRedirect: "example.com",
156 * stripQuery: false,
157 * },
158 * });
159 * const cert = yield* GCP.Compute.SslCertificate("tls", {
160 * certificate: pemCertificate,
161 * privateKey: pemPrivateKey,
162 * });
163 * const proxy = yield* GCP.Compute.TargetHttpsProxy("https", {
164 * urlMap: map.urlMapName,
165 * sslCertificates: [cert.sslCertificateName],
166 * });
167 * ```
168 *
169 * **Example:** Explicit name, QUIC, and description
170 * ```typescript
171 * const proxy = yield* GCP.Compute.TargetHttpsProxy("https", {
172 * targetHttpsProxyName: "web-https",
173 * urlMap: map.selfLink,
174 * sslCertificates: [cert.selfLink],
175 * quicOverride: "ENABLE",
176 * description: "public https",
177 * });
178 * ```
179 *
180 * ### Updating a Target HTTPS Proxy
181 * **Example:** Swap certificates and enable QUIC
182 * ```typescript
183 * const proxy = yield* GCP.Compute.TargetHttpsProxy("https", {
184 * targetHttpsProxyName: "web-https",
185 * urlMap: map.urlMapName,
186 * sslCertificates: [nextCert.sslCertificateName],
187 * quicOverride: "ENABLE",
188 * });
189 * ```
190 *
191 * @resource
192 * @category Compute
193 */
194 export const TargetHttpsProxy = Resource<TargetHttpsProxy>("GCP.Compute.TargetHttpsProxy");
195
196 export class TargetHttpsProxyNotResolved extends Data.TaggedError(
197 "GCP.Compute.TargetHttpsProxyNotResolved",
198 )<{
199 targetHttpsProxyName: string;
200 }> {}
201
202 const toName = (id: string, name: string | undefined, existing?: string) =>
203 Effect.gen(function* () {
204 if (name !== undefined) return name;
205 if (existing !== undefined) return existing;
206 const generated = yield* createPhysicalName({
207 id,
208 maxLength: 63,
209 lowercase: true,
210 });
211 return /^[a-z]/.test(generated) ? generated : `h${generated}`.slice(0, 63);
212 });
213
214 const encodeDescription = (
215 labels: Record<string, string>,
216 description: string | undefined,
217 ): string => {
218 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
219 return description ? `${marker}\n${description}` : marker;
220 };
221
222 const parseDescription = (
223 description: string | undefined,
224 ): {
225 labels: Record<string, string>;
226 description: string | undefined;
227 } => {
228 if (!description?.startsWith("[alchemy ")) {
229 return { labels: {}, description };
230 }
231 const end = description.indexOf("]");
232 if (end < 0) return { labels: {}, description };
233 const labels: Record<string, string> = {};
234 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
235 const eq = part.indexOf("=");
236 if (eq > 0) {
237 labels[part.slice(0, eq)] = part.slice(eq + 1);
238 }
239 }
240 const rest = description.slice(end + 1).replace(/^\n/, "");
241 return { labels, description: rest.length > 0 ? rest : undefined };
242 };
243
244 const resourceTail = (value: string | undefined): string => {
245 if (value === undefined || value.length === 0) return "";
246 const parts = value.split("/").filter((part) => part.length > 0);
247 return parts[parts.length - 1] ?? "";
248 };
249
250 const toUrlMapRef = (project: string, urlMap: string): string => {
251 if (urlMap.includes("/")) return urlMap;
252 return `projects/${project}/global/urlMaps/${urlMap}`;
253 };
254
255 const toSslCertRef = (project: string, cert: string): string => {
256 if (cert.includes("/")) return cert;
257 return `projects/${project}/global/sslCertificates/${cert}`;
258 };
259
260 const sameResourceList = (
261 left: readonly string[] | undefined,
262 right: readonly string[] | undefined,
263 ) => {
264 const a = [...(left ?? [])].map(resourceTail).sort();
265 const b = [...(right ?? [])].map(resourceTail).sort();
266 return a.length === b.length && a.every((value, i) => value === b[i]);
267 };
268
269 const toAttrs = (proxy: compute.TargetHttpsProxy, project: string) => {
270 const parsed = parseDescription(proxy.description);
271 return {
272 targetHttpsProxyName: proxy.name ?? proxy.id ?? "",
273 project,
274 description: parsed.description,
275 urlMap: proxy.urlMap ?? "",
276 sslCertificates: [...(proxy.sslCertificates ?? [])],
277 certificateMap: proxy.certificateMap,
278 sslPolicy: proxy.sslPolicy,
279 quicOverride: proxy.quicOverride,
280 httpKeepAliveTimeoutSec: proxy.httpKeepAliveTimeoutSec,
281 tlsEarlyData: proxy.tlsEarlyData,
282 proxyBind: proxy.proxyBind === true,
283 serverTlsPolicy: proxy.serverTlsPolicy,
284 authorizationPolicy: proxy.authorizationPolicy,
285 selfLink: proxy.selfLink,
286 targetHttpsProxyId: proxy.id,
287 fingerprint: proxy.fingerprint,
288 creationTimestamp: proxy.creationTimestamp,
289 kind: proxy.kind,
290 };
291 };
292
293 const getByName = (project: string, targetHttpsProxy: string) =>
294 compute
295 .getTargetHttpsProxies({ project, targetHttpsProxy })
296 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
297
298 export const TargetHttpsProxyProvider = () =>
299 Provider.succeed(TargetHttpsProxy, {
300 nuke: {
301 dependsOn: ["GCP.Compute.UrlMap"],
302 },
303 stables: [
304 "targetHttpsProxyName",
305 "project",
306 "targetHttpsProxyId",
307 "selfLink",
308 "creationTimestamp",
309 ],
310
311 diff: Effect.fn(function* ({ news, olds, output }) {
312 if (!isResolved(news)) return undefined;
313 const previous = olds?.targetHttpsProxyName ?? output?.targetHttpsProxyName;
314 const next = news.targetHttpsProxyName;
315 if (previous !== undefined && next !== undefined && previous !== next) {
316 return { action: "replace" as const, deleteFirst: true };
317 }
318 return undefined;
319 }),
320
321 read: Effect.fn(function* ({ id, olds, output, previous }) {
322 const env = yield* GcpEnvironment.current;
323 const targetHttpsProxyName = yield* toName(
324 id,
325 olds?.targetHttpsProxyName,
326 output?.targetHttpsProxyName,
327 );
328 const existing = yield* getByName(env.project, targetHttpsProxyName);
329 if (existing === undefined) return undefined;
330 const attrs = toAttrs(existing, env.project);
331 const { labels } = parseDescription(existing.description);
332 return (yield* hasAlchemyLabels(id, labels))
333 ? attrs
334 : unownedUnlessPrevious(attrs, previous, "targetHttpsProxyName");
335 }),
336
337 list: () =>
338 Effect.gen(function* () {
339 const env = yield* GcpEnvironment.current;
340 return yield* compute.listTargetHttpsProxies
341 .items({ project: env.project, maxResults: 500 })
342 .pipe(
343 Stream.filter((proxy) => {
344 const { labels } = parseDescription(proxy.description);
345 return Object.keys(labels).some((key) => key.startsWith("alchemy-"));
346 }),
347 Stream.map((proxy) => toAttrs(proxy, env.project)),
348 Stream.runCollect,
349 Effect.map((chunk) => Array.from(chunk)),
350 );
351 }),
352
353 reconcile: Effect.fn(function* ({ id, news, output }) {
354 const env = yield* GcpEnvironment.current;
355 const targetHttpsProxyName = yield* toName(
356 id,
357 news.targetHttpsProxyName,
358 output?.targetHttpsProxyName,
359 );
360 const ownership = yield* createInternalLabels(id);
361 const desiredDescription = encodeDescription(ownership, news.description);
362 const desiredUrlMap = toUrlMapRef(env.project, news.urlMap);
363 const desiredCerts = (news.sslCertificates ?? []).map((cert) =>
364 toSslCertRef(env.project, cert),
365 );
366 const desiredQuic = news.quicOverride ?? DEFAULT_QUIC;
367
368 let current = yield* getByName(env.project, targetHttpsProxyName);
369
370 if (current === undefined) {
371 const body: compute.TargetHttpsProxy = {
372 name: targetHttpsProxyName,
373 description: desiredDescription,
374 urlMap: desiredUrlMap,
375 };
376 if (desiredCerts.length > 0) {
377 body.sslCertificates = desiredCerts;
378 }
379 if (news.certificateMap !== undefined) {
380 body.certificateMap = news.certificateMap;
381 }
382 if (news.sslPolicy !== undefined) {
383 body.sslPolicy = news.sslPolicy;
384 }
385 if (news.quicOverride !== undefined) {
386 body.quicOverride = news.quicOverride;
387 }
388 if (news.httpKeepAliveTimeoutSec !== undefined) {
389 body.httpKeepAliveTimeoutSec = news.httpKeepAliveTimeoutSec;
390 }
391 if (news.tlsEarlyData !== undefined) {
392 body.tlsEarlyData = news.tlsEarlyData;
393 }
394 if (news.proxyBind !== undefined) {
395 body.proxyBind = news.proxyBind;
396 }
397 if (news.serverTlsPolicy !== undefined) {
398 body.serverTlsPolicy = news.serverTlsPolicy;
399 }
400 if (news.authorizationPolicy !== undefined) {
401 body.authorizationPolicy = news.authorizationPolicy;
402 }
403 yield* compute
404 .insertTargetHttpsProxies({
405 project: env.project,
406 body,
407 })
408 .pipe(
409 Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)),
410 Effect.catchTag("Conflict", () => Effect.undefined),
411 );
412 current = yield* getByName(env.project, targetHttpsProxyName);
413 }
414
415 if (current === undefined) {
416 return yield* new TargetHttpsProxyNotResolved({
417 targetHttpsProxyName,
418 });
419 }
420
421 if (resourceTail(current.urlMap) !== resourceTail(desiredUrlMap)) {
422 yield* compute
423 .setUrlMapTargetHttpsProxies({
424 project: env.project,
425 targetHttpsProxy: targetHttpsProxyName,
426 body: { urlMap: desiredUrlMap },
427 })
428 .pipe(Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)));
429 current = yield* getByName(env.project, targetHttpsProxyName);
430 if (current === undefined) {
431 return yield* new TargetHttpsProxyNotResolved({
432 targetHttpsProxyName,
433 });
434 }
435 }
436
437 if (
438 news.sslCertificates !== undefined &&
439 !sameResourceList(current.sslCertificates, desiredCerts)
440 ) {
441 yield* compute
442 .setSslCertificatesTargetHttpsProxies({
443 project: env.project,
444 targetHttpsProxy: targetHttpsProxyName,
445 body: { sslCertificates: desiredCerts },
446 })
447 .pipe(Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)));
448 current = yield* getByName(env.project, targetHttpsProxyName);
449 if (current === undefined) {
450 return yield* new TargetHttpsProxyNotResolved({
451 targetHttpsProxyName,
452 });
453 }
454 }
455
456 if (
457 news.certificateMap !== undefined &&
458 (current.certificateMap ?? "") !== news.certificateMap
459 ) {
460 yield* compute
461 .setCertificateMapTargetHttpsProxies({
462 project: env.project,
463 targetHttpsProxy: targetHttpsProxyName,
464 body: { certificateMap: news.certificateMap },
465 })
466 .pipe(Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)));
467 current = yield* getByName(env.project, targetHttpsProxyName);
468 if (current === undefined) {
469 return yield* new TargetHttpsProxyNotResolved({
470 targetHttpsProxyName,
471 });
472 }
473 }
474
475 if ((current.quicOverride ?? DEFAULT_QUIC) !== desiredQuic) {
476 yield* compute
477 .setQuicOverrideTargetHttpsProxies({
478 project: env.project,
479 targetHttpsProxy: targetHttpsProxyName,
480 body: { quicOverride: desiredQuic },
481 })
482 .pipe(Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)));
483 current = yield* getByName(env.project, targetHttpsProxyName);
484 if (current === undefined) {
485 return yield* new TargetHttpsProxyNotResolved({
486 targetHttpsProxyName,
487 });
488 }
489 }
490
491 if (news.sslPolicy !== undefined && (current.sslPolicy ?? "") !== news.sslPolicy) {
492 yield* compute
493 .setSslPolicyTargetHttpsProxies({
494 project: env.project,
495 targetHttpsProxy: targetHttpsProxyName,
496 body: { sslPolicy: news.sslPolicy },
497 })
498 .pipe(Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)));
499 current = yield* getByName(env.project, targetHttpsProxyName);
500 if (current === undefined) {
501 return yield* new TargetHttpsProxyNotResolved({
502 targetHttpsProxyName,
503 });
504 }
505 }
506
507 const descriptionChanged = (current.description ?? "") !== desiredDescription;
508 const keepAliveChanged =
509 news.httpKeepAliveTimeoutSec !== undefined &&
510 current.httpKeepAliveTimeoutSec !== news.httpKeepAliveTimeoutSec;
511 const tlsEarlyDataChanged =
512 news.tlsEarlyData !== undefined &&
513 (current.tlsEarlyData ?? "DISABLED") !== news.tlsEarlyData;
514 const proxyBindChanged =
515 news.proxyBind !== undefined && (current.proxyBind === true) !== news.proxyBind;
516 const serverTlsChanged =
517 news.serverTlsPolicy !== undefined &&
518 (current.serverTlsPolicy ?? "") !== news.serverTlsPolicy;
519 const authorizationChanged =
520 news.authorizationPolicy !== undefined &&
521 (current.authorizationPolicy ?? "") !== news.authorizationPolicy;
522
523 if (
524 descriptionChanged ||
525 keepAliveChanged ||
526 tlsEarlyDataChanged ||
527 proxyBindChanged ||
528 serverTlsChanged ||
529 authorizationChanged
530 ) {
531 const body: compute.TargetHttpsProxy = {
532 fingerprint: current.fingerprint,
533 description: desiredDescription,
534 };
535 if (news.httpKeepAliveTimeoutSec !== undefined) {
536 body.httpKeepAliveTimeoutSec = news.httpKeepAliveTimeoutSec;
537 }
538 if (news.tlsEarlyData !== undefined) {
539 body.tlsEarlyData = news.tlsEarlyData;
540 }
541 if (news.proxyBind !== undefined) {
542 body.proxyBind = news.proxyBind;
543 }
544 if (news.serverTlsPolicy !== undefined) {
545 body.serverTlsPolicy = news.serverTlsPolicy;
546 }
547 if (news.authorizationPolicy !== undefined) {
548 body.authorizationPolicy = news.authorizationPolicy;
549 }
550 yield* compute
551 .patchTargetHttpsProxies({
552 project: env.project,
553 targetHttpsProxy: targetHttpsProxyName,
554 body,
555 })
556 .pipe(Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)));
557 current = yield* getByName(env.project, targetHttpsProxyName);
558 if (current === undefined) {
559 return yield* new TargetHttpsProxyNotResolved({
560 targetHttpsProxyName,
561 });
562 }
563 }
564
565 return toAttrs(current, env.project);
566 }),
567
568 delete: Effect.fn(function* ({ output }) {
569 const env = yield* GcpEnvironment.current;
570 const operation = yield* compute
571 .deleteTargetHttpsProxies({
572 project: env.project,
573 targetHttpsProxy: output.targetHttpsProxyName,
574 })
575 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
576 if (operation !== undefined) {
577 yield* waitGlobalOperation(env.project, operation).pipe(
578 Effect.catchTag("NotFound", () => Effect.void),
579 );
580 }
581 }),
582 });