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 privateca from "@distilled.cloud/gcp/privateca_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 { waitForOperation as waitForGcpOperation } from "../Operation.ts"; |
| 21 | import type { Providers } from "../Providers.ts"; |
| 22 | |
| 23 | const MAX_NAME_LENGTH = 63; |
| 24 | |
| 25 | /** CEL expression used to validate a certificate Subject / SAN. */ |
| 26 | export type CelExpression = { |
| 27 | /** CEL text. */ |
| 28 | expression?: string; |
| 29 | /** Short title shown in UIs. */ |
| 30 | title?: string; |
| 31 | /** Longer description of the expression. */ |
| 32 | description?: string; |
| 33 | /** Source location used in error reporting. */ |
| 34 | location?: string; |
| 35 | }; |
| 36 | |
| 37 | /** |
| 38 | * Constraints on identities that may appear in certificates issued with |
| 39 | * this template. When set, both passthrough flags are required by the API. |
| 40 | */ |
| 41 | export type CertificateIdentityConstraints = { |
| 42 | /** |
| 43 | * Copy the requested Subject into the issued certificate. |
| 44 | */ |
| 45 | allowSubjectPassthrough?: boolean; |
| 46 | /** |
| 47 | * Copy the requested Subject Alternative Names into the issued |
| 48 | * certificate. |
| 49 | */ |
| 50 | allowSubjectAltNamesPassthrough?: boolean; |
| 51 | /** Optional CEL expression evaluated against the resolved identity. */ |
| 52 | celExpression?: CelExpression; |
| 53 | }; |
| 54 | |
| 55 | export type KnownCertificateExtension = |
| 56 | | "KNOWN_CERTIFICATE_EXTENSION_UNSPECIFIED" |
| 57 | | "BASE_KEY_USAGE" |
| 58 | | "EXTENDED_KEY_USAGE" |
| 59 | | "CA_OPTIONS" |
| 60 | | "POLICY_IDS" |
| 61 | | "AIA_OCSP_SERVERS" |
| 62 | | "NAME_CONSTRAINTS"; |
| 63 | |
| 64 | export type ObjectId = { |
| 65 | /** OID path, most significant component first (e.g. `[1, 3, 6, 1]`). */ |
| 66 | objectIdPath?: number[]; |
| 67 | }; |
| 68 | |
| 69 | /** X.509 extensions that may be copied from a certificate request. */ |
| 70 | export type CertificateExtensionConstraints = { |
| 71 | /** Named X.509 extensions that may appear on issued certificates. */ |
| 72 | knownExtensions?: Array<KnownCertificateExtension | (string & {})>; |
| 73 | /** Custom extension OIDs that may appear on issued certificates. */ |
| 74 | additionalExtensions?: ObjectId[]; |
| 75 | }; |
| 76 | |
| 77 | export type KeyUsageOptions = { |
| 78 | digitalSignature?: boolean; |
| 79 | contentCommitment?: boolean; |
| 80 | keyEncipherment?: boolean; |
| 81 | dataEncipherment?: boolean; |
| 82 | keyAgreement?: boolean; |
| 83 | certSign?: boolean; |
| 84 | crlSign?: boolean; |
| 85 | encipherOnly?: boolean; |
| 86 | decipherOnly?: boolean; |
| 87 | }; |
| 88 | |
| 89 | export type ExtendedKeyUsageOptions = { |
| 90 | serverAuth?: boolean; |
| 91 | clientAuth?: boolean; |
| 92 | codeSigning?: boolean; |
| 93 | emailProtection?: boolean; |
| 94 | timeStamping?: boolean; |
| 95 | ocspSigning?: boolean; |
| 96 | }; |
| 97 | |
| 98 | export type KeyUsage = { |
| 99 | baseKeyUsage?: KeyUsageOptions; |
| 100 | extendedKeyUsage?: ExtendedKeyUsageOptions; |
| 101 | unknownExtendedKeyUsages?: ObjectId[]; |
| 102 | }; |
| 103 | |
| 104 | export type CaOptions = { |
| 105 | /** When missing, the basic-constraints extension is omitted. */ |
| 106 | isCa?: boolean; |
| 107 | /** Depth of allowed subordinate CAs. Omitted when unset. */ |
| 108 | maxIssuerPathLength?: number; |
| 109 | }; |
| 110 | |
| 111 | export type NameConstraints = { |
| 112 | critical?: boolean; |
| 113 | permittedDnsNames?: string[]; |
| 114 | excludedDnsNames?: string[]; |
| 115 | permittedIpRanges?: string[]; |
| 116 | excludedIpRanges?: string[]; |
| 117 | permittedEmailAddresses?: string[]; |
| 118 | excludedEmailAddresses?: string[]; |
| 119 | permittedUris?: string[]; |
| 120 | excludedUris?: string[]; |
| 121 | }; |
| 122 | |
| 123 | export type X509Extension = { |
| 124 | objectId?: ObjectId; |
| 125 | critical?: boolean; |
| 126 | /** Base64-encoded extension value. */ |
| 127 | value?: string; |
| 128 | }; |
| 129 | |
| 130 | /** X.509 values applied to every certificate issued with this template. */ |
| 131 | export type X509Parameters = { |
| 132 | keyUsage?: KeyUsage; |
| 133 | caOptions?: CaOptions; |
| 134 | policyIds?: ObjectId[]; |
| 135 | aiaOcspServers?: string[]; |
| 136 | nameConstraints?: NameConstraints; |
| 137 | additionalExtensions?: X509Extension[]; |
| 138 | }; |
| 139 | |
| 140 | export type CertificateTemplateProps = { |
| 141 | /** |
| 142 | * Template id (the `{certificateTemplate}` segment of |
| 143 | * `projects/{project}/locations/{location}/certificateTemplates/{certificateTemplate}`). |
| 144 | * If omitted, a unique name is generated from the stack, stage, and |
| 145 | * logical id. Must match `[a-zA-Z0-9_-]{1,63}`. Immutable — changing it |
| 146 | * replaces the template. |
| 147 | */ |
| 148 | certificateTemplateId?: string; |
| 149 | /** |
| 150 | * Location of the template (`us-central1`, …). Immutable — changing it |
| 151 | * replaces the template. `US-CENTRAL1` is accepted and normalized to |
| 152 | * `us-central1`. |
| 153 | * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`) |
| 154 | */ |
| 155 | location?: string; |
| 156 | /** |
| 157 | * Human-readable description of scenarios this template is intended for. |
| 158 | */ |
| 159 | description?: string; |
| 160 | /** |
| 161 | * User labels. Alchemy ownership labels are merged in automatically. |
| 162 | */ |
| 163 | labels?: Record<string, string>; |
| 164 | /** |
| 165 | * Maximum lifetime allowed for issued certificates (e.g. `"86400s"`). |
| 166 | * The issuing CaPool may shorten this further. |
| 167 | */ |
| 168 | maximumLifetime?: string; |
| 169 | /** |
| 170 | * Constraints on identities that may appear in issued certificates. |
| 171 | * When set, `allowSubjectPassthrough` and |
| 172 | * `allowSubjectAltNamesPassthrough` are required. |
| 173 | */ |
| 174 | identityConstraints?: CertificateIdentityConstraints; |
| 175 | /** |
| 176 | * X.509 extensions that may appear on certificates issued with this |
| 177 | * template. Extensions outside this set are dropped (except those in |
| 178 | * `predefinedValues`). |
| 179 | */ |
| 180 | passthroughExtensions?: CertificateExtensionConstraints; |
| 181 | /** |
| 182 | * X.509 values applied to every certificate issued with this template. |
| 183 | * Conflicting values in the request are overwritten. |
| 184 | */ |
| 185 | predefinedValues?: X509Parameters; |
| 186 | }; |
| 187 | |
| 188 | export type CertificateTemplate = Resource< |
| 189 | "GCP.PrivateCA.CertificateTemplate", |
| 190 | CertificateTemplateProps, |
| 191 | { |
| 192 | /** Full resource name `projects/{project}/locations/{location}/certificateTemplates/{certificateTemplate}`. */ |
| 193 | name: string; |
| 194 | /** Template id (last path segment). */ |
| 195 | certificateTemplateId: string; |
| 196 | /** Project id. */ |
| 197 | project: string; |
| 198 | /** Location id (`us-central1`). */ |
| 199 | location: string; |
| 200 | /** User-provided description. */ |
| 201 | description: string | undefined; |
| 202 | /** User labels (Alchemy ownership labels stripped). */ |
| 203 | labels: Record<string, string>; |
| 204 | /** Maximum lifetime of issued certificates. */ |
| 205 | maximumLifetime: string | undefined; |
| 206 | /** Identity constraints applied at issuance. */ |
| 207 | identityConstraints: CertificateIdentityConstraints | undefined; |
| 208 | /** Allowed X.509 extensions. */ |
| 209 | passthroughExtensions: CertificateExtensionConstraints | undefined; |
| 210 | /** Predefined X.509 values. */ |
| 211 | predefinedValues: X509Parameters | undefined; |
| 212 | /** RFC3339 creation timestamp. */ |
| 213 | createTime: string | undefined; |
| 214 | /** RFC3339 last-update timestamp. */ |
| 215 | updateTime: string | undefined; |
| 216 | }, |
| 217 | never, |
| 218 | Providers |
| 219 | >; |
| 220 | |
| 221 | /** |
| 222 | * A Certificate Authority Service certificate template — reusable issuance |
| 223 | * policy (identity constraints, X.509 defaults, and allowed extensions) |
| 224 | * applied when issuing certificates from a CaPool. |
| 225 | * |
| 226 | * Changing `certificateTemplateId` or `location` replaces the template. |
| 227 | * Description, labels, lifetime, identity constraints, passthrough |
| 228 | * extensions, and predefined X.509 values update in place. |
| 229 | * |
| 230 | * ### Creating a Certificate Template |
| 231 | * **Example:** Generated name |
| 232 | * ```typescript |
| 233 | * const template = yield* GCP.PrivateCA.CertificateTemplate("LeafTls", { |
| 234 | * description: "leaf TLS certificates", |
| 235 | * identityConstraints: { |
| 236 | * allowSubjectPassthrough: true, |
| 237 | * allowSubjectAltNamesPassthrough: true, |
| 238 | * }, |
| 239 | * }); |
| 240 | * ``` |
| 241 | * |
| 242 | * **Example:** Explicit id, lifetime, and labels |
| 243 | * ```typescript |
| 244 | * const template = yield* GCP.PrivateCA.CertificateTemplate("LeafTls", { |
| 245 | * certificateTemplateId: "leaf-tls", |
| 246 | * location: "us-central1", |
| 247 | * description: "leaf TLS certificates", |
| 248 | * maximumLifetime: "86400s", |
| 249 | * labels: { env: "prod" }, |
| 250 | * identityConstraints: { |
| 251 | * allowSubjectPassthrough: true, |
| 252 | * allowSubjectAltNamesPassthrough: true, |
| 253 | * }, |
| 254 | * passthroughExtensions: { |
| 255 | * knownExtensions: ["EXTENDED_KEY_USAGE"], |
| 256 | * }, |
| 257 | * predefinedValues: { |
| 258 | * caOptions: { isCa: false }, |
| 259 | * keyUsage: { |
| 260 | * baseKeyUsage: { |
| 261 | * digitalSignature: true, |
| 262 | * keyEncipherment: true, |
| 263 | * }, |
| 264 | * extendedKeyUsage: { serverAuth: true }, |
| 265 | * }, |
| 266 | * }, |
| 267 | * }); |
| 268 | * ``` |
| 269 | * |
| 270 | * ### Updating a Certificate Template |
| 271 | * **Example:** Description, labels, and lifetime |
| 272 | * ```typescript |
| 273 | * const template = yield* GCP.PrivateCA.CertificateTemplate("LeafTls", { |
| 274 | * certificateTemplateId: "leaf-tls", |
| 275 | * description: "leaf TLS certificates v2", |
| 276 | * maximumLifetime: "172800s", |
| 277 | * labels: { env: "prod", role: "tls" }, |
| 278 | * identityConstraints: { |
| 279 | * allowSubjectPassthrough: true, |
| 280 | * allowSubjectAltNamesPassthrough: false, |
| 281 | * }, |
| 282 | * }); |
| 283 | * ``` |
| 284 | * |
| 285 | * @resource |
| 286 | * @category PrivateCA |
| 287 | */ |
| 288 | export const CertificateTemplate = Resource<CertificateTemplate>( |
| 289 | "GCP.PrivateCA.CertificateTemplate", |
| 290 | ); |
| 291 | |
| 292 | export class CertificateTemplateNotResolved extends Data.TaggedError( |
| 293 | "GCP.PrivateCA.CertificateTemplateNotResolved", |
| 294 | )<{ |
| 295 | resourceName: string; |
| 296 | }> {} |
| 297 | |
| 298 | export class CertificateTemplateStillExists extends Data.TaggedError( |
| 299 | "GCP.PrivateCA.CertificateTemplateStillExists", |
| 300 | )<{ |
| 301 | resourceName: string; |
| 302 | }> {} |
| 303 | |
| 304 | const lastSegment = (value: string) => { |
| 305 | const trimmed = value.replace(/\/+$/, ""); |
| 306 | const parts = trimmed.split("/"); |
| 307 | return parts[parts.length - 1] || trimmed; |
| 308 | }; |
| 309 | |
| 310 | const normalizeLocation = (location: string) => lastSegment(location).toLowerCase(); |
| 311 | |
| 312 | const resourceName = (project: string, location: string, certificateTemplateId: string) => |
| 313 | `projects/${project}/locations/${location}/certificateTemplates/${certificateTemplateId}`; |
| 314 | |
| 315 | const locationParent = (project: string, location: string) => |
| 316 | `projects/${project}/locations/${location}`; |
| 317 | |
| 318 | const parseName = (name: string) => { |
| 319 | const parts = name.split("/").filter((part) => part.length > 0); |
| 320 | const templatesAt = parts.lastIndexOf("certificateTemplates"); |
| 321 | const locationsAt = parts.lastIndexOf("locations"); |
| 322 | const projectsAt = parts.lastIndexOf("projects"); |
| 323 | return { |
| 324 | project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "", |
| 325 | location: locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : "", |
| 326 | certificateTemplateId: |
| 327 | templatesAt >= 0 && parts[templatesAt + 1] ? parts[templatesAt + 1]! : lastSegment(name), |
| 328 | }; |
| 329 | }; |
| 330 | |
| 331 | const userLabels = ( |
| 332 | labels: Record<string, string | undefined> | null | undefined, |
| 333 | ): Record<string, string> => stripInternalLabels(tagRecord(labels)); |
| 334 | |
| 335 | const toId = (id: string, certificateTemplateId: string | undefined, existing?: string) => |
| 336 | Effect.gen(function* () { |
| 337 | return ( |
| 338 | certificateTemplateId ?? |
| 339 | existing ?? |
| 340 | (yield* createPhysicalName({ |
| 341 | id, |
| 342 | maxLength: MAX_NAME_LENGTH, |
| 343 | lowercase: true, |
| 344 | })) |
| 345 | ); |
| 346 | }); |
| 347 | |
| 348 | const toObjectId = (value: privateca.ObjectId | ObjectId | undefined) => |
| 349 | value === undefined ? undefined : { objectIdPath: value.objectIdPath ?? undefined }; |
| 350 | |
| 351 | const toObjectIds = ( |
| 352 | values: ReadonlyArray<privateca.ObjectId | ObjectId> | undefined, |
| 353 | ): ObjectId[] | undefined => { |
| 354 | if (values === undefined) return undefined; |
| 355 | return values.map((value) => toObjectId(value) ?? {}); |
| 356 | }; |
| 357 | |
| 358 | const toCelExpression = ( |
| 359 | value: privateca.Expr | CelExpression | undefined, |
| 360 | ): CelExpression | undefined => { |
| 361 | if (value === undefined) return undefined; |
| 362 | if ( |
| 363 | value.expression === undefined && |
| 364 | value.title === undefined && |
| 365 | value.description === undefined && |
| 366 | value.location === undefined |
| 367 | ) { |
| 368 | return undefined; |
| 369 | } |
| 370 | return { |
| 371 | expression: value.expression, |
| 372 | title: value.title, |
| 373 | description: value.description, |
| 374 | location: value.location, |
| 375 | }; |
| 376 | }; |
| 377 | |
| 378 | const toIdentityConstraints = ( |
| 379 | value: privateca.CertificateIdentityConstraints | CertificateIdentityConstraints | undefined, |
| 380 | ): CertificateIdentityConstraints | undefined => { |
| 381 | if (value === undefined) return undefined; |
| 382 | return { |
| 383 | allowSubjectPassthrough: value.allowSubjectPassthrough, |
| 384 | allowSubjectAltNamesPassthrough: value.allowSubjectAltNamesPassthrough, |
| 385 | celExpression: toCelExpression(value.celExpression), |
| 386 | }; |
| 387 | }; |
| 388 | |
| 389 | const toPassthroughExtensions = ( |
| 390 | value: privateca.CertificateExtensionConstraints | CertificateExtensionConstraints | undefined, |
| 391 | ): CertificateExtensionConstraints | undefined => { |
| 392 | if (value === undefined) return undefined; |
| 393 | return { |
| 394 | knownExtensions: value.knownExtensions, |
| 395 | additionalExtensions: toObjectIds(value.additionalExtensions), |
| 396 | }; |
| 397 | }; |
| 398 | |
| 399 | const toKeyUsage = (value: privateca.KeyUsage | KeyUsage | undefined): KeyUsage | undefined => { |
| 400 | if (value === undefined) return undefined; |
| 401 | return { |
| 402 | baseKeyUsage: value.baseKeyUsage, |
| 403 | extendedKeyUsage: value.extendedKeyUsage, |
| 404 | unknownExtendedKeyUsages: toObjectIds(value.unknownExtendedKeyUsages), |
| 405 | }; |
| 406 | }; |
| 407 | |
| 408 | const toNameConstraints = ( |
| 409 | value: privateca.NameConstraints | NameConstraints | undefined, |
| 410 | ): NameConstraints | undefined => { |
| 411 | if (value === undefined) return undefined; |
| 412 | return { |
| 413 | critical: value.critical, |
| 414 | permittedDnsNames: value.permittedDnsNames, |
| 415 | excludedDnsNames: value.excludedDnsNames, |
| 416 | permittedIpRanges: value.permittedIpRanges, |
| 417 | excludedIpRanges: value.excludedIpRanges, |
| 418 | permittedEmailAddresses: value.permittedEmailAddresses, |
| 419 | excludedEmailAddresses: value.excludedEmailAddresses, |
| 420 | permittedUris: value.permittedUris, |
| 421 | excludedUris: value.excludedUris, |
| 422 | }; |
| 423 | }; |
| 424 | |
| 425 | const toX509Extension = (value: privateca.X509Extension | X509Extension): X509Extension => ({ |
| 426 | objectId: toObjectId(value.objectId), |
| 427 | critical: value.critical, |
| 428 | value: value.value, |
| 429 | }); |
| 430 | |
| 431 | const toPredefinedValues = ( |
| 432 | value: privateca.X509Parameters | X509Parameters | undefined, |
| 433 | ): X509Parameters | undefined => { |
| 434 | if (value === undefined) return undefined; |
| 435 | return { |
| 436 | keyUsage: toKeyUsage(value.keyUsage), |
| 437 | caOptions: value.caOptions |
| 438 | ? { |
| 439 | isCa: value.caOptions.isCa, |
| 440 | maxIssuerPathLength: value.caOptions.maxIssuerPathLength, |
| 441 | } |
| 442 | : undefined, |
| 443 | policyIds: toObjectIds(value.policyIds), |
| 444 | aiaOcspServers: value.aiaOcspServers, |
| 445 | nameConstraints: toNameConstraints(value.nameConstraints), |
| 446 | additionalExtensions: value.additionalExtensions?.map(toX509Extension), |
| 447 | }; |
| 448 | }; |
| 449 | |
| 450 | const stable = (value: unknown): unknown => { |
| 451 | if (value === null || value === undefined) return null; |
| 452 | if (Array.isArray(value)) return value.map(stable); |
| 453 | if (typeof value === "object") { |
| 454 | return Object.fromEntries( |
| 455 | Object.entries(value as Record<string, unknown>) |
| 456 | .filter(([, nested]) => nested !== undefined) |
| 457 | .sort(([left], [right]) => left.localeCompare(right)) |
| 458 | .map(([key, nested]) => [key, stable(nested)]), |
| 459 | ); |
| 460 | } |
| 461 | return value; |
| 462 | }; |
| 463 | |
| 464 | const fingerprint = (value: unknown) => JSON.stringify(stable(value)); |
| 465 | |
| 466 | const toAttrs = (template: privateca.CertificateTemplate, project: string) => { |
| 467 | const name = template.name ?? ""; |
| 468 | const parsed = parseName(name); |
| 469 | return { |
| 470 | name, |
| 471 | certificateTemplateId: parsed.certificateTemplateId, |
| 472 | project: parsed.project || project, |
| 473 | location: parsed.location, |
| 474 | description: template.description, |
| 475 | labels: userLabels(template.labels), |
| 476 | maximumLifetime: template.maximumLifetime, |
| 477 | identityConstraints: toIdentityConstraints(template.identityConstraints), |
| 478 | passthroughExtensions: toPassthroughExtensions(template.passthroughExtensions), |
| 479 | predefinedValues: toPredefinedValues(template.predefinedValues), |
| 480 | createTime: template.createTime, |
| 481 | updateTime: template.updateTime, |
| 482 | }; |
| 483 | }; |
| 484 | |
| 485 | const desiredBody = ( |
| 486 | news: CertificateTemplateProps, |
| 487 | desiredLabels: Record<string, string>, |
| 488 | ): privateca.CertificateTemplate => ({ |
| 489 | description: news.description, |
| 490 | labels: desiredLabels, |
| 491 | maximumLifetime: news.maximumLifetime, |
| 492 | identityConstraints: news.identityConstraints, |
| 493 | passthroughExtensions: news.passthroughExtensions, |
| 494 | predefinedValues: news.predefinedValues, |
| 495 | }); |
| 496 | |
| 497 | const getByName = (name: string) => |
| 498 | privateca |
| 499 | .getProjectsLocationsCertificateTemplates({ name }) |
| 500 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 501 | |
| 502 | /** |
| 503 | * Wait for a Certificate Authority Service operation; CA creation and |
| 504 | * activation take a few minutes. ALREADY_EXISTS (code 6) counts as success |
| 505 | * (create race); with `notFoundOk`, so does NOT_FOUND (code 5, delete race) |
| 506 | * and an operation that is already gone. |
| 507 | */ |
| 508 | const waitForOperation = (operation: privateca.Operation, options?: { notFoundOk?: boolean }) => |
| 509 | waitForGcpOperation(operation, (name) => privateca.getProjectsLocationsOperations({ name }), { |
| 510 | budget: "15 minutes", |
| 511 | }).pipe( |
| 512 | Effect.catchIf( |
| 513 | (error) => |
| 514 | (error._tag === "GCP.OperationFailed" && |
| 515 | (error.code === 6 || (options?.notFoundOk === true && error.code === 5))) || |
| 516 | (options?.notFoundOk === true && error._tag === "NotFound"), |
| 517 | () => Effect.succeed(operation), |
| 518 | ), |
| 519 | ); |
| 520 | |
| 521 | const waitUntilExists = (name: string) => |
| 522 | getByName(name).pipe( |
| 523 | Effect.flatMap((template) => |
| 524 | template |
| 525 | ? Effect.succeed(template) |
| 526 | : Effect.fail(new CertificateTemplateNotResolved({ resourceName: name })), |
| 527 | ), |
| 528 | Effect.retry({ |
| 529 | while: (error) => error._tag === "GCP.PrivateCA.CertificateTemplateNotResolved", |
| 530 | times: 8, |
| 531 | schedule: Schedule.spaced("1 second"), |
| 532 | }), |
| 533 | ); |
| 534 | |
| 535 | const waitUntilGone = (name: string) => |
| 536 | getByName(name).pipe( |
| 537 | Effect.flatMap((template) => |
| 538 | template === undefined |
| 539 | ? Effect.void |
| 540 | : Effect.fail(new CertificateTemplateStillExists({ resourceName: name })), |
| 541 | ), |
| 542 | Effect.retry({ |
| 543 | while: (error) => error._tag === "GCP.PrivateCA.CertificateTemplateStillExists", |
| 544 | times: 10, |
| 545 | schedule: Schedule.spaced("1 second"), |
| 546 | }), |
| 547 | ); |
| 548 | |
| 549 | const listOwnedTemplates = (project: string) => |
| 550 | privateca.listProjectsLocationsCertificateTemplates |
| 551 | .pages({ |
| 552 | parent: `projects/${project}/locations/-`, |
| 553 | pageSize: 1000, |
| 554 | }) |
| 555 | .pipe( |
| 556 | Stream.flatMap((page) => Stream.fromIterable(page.certificateTemplates ?? [])), |
| 557 | Stream.filter((template) => |
| 558 | Object.keys(template.labels ?? {}).some((key) => key.startsWith("alchemy-")), |
| 559 | ), |
| 560 | Stream.map((template) => toAttrs(template, project)), |
| 561 | Stream.runCollect, |
| 562 | Effect.map((chunk) => Array.from(chunk)), |
| 563 | Effect.catchTag("NotFound", () => Effect.succeed([])), |
| 564 | ); |
| 565 | |
| 566 | export const CertificateTemplateProvider = () => |
| 567 | Provider.succeed(CertificateTemplate, { |
| 568 | stables: ["name", "certificateTemplateId", "project", "location", "createTime"], |
| 569 | |
| 570 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 571 | if (!isResolved(news)) return undefined; |
| 572 | const env = yield* GcpEnvironment.current; |
| 573 | |
| 574 | const previousId = olds?.certificateTemplateId ?? output?.certificateTemplateId; |
| 575 | const nextId = news.certificateTemplateId ?? previousId; |
| 576 | const previousLocation = normalizeLocation(olds?.location ?? output?.location ?? env.region); |
| 577 | const nextLocation = normalizeLocation( |
| 578 | news.location ?? olds?.location ?? output?.location ?? env.region, |
| 579 | ); |
| 580 | |
| 581 | const replace = |
| 582 | (previousId !== undefined && nextId !== undefined && nextId !== previousId) || |
| 583 | previousLocation !== nextLocation; |
| 584 | |
| 585 | if (!replace) return undefined; |
| 586 | return { action: "replace" as const }; |
| 587 | }), |
| 588 | |
| 589 | read: Effect.fn(function* ({ id, olds, output }) { |
| 590 | const env = yield* GcpEnvironment.current; |
| 591 | const certificateTemplateId = yield* toId( |
| 592 | id, |
| 593 | olds?.certificateTemplateId, |
| 594 | output?.certificateTemplateId, |
| 595 | ); |
| 596 | const location = normalizeLocation(olds?.location ?? output?.location ?? env.region); |
| 597 | const name = output?.name ?? resourceName(env.project, location, certificateTemplateId); |
| 598 | const existing = yield* getByName(name); |
| 599 | if (existing === undefined) return undefined; |
| 600 | const attrs = toAttrs(existing, env.project); |
| 601 | return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs); |
| 602 | }), |
| 603 | |
| 604 | list: () => |
| 605 | Effect.gen(function* () { |
| 606 | const env = yield* GcpEnvironment.current; |
| 607 | return yield* listOwnedTemplates(env.project); |
| 608 | }), |
| 609 | |
| 610 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 611 | const env = yield* GcpEnvironment.current; |
| 612 | const certificateTemplateId = yield* toId( |
| 613 | id, |
| 614 | news.certificateTemplateId, |
| 615 | output?.certificateTemplateId, |
| 616 | ); |
| 617 | const location = normalizeLocation(news.location ?? output?.location ?? env.region); |
| 618 | const name = resourceName(env.project, location, certificateTemplateId); |
| 619 | const desiredLabels = { |
| 620 | ...toLabels(news.labels), |
| 621 | ...(yield* createInternalLabels(id)), |
| 622 | }; |
| 623 | const body = desiredBody(news, desiredLabels); |
| 624 | |
| 625 | let current = yield* getByName(name); |
| 626 | |
| 627 | if (current === undefined) { |
| 628 | const created = yield* privateca |
| 629 | .createProjectsLocationsCertificateTemplates({ |
| 630 | parent: locationParent(env.project, location), |
| 631 | certificateTemplateId, |
| 632 | body, |
| 633 | }) |
| 634 | .pipe( |
| 635 | Effect.retry({ |
| 636 | while: (error) => error._tag === "Conflict", |
| 637 | times: 5, |
| 638 | schedule: Schedule.spaced("2 seconds"), |
| 639 | }), |
| 640 | Effect.catchTag("Conflict", () => Effect.undefined), |
| 641 | ); |
| 642 | if (created !== undefined) { |
| 643 | yield* waitForOperation(created); |
| 644 | } |
| 645 | current = yield* waitUntilExists(name); |
| 646 | } |
| 647 | |
| 648 | if (current === undefined) { |
| 649 | return yield* new CertificateTemplateNotResolved({ resourceName: name }); |
| 650 | } |
| 651 | |
| 652 | const observed = toAttrs(current, env.project); |
| 653 | const observedLabels = tagRecord(current.labels); |
| 654 | const { upsert, removed } = diffLabels(observedLabels, desiredLabels); |
| 655 | const labelsChanged = upsert.length > 0 || removed.length > 0; |
| 656 | const descriptionChanged = (observed.description ?? "") !== (news.description ?? ""); |
| 657 | const lifetimeChanged = (observed.maximumLifetime ?? "") !== (news.maximumLifetime ?? ""); |
| 658 | const identityChanged = |
| 659 | fingerprint(observed.identityConstraints) !== |
| 660 | fingerprint(toIdentityConstraints(news.identityConstraints)); |
| 661 | const passthroughChanged = |
| 662 | fingerprint(observed.passthroughExtensions) !== |
| 663 | fingerprint(toPassthroughExtensions(news.passthroughExtensions)); |
| 664 | const predefinedChanged = |
| 665 | fingerprint(observed.predefinedValues) !== |
| 666 | fingerprint(toPredefinedValues(news.predefinedValues)); |
| 667 | |
| 668 | if ( |
| 669 | labelsChanged || |
| 670 | descriptionChanged || |
| 671 | lifetimeChanged || |
| 672 | identityChanged || |
| 673 | passthroughChanged || |
| 674 | predefinedChanged |
| 675 | ) { |
| 676 | const updateMask = [ |
| 677 | labelsChanged ? "labels" : undefined, |
| 678 | descriptionChanged ? "description" : undefined, |
| 679 | lifetimeChanged ? "maximumLifetime" : undefined, |
| 680 | identityChanged ? "identityConstraints" : undefined, |
| 681 | passthroughChanged ? "passthroughExtensions" : undefined, |
| 682 | predefinedChanged ? "predefinedValues" : undefined, |
| 683 | ].filter((field): field is string => field !== undefined); |
| 684 | |
| 685 | const operation = yield* privateca.patchProjectsLocationsCertificateTemplates({ |
| 686 | name, |
| 687 | updateMask: updateMask.join(","), |
| 688 | body: { |
| 689 | name, |
| 690 | ...body, |
| 691 | }, |
| 692 | }); |
| 693 | yield* waitForOperation(operation); |
| 694 | current = yield* waitUntilExists(name); |
| 695 | } |
| 696 | |
| 697 | return toAttrs(current, env.project); |
| 698 | }), |
| 699 | |
| 700 | delete: Effect.fn(function* ({ output }) { |
| 701 | const operation = yield* privateca |
| 702 | .deleteProjectsLocationsCertificateTemplates({ name: output.name }) |
| 703 | .pipe( |
| 704 | Effect.retry({ |
| 705 | while: (error) => error._tag === "Conflict", |
| 706 | times: 8, |
| 707 | schedule: Schedule.spaced("2 seconds"), |
| 708 | }), |
| 709 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 710 | ); |
| 711 | if (operation !== undefined) { |
| 712 | yield* waitForOperation(operation, { notFoundOk: true }); |
| 713 | } |
| 714 | yield* waitUntilGone(output.name); |
| 715 | }), |
| 716 | }); |