The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as kms from "@distilled.cloud/gcp/cloudkms_v1"; |
| 2 | import { isResolved } from "alchemy/Diff"; |
| 3 | import * as Provider from "alchemy/Provider"; |
| 4 | import { Resource } from "alchemy/Resource"; |
| 5 | import * as Data from "effect/Data"; |
| 6 | import * as Effect from "effect/Effect"; |
| 7 | import * as Schedule from "effect/Schedule"; |
| 8 | import { GcpEnvironment } from "../Environment.ts"; |
| 9 | import { |
| 10 | type OperationFailed, |
| 11 | type OperationTimedOut, |
| 12 | waitForOperation as waitForGcpOperation, |
| 13 | } from "../Operation.ts"; |
| 14 | import type { Providers } from "../Providers.ts"; |
| 15 | |
| 16 | const DEFAULT_STATE: kms.CryptoKeyVersionStateEnum = "ENABLED"; |
| 17 | const DELETABLE_STATES = new Set(["DESTROYED", "IMPORT_FAILED", "GENERATION_FAILED"]); |
| 18 | const DESTROYABLE_STATES = new Set(["ENABLED", "DISABLED"]); |
| 19 | const PATCHABLE_STATES = new Set(["ENABLED", "DISABLED"]); |
| 20 | |
| 21 | export type CryptoKeyVersionExternalProtectionLevelOptions = { |
| 22 | /** |
| 23 | * URI of the external key this version represents. EXTERNAL |
| 24 | * protection level only. |
| 25 | */ |
| 26 | externalKeyUri?: string; |
| 27 | /** |
| 28 | * Path to the external key material on the EKM when using an |
| 29 | * EkmConnection (e.g. `"v0/my/key"`). EXTERNAL_VPC protection level |
| 30 | * only. |
| 31 | */ |
| 32 | ekmConnectionKeyPath?: string; |
| 33 | }; |
| 34 | |
| 35 | export type CryptoKeyVersionProps = { |
| 36 | /** |
| 37 | * Parent CryptoKey. Full name |
| 38 | * `projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey}` |
| 39 | * or the crypto key id (combined with `keyRing` / `location`). |
| 40 | * Immutable — changing it replaces the version. |
| 41 | */ |
| 42 | cryptoKey: string; |
| 43 | /** |
| 44 | * Parent KeyRing. Full name |
| 45 | * `projects/{project}/locations/{location}/keyRings/{keyRing}` or the |
| 46 | * key ring id. Used when `cryptoKey` is a bare id. Immutable — |
| 47 | * changing it replaces the version. |
| 48 | */ |
| 49 | keyRing?: string; |
| 50 | /** |
| 51 | * Cloud KMS location (`us-central1`, `global`, `us`, …). Used when |
| 52 | * `cryptoKey` is a bare id. Immutable — changing it replaces the |
| 53 | * version. `US-CENTRAL1` is accepted and normalized to `us-central1`. |
| 54 | * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`) |
| 55 | */ |
| 56 | location?: string; |
| 57 | /** |
| 58 | * CryptoKeyVersion id (the last path segment, typically a decimal |
| 59 | * sequence assigned by Cloud KMS). Create always assigns the next |
| 60 | * sequential id; this field targets an existing version on adopt or |
| 61 | * update. Changing it replaces the version. |
| 62 | */ |
| 63 | cryptoKeyVersionId?: string; |
| 64 | /** |
| 65 | * Desired version state. `ENABLED` and `DISABLED` patch in place. |
| 66 | * Other transitions use Destroy / Restore. Cloud KMS sets |
| 67 | * `PENDING_GENERATION` on create until the key material is ready. |
| 68 | * @default "ENABLED" |
| 69 | */ |
| 70 | state?: kms.CryptoKeyVersionStateEnum; |
| 71 | /** |
| 72 | * External / EXTERNAL_VPC key material pointer. Ignored for SOFTWARE |
| 73 | * and HSM keys. |
| 74 | */ |
| 75 | externalProtectionLevelOptions?: CryptoKeyVersionExternalProtectionLevelOptions; |
| 76 | }; |
| 77 | |
| 78 | export type CryptoKeyVersionAttrs = { |
| 79 | /** Full resource name `projects/.../cryptoKeyVersions/{version}`. */ |
| 80 | name: string; |
| 81 | /** CryptoKeyVersion id (last path segment). */ |
| 82 | cryptoKeyVersionId: string; |
| 83 | /** Parent CryptoKey resource name. */ |
| 84 | cryptoKey: string; |
| 85 | /** Parent KeyRing resource name. */ |
| 86 | keyRing: string; |
| 87 | /** Location id (`us-central1`, `global`, …). */ |
| 88 | location: string; |
| 89 | /** Project id. */ |
| 90 | project: string; |
| 91 | /** Current version state. */ |
| 92 | state: string; |
| 93 | /** Algorithm from the parent CryptoKey version template. */ |
| 94 | algorithm: string | undefined; |
| 95 | /** Protection level of this version. */ |
| 96 | protectionLevel: string | undefined; |
| 97 | /** External key pointer, if any. */ |
| 98 | externalProtectionLevelOptions: CryptoKeyVersionExternalProtectionLevelOptions | undefined; |
| 99 | /** Import job that produced this version, if imported. */ |
| 100 | importJob: string | undefined; |
| 101 | /** Whether the version can be reimported. */ |
| 102 | reimportEligible: boolean; |
| 103 | /** RFC3339 creation timestamp. */ |
| 104 | createTime: string | undefined; |
| 105 | /** RFC3339 generation timestamp. */ |
| 106 | generateTime: string | undefined; |
| 107 | /** RFC3339 scheduled-destruction timestamp. */ |
| 108 | destroyTime: string | undefined; |
| 109 | /** RFC3339 time key material was destroyed. */ |
| 110 | destroyEventTime: string | undefined; |
| 111 | /** Generation failure reason, if `state` is `GENERATION_FAILED`. */ |
| 112 | generationFailureReason: string | undefined; |
| 113 | }; |
| 114 | |
| 115 | export type CryptoKeyVersion = Resource< |
| 116 | "GCP.KMS.CryptoKeyVersion", |
| 117 | CryptoKeyVersionProps, |
| 118 | CryptoKeyVersionAttrs, |
| 119 | never, |
| 120 | Providers |
| 121 | >; |
| 122 | |
| 123 | /** |
| 124 | * A Cloud KMS CryptoKeyVersion — one generation of key material under a |
| 125 | * CryptoKey. |
| 126 | * |
| 127 | * Parent CryptoKey, KeyRing, location, and version id are identity |
| 128 | * (changing them replaces the version). `state` toggles between |
| 129 | * `ENABLED` and `DISABLED` in place. Cloud KMS assigns sequential |
| 130 | * version ids on create; versions have no labels, so `list` returns |
| 131 | * versions whose parent CryptoKey carries Alchemy ownership labels. |
| 132 | * |
| 133 | * Destroy schedules destruction (`DESTROY_SCHEDULED`, minimum 24h). |
| 134 | * Permanent `delete` is only possible for `DESTROYED`, `IMPORT_FAILED`, |
| 135 | * or `GENERATION_FAILED` versions that were never successfully imported. |
| 136 | * |
| 137 | * ### Creating a CryptoKeyVersion |
| 138 | * **Example:** Next version on an existing CryptoKey |
| 139 | * ```typescript |
| 140 | * const ring = yield* GCP.KMS.KeyRing("Keys", {}); |
| 141 | * const key = yield* GCP.KMS.CryptoKey("Data", { |
| 142 | * keyRing: ring.name, |
| 143 | * skipInitialVersionCreation: true, |
| 144 | * }); |
| 145 | * const version = yield* GCP.KMS.CryptoKeyVersion("V1", { |
| 146 | * cryptoKey: key.name, |
| 147 | * }); |
| 148 | * ``` |
| 149 | * |
| 150 | * **Example:** Disabled version |
| 151 | * ```typescript |
| 152 | * const version = yield* GCP.KMS.CryptoKeyVersion("V1", { |
| 153 | * cryptoKey: key.name, |
| 154 | * state: "DISABLED", |
| 155 | * }); |
| 156 | * ``` |
| 157 | * |
| 158 | * @resource |
| 159 | * @category KMS |
| 160 | */ |
| 161 | export const CryptoKeyVersion = Resource<CryptoKeyVersion>("GCP.KMS.CryptoKeyVersion"); |
| 162 | |
| 163 | export class CryptoKeyVersionNotResolved extends Data.TaggedError( |
| 164 | "GCP.KMS.CryptoKeyVersionNotResolved", |
| 165 | )<{ |
| 166 | resourceName: string; |
| 167 | }> {} |
| 168 | |
| 169 | export class CryptoKeyVersionOperationFailed extends Data.TaggedError( |
| 170 | "GCP.KMS.CryptoKeyVersionOperationFailed", |
| 171 | )<{ |
| 172 | operation: string; |
| 173 | message: string; |
| 174 | }> {} |
| 175 | |
| 176 | export class CryptoKeyVersionNotReady extends Data.TaggedError("GCP.KMS.CryptoKeyVersionNotReady")<{ |
| 177 | resourceName: string; |
| 178 | state: string; |
| 179 | }> {} |
| 180 | |
| 181 | const lastSegment = (value: string) => { |
| 182 | const trimmed = value.replace(/\/+$/, ""); |
| 183 | const parts = trimmed.split("/"); |
| 184 | return parts[parts.length - 1] || trimmed; |
| 185 | }; |
| 186 | |
| 187 | const normalizeLocation = (location: string | undefined, fallback: string) => |
| 188 | lastSegment(location ?? fallback).toLowerCase(); |
| 189 | |
| 190 | const parseName = (name: string, fallbackLocation: string) => { |
| 191 | const parts = name.split("/").filter((part) => part.length > 0); |
| 192 | const versionsAt = parts.lastIndexOf("cryptoKeyVersions"); |
| 193 | const cryptoKeysAt = parts.lastIndexOf("cryptoKeys"); |
| 194 | const keyRingsAt = parts.lastIndexOf("keyRings"); |
| 195 | const locationsAt = parts.lastIndexOf("locations"); |
| 196 | const projectsAt = parts.lastIndexOf("projects"); |
| 197 | const cryptoKey = cryptoKeysAt >= 0 ? parts.slice(0, cryptoKeysAt + 2).join("/") : ""; |
| 198 | const keyRing = keyRingsAt >= 0 ? parts.slice(0, keyRingsAt + 2).join("/") : ""; |
| 199 | return { |
| 200 | project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "", |
| 201 | location: |
| 202 | locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : fallbackLocation, |
| 203 | keyRing, |
| 204 | cryptoKey, |
| 205 | cryptoKeyVersionId: |
| 206 | versionsAt >= 0 && parts[versionsAt + 1] ? parts[versionsAt + 1]! : lastSegment(name), |
| 207 | }; |
| 208 | }; |
| 209 | |
| 210 | const resolveParent = ( |
| 211 | project: string, |
| 212 | cryptoKey: string, |
| 213 | keyRing: string | undefined, |
| 214 | location: string | undefined, |
| 215 | region: string, |
| 216 | ) => { |
| 217 | if (cryptoKey.includes("/cryptoKeyVersions/")) { |
| 218 | const parsed = parseName(cryptoKey, region); |
| 219 | return { |
| 220 | parent: parsed.cryptoKey, |
| 221 | location: parsed.location, |
| 222 | project: parsed.project || project, |
| 223 | }; |
| 224 | } |
| 225 | if (cryptoKey.includes("/cryptoKeys/")) { |
| 226 | const parsed = parseName(`${cryptoKey}/cryptoKeyVersions/_`, region); |
| 227 | return { |
| 228 | parent: parsed.cryptoKey, |
| 229 | location: parsed.location, |
| 230 | project: parsed.project || project, |
| 231 | }; |
| 232 | } |
| 233 | const loc = normalizeLocation(location, region); |
| 234 | const ring = |
| 235 | keyRing !== undefined && keyRing.includes("/") |
| 236 | ? keyRing |
| 237 | : `projects/${project}/locations/${loc}/keyRings/${keyRing ?? "default"}`; |
| 238 | return { |
| 239 | parent: `${ring}/cryptoKeys/${cryptoKey}`, |
| 240 | location: loc, |
| 241 | project, |
| 242 | }; |
| 243 | }; |
| 244 | |
| 245 | const resourceName = (parent: string, cryptoKeyVersionId: string) => |
| 246 | `${parent}/cryptoKeyVersions/${cryptoKeyVersionId}`; |
| 247 | |
| 248 | const desiredState = (value: string | undefined): kms.CryptoKeyVersionStateEnum => |
| 249 | !value || value === "CRYPTO_KEY_VERSION_STATE_UNSPECIFIED" |
| 250 | ? DEFAULT_STATE |
| 251 | : (value as kms.CryptoKeyVersionStateEnum); |
| 252 | |
| 253 | const toAttrs = ( |
| 254 | version: kms.CryptoKeyVersion, |
| 255 | project: string, |
| 256 | region: string, |
| 257 | ): CryptoKeyVersionAttrs => { |
| 258 | const name = version.name ?? ""; |
| 259 | const parsed = parseName(name, region); |
| 260 | const options = version.externalProtectionLevelOptions; |
| 261 | return { |
| 262 | name, |
| 263 | cryptoKeyVersionId: parsed.cryptoKeyVersionId, |
| 264 | cryptoKey: parsed.cryptoKey, |
| 265 | keyRing: parsed.keyRing, |
| 266 | location: parsed.location, |
| 267 | project: parsed.project || project, |
| 268 | state: version.state ?? DEFAULT_STATE, |
| 269 | algorithm: version.algorithm, |
| 270 | protectionLevel: version.protectionLevel, |
| 271 | externalProtectionLevelOptions: |
| 272 | options === undefined |
| 273 | ? undefined |
| 274 | : { |
| 275 | externalKeyUri: options.externalKeyUri, |
| 276 | ekmConnectionKeyPath: options.ekmConnectionKeyPath, |
| 277 | }, |
| 278 | importJob: version.importJob, |
| 279 | reimportEligible: version.reimportEligible === true, |
| 280 | createTime: version.createTime, |
| 281 | generateTime: version.generateTime, |
| 282 | destroyTime: version.destroyTime, |
| 283 | destroyEventTime: version.destroyEventTime, |
| 284 | generationFailureReason: version.generationFailureReason, |
| 285 | }; |
| 286 | }; |
| 287 | |
| 288 | const getByName = (name: string) => |
| 289 | kms |
| 290 | .getProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersions({ name }) |
| 291 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 292 | |
| 293 | const paginate = <A, E, R>( |
| 294 | fetch: ( |
| 295 | pageToken: string | undefined, |
| 296 | ) => Effect.Effect<{ items: A[]; nextPageToken?: string }, E, R>, |
| 297 | ) => |
| 298 | Effect.gen(function* () { |
| 299 | const found: A[] = []; |
| 300 | let pageToken: string | undefined; |
| 301 | for (let page = 0; page < 10; page++) { |
| 302 | const response = yield* fetch(pageToken); |
| 303 | found.push(...response.items); |
| 304 | pageToken = response.nextPageToken; |
| 305 | if (pageToken === undefined || pageToken === "") break; |
| 306 | } |
| 307 | return found; |
| 308 | }); |
| 309 | |
| 310 | const listKeyRingsAt = (parent: string) => |
| 311 | paginate((pageToken) => |
| 312 | kms |
| 313 | .listProjectsLocationsKeyRings({ |
| 314 | parent, |
| 315 | pageSize: 1000, |
| 316 | pageToken, |
| 317 | }) |
| 318 | .pipe( |
| 319 | Effect.map((response) => ({ |
| 320 | items: response.keyRings ?? [], |
| 321 | nextPageToken: response.nextPageToken, |
| 322 | })), |
| 323 | Effect.catchTag("NotFound", () => |
| 324 | Effect.succeed({ |
| 325 | items: [] as kms.KeyRing[], |
| 326 | nextPageToken: undefined, |
| 327 | }), |
| 328 | ), |
| 329 | ), |
| 330 | ); |
| 331 | |
| 332 | const listAlchemyKeysInRing = (parent: string) => |
| 333 | paginate((pageToken) => |
| 334 | kms |
| 335 | .listProjectsLocationsKeyRingsCryptoKeys({ |
| 336 | parent, |
| 337 | pageSize: 1000, |
| 338 | pageToken, |
| 339 | }) |
| 340 | .pipe( |
| 341 | Effect.map((response) => ({ |
| 342 | items: (response.cryptoKeys ?? []).filter((key) => |
| 343 | Object.keys(key.labels ?? {}).some((label) => label.startsWith("alchemy-")), |
| 344 | ), |
| 345 | nextPageToken: response.nextPageToken, |
| 346 | })), |
| 347 | Effect.catchTag("NotFound", () => |
| 348 | Effect.succeed({ |
| 349 | items: [] as kms.CryptoKey[], |
| 350 | nextPageToken: undefined, |
| 351 | }), |
| 352 | ), |
| 353 | ), |
| 354 | ); |
| 355 | |
| 356 | const listVersionsInKey = (parent: string) => |
| 357 | paginate((pageToken) => |
| 358 | kms |
| 359 | .listProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersions({ |
| 360 | parent, |
| 361 | pageSize: 1000, |
| 362 | pageToken, |
| 363 | }) |
| 364 | .pipe( |
| 365 | Effect.map((response) => ({ |
| 366 | items: response.cryptoKeyVersions ?? [], |
| 367 | nextPageToken: response.nextPageToken, |
| 368 | })), |
| 369 | Effect.catchTag("NotFound", () => |
| 370 | Effect.succeed({ |
| 371 | items: [] as kms.CryptoKeyVersion[], |
| 372 | nextPageToken: undefined, |
| 373 | }), |
| 374 | ), |
| 375 | ), |
| 376 | ); |
| 377 | |
| 378 | const listVersionsAt = (locationParent: string) => |
| 379 | Effect.gen(function* () { |
| 380 | const rings = yield* listKeyRingsAt(locationParent); |
| 381 | const keyPages = yield* Effect.forEach( |
| 382 | rings, |
| 383 | (ring) => |
| 384 | ring.name ? listAlchemyKeysInRing(ring.name) : Effect.succeed([] as kms.CryptoKey[]), |
| 385 | { concurrency: 4 }, |
| 386 | ); |
| 387 | const keys = keyPages.flat(); |
| 388 | const versionPages = yield* Effect.forEach( |
| 389 | keys, |
| 390 | (key) => |
| 391 | key.name ? listVersionsInKey(key.name) : Effect.succeed([] as kms.CryptoKeyVersion[]), |
| 392 | { concurrency: 4 }, |
| 393 | ); |
| 394 | return versionPages.flat(); |
| 395 | }); |
| 396 | |
| 397 | const waitOperation = (operation: kms.Operation) => |
| 398 | waitForGcpOperation(operation, (name) => kms.getProjectsLocationsOperations({ name }), { |
| 399 | budget: "10 minutes", |
| 400 | }).pipe( |
| 401 | // Re-read the finished operation for its typed response. |
| 402 | Effect.flatMap(() => |
| 403 | operation.name === undefined |
| 404 | ? Effect.succeed(operation) |
| 405 | : kms.getProjectsLocationsOperations({ name: operation.name }), |
| 406 | ), |
| 407 | ); |
| 408 | |
| 409 | const waitReady = ( |
| 410 | name: string, |
| 411 | ): Effect.Effect< |
| 412 | kms.CryptoKeyVersion, |
| 413 | | CryptoKeyVersionNotResolved |
| 414 | | CryptoKeyVersionOperationFailed |
| 415 | | CryptoKeyVersionNotReady |
| 416 | | kms.GetProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsError, |
| 417 | kms.GcpOpContext |
| 418 | > => { |
| 419 | const probe: Effect.Effect< |
| 420 | kms.CryptoKeyVersion, |
| 421 | | CryptoKeyVersionNotResolved |
| 422 | | CryptoKeyVersionOperationFailed |
| 423 | | CryptoKeyVersionNotReady |
| 424 | | kms.GetProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsError, |
| 425 | kms.GcpOpContext |
| 426 | > = getByName(name).pipe( |
| 427 | Effect.flatMap( |
| 428 | ( |
| 429 | version, |
| 430 | ): Effect.Effect< |
| 431 | kms.CryptoKeyVersion, |
| 432 | CryptoKeyVersionNotResolved | CryptoKeyVersionOperationFailed | CryptoKeyVersionNotReady |
| 433 | > => { |
| 434 | if (version === undefined) { |
| 435 | return Effect.fail(new CryptoKeyVersionNotResolved({ resourceName: name })); |
| 436 | } |
| 437 | const state = version.state; |
| 438 | if ( |
| 439 | state === undefined || |
| 440 | state === "ENABLED" || |
| 441 | state === "DISABLED" || |
| 442 | state === "DESTROY_SCHEDULED" || |
| 443 | state === "DESTROYED" |
| 444 | ) { |
| 445 | return Effect.succeed(version); |
| 446 | } |
| 447 | if (state === "GENERATION_FAILED") { |
| 448 | return Effect.fail( |
| 449 | new CryptoKeyVersionOperationFailed({ |
| 450 | operation: version.name ?? name, |
| 451 | message: version.generationFailureReason ?? state, |
| 452 | }), |
| 453 | ); |
| 454 | } |
| 455 | if (state === "IMPORT_FAILED") { |
| 456 | return Effect.fail( |
| 457 | new CryptoKeyVersionOperationFailed({ |
| 458 | operation: version.name ?? name, |
| 459 | message: version.importFailureReason ?? state, |
| 460 | }), |
| 461 | ); |
| 462 | } |
| 463 | return Effect.fail( |
| 464 | new CryptoKeyVersionNotReady({ |
| 465 | resourceName: name, |
| 466 | state: state ?? "PENDING_GENERATION", |
| 467 | }), |
| 468 | ); |
| 469 | }, |
| 470 | ), |
| 471 | ); |
| 472 | return probe.pipe( |
| 473 | Effect.retry({ |
| 474 | while: (error) => error._tag === "GCP.KMS.CryptoKeyVersionNotReady", |
| 475 | times: 8, |
| 476 | schedule: Schedule.spaced("500 millis"), |
| 477 | }), |
| 478 | ); |
| 479 | }; |
| 480 | |
| 481 | const optionsEqual = ( |
| 482 | observed: kms.ExternalProtectionLevelOptions | undefined, |
| 483 | desired: CryptoKeyVersionExternalProtectionLevelOptions | undefined, |
| 484 | ) => |
| 485 | (observed?.externalKeyUri ?? "") === (desired?.externalKeyUri ?? "") && |
| 486 | (observed?.ekmConnectionKeyPath ?? "") === (desired?.ekmConnectionKeyPath ?? ""); |
| 487 | |
| 488 | const destroyVersion = (name: string) => |
| 489 | kms |
| 490 | .destroyProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersions({ |
| 491 | name, |
| 492 | body: {}, |
| 493 | }) |
| 494 | .pipe( |
| 495 | Effect.catchTags({ |
| 496 | NotFound: () => Effect.undefined, |
| 497 | BadRequest: () => Effect.undefined, |
| 498 | Conflict: () => Effect.undefined, |
| 499 | }), |
| 500 | ); |
| 501 | |
| 502 | const restoreVersion = (name: string) => |
| 503 | kms |
| 504 | .restoreProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersions({ |
| 505 | name, |
| 506 | body: {}, |
| 507 | }) |
| 508 | .pipe( |
| 509 | Effect.catchTags({ |
| 510 | NotFound: () => Effect.undefined, |
| 511 | BadRequest: () => Effect.undefined, |
| 512 | Conflict: () => Effect.undefined, |
| 513 | }), |
| 514 | ); |
| 515 | |
| 516 | const deleteVersion = (name: string) => |
| 517 | kms.deleteProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersions({ name }).pipe( |
| 518 | Effect.catchTags({ |
| 519 | NotFound: () => Effect.undefined, |
| 520 | BadRequest: () => Effect.undefined, |
| 521 | Conflict: () => Effect.undefined, |
| 522 | }), |
| 523 | Effect.flatMap( |
| 524 | ( |
| 525 | operation, |
| 526 | ): Effect.Effect< |
| 527 | void, |
| 528 | | CryptoKeyVersionOperationFailed |
| 529 | | OperationFailed |
| 530 | | OperationTimedOut |
| 531 | | kms.GetProjectsLocationsOperationsError, |
| 532 | kms.GcpOpContext |
| 533 | > => (operation === undefined ? Effect.void : waitOperation(operation).pipe(Effect.asVoid)), |
| 534 | ), |
| 535 | ); |
| 536 | |
| 537 | const resolveName = (args: { |
| 538 | outputName: string | undefined; |
| 539 | outputVersionId: string | undefined; |
| 540 | propsVersionId: string | undefined; |
| 541 | parent: string; |
| 542 | }) => { |
| 543 | if (args.outputName !== undefined) return args.outputName; |
| 544 | const versionId = args.propsVersionId ?? args.outputVersionId; |
| 545 | return versionId !== undefined ? resourceName(args.parent, versionId) : undefined; |
| 546 | }; |
| 547 | |
| 548 | export const CryptoKeyVersionProvider = () => |
| 549 | Provider.succeed(CryptoKeyVersion, { |
| 550 | stables: [ |
| 551 | "name", |
| 552 | "cryptoKeyVersionId", |
| 553 | "cryptoKey", |
| 554 | "keyRing", |
| 555 | "location", |
| 556 | "project", |
| 557 | "algorithm", |
| 558 | "protectionLevel", |
| 559 | "createTime", |
| 560 | ], |
| 561 | |
| 562 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 563 | if (!isResolved(news)) return undefined; |
| 564 | const env = yield* GcpEnvironment.current; |
| 565 | |
| 566 | const previousId = olds?.cryptoKeyVersionId ?? output?.cryptoKeyVersionId; |
| 567 | const nextId = news.cryptoKeyVersionId ?? previousId; |
| 568 | const idChanged = previousId !== undefined && nextId !== undefined && nextId !== previousId; |
| 569 | |
| 570 | const previousParent = |
| 571 | output?.cryptoKey ?? |
| 572 | (olds?.cryptoKey |
| 573 | ? resolveParent("", olds.cryptoKey, olds.keyRing, olds.location, env.region).parent |
| 574 | : undefined); |
| 575 | const nextParent = resolveParent( |
| 576 | output?.project ?? "", |
| 577 | news.cryptoKey, |
| 578 | news.keyRing ?? output?.keyRing, |
| 579 | news.location ?? output?.location, |
| 580 | env.region, |
| 581 | ).parent; |
| 582 | const parentChanged = previousParent !== undefined && previousParent !== nextParent; |
| 583 | |
| 584 | if (!idChanged && !parentChanged) return undefined; |
| 585 | return { action: "replace" as const, deleteFirst: false }; |
| 586 | }), |
| 587 | |
| 588 | read: Effect.fn(function* ({ olds, output }) { |
| 589 | const env = yield* GcpEnvironment.current; |
| 590 | const parent = |
| 591 | olds?.cryptoKey || output?.cryptoKey |
| 592 | ? resolveParent( |
| 593 | env.project, |
| 594 | olds?.cryptoKey ?? output?.cryptoKey ?? "", |
| 595 | olds?.keyRing ?? output?.keyRing, |
| 596 | olds?.location ?? output?.location, |
| 597 | env.region, |
| 598 | ).parent |
| 599 | : undefined; |
| 600 | const name = resolveName({ |
| 601 | outputName: output?.name, |
| 602 | outputVersionId: output?.cryptoKeyVersionId, |
| 603 | propsVersionId: olds?.cryptoKeyVersionId, |
| 604 | parent: parent ?? "", |
| 605 | }); |
| 606 | if (name === undefined) return undefined; |
| 607 | const existing = yield* getByName(name); |
| 608 | if (existing === undefined) return undefined; |
| 609 | if (DELETABLE_STATES.has(existing.state ?? "")) return undefined; |
| 610 | // Versions have no labels. Existence at the stored name is |
| 611 | // ownership; adopting a version of an alchemy-labeled key is |
| 612 | // harmless. |
| 613 | return toAttrs(existing, env.project, env.region); |
| 614 | }), |
| 615 | |
| 616 | list: () => |
| 617 | Effect.gen(function* () { |
| 618 | const env = yield* GcpEnvironment.current; |
| 619 | const found: CryptoKeyVersionAttrs[] = []; |
| 620 | let pageToken: string | undefined; |
| 621 | for (let page = 0; page < 10; page++) { |
| 622 | const response = yield* kms.listProjectsLocations({ |
| 623 | name: `projects/${env.project}`, |
| 624 | pageSize: 100, |
| 625 | pageToken, |
| 626 | }); |
| 627 | const parents = (response.locations ?? []) |
| 628 | .map((location) => location.name) |
| 629 | .filter((name): name is string => !!name); |
| 630 | const batches = yield* Effect.forEach(parents, (parent) => listVersionsAt(parent), { |
| 631 | concurrency: 4, |
| 632 | }); |
| 633 | for (const versions of batches) { |
| 634 | for (const version of versions) { |
| 635 | if (version.state === "DESTROY_SCHEDULED") continue; |
| 636 | found.push(toAttrs(version, env.project, env.region)); |
| 637 | } |
| 638 | } |
| 639 | pageToken = response.nextPageToken; |
| 640 | if (pageToken === undefined || pageToken === "") break; |
| 641 | } |
| 642 | return found; |
| 643 | }), |
| 644 | |
| 645 | reconcile: Effect.fn(function* ({ news, output }) { |
| 646 | const env = yield* GcpEnvironment.current; |
| 647 | const parent = resolveParent( |
| 648 | env.project, |
| 649 | news.cryptoKey, |
| 650 | news.keyRing ?? output?.keyRing, |
| 651 | news.location ?? output?.location, |
| 652 | env.region, |
| 653 | ); |
| 654 | const name = resolveName({ |
| 655 | outputName: output?.name, |
| 656 | outputVersionId: output?.cryptoKeyVersionId, |
| 657 | propsVersionId: news.cryptoKeyVersionId, |
| 658 | parent: parent.parent, |
| 659 | }); |
| 660 | const targetState = desiredState(news.state); |
| 661 | |
| 662 | let current = name === undefined ? undefined : yield* getByName(name); |
| 663 | |
| 664 | if (current !== undefined && DELETABLE_STATES.has(current.state ?? "")) { |
| 665 | if (current.name !== undefined) { |
| 666 | yield* deleteVersion(current.name); |
| 667 | } |
| 668 | current = undefined; |
| 669 | } |
| 670 | |
| 671 | if (current === undefined) { |
| 672 | const created = yield* kms |
| 673 | .createProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersions({ |
| 674 | parent: parent.parent, |
| 675 | body: { |
| 676 | state: targetState === "DISABLED" ? "DISABLED" : undefined, |
| 677 | externalProtectionLevelOptions: news.externalProtectionLevelOptions, |
| 678 | }, |
| 679 | }) |
| 680 | .pipe( |
| 681 | Effect.catchTag("Conflict", () => |
| 682 | name !== undefined ? getByName(name) : Effect.undefined, |
| 683 | ), |
| 684 | ); |
| 685 | current = created ?? undefined; |
| 686 | } |
| 687 | |
| 688 | if (current === undefined || current.name === undefined) { |
| 689 | return yield* new CryptoKeyVersionNotResolved({ |
| 690 | resourceName: name ?? resourceName(parent.parent, "unknown"), |
| 691 | }); |
| 692 | } |
| 693 | |
| 694 | const currentName = current.name; |
| 695 | if (current.state === "PENDING_GENERATION" || current.state === "PENDING_IMPORT") { |
| 696 | current = yield* waitReady(currentName); |
| 697 | } |
| 698 | |
| 699 | if (current.state === "DESTROY_SCHEDULED" && PATCHABLE_STATES.has(targetState)) { |
| 700 | const restored = yield* restoreVersion(currentName); |
| 701 | current = restored ?? (yield* waitReady(currentName)); |
| 702 | } |
| 703 | |
| 704 | const observedState = current.state ?? DEFAULT_STATE; |
| 705 | const stateChanged = |
| 706 | PATCHABLE_STATES.has(targetState) && |
| 707 | PATCHABLE_STATES.has(observedState) && |
| 708 | observedState !== targetState; |
| 709 | const optionsChanged = |
| 710 | news.externalProtectionLevelOptions !== undefined && |
| 711 | !optionsEqual(current.externalProtectionLevelOptions, news.externalProtectionLevelOptions); |
| 712 | |
| 713 | if (stateChanged || optionsChanged) { |
| 714 | const updateMask = [ |
| 715 | stateChanged ? "state" : undefined, |
| 716 | optionsChanged ? "externalProtectionLevelOptions" : undefined, |
| 717 | ] |
| 718 | .filter((field): field is string => field !== undefined) |
| 719 | .join(","); |
| 720 | current = yield* kms.patchProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersions({ |
| 721 | name: currentName, |
| 722 | updateMask, |
| 723 | body: { |
| 724 | state: stateChanged ? targetState : undefined, |
| 725 | externalProtectionLevelOptions: optionsChanged |
| 726 | ? news.externalProtectionLevelOptions |
| 727 | : undefined, |
| 728 | }, |
| 729 | }); |
| 730 | } |
| 731 | |
| 732 | return toAttrs(current, env.project, env.region); |
| 733 | }), |
| 734 | |
| 735 | delete: Effect.fn(function* ({ output }) { |
| 736 | const name = output.name; |
| 737 | const current = yield* getByName(name); |
| 738 | if (current === undefined) return; |
| 739 | |
| 740 | const state = current.state ?? ""; |
| 741 | if (DESTROYABLE_STATES.has(state)) { |
| 742 | yield* destroyVersion(name); |
| 743 | return; |
| 744 | } |
| 745 | if (DELETABLE_STATES.has(state)) { |
| 746 | yield* deleteVersion(name); |
| 747 | } |
| 748 | }), |
| 749 | }); |