@cdkd/cli 0.337.0 → 0.339.0

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.
Files changed (43) hide show
  1. package/dist/{ambient-client-defaults-B9bnuob2.js → ambient-client-defaults-D2df_dIB.js} +24 -4
  2. package/dist/ambient-client-defaults-D2df_dIB.js.map +1 -0
  3. package/dist/{asg-provider-D9utqY50.js → asg-provider-BiLQ0XWy.js} +5 -5
  4. package/dist/{asg-provider-D9utqY50.js.map → asg-provider-BiLQ0XWy.js.map} +1 -1
  5. package/dist/{aws-clients-ez_oXu6x.js → aws-clients-D3Z_tFc1.js} +4 -25
  6. package/dist/aws-clients-D3Z_tFc1.js.map +1 -0
  7. package/dist/{aws-failure-text-CoS1huLy.js → aws-failure-text-FKztQiaJ.js} +13 -4
  8. package/dist/aws-failure-text-FKztQiaJ.js.map +1 -0
  9. package/dist/cli.js +2 -2
  10. package/dist/{db-instance-modify-retry-Dj3Og4oJ.js → db-instance-modify-retry-DR1oW9Ln.js} +4 -4
  11. package/dist/{db-instance-modify-retry-Dj3Og4oJ.js.map → db-instance-modify-retry-DR1oW9Ln.js.map} +1 -1
  12. package/dist/{deploy-engine-KBE8BcSM.js → deploy-engine-BFlLAOb5.js} +214 -30
  13. package/dist/deploy-engine-BFlLAOb5.js.map +1 -0
  14. package/dist/{ecr-uri-CNcdSjXO.js → ecr-uri-DWcC0h82.js} +3 -3
  15. package/dist/{ecr-uri-CNcdSjXO.js.map → ecr-uri-DWcC0h82.js.map} +1 -1
  16. package/dist/{iam-role-provider-C5lQDb0K.js → iam-role-provider-m_Kd7_uy.js} +6 -6
  17. package/dist/{iam-role-provider-C5lQDb0K.js.map → iam-role-provider-m_Kd7_uy.js.map} +1 -1
  18. package/dist/index.d.ts +3 -0
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +5 -5
  21. package/dist/{neptune-provider-Xa6FSs0P.js → neptune-provider-Du2C7Q5P.js} +6 -6
  22. package/dist/{neptune-provider-Xa6FSs0P.js.map → neptune-provider-Du2C7Q5P.js.map} +1 -1
  23. package/dist/{program-Dp0YN4u2.js → program-B-C6eA7H.js} +21 -36
  24. package/dist/program-B-C6eA7H.js.map +1 -0
  25. package/dist/{provider-classes-BnjGVEVP.js → provider-classes-ZB2dhH_W.js} +12 -12
  26. package/dist/{provider-classes-BnjGVEVP.js.map → provider-classes-ZB2dhH_W.js.map} +1 -1
  27. package/dist/{rds-provider-DmYhP_4t.js → rds-provider-DzsTP_11.js} +462 -168
  28. package/dist/rds-provider-DzsTP_11.js.map +1 -0
  29. package/dist/{read-replica-CxxoxTT6.js → read-replica-DIfL8kl8.js} +5 -19
  30. package/dist/read-replica-DIfL8kl8.js.map +1 -0
  31. package/dist/rolldown-runtime-CNh9ExCG.js +17 -0
  32. package/dist/{update-removal-Dh6W86TO.js → update-removal-DTvJXMeM.js} +3 -3
  33. package/dist/{update-removal-Dh6W86TO.js.map → update-removal-DTvJXMeM.js.map} +1 -1
  34. package/dist/{version-12lmTkBz.js → version-eQ4CwKON.js} +2 -2
  35. package/dist/{version-12lmTkBz.js.map → version-eQ4CwKON.js.map} +1 -1
  36. package/package.json +11 -11
  37. package/dist/ambient-client-defaults-B9bnuob2.js.map +0 -1
  38. package/dist/aws-clients-ez_oXu6x.js.map +0 -1
  39. package/dist/aws-failure-text-CoS1huLy.js.map +0 -1
  40. package/dist/deploy-engine-KBE8BcSM.js.map +0 -1
  41. package/dist/program-Dp0YN4u2.js.map +0 -1
  42. package/dist/rds-provider-DmYhP_4t.js.map +0 -1
  43. package/dist/read-replica-CxxoxTT6.js.map +0 -1
@@ -1,13 +1,13 @@
1
- import { $ as safeMsg, n as describeAwsFailure, s as getLogger, y as generatedNameFor } from "./aws-failure-text-CoS1huLy.js";
2
- import { E as relayedNameCollision, H as markNonRetryable, U as markRedactedCause, W as wrapMaskedAwsError, Z as CdkdError, h as ResourceUpdateNotSupportedError, nt as ProvisioningError, t as ambientClientDefaults } from "./ambient-client-defaults-B9bnuob2.js";
1
+ import { $ as safeMsg, n as describeAwsFailure, s as getLogger, y as generatedNameFor } from "./aws-failure-text-FKztQiaJ.js";
2
+ import { D as relayedNameCollision, G as wrapMaskedAwsError, Q as CdkdError, U as markNonRetryable, W as markRedactedCause, g as ResourceUpdateNotSupportedError, rt as ProvisioningError, t as ambientClientDefaults } from "./ambient-client-defaults-D2df_dIB.js";
3
+ import { $ as deleteAfterProtectionFlipWithFinalSnapshot, B as resolveExplicitPhysicalId, H as assertRegionMatch, I as normalizeAwsTagsToCfn, It as maskerOrIdentity, J as observeThenDisableProtection, K as deleteWithProtectionCompensation, Kt as markAuxiliaryFailure, Lt as withDerivedNameMasks, Mt as createMaskedLogSinks, Q as PROTECTION_FLIP_RETRY_WAIT_MS, V as RESOURCE_NOT_FOUND, W as markNotGone, Y as rdsFamilyProtectionSite, a as withRemovalDefaults, f as retractCreatedResource, gt as protectedReplacementAdvice, ht as pasteableAwsCommand, it as ProtectionFlipRegistry, j as withoutServerErrorRetries, nt as isTerminalDbWaitStatus, ot as protectionFlipKey, qt as markCreatedBeforeFailure, t as clearOnUpdateRemoval, u as reportCreatedResource } from "./update-removal-DTvJXMeM.js";
3
4
  import { c as ambientRegion } from "./aws-client-defaults-BLXFsfMa.js";
4
- import { $i as tagPlanWarning, Gi as definedAttributes, Ki as stringifyIfAssigned, Nt as enclosingDeadlineRemainingMs, Sl as dynamicReferenceTokens, Yi as planTagDiff, Zi as refuseMalformedDesiredTags, ba as slowCcOperationTimeoutMs, jc as dbInstanceEngineChangeIsInPlace, ta as markDeleteStarted } from "./deploy-engine-KBE8BcSM.js";
5
- import { $ as deleteAfterProtectionFlipWithFinalSnapshot, B as resolveExplicitPhysicalId, H as assertRegionMatch, I as normalizeAwsTagsToCfn, It as maskerOrIdentity, J as observeThenDisableProtection, K as deleteWithProtectionCompensation, Kt as markAuxiliaryFailure, Lt as withDerivedNameMasks, Mt as createMaskedLogSinks, Q as PROTECTION_FLIP_RETRY_WAIT_MS, V as RESOURCE_NOT_FOUND, W as markNotGone, Y as rdsFamilyProtectionSite, a as withRemovalDefaults, f as retractCreatedResource, gt as protectedReplacementAdvice, ht as pasteableAwsCommand, it as ProtectionFlipRegistry, j as withoutServerErrorRetries, nt as isTerminalDbWaitStatus, ot as protectionFlipKey, qt as markCreatedBeforeFailure, t as clearOnUpdateRemoval, u as reportCreatedResource } from "./update-removal-Dh6W86TO.js";
6
- import { a as associatedRoleList, c as canonicalAssociatedRoles, i as associatedRoleKey, l as isRoleCallNotAvailableRefusal, n as modifyDbInstanceWhenAvailable, o as associatedRolesNamed, r as associatedRoleArns, s as associatedRolesReadback, t as isModifyNotAvailableRefusal, u as planAssociatedRoleChanges } from "./db-instance-modify-retry-Dj3Og4oJ.js";
7
- import { a as refuseMalformedReplicaSource, c as replicaEngine, d as replicaSourceChange, f as replicaSourceOf, l as replicaModifyAfterCreateInput, m as withPreviousReplicaSource, n as isLiveReadReplica, o as refuseUnknownSourceRegion, p as sameReplicaSource, r as ownScopeOf, s as replicaCreateInput, t as describeReplicaSource, u as replicaNeedsModifyAfterCreate } from "./read-replica-CxxoxTT6.js";
5
+ import { $i as refuseMalformedDesiredTags, Ft as enclosingDeadlineRemainingMs, Ji as stringifyIfAssigned, Nc as dbInstanceEngineChangeIsInPlace, Sa as slowCcOperationTimeoutMs, Zi as planTagDiff, qi as definedAttributes, ra as markDeleteStarted, ta as tagPlanWarning, wl as dynamicReferenceTokens } from "./deploy-engine-BFlLAOb5.js";
6
+ import { a as associatedRoleList, c as canonicalAssociatedRoles, i as associatedRoleKey, l as isRoleCallNotAvailableRefusal, n as modifyDbInstanceWhenAvailable, o as associatedRolesNamed, r as associatedRoleArns, s as associatedRolesReadback, t as isModifyNotAvailableRefusal, u as planAssociatedRoleChanges } from "./db-instance-modify-retry-DR1oW9Ln.js";
7
+ import { a as refuseMalformedReplicaSource, c as replicaEngine, d as replicaSourceChange, f as replicaSourceOf, l as replicaModifyAfterCreateInput, m as withPreviousReplicaSource, n as isLiveReadReplica, o as refuseUnknownSourceRegion, p as sameReplicaSource, r as ownScopeOf, s as replicaCreateInput, t as describeReplicaSource, u as replicaNeedsModifyAfterCreate } from "./read-replica-DIfL8kl8.js";
8
8
  import { DescribeSecurityGroupsCommand, EC2Client } from "@aws-sdk/client-ec2";
