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