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_LIFETIME = "2592000s"; |
| 25 | const DEFAULT_ROTATION = 66; |
| 26 | const DEFAULT_KEY_ALGORITHM: CertificateIssuanceConfigKeyAlgorithm = "RSA_2048"; |
| 27 | const MAX_NAME_LENGTH = 63; |
| 28 | |
| 29 | export type CertificateIssuanceConfigKeyAlgorithm = "RSA_2048" | "ECDSA_P256" | (string & {}); |
| 30 | |
| 31 | export type CertificateAuthorityServiceConfig = { |
| 32 | /** |
| 33 | * CA pool that issues workload certificates |
| 34 | * (`projects/{project}/locations/{location}/caPools/{caPool}`). |
| 35 | * A bare pool id is expanded with this issuance config's project and |
| 36 | * location. Immutable — changing it replaces the issuance config. |
| 37 | */ |
| 38 | caPool: string; |
| 39 | }; |
| 40 | |
| 41 | export type CertificateAuthorityConfig = { |
| 42 | /** Certificate Authority Service pool used to mint certificates. */ |
| 43 | certificateAuthorityServiceConfig: CertificateAuthorityServiceConfig; |
| 44 | }; |
| 45 | |
| 46 | export type CertificateIssuanceConfigProps = { |
| 47 | /** |
| 48 | * CertificateIssuanceConfig id (the `{certificateIssuanceConfig}` |
| 49 | * segment of `projects/{project}/locations/{location}/certificateIssuanceConfigs/{certificateIssuanceConfig}`). |
| 50 | * If omitted, a unique name is generated from the stack, stage, and |
| 51 | * logical id. Must be 1-63 characters, start with a letter, and match |
| 52 | * `[a-z]([-a-z0-9]*[a-z0-9])?`. Immutable — changing it replaces the |
| 53 | * issuance config. Ids are unique across all locations. |
| 54 | */ |
| 55 | certificateIssuanceConfigId?: string; |
| 56 | /** |
| 57 | * Certificate Manager location (`global`, `us-central1`, …). Immutable — |
| 58 | * changing it replaces the issuance config. `US-CENTRAL1` is accepted |
| 59 | * and normalized to `us-central1`. A regional CA pool may be referenced |
| 60 | * from a `global` issuance config. |
| 61 | * @default "global" |
| 62 | */ |
| 63 | location?: string; |
| 64 | /** |
| 65 | * Human-readable description. |
| 66 | */ |
| 67 | description?: string; |
| 68 | /** |
| 69 | * User labels. Alchemy ownership labels are merged in automatically. |
| 70 | */ |
| 71 | labels?: Record<string, string>; |
| 72 | /** |
| 73 | * Requested lifetime of issued certificates as a protobuf Duration |
| 74 | * (`2592000s` for 30 days). Valid range is 21-30 days. Immutable — |
| 75 | * changing it replaces the issuance config. |
| 76 | * @default "2592000s" |
| 77 | */ |
| 78 | lifetime?: string; |
| 79 | /** |
| 80 | * Percentage of elapsed lifetime at which renewal begins. Must be |
| 81 | * 1-99 and leave at least 7 days after issuance and before expiry. |
| 82 | * Immutable — changing it replaces the issuance config. |
| 83 | * @default 66 |
| 84 | */ |
| 85 | rotationWindowPercentage?: number; |
| 86 | /** |
| 87 | * Key algorithm used when generating the private key. `RSA_2048` or |
| 88 | * `ECDSA_P256`. Immutable — changing it replaces the issuance config. |
| 89 | * @default "RSA_2048" |
| 90 | */ |
| 91 | keyAlgorithm?: CertificateIssuanceConfigKeyAlgorithm; |
| 92 | /** |
| 93 | * CA that issues the workload certificate. Immutable — changing the |
| 94 | * CA pool replaces the issuance config. |
| 95 | */ |
| 96 | certificateAuthorityConfig: CertificateAuthorityConfig; |
| 97 | }; |
| 98 | |
| 99 | export type CertificateIssuanceConfig = Resource< |
| 100 | "GCP.CertificateManager.CertificateIssuanceConfig", |
| 101 | CertificateIssuanceConfigProps, |
| 102 | { |
| 103 | /** Full resource name `projects/{project}/locations/{location}/certificateIssuanceConfigs/{certificateIssuanceConfig}`. */ |
| 104 | name: string; |
| 105 | /** CertificateIssuanceConfig id (last path segment). */ |
| 106 | certificateIssuanceConfigId: string; |
| 107 | /** Project id. */ |
| 108 | project: string; |
| 109 | /** Location id (`global`, `us-central1`, …). */ |
| 110 | location: string; |
| 111 | /** User-provided description. */ |
| 112 | description: string | undefined; |
| 113 | /** User labels (Alchemy ownership labels stripped). */ |
| 114 | labels: Record<string, string>; |
| 115 | /** Requested certificate lifetime (protobuf Duration). */ |
| 116 | lifetime: string; |
| 117 | /** Percentage of elapsed lifetime at which renewal begins. */ |
| 118 | rotationWindowPercentage: number; |
| 119 | /** Key algorithm (`RSA_2048` or `ECDSA_P256`). */ |
| 120 | keyAlgorithm: string; |
| 121 | /** CA pool resource name used to issue certificates. */ |
| 122 | caPool: string; |
| 123 | /** RFC3339 creation timestamp. */ |
| 124 | createTime: string | undefined; |
| 125 | /** RFC3339 last-update timestamp. */ |
| 126 | updateTime: string | undefined; |
| 127 | }, |
| 128 | never, |
| 129 | Providers |
| 130 | >; |
| 131 | |
| 132 | /** |
| 133 | * A Certificate Manager issuance config — how Google-managed certificates |
| 134 | * are minted from Certificate Authority Service (lifetime, rotation, |
| 135 | * key algorithm, and CA pool). |
| 136 | * |
| 137 | * Changing `certificateIssuanceConfigId`, `location`, `lifetime`, |
| 138 | * `rotationWindowPercentage`, `keyAlgorithm`, or the CA pool replaces |
| 139 | * the resource. Description and labels update in place. |
| 140 | * |
| 141 | * ### Creating an Issuance Config |
| 142 | * **Example:** Generated name |
| 143 | * ```typescript |
| 144 | * const pool = yield* GCP.PrivateCA.CaPool("AppCa", { |
| 145 | * location: "us-central1", |
| 146 | * }); |
| 147 | * const issuance = yield* GCP.CertificateManager.CertificateIssuanceConfig( |
| 148 | * "WorkloadTls", |
| 149 | * { |
| 150 | * certificateAuthorityConfig: { |
| 151 | * certificateAuthorityServiceConfig: { caPool: pool.name }, |
| 152 | * }, |
| 153 | * }, |
| 154 | * ); |
| 155 | * ``` |
| 156 | * |
| 157 | * **Example:** Named config with labels |
| 158 | * ```typescript |
| 159 | * const issuance = yield* GCP.CertificateManager.CertificateIssuanceConfig( |
| 160 | * "WorkloadTls", |
| 161 | * { |
| 162 | * certificateIssuanceConfigId: "app-workload-tls", |
| 163 | * description: "prod workload certs", |
| 164 | * labels: { env: "prod" }, |
| 165 | * lifetime: "2592000s", |
| 166 | * rotationWindowPercentage: 66, |
| 167 | * keyAlgorithm: "ECDSA_P256", |
| 168 | * certificateAuthorityConfig: { |
| 169 | * certificateAuthorityServiceConfig: { caPool: pool.name }, |
| 170 | * }, |
| 171 | * }, |
| 172 | * ); |
| 173 | * ``` |
| 174 | * |
| 175 | * ### Regional Issuance Config |
| 176 | * **Example:** us-central1 issuance config |
| 177 | * ```typescript |
| 178 | * const issuance = yield* GCP.CertificateManager.CertificateIssuanceConfig( |
| 179 | * "RegionalTls", |
| 180 | * { |
| 181 | * location: "us-central1", |
| 182 | * certificateAuthorityConfig: { |
| 183 | * certificateAuthorityServiceConfig: { caPool: pool.name }, |
| 184 | * }, |
| 185 | * }, |
| 186 | * ); |
| 187 | * ``` |
| 188 | * |
| 189 | * ### Google-Managed Private Certificates |
| 190 | * **Example:** Issue a managed certificate from an issuance config |
| 191 | * ```typescript |
| 192 | * const cert = yield* GCP.CertificateManager.Certificate("FrontendTls", { |
| 193 | * type: "MANAGED", |
| 194 | * managed: { |
| 195 | * domains: ["www.example.com"], |
| 196 | * issuanceConfig: issuance.name, |
| 197 | * }, |
| 198 | * }); |
| 199 | * ``` |
| 200 | * |
| 201 | * @resource |
| 202 | * @category CertificateManager |
| 203 | */ |
| 204 | export const CertificateIssuanceConfig = Resource<CertificateIssuanceConfig>( |
| 205 | "GCP.CertificateManager.CertificateIssuanceConfig", |
| 206 | ); |
| 207 | |
| 208 | export class CertificateIssuanceConfigNotResolved extends Data.TaggedError( |
| 209 | "GCP.CertificateManager.CertificateIssuanceConfigNotResolved", |
| 210 | )<{ |
| 211 | resourceName: string; |
| 212 | }> {} |
| 213 | |
| 214 | export class CertificateIssuanceConfigStillExists extends Data.TaggedError( |
| 215 | "GCP.CertificateManager.CertificateIssuanceConfigStillExists", |
| 216 | )<{ |
| 217 | resourceName: string; |
| 218 | }> {} |
| 219 | |
| 220 | const lastSegment = (value: string) => { |
| 221 | const trimmed = value.replace(/\/+$/, ""); |
| 222 | const parts = trimmed.split("/"); |
| 223 | return parts[parts.length - 1] || trimmed; |
| 224 | }; |
| 225 | |
| 226 | const rfc1035 = (name: string): string => { |
| 227 | let next = name |
| 228 | .toLowerCase() |
| 229 | .replace(/[^a-z0-9-]/g, "-") |
| 230 | .replace(/-+/g, "-") |
| 231 | .replace(/^-+/, "") |
| 232 | .replace(/-+$/, ""); |
| 233 | if (!/^[a-z]/.test(next)) { |
| 234 | next = `c${next}`; |
| 235 | } |
| 236 | next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/, ""); |
| 237 | return next.length > 0 ? next : "issuance-config"; |
| 238 | }; |
| 239 | |
| 240 | const normalizeLocation = (location: string | undefined) => |
| 241 | lastSegment(location ?? DEFAULT_LOCATION).toLowerCase(); |
| 242 | |
| 243 | const resourceName = (project: string, location: string, certificateIssuanceConfigId: string) => |
| 244 | `projects/${project}/locations/${location}/certificateIssuanceConfigs/${certificateIssuanceConfigId}`; |
| 245 | |
| 246 | const parseName = (name: string) => { |
| 247 | const parts = name.split("/").filter((part) => part.length > 0); |
| 248 | const configsAt = parts.lastIndexOf("certificateIssuanceConfigs"); |
| 249 | const locationsAt = parts.lastIndexOf("locations"); |
| 250 | const projectsAt = parts.lastIndexOf("projects"); |
| 251 | return { |
| 252 | project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "", |
| 253 | location: |
| 254 | locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : DEFAULT_LOCATION, |
| 255 | certificateIssuanceConfigId: |
| 256 | configsAt >= 0 && parts[configsAt + 1] ? parts[configsAt + 1]! : lastSegment(name), |
| 257 | }; |
| 258 | }; |
| 259 | |
| 260 | const userLabels = ( |
| 261 | labels: Record<string, string | undefined> | null | undefined, |
| 262 | ): Record<string, string> => stripInternalLabels(tagRecord(labels)); |
| 263 | |
| 264 | const toId = (id: string, certificateIssuanceConfigId: string | undefined, existing?: string) => |
| 265 | Effect.gen(function* () { |
| 266 | if (certificateIssuanceConfigId !== undefined) { |
| 267 | return certificateIssuanceConfigId; |
| 268 | } |
| 269 | if (existing !== undefined) return existing; |
| 270 | return rfc1035( |
| 271 | yield* createPhysicalName({ |
| 272 | id, |
| 273 | maxLength: MAX_NAME_LENGTH, |
| 274 | lowercase: true, |
| 275 | }), |
| 276 | ); |
| 277 | }); |
| 278 | |
| 279 | const parseDurationSeconds = (value: string | undefined): number | undefined => { |
| 280 | if (value === undefined || value.trim() === "") return undefined; |
| 281 | const trimmed = value.trim(); |
| 282 | const seconds = /^(-?\d+(?:\.\d+)?)s$/i.exec(trimmed); |
| 283 | if (seconds) return Number(seconds[1]); |
| 284 | const days = /^(-?\d+(?:\.\d+)?)d$/i.exec(trimmed); |
| 285 | if (days) return Number(days[1]) * 86400; |
| 286 | return undefined; |
| 287 | }; |
| 288 | |
| 289 | const normalizeLifetime = (value: string | undefined): string => { |
| 290 | const raw = value === undefined || value.trim() === "" ? DEFAULT_LIFETIME : value; |
| 291 | const seconds = parseDurationSeconds(raw); |
| 292 | return seconds !== undefined && Number.isFinite(seconds) ? `${Math.trunc(seconds)}s` : raw; |
| 293 | }; |
| 294 | |
| 295 | const lifetimeEquals = (left: string | undefined, right: string | undefined) => |
| 296 | normalizeLifetime(left) === normalizeLifetime(right); |
| 297 | |
| 298 | const normalizeKeyAlgorithm = (value: string | undefined): string => { |
| 299 | const compact = (value ?? "").trim().toUpperCase().replace(/-/g, "_"); |
| 300 | if (compact === "" || compact === "KEY_ALGORITHM_UNSPECIFIED" || compact === "UNSPECIFIED") { |
| 301 | return DEFAULT_KEY_ALGORITHM; |
| 302 | } |
| 303 | if ( |
| 304 | compact === "ECDSA_P256" || |
| 305 | compact === "ECDSA" || |
| 306 | compact === "EC_P256" || |
| 307 | compact === "ECDSA_P_256" |
| 308 | ) { |
| 309 | return "ECDSA_P256"; |
| 310 | } |
| 311 | if (compact === "RSA_2048" || compact === "RSA") { |
| 312 | return "RSA_2048"; |
| 313 | } |
| 314 | return compact; |
| 315 | }; |
| 316 | |
| 317 | const normalizeRotation = (value: number | undefined): number => value ?? DEFAULT_ROTATION; |
| 318 | |
| 319 | const normalizeCaPool = (value: string | undefined, project: string, location: string): string => { |
| 320 | if (value === undefined) return ""; |
| 321 | const trimmed = value.replace(/\/+$/, "").trim(); |
| 322 | if (trimmed.length === 0) return ""; |
| 323 | if (trimmed.includes("/")) return trimmed; |
| 324 | return `projects/${project}/locations/${location}/caPools/${trimmed}`; |
| 325 | }; |
| 326 | |
| 327 | const caPoolOf = ( |
| 328 | config: CertificateAuthorityConfig | certificatemanager.CertificateAuthorityConfig | undefined, |
| 329 | ) => config?.certificateAuthorityServiceConfig?.caPool; |
| 330 | |
| 331 | const toAttrs = (config: certificatemanager.CertificateIssuanceConfig, project: string) => { |
| 332 | const name = config.name ?? ""; |
| 333 | const parsed = parseName(name); |
| 334 | const location = parsed.location; |
| 335 | const resolvedProject = parsed.project || project; |
| 336 | return { |
| 337 | name, |
| 338 | certificateIssuanceConfigId: parsed.certificateIssuanceConfigId, |
| 339 | project: resolvedProject, |
| 340 | location, |
| 341 | description: config.description, |
| 342 | labels: userLabels(config.labels), |
| 343 | lifetime: normalizeLifetime(config.lifetime), |
| 344 | rotationWindowPercentage: normalizeRotation(config.rotationWindowPercentage), |
| 345 | keyAlgorithm: normalizeKeyAlgorithm(config.keyAlgorithm), |
| 346 | caPool: normalizeCaPool(caPoolOf(config.certificateAuthorityConfig), resolvedProject, location), |
| 347 | createTime: config.createTime, |
| 348 | updateTime: config.updateTime, |
| 349 | }; |
| 350 | }; |
| 351 | |
| 352 | const getByName = (name: string) => |
| 353 | certificatemanager |
| 354 | .getProjectsLocationsCertificateIssuanceConfigs({ name }) |
| 355 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 356 | |
| 357 | const waitUntilExists = (name: string) => |
| 358 | getByName(name).pipe( |
| 359 | Effect.flatMap((config) => |
| 360 | config |
| 361 | ? Effect.succeed(config) |
| 362 | : Effect.fail(new CertificateIssuanceConfigNotResolved({ resourceName: name })), |
| 363 | ), |
| 364 | Effect.retry({ |
| 365 | while: (error) => |
| 366 | error._tag === "GCP.CertificateManager.CertificateIssuanceConfigNotResolved", |
| 367 | times: 8, |
| 368 | schedule: Schedule.spaced("1 second"), |
| 369 | }), |
| 370 | ); |
| 371 | |
| 372 | const waitUntilGone = (name: string) => |
| 373 | getByName(name).pipe( |
| 374 | Effect.flatMap((config) => |
| 375 | config === undefined |
| 376 | ? Effect.void |
| 377 | : Effect.fail(new CertificateIssuanceConfigStillExists({ resourceName: name })), |
| 378 | ), |
| 379 | Effect.retry({ |
| 380 | while: (error) => |
| 381 | error._tag === "GCP.CertificateManager.CertificateIssuanceConfigStillExists", |
| 382 | times: 10, |
| 383 | schedule: Schedule.spaced("1 second"), |
| 384 | }), |
| 385 | ); |
| 386 | |
| 387 | const listOwnedIssuanceConfigs = (project: string) => |
| 388 | certificatemanager.listProjectsLocationsCertificateIssuanceConfigs |
| 389 | .pages({ |
| 390 | parent: `projects/${project}/locations/-`, |
| 391 | pageSize: 1000, |
| 392 | }) |
| 393 | .pipe( |
| 394 | Stream.flatMap((page) => Stream.fromIterable(page.certificateIssuanceConfigs ?? [])), |
| 395 | Stream.filter((config) => |
| 396 | Object.keys(config.labels ?? {}).some((key) => key.startsWith("alchemy-")), |
| 397 | ), |
| 398 | Stream.map((config) => toAttrs(config, project)), |
| 399 | Stream.runCollect, |
| 400 | Effect.map((chunk) => Array.from(chunk)), |
| 401 | Effect.catchTag("NotFound", () => Effect.succeed([])), |
| 402 | ); |
| 403 | |
| 404 | const desiredCaPool = (news: CertificateIssuanceConfigProps, project: string, location: string) => |
| 405 | normalizeCaPool(caPoolOf(news.certificateAuthorityConfig), project, location); |
| 406 | |
| 407 | const toCreateBody = ( |
| 408 | news: CertificateIssuanceConfigProps, |
| 409 | desiredLabels: Record<string, string>, |
| 410 | caPool: string, |
| 411 | ): certificatemanager.CertificateIssuanceConfig => ({ |
| 412 | description: news.description, |
| 413 | labels: desiredLabels, |
| 414 | lifetime: normalizeLifetime(news.lifetime), |
| 415 | rotationWindowPercentage: normalizeRotation(news.rotationWindowPercentage), |
| 416 | keyAlgorithm: normalizeKeyAlgorithm(news.keyAlgorithm), |
| 417 | certificateAuthorityConfig: { |
| 418 | certificateAuthorityServiceConfig: { caPool }, |
| 419 | }, |
| 420 | }); |
| 421 | |
| 422 | export const CertificateIssuanceConfigProvider = () => |
| 423 | Provider.succeed(CertificateIssuanceConfig, { |
| 424 | stables: [ |
| 425 | "name", |
| 426 | "certificateIssuanceConfigId", |
| 427 | "project", |
| 428 | "location", |
| 429 | "lifetime", |
| 430 | "rotationWindowPercentage", |
| 431 | "keyAlgorithm", |
| 432 | "caPool", |
| 433 | "createTime", |
| 434 | ], |
| 435 | |
| 436 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 437 | if (!isResolved(news)) return undefined; |
| 438 | |
| 439 | const previousId = olds?.certificateIssuanceConfigId ?? output?.certificateIssuanceConfigId; |
| 440 | const nextId = news.certificateIssuanceConfigId ?? previousId; |
| 441 | const previousLocation = normalizeLocation(olds?.location ?? output?.location); |
| 442 | const nextLocation = normalizeLocation(news.location ?? olds?.location ?? output?.location); |
| 443 | const previousLifetime = olds?.lifetime ?? output?.lifetime; |
| 444 | const previousRotation = normalizeRotation( |
| 445 | olds?.rotationWindowPercentage ?? output?.rotationWindowPercentage, |
| 446 | ); |
| 447 | const nextRotation = normalizeRotation(news.rotationWindowPercentage); |
| 448 | const previousAlgorithm = normalizeKeyAlgorithm(olds?.keyAlgorithm ?? output?.keyAlgorithm); |
| 449 | const nextAlgorithm = normalizeKeyAlgorithm(news.keyAlgorithm); |
| 450 | const previousCaPool = normalizeCaPool( |
| 451 | olds?.certificateAuthorityConfig |
| 452 | ? caPoolOf(olds.certificateAuthorityConfig) |
| 453 | : output?.caPool, |
| 454 | output?.project ?? "", |
| 455 | previousLocation, |
| 456 | ); |
| 457 | const nextCaPool = normalizeCaPool( |
| 458 | caPoolOf(news.certificateAuthorityConfig) ?? output?.caPool, |
| 459 | output?.project ?? "", |
| 460 | nextLocation, |
| 461 | ); |
| 462 | |
| 463 | const replace = |
| 464 | (previousId !== undefined && nextId !== undefined && nextId !== previousId) || |
| 465 | previousLocation !== nextLocation || |
| 466 | (previousLifetime !== undefined && |
| 467 | !lifetimeEquals(news.lifetime ?? previousLifetime, previousLifetime)) || |
| 468 | previousRotation !== nextRotation || |
| 469 | previousAlgorithm !== nextAlgorithm || |
| 470 | (previousCaPool !== "" && nextCaPool !== "" && previousCaPool !== nextCaPool); |
| 471 | |
| 472 | if (!replace) return undefined; |
| 473 | return { |
| 474 | action: "replace" as const, |
| 475 | deleteFirst: |
| 476 | previousLocation === nextLocation && previousId !== undefined && nextId === previousId, |
| 477 | }; |
| 478 | }), |
| 479 | |
| 480 | read: Effect.fn(function* ({ id, olds, output }) { |
| 481 | const env = yield* GcpEnvironment.current; |
| 482 | const certificateIssuanceConfigId = yield* toId( |
| 483 | id, |
| 484 | olds?.certificateIssuanceConfigId, |
| 485 | output?.certificateIssuanceConfigId, |
| 486 | ); |
| 487 | const location = normalizeLocation(olds?.location ?? output?.location); |
| 488 | const name = output?.name ?? resourceName(env.project, location, certificateIssuanceConfigId); |
| 489 | const existing = yield* getByName(name); |
| 490 | if (existing === undefined) return undefined; |
| 491 | const attrs = toAttrs(existing, env.project); |
| 492 | return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs); |
| 493 | }), |
| 494 | |
| 495 | list: () => |
| 496 | Effect.gen(function* () { |
| 497 | const env = yield* GcpEnvironment.current; |
| 498 | return yield* listOwnedIssuanceConfigs(env.project); |
| 499 | }), |
| 500 | |
| 501 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 502 | const env = yield* GcpEnvironment.current; |
| 503 | const certificateIssuanceConfigId = yield* toId( |
| 504 | id, |
| 505 | news.certificateIssuanceConfigId, |
| 506 | output?.certificateIssuanceConfigId, |
| 507 | ); |
| 508 | const location = normalizeLocation(news.location ?? output?.location); |
| 509 | const name = resourceName(env.project, location, certificateIssuanceConfigId); |
| 510 | const desiredLabels = { |
| 511 | ...toLabels(news.labels), |
| 512 | ...(yield* createInternalLabels(id)), |
| 513 | }; |
| 514 | const caPool = desiredCaPool(news, env.project, location); |
| 515 | |
| 516 | let current = yield* getByName(name); |
| 517 | |
| 518 | if (current === undefined) { |
| 519 | yield* Effect.gen(function* () { |
| 520 | const created = yield* certificatemanager |
| 521 | .createProjectsLocationsCertificateIssuanceConfigs({ |
| 522 | parent: `projects/${env.project}/locations/${location}`, |
| 523 | certificateIssuanceConfigId, |
| 524 | body: toCreateBody(news, desiredLabels, caPool), |
| 525 | }) |
| 526 | .pipe( |
| 527 | Effect.retry({ |
| 528 | while: (error) => error._tag === "Conflict", |
| 529 | times: 5, |
| 530 | schedule: Schedule.spaced("2 seconds"), |
| 531 | }), |
| 532 | Effect.catchTag("Conflict", () => Effect.undefined), |
| 533 | ); |
| 534 | if (created !== undefined) { |
| 535 | yield* waitForOperation(created); |
| 536 | } |
| 537 | }).pipe( |
| 538 | Effect.retry({ |
| 539 | // "config validation failed" (INVALID_ARGUMENT) while the CA |
| 540 | // pool grant for the Certificate Manager agent propagates. |
| 541 | while: (error) => error._tag === "GCP.OperationFailed" && error.code === 3, |
| 542 | times: 8, |
| 543 | schedule: Schedule.spaced("3 seconds"), |
| 544 | }), |
| 545 | ); |
| 546 | current = yield* waitUntilExists(name); |
| 547 | } |
| 548 | |
| 549 | if (current === undefined) { |
| 550 | return yield* new CertificateIssuanceConfigNotResolved({ resourceName: name }); |
| 551 | } |
| 552 | |
| 553 | const observedLabels = tagRecord(current.labels); |
| 554 | const { upsert, removed } = diffLabels(observedLabels, desiredLabels); |
| 555 | const labelsChanged = upsert.length > 0 || removed.length > 0; |
| 556 | const descriptionChanged = (current.description ?? "") !== (news.description ?? ""); |
| 557 | |
| 558 | if (labelsChanged || descriptionChanged) { |
| 559 | const updateMask = [ |
| 560 | labelsChanged ? "labels" : undefined, |
| 561 | descriptionChanged ? "description" : undefined, |
| 562 | ].filter((field): field is string => field !== undefined); |
| 563 | |
| 564 | const operation = |
| 565 | yield* certificatemanager.patchProjectsLocationsCertificateIssuanceConfigs({ |
| 566 | name, |
| 567 | updateMask: updateMask.join(","), |
| 568 | body: { |
| 569 | name, |
| 570 | labels: desiredLabels, |
| 571 | description: news.description, |
| 572 | }, |
| 573 | }); |
| 574 | yield* waitForOperation(operation); |
| 575 | current = yield* waitUntilExists(name); |
| 576 | } |
| 577 | |
| 578 | return toAttrs(current, env.project); |
| 579 | }), |
| 580 | |
| 581 | delete: Effect.fn(function* ({ output }) { |
| 582 | const operation = yield* certificatemanager |
| 583 | .deleteProjectsLocationsCertificateIssuanceConfigs({ |
| 584 | name: output.name, |
| 585 | }) |
| 586 | .pipe( |
| 587 | Effect.retry({ |
| 588 | while: (error) => error._tag === "Conflict", |
| 589 | times: 8, |
| 590 | schedule: Schedule.spaced("2 seconds"), |
| 591 | }), |
| 592 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 593 | ); |
| 594 | if (operation !== undefined) { |
| 595 | yield* waitForOperation(operation, { notFoundOk: true }); |
| 596 | } |
| 597 | yield* waitUntilGone(output.name); |
| 598 | }), |
| 599 | }); |