@go-to-k/cdkd 0.219.9 → 0.220.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3383,6 +3383,60 @@ var S3StateBackend = class {
3383
3383
  }
3384
3384
  }
3385
3385
  /**
3386
+ * Raw sidecar-object write under the state bucket. Used for non-state
3387
+ * auxiliary files that share the bucket + region-resolution plumbing
3388
+ * (e.g. deployment-event JSONL streams + their `index.json`, issue
3389
+ * #808) without going through the state-schema validation that
3390
+ * `saveState` applies. No optimistic locking — callers own their key
3391
+ * uniqueness / last-writer-wins semantics.
3392
+ */
3393
+ async putRawObject(key, body, contentType = "application/json") {
3394
+ await this.ensureClientForBucket();
3395
+ await this.s3Client.send(new PutObjectCommand({
3396
+ Bucket: this.config.bucket,
3397
+ Key: key,
3398
+ Body: body,
3399
+ ContentLength: Buffer.byteLength(body),
3400
+ ContentType: contentType
3401
+ }));
3402
+ }
3403
+ /**
3404
+ * Raw sidecar-object read under the state bucket. Returns `null` when
3405
+ * the key does not exist; other errors propagate.
3406
+ */
3407
+ async getRawObject(key) {
3408
+ await this.ensureClientForBucket();
3409
+ try {
3410
+ return await (await this.s3Client.send(new GetObjectCommand({
3411
+ Bucket: this.config.bucket,
3412
+ Key: key
3413
+ }))).Body?.transformToString() ?? null;
3414
+ } catch (error) {
3415
+ if (isNoSuchKey(error) || error.name === "NotFound") return null;
3416
+ throw error;
3417
+ }
3418
+ }
3419
+ /**
3420
+ * Raw key listing under an arbitrary key prefix in the state bucket
3421
+ * (paginated). Used by `cdkd events` to discover regions / runs under
3422
+ * `{prefix}/{stackName}/.../deployments/`.
3423
+ */
3424
+ async listRawKeys(keyPrefix) {
3425
+ await this.ensureClientForBucket();
3426
+ const keys = [];
3427
+ let continuationToken;
3428
+ do {
3429
+ const response = await this.s3Client.send(new ListObjectsV2Command({
3430
+ Bucket: this.config.bucket,
3431
+ Prefix: keyPrefix,
3432
+ ...continuationToken && { ContinuationToken: continuationToken }
3433
+ }));
3434
+ for (const obj of response.Contents ?? []) if (obj.Key) keys.push(obj.Key);
3435
+ continuationToken = response.IsTruncated ? response.NextContinuationToken : void 0;
3436
+ } while (continuationToken);
3437
+ return keys;
3438
+ }
3439
+ /**
3386
3440
  * HeadObject probe — returns true on 200, false on NotFound. Other errors
3387
3441
  * propagate so we don't accidentally swallow IAM denials.
3388
3442
  */