9
9
  import { isDeepStrictEqual } from "node:util";
10
- import { AddRoleToDBClusterCommand, AddRoleToDBInstanceCommand, AddTagsToResourceCommand, CreateDBClusterCommand, CreateDBInstanceCommand, CreateDBInstanceReadReplicaCommand, CreateDBSubnetGroupCommand, DeleteDBClusterCommand, DeleteDBInstanceCommand, DeleteDBSubnetGroupCommand, DescribeDBClustersCommand, DescribeDBInstancesCommand, DescribeDBSubnetGroupsCommand, DescribeGlobalClustersCommand, DisableHttpEndpointCommand, EnableHttpEndpointCommand, ListTagsForResourceCommand, ModifyDBClusterCommand, ModifyDBInstanceCommand, ModifyDBSubnetGroupCommand, PromoteReadReplicaCommand, RDSClient, RebootDBInstanceCommand, RemoveFromGlobalClusterCommand, RemoveRoleFromDBClusterCommand, RemoveRoleFromDBInstanceCommand, RemoveTagsFromResourceCommand } from "@aws-sdk/client-rds";
10
+ import { AddRoleToDBClusterCommand, AddRoleToDBInstanceCommand, AddTagsToResourceCommand, CreateDBClusterCommand, CreateDBInstanceCommand, CreateDBInstanceReadReplicaCommand, CreateDBSubnetGroupCommand, DeleteDBClusterCommand, DeleteDBInstanceCommand, DeleteDBSubnetGroupCommand, DescribeDBClustersCommand, DescribeDBInstanceAutomatedBackupsCommand, DescribeDBInstancesCommand, DescribeDBSubnetGroupsCommand, DescribeGlobalClustersCommand, DisableHttpEndpointCommand, EnableHttpEndpointCommand, ListTagsForResourceCommand, ModifyDBClusterCommand, ModifyDBInstanceCommand, ModifyDBSubnetGroupCommand, PromoteReadReplicaCommand, RDSClient, RebootDBInstanceCommand, RemoveFromGlobalClusterCommand, RemoveRoleFromDBClusterCommand, RemoveRoleFromDBInstanceCommand, RemoveTagsFromResourceCommand, StartDBInstanceAutomatedBackupsReplicationCommand, StopDBInstanceAutomatedBackupsReplicationCommand } from "@aws-sdk/client-rds";
11
11
 
12
12
  // src/provisioning/providers/rds/shared.ts
13
13
  const RDS_DELETE_WAIT_MS = Math.max(18e5, slowCcOperationTimeoutMs("AWS::RDS::DBCluster", "DELETE"), slowCcOperationTimeoutMs("AWS::RDS::DBInstance", "DELETE"));
@@ -450,6 +450,83 @@ function engineLifecycleSupportRefusalText(resourceType, logicalId, physicalId,
450
450
  const cli = kind === "DB cluster" ? "aws rds modify-db-cluster" : "aws rds modify-db-instance";
451
451
  return `${resourceType} ${logicalId}: EngineLifecycleSupport cannot change on an existing ${kind}. CloudFormation refuses the same update ("EngineLifecycleSupport cannot be modified."), whether the value changes, is added or is removed. Nothing was applied to ${kind} ${physicalId}. ` + (liveRead === "unreadable" ? `cdkd could not read the live setting (an AWS read failed), so it could not tell whether the ${kind} already holds the declared value; a re-run may succeed. ` : liveRead === "not-found" ? `RDS reports no such ${kind}: it was deleted outside cdkd, so the state record no longer matches AWS. ` : "") + `Declare the value the previous deploy declared (or none, if it declared none). To change the live setting, run ${cli} with --engine-lifecycle-support and --apply-immediately, then declare that value: a declared value the ${kind} already holds is no change.`;
452
452
  }
453
+ const BACKUP_REPLICATION_KEYS = [
454
+ "AutomaticBackupReplicationRegion",
455
+ "AutomaticBackupReplicationKmsKeyId",
456
+ "AutomaticBackupReplicationRetentionPeriod"
457
+ ];
458
+ const MALFORMED = Symbol("malformed");
459
+ function optionalString(value) {
460
+ if (value == null || value === "") return void 0;
461
+ return typeof value === "string" ? value : MALFORMED;
462
+ }
463
+ function optionalWholeNumber(value) {
464
+ if (value == null || value === "") return void 0;
465
+ const parsed = typeof value === "number" ? value : typeof value === "string" ? Number(value) : NaN;
466
+ return Number.isInteger(parsed) ? parsed : MALFORMED;
467
+ }
468
+ function backupReplicationOf(bag) {
469
+ const region = optionalString(bag["AutomaticBackupReplicationRegion"]);
470
+ const kmsKeyId = optionalString(bag["AutomaticBackupReplicationKmsKeyId"]);
471
+ const retention = optionalWholeNumber(bag["AutomaticBackupReplicationRetentionPeriod"]);
472
+ if (region === MALFORMED || kmsKeyId === MALFORMED || retention === MALFORMED) return "malformed";
473
+ return {
474
+ region,
475
+ kmsKeyId,
476
+ retention
477
+ };
478
+ }
479
+ function backupRetentionPeriodOf(bag) {
480
+ const value = optionalWholeNumber(bag["BackupRetentionPeriod"]);
481
+ return value === MALFORMED ? void 0 : value;
482
+ }
483
+ function backupReplicationPlan(properties, previousProperties, resourceType, logicalId, physicalId, stateBorne, warn) {
484
+ const none = {
485
+ stop: false,
486
+ start: void 0
487
+ };
488
+ const keys = [...BACKUP_REPLICATION_KEYS, "BackupRetentionPeriod"];
489
+ const desired = backupReplicationOf(properties);
490
+ const previous = backupReplicationOf(previousProperties);
491
+ if (desired === "malformed") {
492
+ if (keys.every((key) => isDeepStrictEqual(properties[key], previousProperties[key]))) return none;
493
+ throw markNonRetryable(new ProvisioningError(`${resourceType} ${logicalId}: AutomaticBackupReplicationRegion and AutomaticBackupReplicationKmsKeyId must be strings, and AutomaticBackupReplicationRetentionPeriod a whole number`, resourceType, logicalId, physicalId));
494
+ }
495
+ const misuse = desired.region === void 0 ? desired.kmsKeyId !== void 0 ? "You must specify the AutomaticBackupReplicationRegion parameter when setting the AutomaticBackupReplicationKmsKeyId parameter" : desired.retention !== void 0 ? "You must specify the AutomaticBackupReplicationRegion parameter when setting the AutomaticBackupReplicationRetentionPeriod parameter" : void 0 : backupRetentionPeriodOf(properties) === 0 ? "AutomaticBackupReplicationRegion cannot be specified when BackupRetentionPeriod is 0" : void 0;
496
+ if (misuse !== void 0) {
497
+ const message = `${resourceType} ${logicalId}: ${misuse} (as CloudFormation refuses it)`;
498
+ if (!stateBorne) throw markNonRetryable(new ProvisioningError(message, resourceType, logicalId, physicalId));
499
+ warn(`${message}; the restored properties declare it, so it is applied as declared`);
500
+ }
501
+ const start = desired.region === void 0 ? void 0 : {
502
+ ...desired,
503
+ region: desired.region
504
+ };
505
+ if (previous === "malformed") return {
506
+ stop: true,
507
+ start
508
+ };
509
+ if (previous.region === void 0) return {
510
+ stop: false,
511
+ start
512
+ };
513
+ if (desired.region === void 0) return {
514
+ stop: true,
515
+ start: void 0
516
+ };
517
+ return desired.retention === void 0 && backupRetentionPeriodOf(properties) !== void 0 && backupRetentionPeriodOf(properties) !== backupRetentionPeriodOf(previousProperties) || desired.region !== previous.region || desired.kmsKeyId !== previous.kmsKeyId || desired.retention !== previous.retention ? {
518
+ stop: true,
519
+ start
520
+ } : none;
521
+ }
522
+ function liveBackupReplicationRegions(instance) {
523
+ const regions = [];
524
+ for (const replication of instance.DBInstanceAutomatedBackupsReplications ?? []) {
525
+ const region = replication.DBInstanceAutomatedBackupsArn?.split(":")[3];
526
+ if (region !== void 0 && region !== "" && !regions.includes(region)) regions.push(region);
527
+ }
528
+ return regions;
529
+ }
453
530
 
454
531
  // src/provisioning/providers/rds/cluster-members.ts
