@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, 06:00 UTC

main
ts 480 lines 15.4 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 { waitGlobalOperation } from "./operations.ts";
15
16 export type SslCertificateType = "SELF_MANAGED" | "MANAGED";
17
18 export type SslCertificateSelfManaged = {
19 /** PEM-encoded certificate chain. Leaf first, then intermediates. */
20 certificate?: string;
21 /** PEM-encoded private key. Write-only on insert. */
22 privateKey?: string;
23 };
24
25 export type SslCertificateManaged = {
26 /**
27 * Domains for a Google-managed certificate. Each certificate supports
28 * up to the project quota (typically 100).
29 */
30 domains?: string[];
31 };
32
33 export type SslCertificateProps = {
34 /**
35 * Certificate name (RFC1035, 1-63 chars). If omitted, a unique name is
36 * generated from the stack, stage, and logical id. Changing it replaces
37 * the resource.
38 */
39 sslCertificateName?: string;
40 /**
41 * Optional description. Compute SSL certificates have no labels field
42 * and no update API, so Alchemy ownership is stored in a `[alchemy …]`
43 * prefix and any description change replaces the certificate.
44 */
45 description?: string;
46 /**
47 * `SELF_MANAGED` (upload PEM) or `MANAGED` (Google provisions). Inferred
48 * from `managed.domains` vs `certificate` / `selfManaged` when omitted.
49 * Immutable — changing it replaces the certificate.
50 * @default "SELF_MANAGED"
51 */
52 type?: SslCertificateType;
53 /**
54 * PEM certificate chain for a self-managed certificate. Immutable —
55 * changing it replaces the certificate.
56 */
57 certificate?: string;
58 /**
59 * PEM private key for a self-managed certificate. Write-only; not
60 * returned by the API. Immutable — changing it replaces the certificate.
61 */
62 privateKey?: string;
63 /**
64 * Nested self-managed payload. `certificate` / `privateKey` on the
65 * resource take precedence when both are set.
66 */
67 selfManaged?: SslCertificateSelfManaged;
68 /**
69 * Google-managed certificate configuration. Immutable — changing domains
70 * replaces the certificate.
71 */
72 managed?: SslCertificateManaged;
73 };
74
75 export type SslCertificate = Resource<
76 "GCP.Compute.SslCertificate",
77 SslCertificateProps,
78 {
79 /** Certificate name. */
80 sslCertificateName: string;
81 /** Project id. */
82 project: string;
83 /** `SELF_MANAGED` or `MANAGED`. */
84 type: SslCertificateType;
85 /** User description with the Alchemy ownership prefix stripped. */
86 description: string | undefined;
87 /** PEM certificate returned by the API (self-managed; empty until a managed cert is ACTIVE). */
88 certificate: string | undefined;
89 /** RFC3339 expiry, if known. */
90 expireTime: string | undefined;
91 /** Subject alternative names on the certificate. */
92 subjectAlternativeNames: string[];
93 /** Google-managed domains, if this is a managed certificate. */
94 managedDomains: string[];
95 /** Provisioning status of a managed certificate. */
96 managedStatus: string | undefined;
97 /** Per-domain status of a managed certificate. */
98 managedDomainStatus: Record<string, string>;
99 /** Server-defined URL. */
100 selfLink: string | undefined;
101 /** Server-assigned numeric id. */
102 sslCertificateId: string | undefined;
103 /** RFC3339 creation timestamp. */
104 creationTimestamp: string | undefined;
105 /** Resource kind. */
106 kind: string | undefined;
107 },
108 never,
109 Providers
110 >;
111
112 /**
113 * A global Compute Engine SSL certificate for HTTPS / SSL load balancing.
114 *
115 * Maps to the global `sslCertificates` collection (`regionSslCertificates`
116 * is a separate resource). Certificates cannot be updated in place — every
117 * user-facing field is immutable and changing it replaces the resource.
118 * Compute SSL certificates have no labels field, so Alchemy stamps
119 * ownership into the description for `list` / nuke.
120 *
121 * ### Creating a Self-Managed Certificate
122 * **Example:** Generated name
123 * ```typescript
124 * const cert = yield* GCP.Compute.SslCertificate("Frontend", {
125 * certificate: pemCertificate,
126 * privateKey: pemPrivateKey,
127 * });
128 * ```
129 *
130 * **Example:** Named certificate with a description
131 * ```typescript
132 * const cert = yield* GCP.Compute.SslCertificate("Frontend", {
133 * sslCertificateName: "app-frontend-tls",
134 * description: "prod frontend",
135 * certificate: pemCertificate,
136 * privateKey: pemPrivateKey,
137 * });
138 * ```
139 *
140 * ### Google-Managed Certificates
141 * **Example:** Provision a managed certificate for a domain
142 * ```typescript
143 * const cert = yield* GCP.Compute.SslCertificate("Frontend", {
144 * type: "MANAGED",
145 * managed: { domains: ["www.example.com"] },
146 * });
147 * ```
148 *
149 * @resource
150 * @category Compute
151 */
152 export const SslCertificate = Resource<SslCertificate>("GCP.Compute.SslCertificate");
153
154 export class SslCertificateNotResolved extends Data.TaggedError(
155 "GCP.Compute.SslCertificateNotResolved",
156 )<{
157 sslCertificateName: string;
158 }> {}
159
160 const rfc1035 = (name: string): string => {
161 let next = name
162 .toLowerCase()
163 .replace(/[^a-z0-9-]/g, "-")
164 .replace(/-+/g, "-")
165 .replace(/^-+/, "")
166 .replace(/-+$/, "");
167 if (!/^[a-z]/.test(next)) {
168 next = `s${next}`;
169 }
170 next = next.slice(0, 63).replace(/-+$/, "");
171 return next.length > 0 ? next : "sslcert";
172 };
173
174 const toName = (id: string, name: string | undefined, existing?: string) =>
175 Effect.gen(function* () {
176 if (name !== undefined) return name;
177 if (existing !== undefined) return existing;
178 return rfc1035(
179 yield* createPhysicalName({
180 id,
181 maxLength: 63,
182 lowercase: true,
183 }),
184 );
185 });
186
187 const encodeDescription = (
188 labels: Record<string, string>,
189 description: string | undefined,
190 ): string => {
191 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
192 return description ? `${marker}\n${description}` : marker;
193 };
194
195 const parseDescription = (
196 description: string | undefined,
197 ): {
198 labels: Record<string, string>;
199 description: string | undefined;
200 } => {
201 if (!description?.startsWith("[alchemy ")) {
202 return { labels: {}, description };
203 }
204 const end = description.indexOf("]");
205 if (end < 0) return { labels: {}, description };
206 const labels: Record<string, string> = {};
207 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
208 const eq = part.indexOf("=");
209 if (eq > 0) {
210 labels[part.slice(0, eq)] = part.slice(eq + 1);
211 }
212 }
213 const rest = description.slice(end + 1).replace(/^\n/, "");
214 return { labels, description: rest.length > 0 ? rest : undefined };
215 };
216
217 const hasOwnershipMarker = (description: string | undefined): boolean =>
218 (description ?? "").startsWith("[alchemy ");
219
220 const typeOf = (props: {
221 type?: string;
222 managed?: SslCertificateManaged;
223 certificate?: string;
224 selfManaged?: SslCertificateSelfManaged;
225 }): SslCertificateType => {
226 if (props.type === "MANAGED" || props.type === "SELF_MANAGED") {
227 return props.type;
228 }
229 if ((props.managed?.domains?.length ?? 0) > 0) return "MANAGED";
230 return "SELF_MANAGED";
231 };
232
233 const asType = (type: string | undefined): SslCertificateType =>
234 type === "MANAGED" ? "MANAGED" : "SELF_MANAGED";
235
236 const selfManagedOf = (props: {
237 certificate?: string;
238 privateKey?: string;
239 selfManaged?: SslCertificateSelfManaged;
240 }) => ({
241 certificate: props.certificate ?? props.selfManaged?.certificate,
242 privateKey: props.privateKey ?? props.selfManaged?.privateKey,
243 });
244
245 const normalizePem = (pem: string | undefined): string => (pem ?? "").replace(/\s+/g, "");
246
247 const sameDomains = (left?: readonly string[], right?: readonly string[]) =>
248 [...(left ?? [])].sort().join("\0") === [...(right ?? [])].sort().join("\0");
249
250 const toBody = (
251 sslCertificateName: string,
252 props: SslCertificateProps,
253 ownership: Record<string, string>,
254 ): compute.SslCertificate => {
255 const type = typeOf(props);
256 const description = encodeDescription(ownership, props.description);
257 if (type === "MANAGED") {
258 return {
259 name: sslCertificateName,
260 description,
261 type: "MANAGED",
262 managed: { domains: props.managed?.domains },
263 };
264 }
265 const material = selfManagedOf(props);
266 return {
267 name: sslCertificateName,
268 description,
269 type: "SELF_MANAGED",
270 certificate: material.certificate,
271 privateKey: material.privateKey,
272 selfManaged: {
273 certificate: material.certificate,
274 privateKey: material.privateKey,
275 },
276 };
277 };
278
279 const toAttrs = (cert: compute.SslCertificate, project: string) => {
280 const parsed = parseDescription(cert.description);
281 return {
282 sslCertificateName: cert.name ?? cert.id ?? "",
283 project,
284 type: asType(cert.type),
285 description: parsed.description,
286 certificate: cert.certificate,
287 expireTime: cert.expireTime,
288 subjectAlternativeNames: cert.subjectAlternativeNames ?? [],
289 managedDomains: cert.managed?.domains ?? [],
290 managedStatus: cert.managed?.status,
291 managedDomainStatus: Object.fromEntries(
292 Object.entries(cert.managed?.domainStatus ?? {}).filter(
293 (entry): entry is [string, string] => typeof entry[1] === "string",
294 ),
295 ),
296 selfLink: cert.selfLink,
297 sslCertificateId: cert.id,
298 creationTimestamp: cert.creationTimestamp,
299 kind: cert.kind,
300 };
301 };
302
303 const getByName = (project: string, sslCertificate: string) =>
304 compute
305 .getSslCertificates({ project, sslCertificate })
306 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
307
308 const awaitResource = (project: string, sslCertificateName: string) =>
309 getByName(project, sslCertificateName).pipe(
310 Effect.repeat({
311 schedule: Schedule.spaced("1 second"),
312 until: (cert) => cert !== undefined,
313 times: 8,
314 }),
315 );
316
317 const immutableChanged = (
318 news: SslCertificateProps,
319 olds: Partial<SslCertificateProps> | undefined,
320 output: SslCertificate["Attributes"] | undefined,
321 ) => {
322 const previousType = typeOf({
323 type: olds?.type ?? output?.type,
324 managed: olds?.managed ?? { domains: output?.managedDomains },
325 certificate: olds?.certificate ?? output?.certificate,
326 selfManaged: olds?.selfManaged,
327 });
328 if (typeOf(news) !== previousType) return true;
329
330 const previousDescription = olds?.description ?? output?.description ?? "";
331 if ((news.description ?? "") !== previousDescription) return true;
332
333 if (typeOf(news) === "MANAGED") {
334 const previousDomains = olds?.managed?.domains ?? output?.managedDomains ?? [];
335 if (
336 news.managed?.domains !== undefined &&
337 !sameDomains(news.managed.domains, previousDomains)
338 ) {
339 return true;
340 }
341 return false;
342 }
343
344 const nextMaterial = selfManagedOf(news);
345 const previousMaterial = selfManagedOf({
346 certificate: olds?.certificate ?? output?.certificate,
347 privateKey: olds?.privateKey,
348 selfManaged: olds?.selfManaged,
349 });
350 if (
351 nextMaterial.certificate !== undefined &&
352 normalizePem(nextMaterial.certificate) !== normalizePem(previousMaterial.certificate)
353 ) {
354 return true;
355 }
356 if (
357 nextMaterial.privateKey !== undefined &&
358 previousMaterial.privateKey !== undefined &&
359 normalizePem(nextMaterial.privateKey) !== normalizePem(previousMaterial.privateKey)
360 ) {
361 return true;
362 }
363 return false;
364 };
365
366 export const SslCertificateProvider = () =>
367 Provider.succeed(SslCertificate, {
368 stables: [
369 "sslCertificateName",
370 "project",
371 "sslCertificateId",
372 "selfLink",
373 "creationTimestamp",
374 "type",
375 ],
376
377 diff: Effect.fn(function* ({ news, olds, output }) {
378 if (!isResolved(news)) return undefined;
379 const previousName = olds?.sslCertificateName ?? output?.sslCertificateName;
380 const nextName = news.sslCertificateName ?? previousName;
381 if (previousName === undefined && output === undefined) {
382 return undefined;
383 }
384 const nameChanged =
385 news.sslCertificateName !== undefined &&
386 previousName !== undefined &&
387 news.sslCertificateName !== previousName;
388 if (nameChanged || immutableChanged(news, olds, output)) {
389 return {
390 action: "replace" as const,
391 deleteFirst: nextName !== undefined && nextName === previousName,
392 };
393 }
394 return undefined;
395 }),
396
397 read: Effect.fn(function* ({ id, olds, output }) {
398 const env = yield* GcpEnvironment.current;
399 const sslCertificateName = yield* toName(
400 id,
401 olds?.sslCertificateName,
402 output?.sslCertificateName,
403 );
404 const existing = yield* getByName(env.project, sslCertificateName);
405 if (existing === undefined) return undefined;
406 const attrs = toAttrs(existing, env.project);
407 const { labels } = parseDescription(existing.description);
408 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
409 }),
410
411 list: () =>
412 Effect.gen(function* () {
413 const env = yield* GcpEnvironment.current;
414 return yield* compute.listSslCertificates
415 .items({ project: env.project, maxResults: 500 })
416 .pipe(
417 Stream.filter((cert) => hasOwnershipMarker(cert.description)),
418 Stream.map((cert) => toAttrs(cert, env.project)),
419 Stream.runCollect,
420 Effect.map((chunk) => Array.from(chunk)),
421 );
422 }),
423
424 reconcile: Effect.fn(function* ({ id, news, output }) {
425 const env = yield* GcpEnvironment.current;
426 const sslCertificateName = yield* toName(
427 id,
428 news.sslCertificateName,
429 output?.sslCertificateName,
430 );
431 const ownership = yield* createInternalLabels(id);
432 const desired = toBody(sslCertificateName, news, ownership);
433
434 let current = yield* getByName(env.project, sslCertificateName);
435
436 if (current === undefined) {
437 const created = yield* compute
438 .insertSslCertificates({
439 project: env.project,
440 body: desired,
441 })
442 .pipe(
443 Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)),
444 Effect.catchTag("Conflict", () => Effect.undefined),
445 );
446 current =
447 created !== undefined
448 ? yield* awaitResource(env.project, sslCertificateName)
449 : yield* getByName(env.project, sslCertificateName);
450 }
451
452 if (current === undefined) {
453 return yield* new SslCertificateNotResolved({ sslCertificateName });
454 }
455
456 return toAttrs(current, env.project);
457 }),
458
459 delete: Effect.fn(function* ({ output }) {
460 const env = yield* GcpEnvironment.current;
461 const operation = yield* compute
462 .deleteSslCertificates({
463 project: env.project,
464 sslCertificate: output.sslCertificateName,
465 })
466 .pipe(
467 Effect.retry({
468 while: (e) => e._tag === "Conflict",
469 times: 8,
470 schedule: Schedule.spaced("2 seconds"),
471 }),
472 Effect.catchTag("NotFound", () => Effect.undefined),
473 );
474 if (operation !== undefined) {
475 yield* waitGlobalOperation(env.project, operation).pipe(
476 Effect.catchTag("NotFound", () => Effect.void),
477 );
478 }
479 }),
480 });