@@ -3486,12 +3540,22 @@ function isNoSuchKey(error) {
3486
3540
  *
3487
3541
  * Locks have a TTL (time-to-live). Expired locks are automatically cleaned up
3488
3542
  * during acquisition attempts.
3543
+ *
3544
+ * Like `S3StateBackend`, the lock manager tolerates a state bucket that
3545
+ * lives in a different AWS region from the CLI's base region: before the
3546
+ * first S3 operation it resolves the bucket's actual region via
3547
+ * `GetBucketLocation` and, if it differs from the supplied client's region,
3548
+ * builds a private replacement client for that region (issue #803 — without
3549
+ * this, every lock acquisition against a cross-region bucket failed with
3550
+ * S3's 301 PermanentRedirect while state reads/writes succeeded).
3489
3551
  */
3490
3552
  var LockManager = class {
3491
3553
  logger = getLogger().child("LockManager");
3492
3554
  s3Client;
3493
3555
  config;
3494
3556
  ttlMs;
3557
+ clientResolved = false;
3558
+ resolveInFlight = null;
3495
3559
  constructor(s3Client, config, options) {
3496
3560
  this.s3Client = s3Client;
3497
3561
  this.config = config;
@@ -3499,6 +3563,62 @@ var LockManager = class {
3499
3563
  this.ttlMs = ttlMinutes * 60 * 1e3;
3500
3564
  }
3501
3565
  /**
3566
+ * Resolve the state bucket's actual region and, if it differs from the
3567
+ * supplied client's configured region, replace the client reference with
3568
+ * a new S3Client pointed at the bucket's region.
3569
+ *
3570
+ * Mirrors `S3StateBackend.ensureClientForBucket()` (PR #60) with two
3571
+ * deliberate differences:
3572
+ *
3573
+ * - The replacement client reuses the original client's resolved
3574
+ * credentials provider, so `--profile` / static credentials carry over
3575
+ * without the 8 LockManager call sites having to thread client options.
3576
+ * - The original client is NOT destroyed. It is the shared `AwsClients.s3`
3577
+ * instance that other components (state backend, exports index) still
3578
+ * hold a reference to.
3579
+ *
3580
+ * `resolveBucketRegion` caches per bucket name for the process lifetime,
3581
+ * so when the state backend has already resolved the same bucket this
3582
+ * incurs no additional `GetBucketLocation` call.
3583
+ */
3584
+ async ensureClientForBucket() {
3585
+ if (this.clientResolved) return;
3586
+ if (this.resolveInFlight) return this.resolveInFlight;
3587
+ this.resolveInFlight = (async () => {
3588
+ try {
3589
+ const currentRegion = await this.s3Client.config.region();
3590
+ const fallbackRegion = typeof currentRegion === "string" ? currentRegion : void 0;
3591
+ let probeCredentials;
3592
+ try {
3593
+ probeCredentials = await this.s3Client.config.credentials();
3594
+ } catch {
3595
+ probeCredentials = void 0;
3596
+ }
3597
+ const bucketRegion = await resolveBucketRegion(this.config.bucket, {
3598
+ ...probeCredentials && { credentials: probeCredentials },
3599
+ ...fallbackRegion && { fallbackRegion }
3600
+ });
3601
+ if (bucketRegion !== currentRegion) {
3602
+ this.logger.debug(`State bucket '${this.config.bucket}' is in '${bucketRegion}' (lock client was '${currentRegion}'); building a region-corrected S3 client for lock operations.`);
3603
+ this.s3Client = new S3Client({
3604
+ region: bucketRegion,
3605
+ credentials: this.s3Client.config.credentials,
3606
+ logger: {
3607
+ debug: () => {},
3608
+ info: () => {},
3609
+ warn: () => {},
3610
+ error: () => {}
3611
+ }
3612
+ });
3613
+ }
3614
+ this.clientResolved = true;
3615
+ } finally {
3616
+ this.resolveInFlight = null;
3617
+ }
3618
+ })();
3619
+ return this.resolveInFlight;
3620
+ }
3621
+ /**
3502
3622
  * Get the S3 key for a stack's lock file.
3503
3623
  *
3504
3624
  * Locks are region-scoped, mirroring the state key layout
@@ -3553,6 +3673,7 @@ var LockManager = class {
3553
3673
  * @param operation Operation being performed (e.g., "deploy", "destroy")
3554
3674
  */
3555
3675
  async acquireLock(stackName, region, owner, operation) {
3676
+ await this.ensureClientForBucket();
3556
3677
  const key = this.getLockKey(stackName, region);
3557
3678
  const lockOwner = owner || this.getDefaultOwner();
3558
3679
  const now = Date.now();
@@ -3615,6 +3736,7 @@ var LockManager = class {
3615
3736
  * file (e.g. for state-listing tools that don't yet know the region).
3616
3737
  */
3617
3738
  async getLockInfo(stackName, region) {
3739
+ await this.ensureClientForBucket();
3618
3740
  const key = this.getLockKey(stackName, region);
3619
3741
  try {
3620
3742
  this.logger.debug(`Getting lock info for stack: ${stackName}`);
@@ -3651,6 +3773,7 @@ var LockManager = class {
3651
3773
  * Release a lock for a stack
3652
3774
  */
3653
3775
  async releaseLock(stackName, region) {
3776
+ await this.ensureClientForBucket();
3654
3777
  const key = this.getLockKey(stackName, region);
3655
3778
  try {
3656
3779
  this.logger.debug(`Releasing lock for stack: ${stackName} (${region})`);
@@ -3685,6 +3808,7 @@ var LockManager = class {
3685
3808
  * Internal method to delete the lock file from S3
3686
3809
  */
3687
3810
  async deleteLock(stackName, region) {
3811
+ await this.ensureClientForBucket();
3688
3812
  const key = this.getLockKey(stackName, region);
3689
3813
  await this.s3Client.send(new DeleteObjectCommand({
3690
3814
  Bucket: this.config.bucket,
@@ -11049,6 +11173,37 @@ var DagExecutor = class {
11049
11173
  }
11050
11174
  };
11051
11175
 
11176
+ //#endregion
11177
+ //#region src/types/deployment-events.ts
11178
+ /**
11179
+ * Walk an error's `.cause` chain (bounded) and extract metadata for a
11180
+ * deployment event. The outermost error supplies `name` / `message`
11181
+ * (matching what the user sees in the log); the innermost AWS-SDK-shaped
11182
+ * error (the one carrying `$metadata`) supplies `awsErrorCode` /
11183
+ * `requestId` when present.
11184
+ */
11185
+ function extractDeploymentEventError(err) {
11186
+ if (!(err instanceof Error)) return {
11187
+ name: "UnknownError",
11188
+ message: String(err)
11189
+ };
11190
+ const result = {
11191
+ name: err.name || "Error",
11192
+ message: err.message
11193
+ };
11194
+ let current = err;
11195
+ for (let depth = 0; depth < 10 && current instanceof Error; depth++) {
11196
+ const maybeAws = current;
11197
+ if (maybeAws.$metadata !== void 0) {
11198
+ const code = maybeAws.Code ?? maybeAws.name;
11199
+ if (code) result.awsErrorCode = code;
11200
+ if (maybeAws.$metadata.requestId) result.requestId = maybeAws.$metadata.requestId;
11201
+ }
11202
+ current = current.cause;
11203
+ }
11204
+ return result;
11205
+ }
11206
+
11052
11207
  //#endregion
11053
11208
  //#region src/analyzer/implicit-delete-deps.ts
11054
11209
  /**
@@ -11925,25 +12080,33 @@ var DeployEngine = class {
11925
12080
  * information from state, then processes UPDATE/DELETE rollbacks, and finally
11926
12081
  * processes sorted CREATE rollback deletions.
11927
12082
  */
11928
- async performRollback(completedOperations, stateResources, _stackName) {
12083
+ async performRollback(completedOperations, stateResources, stackName) {
11929
12084
  if (completedOperations.length === 0) {
11930
12085
  this.logger.info("No completed operations to roll back.");
11931
12086
  return;
11932
12087
  }
11933
12088
  this.logger.info(`Rolling back ${completedOperations.length} completed operation(s)...`);
12089
+ this.recordEvent({
12090
+ eventType: "ROLLBACK_STARTED",
12091
+ stackName
12092
+ });
11934
12093
  const createOps = [];
11935
12094
  const otherOps = [];
11936
12095
  for (const op of completedOperations) if (op.changeType === "CREATE") createOps.push(op);
11937
12096
  else otherOps.push(op);
11938
12097
  for (let i = otherOps.length - 1; i >= 0; i--) {
11939
12098
  const op = otherOps[i];
11940
- await this.performSingleRollback(op, stateResources);
12099
+ await this.performSingleRollback(op, stateResources, stackName);
11941
12100
  }
11942
12101
  if (createOps.length > 0) {
11943
12102
  const sortedCreateOps = this.sortRollbackCreates(createOps, stateResources);
11944
- for (const op of sortedCreateOps) await this.performSingleRollback(op, stateResources);
12103
+ for (const op of sortedCreateOps) await this.performSingleRollback(op, stateResources, stackName);
11945
12104
  }
11946
12105
  this.logger.info("Rollback completed. Some resources may remain if deletion failed.");
12106
+ this.recordEvent({
12107
+ eventType: "ROLLBACK_FINISHED",
12108
+ stackName
12109
+ });
11947
12110
  }
11948
12111
  /**
11949
12112
  * Sort CREATE rollback operations so that resources depending on others
@@ -11997,7 +12160,7 @@ var DeployEngine = class {
11997
12160
  /**
11998
12161
  * Perform a single rollback operation (extracted for reuse)
11999
12162
  */
12000
- async performSingleRollback(op, stateResources) {
12163
+ async performSingleRollback(op, stateResources, stackName) {
12001
12164
  try {
12002
12165
  switch (op.changeType) {
12003
12166
  case "CREATE": {
@@ -12013,6 +12176,14 @@ var DeployEngine = class {
12013
12176
  await provider.delete(op.logicalId, op.physicalId, op.resourceType, op.properties, { expectedRegion: this.stackRegion });
12014
12177
  delete stateResources[op.logicalId];
12015
12178
  this.logger.info(` Rollback: ${op.logicalId} deleted successfully`);
12179
+ this.recordEvent({
12180
+ eventType: "ROLLBACK_RESOURCE_SUCCEEDED",
12181
+ stackName,
12182
+ operation: "CREATE",
12183
+ logicalId: op.logicalId,
12184
+ resourceType: op.resourceType,
12185
+ ...op.provisionedBy && { provisionedBy: op.provisionedBy }
12186
+ });
12016
12187
  break;
12017
12188
  }
12018
12189
  case "UPDATE": {
@@ -12033,6 +12204,14 @@ var DeployEngine = class {
12033
12204
  await provider.update(op.logicalId, currentResource.physicalId, op.resourceType, op.previousState.properties, currentResource.properties);
12034
12205
  stateResources[op.logicalId] = op.previousState;
12035
12206
  this.logger.info(` Rollback: ${op.logicalId} restored successfully`);
12207
+ this.recordEvent({
12208
+ eventType: "ROLLBACK_RESOURCE_SUCCEEDED",
12209
+ stackName,
12210
+ operation: "UPDATE",
12211
+ logicalId: op.logicalId,
12212
+ resourceType: op.resourceType,
12213
+ ...op.provisionedBy && { provisionedBy: op.provisionedBy }
12214
+ });
12036
12215
  break;
12037
12216
  }
12038
12217
  case "DELETE":
@@ -12042,6 +12221,15 @@ var DeployEngine = class {
12042
12221
  } catch (rollbackError) {
12043
12222
  this.logger.warn(` Rollback failed for ${op.logicalId} (${op.changeType}): ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`);
12044
12223
  this.logger.warn(" Continuing with remaining rollback operations...");
12224
+ this.recordEvent({
12225
+ eventType: "ROLLBACK_RESOURCE_FAILED",
12226
+ stackName,
12227
+ operation: op.changeType,
12228
+ logicalId: op.logicalId,
12229
+ resourceType: op.resourceType,
12230
+ ...op.provisionedBy && { provisionedBy: op.provisionedBy },
12231
+ error: extractDeploymentEventError(rollbackError)
12232
+ });
12045
12233
  }
12046
12234
  }
12047
12235
  /**
@@ -12051,13 +12239,25 @@ var DeployEngine = class {
12051
12239
  const resourceType = change.resourceType;
12052
12240
  const renderer = getLiveRenderer();
12053
12241
  const needsReplacement = change.changeType === "UPDATE" && (change.propertyChanges?.some((pc) => pc.requiresReplacement) ?? false);
12054
- const baseLabel = `${change.changeType === "CREATE" ? "Creating" : change.changeType === "DELETE" ? "Deleting" : needsReplacement ? "Replacing" : "Updating"} ${logicalId} (${resourceType})${this.peekRoutingForLabel(change, stateResources[logicalId]) === "cc-api" ? " [CC API]" : ""}`;
12242
+ const verb = change.changeType === "CREATE" ? "Creating" : change.changeType === "DELETE" ? "Deleting" : needsReplacement ? "Replacing" : "Updating";
12243
+ const labelRouting = this.peekRoutingForLabel(change, stateResources[logicalId]);
12244
+ const baseLabel = `${verb} ${logicalId} (${resourceType})${labelRouting === "cc-api" ? " [CC API]" : ""}`;
12055
12245
  renderer.addTask(logicalId, baseLabel);
12056
12246
  const operationKind = change.changeType === "CREATE" ? "CREATE" : change.changeType === "DELETE" ? "DELETE" : "UPDATE";
12057
12247
  const providerMinTimeoutMs = this.providerRegistry.getProvider(resourceType).getMinResourceTimeoutMs?.() ?? 0;
12058
12248
  const warnAfterMs = this.options.resourceWarnAfterByType?.[resourceType] ?? this.options.resourceWarnAfterMs ?? 3e5;
12059
12249
  const globalTimeoutMs = this.options.resourceTimeoutMs ?? 18e5;
12060
12250
  const timeoutMs = this.options.resourceTimeoutByType?.[resourceType] ?? Math.max(providerMinTimeoutMs, globalTimeoutMs);
12251
+ const eventOp = operationKind;
12252
+ const resourceStartedAt = Date.now();
12253
+ this.recordEvent({
12254
+ eventType: "RESOURCE_STARTED",
12255
+ stackName,
12256
+ operation: eventOp,
12257
+ logicalId,
12258
+ resourceType,
12259
+ ...labelRouting && { provisionedBy: labelRouting }
12260
+ });
12061
12261
  try {
12062
12262
  await withResourceDeadline(async () => {
12063
12263
  await this.provisionResourceBody(logicalId, change, stateResources, stackName, template, parameterValues, conditions, counts, progress);
@@ -12074,10 +12274,30 @@ var DeployEngine = class {
12074
12274
  },
12075
12275
  onTimeout: (elapsedMs) => new ResourceTimeoutError(logicalId, resourceType, this.stackRegion, elapsedMs, operationKind, timeoutMs)
12076
12276
  });
12277
+ this.recordEvent({
12278
+ eventType: "RESOURCE_SUCCEEDED",
12279
+ stackName,
12280
+ operation: eventOp,
12281
+ logicalId,
12282
+ resourceType,
12283
+ ...stateResources[logicalId]?.provisionedBy ? { provisionedBy: stateResources[logicalId]?.provisionedBy } : labelRouting && { provisionedBy: labelRouting },
12284
+ ...stateResources[logicalId]?.physicalId && { physicalId: stateResources[logicalId]?.physicalId },
12285
+ durationMs: Date.now() - resourceStartedAt
12286
+ });
12077
12287
  } catch (error) {
12078
12288
  renderer.removeTask(logicalId);
12079
12289
  const message = error instanceof Error ? error.message : String(error);
12080
12290
  this.logger.error(`Failed to ${change.changeType.toLowerCase()} ${logicalId}: ${message}`);
12291
+ this.recordEvent({
12292
+ eventType: "RESOURCE_FAILED",
12293
+ stackName,
12294
+ operation: eventOp,
12295
+ logicalId,
12296
+ resourceType,
12297
+ ...stateResources[logicalId]?.provisionedBy ? { provisionedBy: stateResources[logicalId]?.provisionedBy } : labelRouting && { provisionedBy: labelRouting },
12298
+ durationMs: Date.now() - resourceStartedAt,
12299
+ error: extractDeploymentEventError(error)
12300
+ });
12081
12301
  throw new ProvisioningError(`Failed to ${change.changeType.toLowerCase()} resource ${logicalId}`, resourceType, logicalId, stateResources[logicalId]?.physicalId, error instanceof Error ? error : void 0);
12082
12302
  } finally {
12083
12303
  renderer.removeTask(logicalId);
@@ -12087,6 +12307,18 @@ var DeployEngine = class {
12087
12307
  return deriveLabelRouting(change, existingState, this.providerRegistry);
12088
12308
  }
12089
12309
  /**
12310
+ * #808 — forward one structured deployment event to the optional
12311
+ * recorder. No-op when no recorder was supplied. `record()` is
12312
+ * contractually synchronous and never-throwing, but we still guard
12313
+ * with a try/catch so an event emission can NEVER abort a deploy.
12314
+ */
12315
+ recordEvent(event) {
12316
+ if (!this.options.eventRecorder) return;
12317
+ try {
12318
+ this.options.eventRecorder.record(event);
12319
+ } catch {}
12320
+ }
12321
+ /**
12090
12322
  * Inner body of provisionResource, extracted so the outer wrapper can
12091
12323
  * apply the per-resource deadline (`withResourceDeadline`) without
12092
12324
  * having the timeout / warn timer code dwarf the real provisioning
@@ -12510,5 +12742,5 @@ var DeployEngine = class {
12510
12742
  };
12511
12743
 
12512
12744
  //#endregion
12513
- export { WorkGraph as A, resolveCaptureObservedState as B, DagBuilder as C, shouldRetainResource as D, S3StateBackend as E, runDockerStreaming as F, CFN_TEMPLATE_BODY_LIMIT as G, resolveStateBucketWithDefault as H, Synthesizer as I, findLargeInlineResources as J, CFN_TEMPLATE_URL_LIMIT as K, getDefaultStateBucketName as L, formatDockerLoginError as M, getDockerCmd as N, AssetPublisher as O, runDockerForeground as P, resolveBucketRegion as Q, getLegacyStateBucketName as R, DiffCalculator as S, LockManager as T, resolveStateBucketWithDefaultAndSource as U, resolveSkipPrefix as V, warnDeprecatedNoPrefixCliFlag as W, AssemblyReader as X, uploadCfnTemplate as Y, clearBucketRegionCache as Z, ProviderRegistry as _, withRetry as a, IntrinsicFunctionResolver as b, formatResourceLine as c, gray as d, green as f, collectInlinePolicyNamesManagedBySiblings as g, IAMRoleProvider as h, withResourceDeadline as i, buildDockerImage as j, stringifyValue as k, bold as l, yellow as m, DEFAULT_RESOURCE_WARN_AFTER_MS as n, isRetryableTransientError as o, red as p, MIGRATE_TMP_PREFIX as q, DeployEngine as r, IMPLICIT_DELETE_DEPENDENCIES as s, DEFAULT_RESOURCE_TIMEOUT_MS as t, cyan as u, findActionableSilentDrops as v, TemplateParser as w, applyRoleArnIfSet as x, CloudControlProvider as y, resolveApp as z };
12514
- //# sourceMappingURL=deploy-engine-DVP4vDXG.js.map
12745
+ export { resolveBucketRegion as $, stringifyValue as A, resolveApp as B, DiffCalculator as C, S3StateBackend as D, LockManager as E, runDockerForeground as F, warnDeprecatedNoPrefixCliFlag as G, resolveSkipPrefix as H, runDockerStreaming as I, MIGRATE_TMP_PREFIX as J, CFN_TEMPLATE_BODY_LIMIT as K, Synthesizer as L, buildDockerImage as M, formatDockerLoginError as N, shouldRetainResource as O, getDockerCmd as P, clearBucketRegionCache as Q, getDefaultStateBucketName as R, applyRoleArnIfSet as S, TemplateParser as T, resolveStateBucketWithDefault as U, resolveCaptureObservedState as V, resolveStateBucketWithDefaultAndSource as W, uploadCfnTemplate as X, findLargeInlineResources as Y, AssemblyReader as Z, collectInlinePolicyNamesManagedBySiblings as _, withRetry as a, CloudControlProvider as b, extractDeploymentEventError as c, cyan as d, gray as f, IAMRoleProvider as g, yellow as h, withResourceDeadline as i, WorkGraph as j, AssetPublisher as k, formatResourceLine as l, red as m, DEFAULT_RESOURCE_WARN_AFTER_MS as n, isRetryableTransientError as o, green as p, CFN_TEMPLATE_URL_LIMIT as q, DeployEngine as r, IMPLICIT_DELETE_DEPENDENCIES as s, DEFAULT_RESOURCE_TIMEOUT_MS as t, bold as u, ProviderRegistry as v, DagBuilder as w, IntrinsicFunctionResolver as x, findActionableSilentDrops as y, getLegacyStateBucketName as z };
12746
+ //# sourceMappingURL=deploy-engine-CcOt3mUO.js.map