455
532
  const CLUSTER_REMOVED_PORT = /* @__PURE__ */ new Map([
@@ -676,6 +753,87 @@ function clusterPortToSend(properties, previousProperties) {
676
753
  return reset === Number(previousProperties["Port"]) ? void 0 : reset;
677
754
  }
678
755
 
756
+ // src/provisioning/providers/rds/express-writer.ts
757
+ const EXPRESS_WRITER_RESOURCE_ID_KEY = "cdkd:ExpressWriterResourceId";
758
+ var ExpressWriterRefusal = class extends Error {
759
+ constructor(message) {
760
+ super(message);
761
+ this.name = "ExpressWriterRefusal";
762
+ }
763
+ };
764
+ function sameDbIdentifier(a, b) {
765
+ return a !== void 0 && a.toLowerCase() === b.toLowerCase();
766
+ }
767
+ function expressWriterIdentifier(dbClusterIdentifier) {
768
+ return `${dbClusterIdentifier}-instance-1`;
769
+ }
770
+ function expressConfigurationFlag(value) {
771
+ return httpEndpointFlag(value);
772
+ }
773
+ function recordedExpressWriterId(attributes) {
774
+ const value = attributes?.[EXPRESS_WRITER_RESOURCE_ID_KEY];
775
+ return typeof value === "string" && value !== "" ? value : void 0;
776
+ }
777
+ async function readExpressWriterId(dbClusterIdentifier, mask) {
778
+ try {
779
+ const writer = await this.describeDBInstance(expressWriterIdentifier(dbClusterIdentifier));
780
+ return sameDbIdentifier(writer?.DBClusterIdentifier, dbClusterIdentifier) ? writer?.DbiResourceId : void 0;
781
+ } catch (error) {
782
+ this.logger.debug(mask(safeMsg`Could not read the express writer of DBCluster ${dbClusterIdentifier}: ${error instanceof Error ? error.name : "unknown error"}`));
783
+ return;
784
+ }
785
+ }
786
+ async function isOwnExpressWriter(dbClusterIdentifier) {
787
+ try {
788
+ return sameDbIdentifier((await this.describeDBInstance(expressWriterIdentifier(dbClusterIdentifier)))?.DBClusterIdentifier, dbClusterIdentifier);
789
+ } catch {
790
+ return false;
791
+ }
792
+ }
793
+ async function deleteExpressWriter(logicalId, physicalId, cluster, recordedWriterId, protectionFlippedOff, mask) {
794
+ if (cluster === void 0) return false;
795
+ if (cluster.DeletionProtection === true && !protectionFlippedOff) return false;
796
+ const writerName = expressWriterIdentifier(physicalId);
797
+ const members = cluster.DBClusterMembers ?? [];
798
+ if (!members.some((member) => sameDbIdentifier(member.DBInstanceIdentifier, writerName))) return false;
799
+ const refuse = (detail) => {
800
+ throw new ExpressWriterRefusal(detail);
801
+ };
802
+ const others = [];
803
+ for (const member of members) {
804
+ const name = member.DBInstanceIdentifier;
805
+ if (name === void 0 || sameDbIdentifier(name, writerName)) continue;
806
+ const instance = await this.describeDBInstance(name).catch((error) => {
807
+ if (this.isNotFoundError(error, "DBInstanceNotFoundFault")) return void 0;
808
+ throw error;
809
+ });
810
+ if (instance !== void 0 && instance.DBInstanceStatus !== "deleting") others.push(name);
811
+ }
812
+ if (others.length > 0) refuse(safeMsg`it still has DB instance(s) ${others.join(", ")} besides the writer express configuration created; delete them first, then re-run`);
813
+ if (recordedWriterId !== void 0) {
814
+ const writer = await this.describeDBInstance(writerName).catch((error) => {
815
+ if (this.isNotFoundError(error, "DBInstanceNotFoundFault")) return void 0;
816
+ throw error;
817
+ });
818
+ if (writer === void 0) return false;
819
+ if (writer.DbiResourceId !== recordedWriterId) refuse(safeMsg`DB instance ${writerName} is not the writer express configuration created for it, so cdkd did not delete it; delete it yourself, then re-run`);
820
+ }
821
+ try {
822
+ await this.getClient().send(new DeleteDBInstanceCommand({
823
+ DBInstanceIdentifier: writerName,
824
+ SkipFinalSnapshot: true
825
+ }));
826
+ } catch (error) {
827
+ if (this.isNotFoundError(error, "DBInstanceNotFoundFault")) return false;
828
+ if (error instanceof Error && error.name === "InvalidDBInstanceStateFault") {
829
+ if ((await this.describeDBInstance(writerName).catch(() => void 0))?.DBInstanceStatus === "deleting") return true;
830
+ }
831
+ throw error;
832
+ }
833
+ this.logger.debug(mask(safeMsg`Deleted the express writer ${writerName} of DBCluster ${logicalId}`));
834
+ return true;
835
+ }
836
+
679
837
  // src/provisioning/providers/rds/cluster-create.ts
680
838
  async function createDBCluster(logicalId, resourceType, properties, mask, replaying = false) {
681
839
  this.logger.debug(`Creating DBCluster ${logicalId}`);
@@ -698,6 +856,9 @@ async function createDBCluster(logicalId, resourceType, properties, mask, replay
698
856
  const availabilityZones = rawAvailabilityZones != null && !availabilityZonesSkipped ? rawAvailabilityZones : void 0;
699
857
  const globalClusterSkipped = !readableGlobalClusterId(properties["GlobalClusterIdentifier"]);
700
858
  const globalClusterId = globalClusterSkipped ? void 0 : recordedGlobalClusterIdentifier(properties);
859
+ const expressFlag = expressConfigurationFlag(properties["WithExpressConfiguration"]);
860
+ const expressSkipped = expressFlag === "malformed";
861
+ const express = expressFlag === true;
701
862
  const classSkipped = malformedInstanceClass(properties["DBClusterInstanceClass"]);
702
863
  const allocatedSkipped = clusterSizeValue(properties["AllocatedStorage"]) === "malformed";
703
864
  const iopsSkipped = clusterSizeValue(properties["Iops"]) === "malformed";
@@ -721,6 +882,12 @@ async function createDBCluster(logicalId, resourceType, properties, mask, replay
721
882
  "a string",
722
883
  "no global cluster"
723
884
  ],
885
+ [
886
+ expressSkipped,
887
+ "WithExpressConfiguration",
888
+ "true or false",
889
+ "no express configuration"
890
+ ],
724
891
  [
725
892
  classSkipped,
726
893
  "DBClusterInstanceClass",
@@ -765,6 +932,7 @@ async function createDBCluster(logicalId, resourceType, properties, mask, replay
765
932
  ...forwardingSkipped ? ["EnableLocalWriteForwarding"] : [],
766
933
  ...availabilityZonesSkipped ? ["AvailabilityZones"] : [],
767
934
  ...globalClusterSkipped ? ["GlobalClusterIdentifier"] : [],
935
+ ...expressSkipped ? ["WithExpressConfiguration"] : [],
768
936
  ...classSkipped ? ["DBClusterInstanceClass"] : [],
769
937
  ...allocatedSkipped ? ["AllocatedStorage"] : [],
770
938
  ...iopsSkipped ? ["Iops"] : [],
@@ -772,7 +940,7 @@ async function createDBCluster(logicalId, resourceType, properties, mask, replay
772
940
  ];
773
941
  const effectiveProperties = skippedKeys.length > 0 ? Object.fromEntries(Object.entries(properties).filter(([key]) => !skippedKeys.includes(key))) : void 0;
774
942
  const logExports = desiredLogExports(properties, resourceType, logicalId);
775
- const dbClusterIdentifier = properties["DBClusterIdentifier"] || generatedNameFor("AWS::RDS::DBCluster", logicalId);
943
+ const dbClusterIdentifier = properties["DBClusterIdentifier"] || generatedNameFor("AWS::RDS::DBCluster", logicalId, { properties });
776
944
  let clusterLeftBehind = false;
777
945
  let createdResourceId;
778
946
  try {
@@ -808,6 +976,7 @@ async function createDBCluster(logicalId, resourceType, properties, mask, replay
808
976
  ...properties["EngineMode"] != null && { EngineMode: properties["EngineMode"] },
809
977
  ...availabilityZones !== void 0 && availabilityZones.length > 0 && { AvailabilityZones: availabilityZones },
810
978
  ...globalClusterId !== void 0 && { GlobalClusterIdentifier: globalClusterId },
979
+ ...expressFlag !== void 0 && !expressSkipped && { WithExpressConfiguration: express },
811
980
  ...tags.length > 0 && { Tags: tags }
812
981
  }));
813
982
  clusterLeftBehind = true;
@@ -820,6 +989,7 @@ async function createDBCluster(logicalId, resourceType, properties, mask, replay
820
989
  if (process.env["CDKD_NO_WAIT"] !== "true") {
821
990
  await this.waitForClusterAvailable(logicalId, dbClusterIdentifier);
822
991
  if (localWriteForwardingFlag(properties["EnableLocalWriteForwarding"]) === true) await this.waitForClusterState(logicalId, dbClusterIdentifier, (cluster) => localWriteForwardingApplied(cluster, true), "local write forwarding setting");
992
+ if (express) await this.waitForInstanceAvailable(logicalId, expressWriterIdentifier(dbClusterIdentifier));
823
993
  }
824
994
  if (roles !== "skipped") try {
825
995
  await this.applyAssociatedRoles("cluster", logicalId, dbClusterIdentifier, roles, [], mask, void 0);
@@ -828,6 +998,7 @@ async function createDBCluster(logicalId, resourceType, properties, mask, replay
828
998
  throw roleError;
829
999
  }
830
1000
  const described = await this.describeDBCluster(dbClusterIdentifier);
1001
+ const expressWriterId = express ? await readExpressWriterId.call(this, dbClusterIdentifier, maskerOrIdentity(mask)) : void 0;
831
1002
  return {
832
1003
  physicalId: dbClusterIdentifier,
833
1004
  attributes: definedAttributes({
@@ -835,11 +1006,13 @@ async function createDBCluster(logicalId, resourceType, properties, mask, replay
835
1006
  "Endpoint.Port": stringifyIfAssigned(described?.Port),
836
1007
  "ReadEndpoint.Address": described?.ReaderEndpoint,
837
1008
  Arn: described?.DBClusterArn,
838
- DBClusterResourceId: described?.DbClusterResourceId
1009
+ DBClusterResourceId: described?.DbClusterResourceId,
1010
+ [EXPRESS_WRITER_RESOURCE_ID_KEY]: expressWriterId
839
1011
  }),
840
1012
  ...effectiveProperties !== void 0 && { effectiveProperties }
841
1013
  };
842
1014
  } catch (innerError) {
1015
+ let ownWriter = false;
843
1016
  try {
844
1017
  if (wantsDeletionProtection) try {
845
1018
  await this.getClient().send(new ModifyDBClusterCommand({
@@ -850,6 +1023,15 @@ async function createDBCluster(logicalId, resourceType, properties, mask, replay
850
1023
  } catch (disableError) {
851
1024
  this.logger.debug(maskerOrIdentity(mask)(`Could not disable DeletionProtection on partially-created DBCluster ${dbClusterIdentifier}: ${describeAwsFailure(disableError).detail} (proceeding with DeleteDBCluster anyway)`));
852
1025
  }
1026
+ ownWriter = express && await isOwnExpressWriter.call(this, dbClusterIdentifier);
1027
+ if (ownWriter) try {
1028
+ await this.getClient().send(new DeleteDBInstanceCommand({
1029
+ DBInstanceIdentifier: expressWriterIdentifier(dbClusterIdentifier),
1030
+ SkipFinalSnapshot: true
1031
+ }));
1032
+ } catch (writerError) {
1033
+ if (!this.isNotFoundError(writerError, "DBInstanceNotFoundFault")) throw writerError;
1034
+ }
853
1035
  await this.getClient().send(new DeleteDBClusterCommand({
854
1036
  DBClusterIdentifier: dbClusterIdentifier,
855
1037
  SkipFinalSnapshot: true
@@ -866,11 +1048,12 @@ async function createDBCluster(logicalId, resourceType, properties, mask, replay
866
1048
  }
867
1049
  const aws = pasteableAwsCommand();
868
1050
  const unprotect = wantsDeletionProtection ? aws`aws rds modify-db-cluster --db-cluster-identifier ${dbClusterIdentifier} --no-deletion-protection --apply-immediately; ` : aws``;
1051
+ const writer = ownWriter ? aws`aws rds delete-db-instance --db-instance-identifier ${expressWriterIdentifier(dbClusterIdentifier)} --skip-final-snapshot; ` : aws``;
869
1052
  const m = maskerOrIdentity(mask);
870
1053
  const cleanupFailure = describeAwsFailure(cleanupError);
871
1054
  const cleanupHead = `Failed to delete partially-created DBCluster ${logicalId} (${dbClusterIdentifier}): `;
872
1055
  if (cleanupFailure.redacted) this.logger.debug(m(`${cleanupHead}${m(cleanupFailure.detail)}`));
873
- this.logger.warn(`${cleanupHead}${cleanupFailure.redacted ? `${m(cleanupFailure.summary)} ` : `${m(cleanupFailure.detail)}. `}THE CLUSTER IS STILL RUNNING AND BILLING. Outside a rollback's re-create, the failed deploy's rollback journal records it for \`cdkd rollback --revert-failed\`${wantsDeletionProtection ? ", which cannot delete it while its DeletionProtection is on" : ""}; otherwise delete it yourself: ${aws`${unprotect}aws rds delete-db-cluster --db-cluster-identifier ${dbClusterIdentifier} --skip-final-snapshot`.render()}`);
1056
+ this.logger.warn(`${cleanupHead}${cleanupFailure.redacted ? `${m(cleanupFailure.summary)} ` : `${m(cleanupFailure.detail)}. `}THE CLUSTER IS STILL RUNNING AND BILLING. Outside a rollback's re-create, the failed deploy's rollback journal records it for \`cdkd rollback --revert-failed\`${wantsDeletionProtection ? ", which cannot delete it while its DeletionProtection is on" : ""}; otherwise delete it yourself: ${aws`${unprotect}${writer}aws rds delete-db-cluster --db-cluster-identifier ${dbClusterIdentifier} --skip-final-snapshot`.render()}`);
874
1057
  }
875
1058
  throw innerError;
876
1059
  }
@@ -1102,7 +1285,8 @@ async function updateDBCluster(logicalId, physicalId, resourceType, properties,
1102
1285
  "Endpoint.Port": stringifyIfAssigned(noWait && portChanged && described !== void 0 ? portToSend : described?.Port),
1103
1286
  "ReadEndpoint.Address": described?.ReaderEndpoint,
1104
1287
  Arn: described?.DBClusterArn,
1105
- DBClusterResourceId: described?.DbClusterResourceId
1288
+ DBClusterResourceId: described?.DbClusterResourceId,
1289
+ [EXPRESS_WRITER_RESOURCE_ID_KEY]: recordedExpressWriterId(context?.recordedAttributes)
1106
1290
  }),
1107
1291
  ...skippedKeys.length > 0 && { effectiveProperties: withPreviousValues(properties, previousProperties, skippedKeys) }
1108
1292
  };
@@ -1263,6 +1447,9 @@ async function deleteDBClusterOnce(logicalId, physicalId, resourceType, properti
1263
1447
  beforeDelete: true,
1264
1448
  removeProtection: context?.removeProtection === true
1265
1449
  }, progress, maskerOrIdentity(context?.maskSecrets)) ? globalClusterId : void 0;
1450
+ if (expressConfigurationFlag(properties?.["WithExpressConfiguration"]) === true) {
1451
+ if (await deleteExpressWriter.call(this, logicalId, physicalId, await this.describeDBCluster(physicalId), recordedExpressWriterId(context?.recordedAttributes), flip.flippedOffByThisRun, maskerOrIdentity(context?.maskSecrets))) progress.stripped = true;
1452
+ }
1266
1453
  const finalSnapshotId = context?.finalSnapshotIdentifier;
1267
1454
  const sendDelete = () => this.getClient().send(new DeleteDBClusterCommand({
1268
1455
  DBClusterIdentifier: physicalId,
@@ -1279,6 +1466,10 @@ async function deleteDBClusterOnce(logicalId, physicalId, resourceType, properti
1279
1466
  this.logger.debug(`Successfully initiated deletion of DBCluster ${logicalId}`);
1280
1467
  await this.waitForClusterDeleted(logicalId, physicalId, RDS_DELETE_WAIT_MS);
1281
1468
  } catch (error) {
1469
+ if (error instanceof ExpressWriterRefusal) {
1470
+ const refusal = markNotGone(markNonRetryable(new ProvisioningError(`Failed to delete DBCluster ${logicalId}: ${maskerOrIdentity(context?.maskSecrets)(error.message)}`, resourceType, logicalId, physicalId, error)));
1471
+ throw progress.stripped ? markDeleteStarted(refusal) : refusal;
1472
+ }
1282
1473
  if (error instanceof GlobalClusterDetachError) {
1283
1474
  const detachFailure = markNotGone(markNonRetryable(new ProvisioningError(`Failed to delete DBCluster ${logicalId}: ${error.message}`, resourceType, logicalId, physicalId, error)));
1284
1475
  throw progress.stripped ? markDeleteStarted(detachFailure) : detachFailure;
@@ -1396,6 +1587,232 @@ async function deleteAfterProtectionFlip(logicalId, physicalId, send) {
1396
1587
  });
1397
1588
  }
1398
1589
 
1590
+ // src/provisioning/providers/rds/calls.ts
1591
+ async function applyTagDiff(arn, resourceType, logicalId, oldTagsRaw, newTagsRaw) {
1592
+ const plan = planTagDiff(oldTagsRaw, newTagsRaw);
1593
+ const tagWarning = tagPlanWarning(plan, resourceType, logicalId);
1594
+ if (tagWarning !== void 0) this.logger.warn(tagWarning);
1595
+ const tagsToAdd = [...plan.set].map(([Key, Value]) => ({
1596
+ Key,
1597
+ Value
1598
+ }));
1599
+ const tagsToRemove = plan.remove;
1600
+ if (tagsToRemove.length > 0) {
1601
+ await this.getClient().send(new RemoveTagsFromResourceCommand({
1602
+ ResourceName: arn,
1603
+ TagKeys: tagsToRemove
1604
+ }));
1605
+ this.logger.debug(`Removed ${tagsToRemove.length} tag(s) from RDS resource ${arn}`);
1606
+ }
1607
+ if (tagsToAdd.length > 0) {
1608
+ await this.getClient().send(new AddTagsToResourceCommand({
1609
+ ResourceName: arn,
1610
+ Tags: tagsToAdd
1611
+ }));
1612
+ this.logger.debug(`Added/updated ${tagsToAdd.length} tag(s) on RDS resource ${arn}`);
1613
+ }
1614
+ }
1615
+ function isNotFoundError(error, faultName) {
1616
+ if (!(error instanceof Error)) return false;
1617
+ const name = error.name ?? "";
1618
+ const message = error.message.toLowerCase();
1619
+ return name === faultName || message.includes("not found") || message.includes("does not exist");
1620
+ }
1621
+ function wrapCaughtError(mask, error, build) {
1622
+ const m = maskerOrIdentity(mask);
1623
+ const failure = describeAwsFailure(error);
1624
+ if (!failure.redacted) return wrapMaskedAwsError(m, error, build);
1625
+ this.logger.debug(m(build(m(failure.detail)).message));
1626
+ const wrapped = build(`${m(failure.summary)}${relayedNameCollision(failure.detail)}`);
1627
+ return error instanceof Error ? markRedactedCause(wrapped) : wrapped;
1628
+ }
1629
+ function wrapDeleteError(mask, error, build) {
1630
+ const thrown = this.wrapCaughtError(mask, error, build);
1631
+ return error instanceof Error && error.name.includes("NotFound") ? markNotGone(thrown) : thrown;
1632
+ }
1633
+ async function engineLifecycleSupportToSend(kind, logicalId, physicalId, resourceType, properties, previousProperties, context) {
1634
+ const action = engineLifecycleSupportAction(properties, previousProperties, context);
1635
+ if (action === "unchanged") return void 0;
1636
+ const desired = engineLifecycleSupportOf(properties);
1637
+ if (action === "send") return desired;
1638
+ const idKey = kind === "DB cluster" ? "DBClusterIdentifier" : "DBInstanceIdentifier";
1639
+ const { mask } = withDerivedNameMasks(this.logger, createMaskedLogSinks(this.logger, context?.maskSecrets), [[previousProperties[idKey], physicalId]]);
1640
+ let liveRead = "read";
1641
+ if (action === "check-live") try {
1642
+ const resource = kind === "DB cluster" ? await this.describeDBCluster(physicalId) : await this.describeDBInstance(physicalId);
1643
+ if (resource === void 0) liveRead = "not-found";
1644
+ else if (resource.EngineLifecycleSupport === desired) liveRead = void 0;
1645
+ } catch (err) {
1646
+ if (err instanceof CdkdError) throw err;
1647
+ const faultName = err?.name;
1648
+ if (faultName === "DBClusterNotFoundFault" || faultName === "DBInstanceNotFoundFault") liveRead = "not-found";
1649
+ else throw this.wrapCaughtError(mask, err, (text) => new ProvisioningError(`${mask(engineLifecycleSupportRefusalText(resourceType, logicalId, physicalId, kind, "unreadable"))} The read failed: ${text}`, resourceType, logicalId, physicalId, err instanceof Error ? err : void 0));
1650
+ }
1651
+ if (liveRead === void 0) return void 0;
1652
+ throw markNonRetryable(new ProvisioningError(mask(engineLifecycleSupportRefusalText(resourceType, logicalId, physicalId, kind, liveRead)), resourceType, logicalId, physicalId));
1653
+ }
1654
+ async function describeDBCluster(dbClusterIdentifier) {
1655
+ return (await this.getClient().send(new DescribeDBClustersCommand({ DBClusterIdentifier: dbClusterIdentifier }))).DBClusters?.[0];
1656
+ }
1657
+ async function securityGroupsToSend(target, logicalId, physicalId, resourceType, properties, previousProperties, context) {
1658
+ const key = target === "DBCluster" ? "VpcSecurityGroupIds" : "VPCSecurityGroups";
1659
+ const noun = target === "DBCluster" ? "cluster" : "instance";
1660
+ const desired = properties[key];
1661
+ if (desired !== void 0) return desired.length > 0 ? desired : void 0;
1662
+ const previous = previousProperties[key];
1663
+ if (context?.desiredFromAwsReadback === true) return void 0;
1664
+ if (!Array.isArray(previous) || previous.length === 0) return void 0;
1665
+ let groupId;
1666
+ let missing;
1667
+ let awsError;
1668
+ try {
1669
+ let subnetGroupName;
1670
+ let vpcId;
1671
+ if (target === "DBInstance") {
1672
+ const subnetGroup = (await this.describeDBInstance(physicalId))?.DBSubnetGroup;
1673
+ subnetGroupName = subnetGroup?.DBSubnetGroupName;
1674
+ vpcId = subnetGroupName ? subnetGroup?.VpcId : void 0;
1675
+ } else {
1676
+ subnetGroupName = (await this.describeDBCluster(physicalId))?.DBSubnetGroup;
1677
+ vpcId = subnetGroupName ? (await this.getClient().send(new DescribeDBSubnetGroupsCommand({ DBSubnetGroupName: subnetGroupName }))).DBSubnetGroups?.[0]?.VpcId : void 0;
1678
+ }
1679
+ if (!subnetGroupName) missing = `the ${noun} reports no DB subnet group`;
1680
+ else if (!vpcId) missing = `DB subnet group ${subnetGroupName} reports no VPC`;
1681
+ else {
1682
+ groupId = (await this.getEc2Client().send(new DescribeSecurityGroupsCommand({ Filters: [{
1683
+ Name: "vpc-id",
1684
+ Values: [vpcId]
1685
+ }, {
1686
+ Name: "group-name",
1687
+ Values: ["default"]
1688
+ }] }))).SecurityGroups?.[0]?.GroupId;
1689
+ if (!groupId) missing = `VPC ${vpcId} has no security group named default`;
1690
+ }
1691
+ } catch (error) {
1692
+ awsError = error;
1693
+ }
1694
+ if (groupId === void 0) {
1695
+ const mask = context?.maskSecrets ?? ((text) => text);
1696
+ const failure = missing === void 0 ? describeAwsFailure(awsError) : void 0;
1697
+ if (failure?.redacted === true) this.logger.debug(safeMsg`${logicalId}: the VPC default security group lookup failed: ${mask(failure.detail)}`);
1698
+ const shown = mask(failure?.summary ?? "");
1699
+ const refusal = new ProvisioningError(`Failed to update ${target} ${logicalId}: ${key} was removed from the template, so the ${noun} moves to its VPC's default security group (as CloudFormation does), but cdkd could not find that group: ${missing ?? shown}. Declare ${key} in the template to choose the ${noun}'s security groups.`, resourceType, logicalId, physicalId, awsError instanceof Error ? awsError : void 0);
1700
+ if (missing !== void 0) throw markNonRetryable(refusal);
1701
+ throw awsError instanceof Error && (failure?.redacted === true || shown !== (failure?.summary ?? "")) ? markRedactedCause(refusal) : refusal;
1702
+ }
1703
+ this.logger.warn(safeMsg`${logicalId}: ${key} was removed from the template; attaching the VPC's default security group ${groupId}, as CloudFormation does.`);
1704
+ return [groupId];
1705
+ }
1706
+ async function describeDBInstance(dbInstanceIdentifier) {
1707
+ return (await this.getClient().send(new DescribeDBInstancesCommand({ DBInstanceIdentifier: dbInstanceIdentifier }))).DBInstances?.[0];
1708
+ }
1709
+ async function sendHttpEndpointChange(logicalId, physicalId, arn, enable) {
1710
+ let delay = 5e3;
1711
+ for (let attempt = 1;; attempt += 1) {
1712
+ await this.waitForClusterState(logicalId, physicalId, (cluster) => cluster.Status === "available", "pending changes to settle before the Data API call");
1713
+ try {
1714
+ await this.getClient().send(enable ? new EnableHttpEndpointCommand({ ResourceArn: arn }) : new DisableHttpEndpointCommand({ ResourceArn: arn }));
1715
+ return;
1716
+ } catch (error) {
1717
+ const name = awsErrorName(error);
1718
+ if (!HTTP_ENDPOINT_BUSY_FAULTS.has(name) || attempt >= 8) throw error;
1719
+ this.logger.debug(safeMsg`DBCluster ${logicalId}: the Data API call was refused as busy (${name}); retrying`);
1720
+ await this.sleep(delay);
1721
+ delay = Math.min(delay * 2, 1e4);
1722
+ }
1723
+ }
1724
+ }
1725
+ async function attachTags(result, arn) {
1726
+ try {
1727
+ const tagsResp = await this.getClient().send(new ListTagsForResourceCommand({ ResourceName: arn }));
1728
+ result["Tags"] = normalizeAwsTagsToCfn(tagsResp.TagList);
1729
+ } catch (err) {
1730
+ this.logger.debug(`RDS ListTagsForResource(${arn}) failed: ${describeAwsFailure(err).detail}`);
1731
+ }
1732
+ }
1733
+ async function sendInRegion(region, call) {
1734
+ const client = new RDSClient({
1735
+ ...ambientClientDefaults(),
1736
+ region
1737
+ });
1738
+ try {
1739
+ return await call(client);
1740
+ } finally {
1741
+ client.destroy();
1742
+ }
1743
+ }
1744
+ const REPLICATION_KMS_KEY_ERROR = "Encrypted instances require a valid KMS key ID";
1745
+ const REPLICATION_BUSY_FAULTS = /* @__PURE__ */ new Set([
1746
+ "InvalidDBInstanceStateFault",
1747
+ "InvalidDBInstanceState",
1748
+ "InvalidDBInstanceAutomatedBackupStateFault",
1749
+ "InvalidDBInstanceAutomatedBackupState"
1750
+ ]);
1751
+ const REPLICATION_MAX_ATTEMPTS = 10;
1752
+ async function sendReplicationCall(logicalId, physicalId, region, call) {
1753
+ for (let attempt = 1;; attempt++) try {
1754
+ return await sendInRegion(region, call);
1755
+ } catch (error) {
1756
+ if (!REPLICATION_BUSY_FAULTS.has(awsErrorName(error)) || attempt >= REPLICATION_MAX_ATTEMPTS) throw error;
1757
+ this.logger.debug(safeMsg`${logicalId}: automated backup replication call refused as busy (${awsErrorName(error)}); waiting to resend`);
1758
+ await this.sleep(15e3);
1759
+ const budgetMs = Math.min(18e5, enclosingDeadlineRemainingMs() - 3e4);
1760
+ if (budgetMs <= 0) throw error;
1761
+ await this.waitForInstanceAvailable(logicalId, physicalId, budgetMs, "changing its automated backup replication");
1762
+ }
1763
+ }
1764
+ async function applyBackupReplication(logicalId, physicalId, plan, fromReadback = false) {
1765
+ if (!plan.stop && plan.start === void 0) return;
1766
+ const waitBudgetMs = Math.min(18e5, enclosingDeadlineRemainingMs() - 3e4);
1767
+ if (waitBudgetMs <= 0) throw new Error("the resource timeout leaves no more time to change the automated backup replication of the instance; re-run the deploy, or with a longer --resource-timeout");
1768
+ if (fromReadback && plan.start !== void 0 && plan.start.kmsKeyId === void 0) {
1769
+ if ((await this.describeDBInstance(physicalId))?.StorageEncrypted === true) throw markNonRetryable(/* @__PURE__ */ new Error(`cdkd drift --revert cannot restart the automated backup replication of storage-encrypted DB instance ${logicalId}: RDS needs a KMS key in ${plan.start.region} for it, and AutomaticBackupReplicationKmsKeyId is write-only, so the revert has none to send. Nothing was stopped or started. Restore it with aws rds start-db-instance-automated-backups-replication --region ${plan.start.region} --source-db-instance-arn <the instance ARN> --kms-key-id <a key in that region>, or change the template's replication properties and run cdkd deploy`));
1770
+ }
1771
+ await this.waitForInstanceAvailable(logicalId, physicalId, waitBudgetMs, "changing its automated backup replication");
1772
+ const instance = await this.describeDBInstance(physicalId);
1773
+ const arn = instance?.DBInstanceArn;
1774
+ if (instance === void 0 || arn === void 0) throw new Error("DescribeDBInstances returned no instance ARN while changing its automated backup replication; nothing was started or stopped");
1775
+ const wait = process.env["CDKD_NO_WAIT"] !== "true";
1776
+ const live = liveBackupReplicationRegions(instance);
1777
+ for (const region of live) {
1778
+ this.logger.debug(safeMsg`Stopping automated backup replication of ${logicalId} to ${region}`);
1779
+ await sendReplicationCall.call(this, logicalId, physicalId, region, (client) => client.send(new StopDBInstanceAutomatedBackupsReplicationCommand({ SourceDBInstanceArn: arn })));
1780
+ }
1781
+ if (live.length > 0 && (wait || plan.start !== void 0)) await this.waitForInstanceState(logicalId, physicalId, (current) => current.DBInstanceStatus === "available" && liveBackupReplicationRegions(current).length === 0, "automated backup replication stop");
1782
+ const start = plan.start;
1783
+ if (start === void 0) return;
1784
+ this.logger.debug(safeMsg`Starting automated backup replication of ${logicalId} to ${start.region}`);
1785
+ try {
1786
+ await sendReplicationCall.call(this, logicalId, physicalId, start.region, (client) => client.send(new StartDBInstanceAutomatedBackupsReplicationCommand({
1787
+ SourceDBInstanceArn: arn,
1788
+ ...start.retention !== void 0 && { BackupRetentionPeriod: start.retention },
1789
+ ...start.kmsKeyId !== void 0 && { KmsKeyId: start.kmsKeyId }
1790
+ })));
1791
+ } catch (error) {
1792
+ if (error instanceof Error && error.message.includes(REPLICATION_KMS_KEY_ERROR)) error.message = `${error.message} Provide a valid value for the AutomaticBackupReplicationKmsKeyId property.`;
1793
+ throw error;
1794
+ }
1795
+ if (wait) await this.waitForInstanceState(logicalId, physicalId, (current) => current.DBInstanceStatus === "available" && liveBackupReplicationRegions(current).includes(start.region), "automated backup replication start");
1796
+ }
1797
+ const RETENTION_READ_SOFT_FAULTS = /* @__PURE__ */ new Set([
1798
+ "DBInstanceAutomatedBackupNotFoundFault",
1799
+ "DBInstanceAutomatedBackupNotFound",
1800
+ "AccessDenied",
1801
+ "AccessDeniedException"
1802
+ ]);
1803
+ async function replicatedBackupRetention(automatedBackupsArn) {
1804
+ const region = automatedBackupsArn.split(":")[3];
1805
+ if (region === void 0 || region === "") return void 0;
1806
+ try {
1807
+ return (await sendInRegion(region, (client) => client.send(new DescribeDBInstanceAutomatedBackupsCommand({ DBInstanceAutomatedBackupsArn: automatedBackupsArn })))).DBInstanceAutomatedBackups?.[0]?.BackupRetentionPeriod;
1808
+ } catch (error) {
1809
+ const name = awsErrorName(error);
1810
+ if (!RETENTION_READ_SOFT_FAULTS.has(name)) throw error;
1811
+ if (name.startsWith("AccessDenied")) this.logger.warn(safeMsg`Could not read the replicated automated backup's retention in ${region} (${name}): AutomaticBackupReplicationRetentionPeriod reads as unset`);
1812
+ return;
1813
+ }
1814
+ }
1815
+
1399
1816
  // src/provisioning/providers/rds/instance-create.ts
1400
1817
  async function createDBInstance(logicalId, resourceType, properties, mask, replaying = false) {
1401
1818
  this.logger.debug(`Creating DBInstance ${logicalId}`);
@@ -1403,6 +1820,7 @@ async function createDBInstance(logicalId, resourceType, properties, mask, repla
1403
1820
  const roles = this.desiredAssociatedRoles(properties, resourceType, logicalId, void 0, replaying);
1404
1821
  const logExports = desiredLogExports(properties, resourceType, logicalId);
1405
1822
  const processor = desiredProcessorFeatures(properties, resourceType, logicalId);
1823
+ const replication = backupReplicationPlan(properties, {}, resourceType, logicalId, void 0, replaying, (message) => this.logger.warn(message));
1406
1824
  refuseMalformedReplicaSource(properties, resourceType, logicalId);
1407
1825
  refuseUnknownSourceRegion(properties, resourceType, logicalId, replaying, (message) => this.logger.warn(message));
1408
1826
  const replicaSource = replicaSourceOf(properties);
@@ -1485,11 +1903,12 @@ async function createDBInstance(logicalId, resourceType, properties, mask, repla
1485
1903
  const modifyAfterCreate = replicaSource !== void 0 && replicaNeedsModifyAfterCreate(properties, replicaEngineName, instance.Engine);
1486
1904
  if (process.env["CDKD_NO_WAIT"] !== "true" || modifyAfterCreate) await this.waitForInstanceAvailable(logicalId, dbInstanceIdentifier);
1487
1905
  if (modifyAfterCreate) await modifyReplicaAfterCreate.call(this, logicalId, dbInstanceIdentifier, properties, replicaEngineName);
1488
- if (roles !== "skipped") try {
1489
- await this.applyAssociatedRoles("instance", logicalId, dbInstanceIdentifier, roles, [], mask, void 0);
1490
- } catch (roleError) {
1491
- markAuxiliaryFailure(roleError, logicalId);
1492
- throw roleError;
1906
+ try {
1907
+ if (roles !== "skipped") await this.applyAssociatedRoles("instance", logicalId, dbInstanceIdentifier, roles, [], mask, void 0);
1908
+ await applyBackupReplication.call(this, logicalId, dbInstanceIdentifier, replication);
1909
+ } catch (auxiliaryError) {
1910
+ markAuxiliaryFailure(auxiliaryError, logicalId);
1911
+ throw auxiliaryError;
1493
1912
  }
1494
1913
  const described = await this.describeDBInstance(dbInstanceIdentifier);
1495
1914
  return {
@@ -1546,6 +1965,7 @@ async function updateDBInstance(logicalId, physicalId, resourceType, properties,
1546
1965
  const roles = this.desiredAssociatedRoles(properties, resourceType, logicalId, physicalId, false);
1547
1966
  const logExportConfig = logExportsDelta(desiredLogExports(properties, resourceType, logicalId, physicalId), previousProperties["EnableCloudwatchLogsExports"]);
1548
1967
  const processorMembers = instanceProcessorFeatureMembers(properties, previousProperties, resourceType, logicalId, physicalId);
1968
+ const replication = backupReplicationPlan(properties, previousProperties, resourceType, logicalId, physicalId, context?.replayingState === true || context?.desiredFromAwsReadback === true, (message) => this.logger.warn(message));
1549
1969
  const vpcSgIds = await this.securityGroupsToSend("DBInstance", logicalId, physicalId, resourceType, properties, previousProperties, context);
1550
1970
  const engineLifecycleSupport = await this.engineLifecycleSupportToSend("DB instance", logicalId, physicalId, resourceType, properties, previousProperties, context);
1551
1971
  let authenticationType = masterUserAuthenticationTypeToSend(properties, previousProperties, context);
@@ -1675,6 +2095,7 @@ async function updateDBInstance(logicalId, physicalId, resourceType, properties,
1675
2095
  const sentGroup = backfillMembers.DBParameterGroupName;
1676
2096
  if (sentGroup !== void 0 || instanceParameterGroupPendingReboot(described) || instanceParameterGroupApplying(described)) described = await this.rebootForPendingParameterGroup(logicalId, physicalId, sentGroup, String(properties["CertificateRotationRestart"]) === "true");
1677
2097
  await this.applyAssociatedRoles("instance", logicalId, physicalId, roles, associatedRoleList(previousProperties["AssociatedRoles"], { featureNameRequired: true }) ?? [], context?.maskSecrets, context);
2098
+ await applyBackupReplication.call(this, logicalId, physicalId, replication, context?.desiredFromAwsReadback === true);
1678
2099
  if (described?.DBInstanceArn) await this.applyTagDiff(described.DBInstanceArn, resourceType, logicalId, previousProperties["Tags"], properties["Tags"]);
1679
2100
  return {
1680
2101
  physicalId,
@@ -1821,150 +2242,6 @@ async function deleteInstanceAfterProtectionFlip(logicalId, physicalId, send) {
1821
2242
  });
1822
2243
  }
1823
2244
 
1824
- // src/provisioning/providers/rds/calls.ts
1825
- async function applyTagDiff(arn, resourceType, logicalId, oldTagsRaw, newTagsRaw) {
1826
- const plan = planTagDiff(oldTagsRaw, newTagsRaw);
1827
- const tagWarning = tagPlanWarning(plan, resourceType, logicalId);
1828
- if (tagWarning !== void 0) this.logger.warn(tagWarning);
1829
- const tagsToAdd = [...plan.set].map(([Key, Value]) => ({
1830
- Key,
1831
- Value
1832
- }));
1833
- const tagsToRemove = plan.remove;
1834
- if (tagsToRemove.length > 0) {
1835
- await this.getClient().send(new RemoveTagsFromResourceCommand({
1836
- ResourceName: arn,
1837
- TagKeys: tagsToRemove
1838
- }));
1839
- this.logger.debug(`Removed ${tagsToRemove.length} tag(s) from RDS resource ${arn}`);
1840
- }
1841
- if (tagsToAdd.length > 0) {
1842
- await this.getClient().send(new AddTagsToResourceCommand({
1843
- ResourceName: arn,
1844
- Tags: tagsToAdd
1845
- }));
1846
- this.logger.debug(`Added/updated ${tagsToAdd.length} tag(s) on RDS resource ${arn}`);
1847
- }
1848
- }
1849
- function isNotFoundError(error, faultName) {
1850
- if (!(error instanceof Error)) return false;
1851
- const name = error.name ?? "";
1852
- const message = error.message.toLowerCase();
1853
- return name === faultName || message.includes("not found") || message.includes("does not exist");
1854
- }
1855
- function wrapCaughtError(mask, error, build) {
1856
- const m = maskerOrIdentity(mask);
1857
- const failure = describeAwsFailure(error);
1858
- if (!failure.redacted) return wrapMaskedAwsError(m, error, build);
1859
- this.logger.debug(m(build(m(failure.detail)).message));
1860
- const wrapped = build(`${m(failure.summary)}${relayedNameCollision(failure.detail)}`);
1861
- return error instanceof Error ? markRedactedCause(wrapped) : wrapped;
1862
- }
1863
- function wrapDeleteError(mask, error, build) {
1864
- const thrown = this.wrapCaughtError(mask, error, build);
1865
- return error instanceof Error && error.name.includes("NotFound") ? markNotGone(thrown) : thrown;
1866
- }
1867
- async function engineLifecycleSupportToSend(kind, logicalId, physicalId, resourceType, properties, previousProperties, context) {
1868
- const action = engineLifecycleSupportAction(properties, previousProperties, context);
1869
- if (action === "unchanged") return void 0;
1870
- const desired = engineLifecycleSupportOf(properties);
1871
- if (action === "send") return desired;
1872
- const idKey = kind === "DB cluster" ? "DBClusterIdentifier" : "DBInstanceIdentifier";
1873
- const { mask } = withDerivedNameMasks(this.logger, createMaskedLogSinks(this.logger, context?.maskSecrets), [[previousProperties[idKey], physicalId]]);
1874
- let liveRead = "read";
1875
- if (action === "check-live") try {
1876
- const resource = kind === "DB cluster" ? await this.describeDBCluster(physicalId) : await this.describeDBInstance(physicalId);
1877
- if (resource === void 0) liveRead = "not-found";
1878
- else if (resource.EngineLifecycleSupport === desired) liveRead = void 0;
1879
- } catch (err) {
1880
- if (err instanceof CdkdError) throw err;
1881
- const faultName = err?.name;
1882
- if (faultName === "DBClusterNotFoundFault" || faultName === "DBInstanceNotFoundFault") liveRead = "not-found";
1883
- else throw this.wrapCaughtError(mask, err, (text) => new ProvisioningError(`${mask(engineLifecycleSupportRefusalText(resourceType, logicalId, physicalId, kind, "unreadable"))} The read failed: ${text}`, resourceType, logicalId, physicalId, err instanceof Error ? err : void 0));
1884
- }
1885
- if (liveRead === void 0) return void 0;
1886
- throw markNonRetryable(new ProvisioningError(mask(engineLifecycleSupportRefusalText(resourceType, logicalId, physicalId, kind, liveRead)), resourceType, logicalId, physicalId));
1887
- }
1888
- async function describeDBCluster(dbClusterIdentifier) {
1889
- return (await this.getClient().send(new DescribeDBClustersCommand({ DBClusterIdentifier: dbClusterIdentifier }))).DBClusters?.[0];
1890
- }
1891
- async function securityGroupsToSend(target, logicalId, physicalId, resourceType, properties, previousProperties, context) {
1892
- const key = target === "DBCluster" ? "VpcSecurityGroupIds" : "VPCSecurityGroups";
1893
- const noun = target === "DBCluster" ? "cluster" : "instance";
1894
- const desired = properties[key];
1895
- if (desired !== void 0) return desired.length > 0 ? desired : void 0;
1896
- const previous = previousProperties[key];
1897
- if (context?.desiredFromAwsReadback === true) return void 0;
1898
- if (!Array.isArray(previous) || previous.length === 0) return void 0;
1899
- let groupId;
1900
- let missing;
1901
- let awsError;
1902
- try {
1903
- let subnetGroupName;
1904
- let vpcId;
1905
- if (target === "DBInstance") {
1906
- const subnetGroup = (await this.describeDBInstance(physicalId))?.DBSubnetGroup;
1907
- subnetGroupName = subnetGroup?.DBSubnetGroupName;
1908
- vpcId = subnetGroupName ? subnetGroup?.VpcId : void 0;
1909
- } else {
1910
- subnetGroupName = (await this.describeDBCluster(physicalId))?.DBSubnetGroup;
1911
- vpcId = subnetGroupName ? (await this.getClient().send(new DescribeDBSubnetGroupsCommand({ DBSubnetGroupName: subnetGroupName }))).DBSubnetGroups?.[0]?.VpcId : void 0;
1912
- }
1913
- if (!subnetGroupName) missing = `the ${noun} reports no DB subnet group`;
1914
- else if (!vpcId) missing = `DB subnet group ${subnetGroupName} reports no VPC`;
1915
- else {
1916
- groupId = (await this.getEc2Client().send(new DescribeSecurityGroupsCommand({ Filters: [{
1917
- Name: "vpc-id",
1918
- Values: [vpcId]
1919
- }, {
1920
- Name: "group-name",
1921
- Values: ["default"]
1922
- }] }))).SecurityGroups?.[0]?.GroupId;
1923
- if (!groupId) missing = `VPC ${vpcId} has no security group named default`;
1924
- }
1925
- } catch (error) {
1926
- awsError = error;
1927
- }
1928
- if (groupId === void 0) {
1929
- const mask = context?.maskSecrets ?? ((text) => text);
1930
- const failure = missing === void 0 ? describeAwsFailure(awsError) : void 0;
1931
- if (failure?.redacted === true) this.logger.debug(safeMsg`${logicalId}: the VPC default security group lookup failed: ${mask(failure.detail)}`);
1932
- const shown = mask(failure?.summary ?? "");
1933
- const refusal = new ProvisioningError(`Failed to update ${target} ${logicalId}: ${key} was removed from the template, so the ${noun} moves to its VPC's default security group (as CloudFormation does), but cdkd could not find that group: ${missing ?? shown}. Declare ${key} in the template to choose the ${noun}'s security groups.`, resourceType, logicalId, physicalId, awsError instanceof Error ? awsError : void 0);
1934
- if (missing !== void 0) throw markNonRetryable(refusal);
1935
- throw awsError instanceof Error && (failure?.redacted === true || shown !== (failure?.summary ?? "")) ? markRedactedCause(refusal) : refusal;
1936
- }
1937
- this.logger.warn(safeMsg`${logicalId}: ${key} was removed from the template; attaching the VPC's default security group ${groupId}, as CloudFormation does.`);
1938
- return [groupId];
1939
- }
1940
- async function describeDBInstance(dbInstanceIdentifier) {
1941
- return (await this.getClient().send(new DescribeDBInstancesCommand({ DBInstanceIdentifier: dbInstanceIdentifier }))).DBInstances?.[0];
1942
- }
1943
- async function sendHttpEndpointChange(logicalId, physicalId, arn, enable) {
1944
- let delay = 5e3;
1945
- for (let attempt = 1;; attempt += 1) {
1946
- await this.waitForClusterState(logicalId, physicalId, (cluster) => cluster.Status === "available", "pending changes to settle before the Data API call");
1947
- try {
1948
- await this.getClient().send(enable ? new EnableHttpEndpointCommand({ ResourceArn: arn }) : new DisableHttpEndpointCommand({ ResourceArn: arn }));
1949
- return;
1950
- } catch (error) {
1951
- const name = awsErrorName(error);
1952
- if (!HTTP_ENDPOINT_BUSY_FAULTS.has(name) || attempt >= 8) throw error;
1953
- this.logger.debug(safeMsg`DBCluster ${logicalId}: the Data API call was refused as busy (${name}); retrying`);
1954
- await this.sleep(delay);
1955
- delay = Math.min(delay * 2, 1e4);
1956
- }
1957
- }
1958
- }
1959
- async function attachTags(result, arn) {
1960
- try {
1961
- const tagsResp = await this.getClient().send(new ListTagsForResourceCommand({ ResourceName: arn }));
1962
- result["Tags"] = normalizeAwsTagsToCfn(tagsResp.TagList);
1963
- } catch (err) {
1964
- this.logger.debug(`RDS ListTagsForResource(${arn}) failed: ${describeAwsFailure(err).detail}`);
1965
- }
1966
- }
1967
-
1968
2245
  // src/provisioning/providers/rds/waits.ts
1969
2246
  async function waitForMemberAfterClusterChange(dbInstanceIdentifier, clusterLogicalId, transitional, change, maxWaitMs = 18e5) {
1970
2247
  const startTime = Date.now();
@@ -2200,10 +2477,16 @@ function getDriftUnknownPaths(resourceType, properties) {
2200
2477
  "AllowMajorVersionUpgrade",
2201
2478
  "CertificateRotationRestart",
2202
2479
  "SourceRegion",
2203
- "UseDefaultProcessorFeatures"
2480
+ "UseDefaultProcessorFeatures",
2481
+ "AutomaticBackupReplicationKmsKeyId"
2204
2482
  ];
2483
+ const retention = properties?.["AutomaticBackupReplicationRetentionPeriod"];
2205
2484
  const declared = properties?.["ProcessorFeatures"];
2206
- return declared == null || Array.isArray(declared) && declared.length === 0 ? [...instanceUnknown, "ProcessorFeatures"] : instanceUnknown;
2485
+ return [
2486
+ ...instanceUnknown,
2487
+ ...declared == null || Array.isArray(declared) && declared.length === 0 ? ["ProcessorFeatures"] : [],
2488
+ ...retention == null || retention === "" ? ["AutomaticBackupReplicationRetentionPeriod"] : []
2489
+ ];
2207
2490
  }
2208
2491
  if (resourceType !== "AWS::RDS::DBCluster") return [];
2209
2492
  const neverRead = [
@@ -2212,7 +2495,8 @@ function getDriftUnknownPaths(resourceType, properties) {
2212
2495
  "ClusterScalabilityType",
2213
2496
  "MasterUserAuthenticationType",
2214
2497
  "GlobalClusterIdentifier",
2215
- "DBInstanceParameterGroupName"
2498
+ "DBInstanceParameterGroupName",
2499
+ "WithExpressConfiguration"
2216
2500
  ];
2217
2501
  if (properties === void 0 || Object.keys(properties).length === 0) return neverRead;
2218
2502
  return (properties?.["ServerlessV2ScalingConfiguration"])?.SecondsUntilAutoPause === void 0 ? [...neverRead, "ServerlessV2ScalingConfiguration.SecondsUntilAutoPause"] : neverRead;
@@ -2412,6 +2696,13 @@ async function readCurrentStateDBInstance(physicalId) {
2412
2696
  Name: feature.Name,
2413
2697
  Value: feature.Value
2414
2698
  }));
2699
+ const replicationArn = inst.DBInstanceAutomatedBackupsReplications?.[0]?.DBInstanceAutomatedBackupsArn;
2700
+ const replicationRegion = replicationArn?.split(":")[3];
2701
+ if (replicationArn !== void 0 && replicationRegion !== void 0 && replicationRegion !== "") {
2702
+ result["AutomaticBackupReplicationRegion"] = replicationRegion;
2703
+ const retention = await replicatedBackupRetention.call(this, replicationArn);
2704
+ if (retention !== void 0) result["AutomaticBackupReplicationRetentionPeriod"] = retention;
2705
+ }
2415
2706
  if (inst.DBName !== void 0) result["DBName"] = inst.DBName;
2416
2707
  if (inst.AvailabilityZone !== void 0 && inst.MultiAZ !== true) result["AvailabilityZone"] = inst.AvailabilityZone;
2417
2708
  if (inst.EngineLifecycleSupport !== void 0 && inst.DBClusterIdentifier === void 0) result["EngineLifecycleSupport"] = inst.EngineLifecycleSupport;
@@ -2590,7 +2881,8 @@ var RDSProvider = class {
2590
2881
  "DBClusterInstanceClass",
2591
2882
  "AllocatedStorage",
2592
2883
  "Iops",
2593
- "DBInstanceParameterGroupName"
2884
+ "DBInstanceParameterGroupName",
2885
+ "WithExpressConfiguration"
2594
2886
  ])],
2595
2887
  ["AWS::RDS::DBInstance", /* @__PURE__ */ new Set([
2596
2888
  "DBInstanceIdentifier",
@@ -2646,14 +2938,16 @@ var RDSProvider = class {
2646
2938
  "SourceDBInstanceIdentifier",
2647
2939
  "SourceRegion",
2648
2940
  "ProcessorFeatures",
2649
- "UseDefaultProcessorFeatures"
2941
+ "UseDefaultProcessorFeatures",
2942
+ "AutomaticBackupReplicationRegion",
2943
+ "AutomaticBackupReplicationKmsKeyId",
2944
+ "AutomaticBackupReplicationRetentionPeriod"
2650
2945
  ])]
2651
2946
  ]);
2652
2947
  unhandledByDesign = /* @__PURE__ */ new Map([["AWS::RDS::DBCluster", /* @__PURE__ */ new Map([
2653
2948
  ["DeleteAutomatedBackups", "delete-time flag, sent on the delete when the record carries it; kept unhandled so a template declaring it keeps its Cloud Control route. Final snapshots are governed by DeletionPolicy: Snapshot, which this flag does not control"],
2654
2949
  ["ScalingConfiguration", "Aurora Serverless v1 only (EngineMode serverless), retired by AWS: no aurora-mysql or aurora-postgresql engine version supports the serverless engine mode (DescribeDBEngineVersions, us-east-1, 2026-11-06). Aurora Serverless v2 uses ServerlessV2ScalingConfiguration"],
2655
- ["DBSystemId", "reserved for future use, per the CloudFormation schema (cloudformation:DescribeType, us-east-1, 2026-11-07); no observable behaviour to wire. Kept unhandled so a template declaring it keeps its Cloud Control route"],
2656
- ["WithExpressConfiguration", "CloudFormation's RDS handler fails to create it (an RDS 500, CREATE_FAILED on 3 stacks, us-east-1, 2026-11-07), Cloud Control calls the same RDS handler, so it is expected to fail the same way (inferred, not measured), and there is no parity oracle for what cdkd should do with the writer instance RDS auto-creates; re-measure tracked in go-to-k/cdkd#5984. Kept unhandled so a template declaring it keeps its Cloud Control route"]
2950
+ ["DBSystemId", "reserved for future use, per the CloudFormation schema (cloudformation:DescribeType, us-east-1, 2026-11-07); no observable behaviour to wire. Kept unhandled so a template declaring it keeps its Cloud Control route"]
2657
2951
  ])], ["AWS::RDS::DBInstance", /* @__PURE__ */ new Map([
2658
2952
  ["DBSecurityGroups", "EC2-Classic-only feature retired by AWS (2022-08-15); new accounts cannot use this — use VPCSecurityGroups instead"],
2659
2953
  ["ApplyImmediately", "cdkd always applies modifications immediately (rds:ModifyDBInstance.ApplyImmediately=true is hardcoded); users wanting maintenance-window deferral should run aws rds modify-db-instance directly"],
@@ -2869,4 +3163,4 @@ var RDSProvider = class {
2869
3163
  };
2870
3164
 
2871
3165
  export { RDSProvider };
2872
- //# sourceMappingURL=rds-provider-DmYhP_4t.js.map
3166
+ //# sourceMappingURL=rds-provider-DzsTP_11.js.map