The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as certificatemanager from "@distilled.cloud/gcp/certificatemanager_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 { tagRecord } from "alchemy/Tags"; |
| 8 | import * as Data from "effect/Data"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import * as Schedule from "effect/Schedule"; |
| 11 | import * as Stream from "effect/Stream"; |
| 12 | import { GcpEnvironment } from "../Environment.ts"; |
| 13 | import { |
| 14 | createInternalLabels, |
| 15 | diffLabels, |
| 16 | hasAlchemyLabels, |
| 17 | stripInternalLabels, |
| 18 | toLabels, |
| 19 | } from "../Labels.ts"; |
| 20 | import type { Providers } from "../Providers.ts"; |
| 21 | import { waitForOperation } from "./operations.ts"; |
| 22 | |
| 23 | const DEFAULT_LOCATION = "global"; |
| 24 | const DEFAULT_SCOPE = "DEFAULT"; |
| 25 | const MAX_NAME_LENGTH = 63; |
| 26 | |
| 27 | export type CertificateType = "SELF_MANAGED" | "MANAGED" | "MANAGED_IDENTITY"; |
| 28 | |
| 29 | export type CertificateScope = "DEFAULT" | "EDGE_CACHE" | "ALL_REGIONS" | "CLIENT_AUTH"; |
| 30 | |
| 31 | export type CertificateSelfManaged = { |
| 32 | /** PEM-encoded certificate chain. Leaf first, then intermediates. Input-only. */ |
| 33 | pemCertificate?: string; |
| 34 | /** PEM-encoded private key of the leaf certificate. Input-only. */ |
| 35 | pemPrivateKey?: string; |
| 36 | }; |
| 37 | |
| 38 | export type CertificateManaged = { |
| 39 | /** |
| 40 | * Domains covered by a Google-managed certificate. Wildcard domains |
| 41 | * require DNS authorization. Immutable — changing them replaces the |
| 42 | * certificate. |
| 43 | */ |
| 44 | domains?: string[]; |
| 45 | /** |
| 46 | * DnsAuthorization resource names used to prove domain ownership. |
| 47 | * Immutable — changing them replaces the certificate. |
| 48 | */ |
| 49 | dnsAuthorizations?: string[]; |
| 50 | /** |
| 51 | * CertificateIssuanceConfig resource name for private PKI certificates. |
| 52 | * Immutable — changing it replaces the certificate. |
| 53 | */ |
| 54 | issuanceConfig?: string; |
| 55 | }; |
| 56 | |
| 57 | export type CertificateManagedIdentity = { |
| 58 | /** |
| 59 | * SPIFFE ID of the Managed Identity used for this certificate. |
| 60 | * Immutable — changing it replaces the certificate. |
| 61 | */ |
| 62 | identity?: string; |
| 63 | }; |
| 64 | |
| 65 | export type CertificateProps = { |
| 66 | /** |
| 67 | * Certificate id (the `{certificate}` segment of |
| 68 | * `projects/{project}/locations/{location}/certificates/{certificate}`). |
| 69 | * If omitted, a unique name is generated from the stack, stage, and |
| 70 | * logical id. Must be 1-63 characters, start with a letter, and match |
| 71 | * `[a-zA-Z][a-zA-Z0-9_-]*`. Immutable — changing it replaces the |
| 72 | * certificate. |
| 73 | */ |
| 74 | certificateId?: string; |
| 75 | /** |
| 76 | * Certificate Manager location (`global`, `us-central1`, …). Immutable — |
| 77 | * changing it replaces the certificate. `US-CENTRAL1` is accepted and |
| 78 | * normalized to `us-central1`. `DEFAULT` / `EDGE_CACHE` / `CLIENT_AUTH` |
| 79 | * / `ALL_REGIONS` certificates live in `global`; omit or set a region |
| 80 | * for a regional certificate. |
| 81 | * @default "global" |
| 82 | */ |
| 83 | location?: string; |
| 84 | /** |
| 85 | * Human-readable description. |
| 86 | */ |
| 87 | description?: string; |
| 88 | /** |
| 89 | * User labels. Alchemy ownership labels are merged in automatically. |
| 90 | */ |
| 91 | labels?: Record<string, string>; |
| 92 | /** |
| 93 | * Certificate serving scope. Immutable — changing it replaces the |
| 94 | * certificate. Inferred from `managed` / `selfManaged` / `managedIdentity` |
| 95 | * when omitted. |
| 96 | * @default "DEFAULT" |
| 97 | */ |
| 98 | scope?: CertificateScope | (string & {}); |
| 99 | /** |
| 100 | * `SELF_MANAGED` (upload PEM), `MANAGED` (Google provisions), or |
| 101 | * `MANAGED_IDENTITY`. Inferred from nested blocks when omitted. |
| 102 | * Immutable — changing it replaces the certificate. |
| 103 | * @default "SELF_MANAGED" |
| 104 | */ |
| 105 | type?: CertificateType; |
| 106 | /** |
| 107 | * PEM certificate chain for a self-managed certificate. Input-only. |
| 108 | * Changing it replaces the certificate. |
| 109 | */ |
| 110 | pemCertificate?: string; |
| 111 | /** |
| 112 | * PEM private key for a self-managed certificate. Input-only. Changing |
| 113 | * it replaces the certificate. |
| 114 | */ |
| 115 | pemPrivateKey?: string; |
| 116 | /** |
| 117 | * Nested self-managed payload. Top-level `pemCertificate` / |
| 118 | * `pemPrivateKey` take precedence when both are set. |
| 119 | */ |
| 120 | selfManaged?: CertificateSelfManaged; |
| 121 | /** |
| 122 | * Google-managed certificate configuration. Immutable — changing |
| 123 | * domains, DNS authorizations, or issuance config replaces the |
| 124 | * certificate. |
| 125 | */ |
| 126 | managed?: CertificateManaged; |
| 127 | /** |
| 128 | * Managed-identity certificate configuration. Immutable — changing |
| 129 | * the identity replaces the certificate. |
| 130 | */ |
| 131 | managedIdentity?: CertificateManagedIdentity; |
| 132 | }; |
| 133 | |
| 134 | export type Certificate = Resource< |
| 135 | "GCP.CertificateManager.Certificate", |
| 136 | CertificateProps, |
| 137 | { |
| 138 | /** Full resource name `projects/{project}/locations/{location}/certificates/{certificate}`. */ |
| 139 | name: string; |
| 140 | /** Certificate id (last path segment). */ |
| 141 | certificateId: string; |
| 142 | /** Project id. */ |
| 143 | project: string; |
| 144 | /** Location id (`global`, `us-central1`, …). */ |
| 145 | location: string; |
| 146 | /** `SELF_MANAGED`, `MANAGED`, or `MANAGED_IDENTITY`. */ |
| 147 | type: CertificateType; |
| 148 | /** Serving scope (`DEFAULT`, `EDGE_CACHE`, `ALL_REGIONS`, `CLIENT_AUTH`). */ |
| 149 | scope: string; |
| 150 | /** User-provided description. */ |
| 151 | description: string | undefined; |
| 152 | /** User labels (Alchemy ownership labels stripped). */ |
| 153 | labels: Record<string, string>; |
| 154 | /** PEM certificate chain returned by the API. */ |
| 155 | pemCertificate: string | undefined; |
| 156 | /** Subject alternative DNS names on the certificate. */ |
| 157 | sanDnsnames: string[]; |
| 158 | /** RFC3339 expiry, if known. */ |
| 159 | expireTime: string | undefined; |
| 160 | /** Google-managed domains, if this is a managed certificate. */ |
| 161 | managedDomains: string[]; |
| 162 | /** Provisioning state of a managed certificate. */ |
| 163 | managedState: string | undefined; |
| 164 | /** DnsAuthorization names used by a managed certificate. */ |
| 165 | managedDnsAuthorizations: string[]; |
| 166 | /** CertificateIssuanceConfig name, if set. */ |
| 167 | issuanceConfig: string | undefined; |
| 168 | /** SPIFFE identity of a managed-identity certificate. */ |
| 169 | managedIdentity: string | undefined; |
| 170 | /** Provisioning-issue reason, if the managed certificate failed. */ |
| 171 | provisioningIssue: string | undefined; |
| 172 | /** Resource names that currently reference this certificate. */ |
| 173 | usedBy: string[]; |
| 174 | /** RFC3339 creation timestamp. */ |
| 175 | createTime: string | undefined; |
| 176 | /** RFC3339 last-update timestamp. */ |
| 177 | updateTime: string | undefined; |
| 178 | }, |
| 179 | never, |
| 180 | Providers |
| 181 | >; |
| 182 | |
| 183 | /** |
| 184 | * A Certificate Manager TLS certificate — self-managed (uploaded PEM), |
| 185 | * Google-managed, or managed-identity. |
| 186 | * |
| 187 | * Changing `certificateId`, `location`, `scope`, certificate type, |
| 188 | * managed-certificate configuration, or self-managed PEM replaces the |
| 189 | * resource (Certificate Manager rejects in-place SAN list updates). |
| 190 | * Description and labels update in place. |
| 191 | * |
| 192 | * ### Creating a Self-Managed Certificate |
| 193 | * **Example:** Generated name |
| 194 | * ```typescript |
| 195 | * const cert = yield* GCP.CertificateManager.Certificate("FrontendTls", { |
| 196 | * pemCertificate, |
| 197 | * pemPrivateKey, |
| 198 | * }); |
| 199 | * ``` |
| 200 | * |
| 201 | * **Example:** Named certificate with labels |
| 202 | * ```typescript |
| 203 | * const cert = yield* GCP.CertificateManager.Certificate("FrontendTls", { |
| 204 | * certificateId: "app-frontend-tls", |
| 205 | * description: "prod frontend", |
| 206 | * labels: { env: "prod" }, |
| 207 | * selfManaged: { |
| 208 | * pemCertificate, |
| 209 | * pemPrivateKey, |
| 210 | * }, |
| 211 | * }); |
| 212 | * ``` |
| 213 | * |
| 214 | * ### Google-Managed Certificates |
| 215 | * **Example:** Provision a managed certificate for a domain |
| 216 | * ```typescript |
| 217 | * const cert = yield* GCP.CertificateManager.Certificate("FrontendTls", { |
| 218 | * type: "MANAGED", |
| 219 | * managed: { |
| 220 | * domains: ["www.example.com"], |
| 221 | * dnsAuthorizations: [authorization.name], |
| 222 | * }, |
| 223 | * }); |
| 224 | * ``` |
| 225 | * |
| 226 | * ### Regional Certificates |
| 227 | * **Example:** Self-managed certificate in us-central1 |
| 228 | * ```typescript |
| 229 | * const cert = yield* GCP.CertificateManager.Certificate("RegionalTls", { |
| 230 | * location: "us-central1", |
| 231 | * pemCertificate, |
| 232 | * pemPrivateKey, |
| 233 | * }); |
| 234 | * ``` |
| 235 | * |
| 236 | * @resource |
| 237 | * @category CertificateManager |
| 238 | */ |
| 239 | export const Certificate = Resource<Certificate>("GCP.CertificateManager.Certificate"); |
| 240 | |
| 241 | export class CertificateNotResolved extends Data.TaggedError( |
| 242 | "GCP.CertificateManager.CertificateNotResolved", |
| 243 | )<{ |
| 244 | resourceName: string; |
| 245 | }> {} |
| 246 | |
| 247 | export class CertificateStillExists extends Data.TaggedError( |
| 248 | "GCP.CertificateManager.CertificateStillExists", |
| 249 | )<{ |
| 250 | resourceName: string; |
| 251 | }> {} |
| 252 | |
| 253 | const lastSegment = (value: string) => { |
| 254 | const trimmed = value.replace(/\/+$/, ""); |
| 255 | const parts = trimmed.split("/"); |
| 256 | return parts[parts.length - 1] || trimmed; |
| 257 | }; |
| 258 | |
| 259 | const rfc1035 = (name: string): string => { |
| 260 | let next = name |
| 261 | .toLowerCase() |
| 262 | .replace(/[^a-z0-9-]/g, "-") |
| 263 | .replace(/-+/g, "-") |
| 264 | .replace(/^-+/, "") |
| 265 | .replace(/-+$/, ""); |
| 266 | if (!/^[a-z]/.test(next)) { |
| 267 | next = `c${next}`; |
| 268 | } |
| 269 | next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/, ""); |
| 270 | return next.length > 0 ? next : "certificate"; |
| 271 | }; |
| 272 | |
| 273 | const normalizeLocation = (location: string | undefined) => |
| 274 | lastSegment(location ?? DEFAULT_LOCATION).toLowerCase(); |
| 275 | |
| 276 | const normalizeScope = (scope: string | undefined) => { |
| 277 | const value = (scope ?? DEFAULT_SCOPE).toUpperCase(); |
| 278 | return value === "SCOPE_UNSPECIFIED" || value === "" ? DEFAULT_SCOPE : value; |
| 279 | }; |
| 280 | |
| 281 | const resourceName = (project: string, location: string, certificateId: string) => |
| 282 | `projects/${project}/locations/${location}/certificates/${certificateId}`; |
| 283 | |
| 284 | const parseName = (name: string) => { |
| 285 | const parts = name.split("/").filter((part) => part.length > 0); |
| 286 | const certificatesAt = parts.lastIndexOf("certificates"); |
| 287 | const locationsAt = parts.lastIndexOf("locations"); |
| 288 | const projectsAt = parts.lastIndexOf("projects"); |
| 289 | return { |
| 290 | project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "", |
| 291 | location: |
| 292 | locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : DEFAULT_LOCATION, |
| 293 | certificateId: |
| 294 | certificatesAt >= 0 && parts[certificatesAt + 1] |
| 295 | ? parts[certificatesAt + 1]! |
| 296 | : lastSegment(name), |
| 297 | }; |
| 298 | }; |
| 299 | |
| 300 | const userLabels = ( |
| 301 | labels: Record<string, string | undefined> | null | undefined, |
| 302 | ): Record<string, string> => stripInternalLabels(tagRecord(labels)); |
| 303 | |
| 304 | const toId = (id: string, certificateId: string | undefined, existing?: string) => |
| 305 | Effect.gen(function* () { |
| 306 | if (certificateId !== undefined) return certificateId; |
| 307 | if (existing !== undefined) return existing; |
| 308 | return rfc1035( |
| 309 | yield* createPhysicalName({ |
| 310 | id, |
| 311 | maxLength: MAX_NAME_LENGTH, |
| 312 | lowercase: true, |
| 313 | }), |
| 314 | ); |
| 315 | }); |
| 316 | |
| 317 | const selfManagedOf = (props: { |
| 318 | pemCertificate?: string; |
| 319 | pemPrivateKey?: string; |
| 320 | selfManaged?: CertificateSelfManaged; |
| 321 | }): CertificateSelfManaged => ({ |
| 322 | pemCertificate: props.pemCertificate ?? props.selfManaged?.pemCertificate, |
| 323 | pemPrivateKey: props.pemPrivateKey ?? props.selfManaged?.pemPrivateKey, |
| 324 | }); |
| 325 | |
| 326 | const typeOf = ( |
| 327 | props: { |
| 328 | type?: string; |
| 329 | managed?: CertificateManaged; |
| 330 | managedIdentity?: CertificateManagedIdentity; |
| 331 | pemCertificate?: string; |
| 332 | pemPrivateKey?: string; |
| 333 | selfManaged?: CertificateSelfManaged; |
| 334 | }, |
| 335 | fallback: CertificateType = "SELF_MANAGED", |
| 336 | ): CertificateType => { |
| 337 | if ( |
| 338 | props.type === "SELF_MANAGED" || |
| 339 | props.type === "MANAGED" || |
| 340 | props.type === "MANAGED_IDENTITY" |
| 341 | ) { |
| 342 | return props.type; |
| 343 | } |
| 344 | if ((props.managedIdentity?.identity ?? "") !== "") { |
| 345 | return "MANAGED_IDENTITY"; |
| 346 | } |
| 347 | if ( |
| 348 | (props.managed?.domains?.length ?? 0) > 0 || |
| 349 | (props.managed?.dnsAuthorizations?.length ?? 0) > 0 || |
| 350 | (props.managed?.issuanceConfig ?? "") !== "" |
| 351 | ) { |
| 352 | return "MANAGED"; |
| 353 | } |
| 354 | if ((selfManagedOf(props).pemCertificate ?? "") !== "") { |
| 355 | return "SELF_MANAGED"; |
| 356 | } |
| 357 | return fallback; |
| 358 | }; |
| 359 | |
| 360 | const typeFromCert = (cert: certificatemanager.Certificate): CertificateType => { |
| 361 | if (cert.managedIdentity !== undefined) return "MANAGED_IDENTITY"; |
| 362 | if (cert.managed !== undefined) return "MANAGED"; |
| 363 | return "SELF_MANAGED"; |
| 364 | }; |
| 365 | |
| 366 | const normalizePem = (pem: string | undefined): string => (pem ?? "").replace(/\s+/g, ""); |
| 367 | |
| 368 | const sameList = (left?: readonly string[], right?: readonly string[]) => |
| 369 | [...(left ?? [])].sort().join("\0") === [...(right ?? [])].sort().join("\0"); |
| 370 | |
| 371 | const pemDiffers = (next: CertificateSelfManaged, previous: CertificateSelfManaged) => { |
| 372 | if ( |
| 373 | next.pemCertificate !== undefined && |
| 374 | normalizePem(next.pemCertificate) !== normalizePem(previous.pemCertificate) |
| 375 | ) { |
| 376 | return true; |
| 377 | } |
| 378 | if ( |
| 379 | next.pemPrivateKey !== undefined && |
| 380 | previous.pemPrivateKey !== undefined && |
| 381 | normalizePem(next.pemPrivateKey) !== normalizePem(previous.pemPrivateKey) |
| 382 | ) { |
| 383 | return true; |
| 384 | } |
| 385 | return false; |
| 386 | }; |
| 387 | |
| 388 | const toAttrs = (cert: certificatemanager.Certificate, project: string) => { |
| 389 | const name = cert.name ?? ""; |
| 390 | const parsed = parseName(name); |
| 391 | return { |
| 392 | name, |
| 393 | certificateId: parsed.certificateId, |
| 394 | project: parsed.project || project, |
| 395 | location: parsed.location, |
| 396 | type: typeFromCert(cert), |
| 397 | scope: normalizeScope(cert.scope), |
| 398 | description: cert.description, |
| 399 | labels: userLabels(cert.labels), |
| 400 | pemCertificate: cert.pemCertificate, |
| 401 | sanDnsnames: cert.sanDnsnames ?? [], |
| 402 | expireTime: cert.expireTime, |
| 403 | managedDomains: cert.managed?.domains ?? [], |
| 404 | managedState: cert.managed?.state, |
| 405 | managedDnsAuthorizations: cert.managed?.dnsAuthorizations ?? [], |
| 406 | issuanceConfig: cert.managed?.issuanceConfig, |
| 407 | managedIdentity: cert.managedIdentity?.identity, |
| 408 | provisioningIssue: cert.managed?.provisioningIssue?.reason, |
| 409 | usedBy: (cert.usedBy ?? []) |
| 410 | .map((entry) => entry.name) |
| 411 | .filter((value): value is string => typeof value === "string"), |
| 412 | createTime: cert.createTime, |
| 413 | updateTime: cert.updateTime, |
| 414 | }; |
| 415 | }; |
| 416 | |
| 417 | const getByName = (name: string) => |
| 418 | certificatemanager |
| 419 | .getProjectsLocationsCertificates({ name }) |
| 420 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 421 | |
| 422 | const waitUntilExists = (name: string) => |
| 423 | getByName(name).pipe( |
| 424 | Effect.flatMap((cert) => |
| 425 | cert ? Effect.succeed(cert) : Effect.fail(new CertificateNotResolved({ resourceName: name })), |
| 426 | ), |
| 427 | Effect.retry({ |
| 428 | while: (error) => error._tag === "GCP.CertificateManager.CertificateNotResolved", |
| 429 | times: 8, |
| 430 | schedule: Schedule.spaced("1 second"), |
| 431 | }), |
| 432 | ); |
| 433 | |
| 434 | const waitUntilGone = (name: string) => |
| 435 | getByName(name).pipe( |
| 436 | Effect.flatMap((cert) => |
| 437 | cert === undefined |
| 438 | ? Effect.void |
| 439 | : Effect.fail(new CertificateStillExists({ resourceName: name })), |
| 440 | ), |
| 441 | Effect.retry({ |
| 442 | while: (error) => error._tag === "GCP.CertificateManager.CertificateStillExists", |
| 443 | times: 10, |
| 444 | schedule: Schedule.spaced("1 second"), |
| 445 | }), |
| 446 | ); |
| 447 | |
| 448 | const listOwnedCertificates = (project: string) => |
| 449 | certificatemanager.listProjectsLocationsCertificates |
| 450 | .pages({ |
| 451 | parent: `projects/${project}/locations/-`, |
| 452 | pageSize: 1000, |
| 453 | }) |
| 454 | .pipe( |
| 455 | Stream.flatMap((page) => Stream.fromIterable(page.certificates ?? [])), |
| 456 | Stream.filter((cert) => |
| 457 | Object.keys(cert.labels ?? {}).some((key) => key.startsWith("alchemy-")), |
| 458 | ), |
| 459 | Stream.map((cert) => toAttrs(cert, project)), |
| 460 | Stream.runCollect, |
| 461 | Effect.map((chunk) => Array.from(chunk)), |
| 462 | Effect.catchTag("NotFound", () => Effect.succeed([])), |
| 463 | ); |
| 464 | |
| 465 | const toCreateBody = ( |
| 466 | news: CertificateProps, |
| 467 | type: CertificateType, |
| 468 | scope: string, |
| 469 | desiredLabels: Record<string, string>, |
| 470 | ): certificatemanager.Certificate => { |
| 471 | const body: certificatemanager.Certificate = { |
| 472 | description: news.description, |
| 473 | labels: desiredLabels, |
| 474 | scope, |
| 475 | }; |
| 476 | if (type === "MANAGED") { |
| 477 | body.managed = { |
| 478 | domains: news.managed?.domains, |
| 479 | dnsAuthorizations: news.managed?.dnsAuthorizations, |
| 480 | issuanceConfig: news.managed?.issuanceConfig, |
| 481 | }; |
| 482 | return body; |
| 483 | } |
| 484 | if (type === "MANAGED_IDENTITY") { |
| 485 | body.managedIdentity = { |
| 486 | identity: news.managedIdentity?.identity, |
| 487 | }; |
| 488 | return body; |
| 489 | } |
| 490 | const material = selfManagedOf(news); |
| 491 | body.selfManaged = { |
| 492 | pemCertificate: material.pemCertificate, |
| 493 | pemPrivateKey: material.pemPrivateKey, |
| 494 | }; |
| 495 | return body; |
| 496 | }; |
| 497 | |
| 498 | const immutableChanged = ( |
| 499 | news: CertificateProps, |
| 500 | olds: Partial<CertificateProps> | undefined, |
| 501 | output: Certificate["Attributes"] | undefined, |
| 502 | ) => { |
| 503 | const previousType = typeOf( |
| 504 | { |
| 505 | type: olds?.type ?? output?.type, |
| 506 | managed: |
| 507 | olds?.managed ?? |
| 508 | (output |
| 509 | ? { |
| 510 | domains: output.managedDomains, |
| 511 | dnsAuthorizations: output.managedDnsAuthorizations, |
| 512 | issuanceConfig: output.issuanceConfig, |
| 513 | } |
| 514 | : undefined), |
| 515 | managedIdentity: |
| 516 | olds?.managedIdentity ?? |
| 517 | (output?.managedIdentity ? { identity: output.managedIdentity } : undefined), |
| 518 | pemCertificate: olds?.pemCertificate ?? output?.pemCertificate, |
| 519 | selfManaged: olds?.selfManaged, |
| 520 | }, |
| 521 | output?.type, |
| 522 | ); |
| 523 | const nextType = typeOf(news, previousType); |
| 524 | if (nextType !== previousType) return true; |
| 525 | |
| 526 | const previousScope = normalizeScope(olds?.scope ?? output?.scope); |
| 527 | const nextScope = normalizeScope(news.scope ?? olds?.scope ?? output?.scope); |
| 528 | if (previousScope !== nextScope) return true; |
| 529 | |
| 530 | if (nextType === "MANAGED") { |
| 531 | const previousDomains = olds?.managed?.domains ?? output?.managedDomains ?? []; |
| 532 | if (news.managed?.domains !== undefined && !sameList(news.managed.domains, previousDomains)) { |
| 533 | return true; |
| 534 | } |
| 535 | const previousAuths = |
| 536 | olds?.managed?.dnsAuthorizations ?? output?.managedDnsAuthorizations ?? []; |
| 537 | if ( |
| 538 | news.managed?.dnsAuthorizations !== undefined && |
| 539 | !sameList(news.managed.dnsAuthorizations, previousAuths) |
| 540 | ) { |
| 541 | return true; |
| 542 | } |
| 543 | const previousIssuance = olds?.managed?.issuanceConfig ?? output?.issuanceConfig ?? ""; |
| 544 | if ( |
| 545 | news.managed?.issuanceConfig !== undefined && |
| 546 | news.managed.issuanceConfig !== previousIssuance |
| 547 | ) { |
| 548 | return true; |
| 549 | } |
| 550 | return false; |
| 551 | } |
| 552 | |
| 553 | if (nextType === "MANAGED_IDENTITY") { |
| 554 | const previousIdentity = olds?.managedIdentity?.identity ?? output?.managedIdentity ?? ""; |
| 555 | if ( |
| 556 | news.managedIdentity?.identity !== undefined && |
| 557 | news.managedIdentity.identity !== previousIdentity |
| 558 | ) { |
| 559 | return true; |
| 560 | } |
| 561 | return false; |
| 562 | } |
| 563 | |
| 564 | // Self-managed PEM is replace: the API rejects SAN list updates |
| 565 | // (`can't update list of Subject Alternative Names`). |
| 566 | const nextMaterial = selfManagedOf(news); |
| 567 | const previousMaterial = selfManagedOf({ |
| 568 | pemCertificate: olds?.pemCertificate ?? output?.pemCertificate, |
| 569 | pemPrivateKey: olds?.pemPrivateKey, |
| 570 | selfManaged: olds?.selfManaged, |
| 571 | }); |
| 572 | if ( |
| 573 | nextMaterial.pemCertificate !== undefined && |
| 574 | previousMaterial.pemCertificate !== undefined && |
| 575 | pemDiffers(nextMaterial, previousMaterial) |
| 576 | ) { |
| 577 | return true; |
| 578 | } |
| 579 | |
| 580 | return false; |
| 581 | }; |
| 582 | |
| 583 | export const CertificateProvider = () => |
| 584 | Provider.succeed(Certificate, { |
| 585 | stables: ["name", "certificateId", "project", "location", "type", "scope", "createTime"], |
| 586 | |
| 587 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 588 | if (!isResolved(news)) return undefined; |
| 589 | |
| 590 | const previousId = olds?.certificateId ?? output?.certificateId; |
| 591 | const nextId = news.certificateId ?? previousId; |
| 592 | const previousLocation = normalizeLocation(olds?.location ?? output?.location); |
| 593 | const nextLocation = normalizeLocation(news.location ?? olds?.location ?? output?.location); |
| 594 | |
| 595 | const replace = |
| 596 | (previousId !== undefined && nextId !== undefined && nextId !== previousId) || |
| 597 | previousLocation !== nextLocation || |
| 598 | immutableChanged(news, olds, output); |
| 599 | |
| 600 | if (!replace) return undefined; |
| 601 | return { |
| 602 | action: "replace" as const, |
| 603 | deleteFirst: |
| 604 | previousLocation === nextLocation && previousId !== undefined && nextId === previousId, |
| 605 | }; |
| 606 | }), |
| 607 | |
| 608 | read: Effect.fn(function* ({ id, olds, output }) { |
| 609 | const env = yield* GcpEnvironment.current; |
| 610 | const certificateId = yield* toId(id, olds?.certificateId, output?.certificateId); |
| 611 | const location = normalizeLocation(olds?.location ?? output?.location); |
| 612 | const name = output?.name ?? resourceName(env.project, location, certificateId); |
| 613 | const existing = yield* getByName(name); |
| 614 | if (existing === undefined) return undefined; |
| 615 | const attrs = toAttrs(existing, env.project); |
| 616 | return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs); |
| 617 | }), |
| 618 | |
| 619 | list: () => |
| 620 | Effect.gen(function* () { |
| 621 | const env = yield* GcpEnvironment.current; |
| 622 | return yield* listOwnedCertificates(env.project); |
| 623 | }), |
| 624 | |
| 625 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 626 | const env = yield* GcpEnvironment.current; |
| 627 | const certificateId = yield* toId(id, news.certificateId, output?.certificateId); |
| 628 | const location = normalizeLocation(news.location ?? output?.location); |
| 629 | const type = typeOf(news, output?.type); |
| 630 | const scope = normalizeScope(news.scope ?? output?.scope); |
| 631 | const name = resourceName(env.project, location, certificateId); |
| 632 | const desiredLabels = { |
| 633 | ...toLabels(news.labels), |
| 634 | ...(yield* createInternalLabels(id)), |
| 635 | }; |
| 636 | |
| 637 | let current = yield* getByName(name); |
| 638 | |
| 639 | if (current === undefined) { |
| 640 | const created = yield* certificatemanager |
| 641 | .createProjectsLocationsCertificates({ |
| 642 | parent: `projects/${env.project}/locations/${location}`, |
| 643 | certificateId, |
| 644 | body: toCreateBody(news, type, scope, desiredLabels), |
| 645 | }) |
| 646 | .pipe( |
| 647 | Effect.retry({ |
| 648 | while: (error) => error._tag === "Conflict", |
| 649 | times: 5, |
| 650 | schedule: Schedule.spaced("2 seconds"), |
| 651 | }), |
| 652 | Effect.catchTag("Conflict", () => Effect.undefined), |
| 653 | ); |
| 654 | if (created !== undefined) { |
| 655 | yield* waitForOperation(created); |
| 656 | } |
| 657 | current = yield* waitUntilExists(name); |
| 658 | } |
| 659 | |
| 660 | if (current === undefined) { |
| 661 | return yield* new CertificateNotResolved({ resourceName: name }); |
| 662 | } |
| 663 | |
| 664 | const observedLabels = tagRecord(current.labels); |
| 665 | const { upsert, removed } = diffLabels(observedLabels, desiredLabels); |
| 666 | const labelsChanged = upsert.length > 0 || removed.length > 0; |
| 667 | const descriptionChanged = (current.description ?? "") !== (news.description ?? ""); |
| 668 | |
| 669 | if (labelsChanged || descriptionChanged) { |
| 670 | const updateMask = [ |
| 671 | labelsChanged ? "labels" : undefined, |
| 672 | descriptionChanged ? "description" : undefined, |
| 673 | ].filter((field): field is string => field !== undefined); |
| 674 | |
| 675 | const operation = yield* certificatemanager.patchProjectsLocationsCertificates({ |
| 676 | name, |
| 677 | updateMask: updateMask.join(","), |
| 678 | body: { |
| 679 | name, |
| 680 | labels: desiredLabels, |
| 681 | description: news.description, |
| 682 | }, |
| 683 | }); |
| 684 | yield* waitForOperation(operation); |
| 685 | current = yield* waitUntilExists(name); |
| 686 | } |
| 687 | |
| 688 | return toAttrs(current, env.project); |
| 689 | }), |
| 690 | |
| 691 | delete: Effect.fn(function* ({ output }) { |
| 692 | const operation = yield* certificatemanager |
| 693 | .deleteProjectsLocationsCertificates({ name: output.name }) |
| 694 | .pipe( |
| 695 | Effect.retry({ |
| 696 | while: (error) => error._tag === "Conflict", |
| 697 | times: 8, |
| 698 | schedule: Schedule.spaced("2 seconds"), |
| 699 | }), |
| 700 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 701 | ); |
| 702 | if (operation !== undefined) { |
| 703 | yield* waitForOperation(operation, { notFoundOk: true }); |
| 704 | } |
| 705 | yield* waitUntilGone(output.name); |
| 706 | }), |
| 707 | }); |