@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 464 lines 16.2 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 TargetSslProxyProxyHeader = compute.TargetSslProxyProxyHeaderEnum;
16
17 const DEFAULT_PROXY_HEADER: TargetSslProxyProxyHeader = "NONE";
18
19 export type TargetSslProxyProps = {
20 /**
21 * TargetSslProxy name (RFC1035, 1-63 characters). If omitted, a unique
22 * name is generated from the stack, stage, and logical id. Changing it
23 * replaces the resource.
24 */
25 targetSslProxyName?: string;
26 /**
27 * Optional description. Alchemy ownership is stored in a `[alchemy …]`
28 * prefix so `list` / nuke can find resources (Compute TargetSslProxy
29 * has no labels field and no update API for description). Changing it
30 * replaces the resource.
31 */
32 description?: string;
33 /**
34 * Backend service this proxy forwards decrypted traffic to. Accepts a
35 * BackendService self-link, a
36 * `projects/{project}/global/backendServices/{name}` path, or the
37 * BackendService name. The backend service protocol must be `SSL`.
38 */
39 service: string;
40 /**
41 * SslCertificate URLs used to terminate SSL. Accepts self-links,
42 * `projects/{project}/global/sslCertificates/{name}` paths, or
43 * certificate names. At least one is required unless `certificateMap`
44 * is set. Up to 15 classic certificates.
45 */
46 sslCertificates?: string[];
47 /**
48 * Certificate Manager map URL
49 * (`//certificatemanager.googleapis.com/projects/{project}/locations/{location}/certificateMaps/{name}`).
50 * When set, `sslCertificates` is ignored. Global SSL proxies only.
51 */
52 certificateMap?: string;
53 /**
54 * SslPolicy URL applied to client TLS. Empty string clears the policy.
55 */
56 sslPolicy?: string;
57 /**
58 * Proxy header appended before sending data to the backend (`NONE` or
59 * `PROXY_V1`).
60 * @default "NONE"
61 */
62 proxyHeader?: TargetSslProxyProxyHeader | (string & {});
63 };
64
65 export type TargetSslProxy = Resource<
66 "GCP.Compute.TargetSslProxy",
67 TargetSslProxyProps,
68 {
69 /** TargetSslProxy name. */
70 targetSslProxyName: string;
71 /** Project id. */
72 project: string;
73 /** User description with the Alchemy ownership prefix stripped. */
74 description: string | undefined;
75 /** URL of the attached BackendService. */
76 service: string;
77 /** SslCertificate URLs. */
78 sslCertificates: string[];
79 /** Certificate Manager map URL, if set. */
80 certificateMap: string | undefined;
81 /** SslPolicy URL, if set. */
82 sslPolicy: string | undefined;
83 /** Proxy header prepended to backend connections. */
84 proxyHeader: string | undefined;
85 /** Server-defined URL. */
86 selfLink: string | undefined;
87 /** Server-assigned numeric id. */
88 targetSslProxyId: string | undefined;
89 /** RFC3339 creation timestamp. */
90 creationTimestamp: string | undefined;
91 /** Resource kind. */
92 kind: string | undefined;
93 },
94 never,
95 Providers
96 >;
97
98 /**
99 * A global Compute Engine target SSL proxy.
100 *
101 * Target SSL proxies terminate SSL/TLS for Proxy Network Load Balancers
102 * (SSL proxy). A forwarding rule points at the proxy; the proxy points at
103 * a backend service (protocol `SSL`) and one or more SSL certificates (or
104 * a Certificate Manager map).
105 *
106 * This resource maps to the global `targetSslProxies` collection. Compute
107 * TargetSslProxy has no labels field — Alchemy ownership is stored in the
108 * description so nuke can find leaked proxies. Description is immutable
109 * after create.
110 *
111 * ### Creating a Target SSL Proxy
112 * **Example:** Generated name in front of an SSL backend
113 * ```typescript
114 * const check = yield* GCP.Compute.HealthCheck("ssl", {
115 * type: "TCP",
116 * tcpHealthCheck: { port: 443 },
117 * });
118 * const backend = yield* GCP.Compute.BackendService("ssl", {
119 * protocol: "SSL",
120 * healthChecks: [check.selfLink],
121 * });
122 * const cert = yield* GCP.Compute.SslCertificate("tls", {
123 * certificate: pemCertificate,
124 * privateKey: pemPrivateKey,
125 * });
126 * const proxy = yield* GCP.Compute.TargetSslProxy("ssl", {
127 * service: backend.name,
128 * sslCertificates: [cert.sslCertificateName],
129 * });
130 * ```
131 *
132 * **Example:** Explicit name, PROXY protocol, and description
133 * ```typescript
134 * const proxy = yield* GCP.Compute.TargetSslProxy("ssl", {
135 * targetSslProxyName: "web-ssl",
136 * service: backend.selfLink,
137 * sslCertificates: [cert.selfLink],
138 * proxyHeader: "PROXY_V1",
139 * description: "public ssl",
140 * });
141 * ```
142 *
143 * ### Updating a Target SSL Proxy
144 * **Example:** Swap the backend and certificates
145 * ```typescript
146 * const proxy = yield* GCP.Compute.TargetSslProxy("ssl", {
147 * targetSslProxyName: "web-ssl",
148 * service: nextBackend.name,
149 * sslCertificates: [nextCert.sslCertificateName],
150 * proxyHeader: "PROXY_V1",
151 * });
152 * ```
153 *
154 * @resource
155 * @category Compute
156 */
157 export const TargetSslProxy = Resource<TargetSslProxy>("GCP.Compute.TargetSslProxy");
158
159 export class TargetSslProxyNotResolved extends Data.TaggedError(
160 "GCP.Compute.TargetSslProxyNotResolved",
161 )<{
162 targetSslProxyName: string;
163 }> {}
164
165 const toName = (id: string, name: string | undefined, existing?: string) =>
166 Effect.gen(function* () {
167 if (name !== undefined) return name;
168 if (existing !== undefined) return existing;
169 const generated = yield* createPhysicalName({
170 id,
171 maxLength: 63,
172 lowercase: true,
173 });
174 return /^[a-z]/.test(generated) ? generated : `s${generated}`.slice(0, 63);
175 });
176
177 const encodeDescription = (
178 labels: Record<string, string>,
179 description: string | undefined,
180 ): string => {
181 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
182 return description ? `${marker}\n${description}` : marker;
183 };
184
185 const parseDescription = (
186 description: string | undefined,
187 ): {
188 labels: Record<string, string>;
189 description: string | undefined;
190 } => {
191 if (!description?.startsWith("[alchemy ")) {
192 return { labels: {}, description };
193 }
194 const end = description.indexOf("]");
195 if (end < 0) return { labels: {}, description };
196 const labels: Record<string, string> = {};
197 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
198 const eq = part.indexOf("=");
199 if (eq > 0) {
200 labels[part.slice(0, eq)] = part.slice(eq + 1);
201 }
202 }
203 const rest = description.slice(end + 1).replace(/^\n/, "");
204 return { labels, description: rest.length > 0 ? rest : undefined };
205 };
206
207 const resourceTail = (value: string | undefined): string => {
208 if (value === undefined || value.length === 0) return "";
209 const parts = value.split("/").filter((part) => part.length > 0);
210 return parts[parts.length - 1] ?? "";
211 };
212
213 const toServiceRef = (project: string, service: string): string => {
214 if (service.includes("/")) return service;
215 return `projects/${project}/global/backendServices/${service}`;
216 };
217
218 const toSslCertRef = (project: string, cert: string): string => {
219 if (cert.includes("/")) return cert;
220 return `projects/${project}/global/sslCertificates/${cert}`;
221 };
222
223 const sameResourceList = (
224 left: readonly string[] | undefined,
225 right: readonly string[] | undefined,
226 ) => {
227 const a = [...(left ?? [])].map(resourceTail).sort();
228 const b = [...(right ?? [])].map(resourceTail).sort();
229 return a.length === b.length && a.every((value, i) => value === b[i]);
230 };
231
232 const toAttrs = (proxy: compute.TargetSslProxy, project: string) => {
233 const parsed = parseDescription(proxy.description);
234 return {
235 targetSslProxyName: proxy.name ?? proxy.id ?? "",
236 project,
237 description: parsed.description,
238 service: proxy.service ?? "",
239 sslCertificates: [...(proxy.sslCertificates ?? [])],
240 certificateMap: proxy.certificateMap,
241 sslPolicy: proxy.sslPolicy,
242 proxyHeader: proxy.proxyHeader,
243 selfLink: proxy.selfLink,
244 targetSslProxyId: proxy.id,
245 creationTimestamp: proxy.creationTimestamp,
246 kind: proxy.kind,
247 };
248 };
249
250 const getByName = (project: string, targetSslProxy: string) =>
251 compute
252 .getTargetSslProxies({ project, targetSslProxy })
253 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
254
255 export const TargetSslProxyProvider = () =>
256 Provider.succeed(TargetSslProxy, {
257 stables: ["targetSslProxyName", "project", "targetSslProxyId", "selfLink", "creationTimestamp"],
258
259 diff: Effect.fn(function* ({ news, olds, output }) {
260 if (!isResolved(news)) return undefined;
261 const previousName = olds?.targetSslProxyName ?? output?.targetSslProxyName;
262 const nextName = news.targetSslProxyName;
263 if (previousName !== undefined && nextName !== undefined && previousName !== nextName) {
264 return { action: "replace" as const, deleteFirst: true };
265 }
266 const previousDescription = olds?.description ?? output?.description;
267 if (
268 (olds !== undefined || output !== undefined) &&
269 previousDescription !== news.description
270 ) {
271 return { action: "replace" as const, deleteFirst: true };
272 }
273 return undefined;
274 }),
275
276 read: Effect.fn(function* ({ id, olds, output, previous }) {
277 const env = yield* GcpEnvironment.current;
278 const targetSslProxyName = yield* toName(
279 id,
280 olds?.targetSslProxyName,
281 output?.targetSslProxyName,
282 );
283 const existing = yield* getByName(env.project, targetSslProxyName);
284 if (existing === undefined) return undefined;
285 const attrs = toAttrs(existing, env.project);
286 const { labels } = parseDescription(existing.description);
287 return (yield* hasAlchemyLabels(id, labels))
288 ? attrs
289 : unownedUnlessPrevious(attrs, previous, "targetSslProxyName");
290 }),
291
292 list: () =>
293 Effect.gen(function* () {
294 const env = yield* GcpEnvironment.current;
295 return yield* compute.listTargetSslProxies
296 .items({ project: env.project, maxResults: 500 })
297 .pipe(
298 Stream.filter((proxy) => {
299 const { labels } = parseDescription(proxy.description);
300 return Object.keys(labels).some((key) => key.startsWith("alchemy-"));
301 }),
302 Stream.map((proxy) => toAttrs(proxy, env.project)),
303 Stream.runCollect,
304 Effect.map((chunk) => Array.from(chunk)),
305 );
306 }),
307
308 reconcile: Effect.fn(function* ({ id, news, output }) {
309 const env = yield* GcpEnvironment.current;
310 const targetSslProxyName = yield* toName(
311 id,
312 news.targetSslProxyName,
313 output?.targetSslProxyName,
314 );
315 const ownership = yield* createInternalLabels(id);
316 const desiredDescription = encodeDescription(ownership, news.description);
317 const desiredService = toServiceRef(env.project, news.service);
318 const desiredCerts = (news.sslCertificates ?? []).map((cert) =>
319 toSslCertRef(env.project, cert),
320 );
321 const desiredProxyHeader = news.proxyHeader ?? DEFAULT_PROXY_HEADER;
322
323 let current = yield* getByName(env.project, targetSslProxyName);
324
325 if (current === undefined) {
326 const body: compute.TargetSslProxy = {
327 name: targetSslProxyName,
328 description: desiredDescription,
329 service: desiredService,
330 };
331 if (desiredCerts.length > 0) {
332 body.sslCertificates = desiredCerts;
333 }
334 if (news.certificateMap !== undefined) {
335 body.certificateMap = news.certificateMap;
336 }
337 if (news.sslPolicy !== undefined) {
338 body.sslPolicy = news.sslPolicy;
339 }
340 if (news.proxyHeader !== undefined) {
341 body.proxyHeader = news.proxyHeader;
342 }
343 yield* compute
344 .insertTargetSslProxies({
345 project: env.project,
346 body,
347 })
348 .pipe(
349 Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)),
350 Effect.catchTag("Conflict", () => Effect.undefined),
351 );
352 current = yield* getByName(env.project, targetSslProxyName);
353 }
354
355 if (current === undefined) {
356 return yield* new TargetSslProxyNotResolved({
357 targetSslProxyName,
358 });
359 }
360
361 if (resourceTail(current.service) !== resourceTail(desiredService)) {
362 yield* compute
363 .setBackendServiceTargetSslProxies({
364 project: env.project,
365 targetSslProxy: targetSslProxyName,
366 body: { service: desiredService },
367 })
368 .pipe(Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)));
369 current = yield* getByName(env.project, targetSslProxyName);
370 if (current === undefined) {
371 return yield* new TargetSslProxyNotResolved({
372 targetSslProxyName,
373 });
374 }
375 }
376
377 if (
378 news.sslCertificates !== undefined &&
379 !sameResourceList(current.sslCertificates, desiredCerts)
380 ) {
381 yield* compute
382 .setSslCertificatesTargetSslProxies({
383 project: env.project,
384 targetSslProxy: targetSslProxyName,
385 body: { sslCertificates: desiredCerts },
386 })
387 .pipe(Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)));
388 current = yield* getByName(env.project, targetSslProxyName);
389 if (current === undefined) {
390 return yield* new TargetSslProxyNotResolved({
391 targetSslProxyName,
392 });
393 }
394 }
395
396 if (
397 news.certificateMap !== undefined &&
398 (current.certificateMap ?? "") !== news.certificateMap
399 ) {
400 yield* compute
401 .setCertificateMapTargetSslProxies({
402 project: env.project,
403 targetSslProxy: targetSslProxyName,
404 body: { certificateMap: news.certificateMap },
405 })
406 .pipe(Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)));
407 current = yield* getByName(env.project, targetSslProxyName);
408 if (current === undefined) {
409 return yield* new TargetSslProxyNotResolved({
410 targetSslProxyName,
411 });
412 }
413 }
414
415 if ((current.proxyHeader ?? DEFAULT_PROXY_HEADER) !== desiredProxyHeader) {
416 yield* compute
417 .setProxyHeaderTargetSslProxies({
418 project: env.project,
419 targetSslProxy: targetSslProxyName,
420 body: { proxyHeader: desiredProxyHeader },
421 })
422 .pipe(Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)));
423 current = yield* getByName(env.project, targetSslProxyName);
424 if (current === undefined) {
425 return yield* new TargetSslProxyNotResolved({
426 targetSslProxyName,
427 });
428 }
429 }
430
431 if (news.sslPolicy !== undefined && (current.sslPolicy ?? "") !== news.sslPolicy) {
432 yield* compute
433 .setSslPolicyTargetSslProxies({
434 project: env.project,
435 targetSslProxy: targetSslProxyName,
436 body: { sslPolicy: news.sslPolicy },
437 })
438 .pipe(Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)));
439 current = yield* getByName(env.project, targetSslProxyName);
440 if (current === undefined) {
441 return yield* new TargetSslProxyNotResolved({
442 targetSslProxyName,
443 });
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 operation = yield* compute
453 .deleteTargetSslProxies({
454 project: env.project,
455 targetSslProxy: output.targetSslProxyName,
456 })
457 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
458 if (operation !== undefined) {
459 yield* waitGlobalOperation(env.project, operation).pipe(
460 Effect.catchTag("NotFound", () => Effect.void),
461 );
462 }
463 }),
464 });