The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import * as docdb from "@distilled.cloud/aws/docdb"; |
| 2 | import { isResolved } from "alchemy/Diff"; |
| 3 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 4 | import * as Provider from "alchemy/Provider"; |
| 5 | import { Resource } from "alchemy/Resource"; |
| 6 | import { createInternalTags, diffTags } from "alchemy/Tags"; |
| 7 | import { toWireDays } from "alchemy/Util/Duration"; |
| 8 | import * as Data from "effect/Data"; |
| 9 | import type * as Duration from "effect/Duration"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import type * as Redacted from "effect/Redacted"; |
| 12 | import * as Schedule from "effect/Schedule"; |
| 13 | import * as Stream from "effect/Stream"; |
| 14 | import type { Providers } from "../Providers.ts"; |
| 15 | |
| 16 | export class DBClusterNotReady extends Data.TaggedError("DBClusterNotReady")<{ |
| 17 | readonly message: string; |
| 18 | readonly cause?: unknown; |
| 19 | }> {} |
| 20 | |
| 21 | export interface DBClusterProps { |
| 22 | /** |
| 23 | * Cluster identifier. If omitted, Alchemy generates one. |
| 24 | */ |
| 25 | dbClusterIdentifier?: string; |
| 26 | /** |
| 27 | * Database engine. DocumentDB only supports `docdb`. |
| 28 | * Changing it forces replacement. |
| 29 | * @default "docdb" |
| 30 | */ |
| 31 | engine?: string; |
| 32 | /** |
| 33 | * Optional engine version, e.g. `5.0.0`. Changed in place via |
| 34 | * `modifyDBCluster` (may require `allowMajorVersionUpgrade`). |
| 35 | */ |
| 36 | engineVersion?: string; |
| 37 | /** |
| 38 | * Subnet group the cluster is placed into. DocumentDB is VPC-only, so this |
| 39 | * is effectively required. Immutable — forces replacement. |
| 40 | */ |
| 41 | dbSubnetGroupName?: string; |
| 42 | /** |
| 43 | * Cluster parameter group name. In-place modify. |
| 44 | */ |
| 45 | dbClusterParameterGroupName?: string; |
| 46 | /** |
| 47 | * Security groups attached to the cluster. In-place modify. |
| 48 | */ |
| 49 | vpcSecurityGroupIds?: string[]; |
| 50 | /** |
| 51 | * Listener port. |
| 52 | * @default 27017 |
| 53 | */ |
| 54 | port?: number; |
| 55 | /** |
| 56 | * Availability zones for cluster placement. Immutable — forces replacement. |
| 57 | */ |
| 58 | availabilityZones?: string[]; |
| 59 | /** |
| 60 | * Backup retention period, e.g. `"7 days"` or `Duration.days(7)`. |
| 61 | * Rounded to whole days on the wire. In-place modify. |
| 62 | */ |
| 63 | backupRetentionPeriod?: Duration.Input; |
| 64 | /** |
| 65 | * Daily backup window, e.g. `07:00-09:00`. In-place modify. |
| 66 | */ |
| 67 | preferredBackupWindow?: string; |
| 68 | /** |
| 69 | * Weekly maintenance window, e.g. `Mon:00:00-Mon:03:00`. In-place modify. |
| 70 | */ |
| 71 | preferredMaintenanceWindow?: string; |
| 72 | /** |
| 73 | * Log types to export to CloudWatch Logs (`audit`, `profiler`). Diffed |
| 74 | * against observed state and applied via the delta-shaped |
| 75 | * `CloudwatchLogsExportConfiguration` on modify. |
| 76 | */ |
| 77 | enableCloudwatchLogsExports?: string[]; |
| 78 | /** |
| 79 | * Block accidental deletion. In-place modify. |
| 80 | */ |
| 81 | deletionProtection?: boolean; |
| 82 | /** |
| 83 | * Whether the storage is encrypted. Immutable — forces replacement. |
| 84 | */ |
| 85 | storageEncrypted?: boolean; |
| 86 | /** |
| 87 | * Optional KMS key used for storage encryption. Immutable — forces replace. |
| 88 | */ |
| 89 | kmsKeyId?: string; |
| 90 | /** |
| 91 | * Storage type, e.g. `standard` | `iopt1`. In-place modify. |
| 92 | */ |
| 93 | storageType?: string; |
| 94 | /** |
| 95 | * Network type: `IPV4` | `DUAL`. In-place modify. |
| 96 | */ |
| 97 | networkType?: string; |
| 98 | /** |
| 99 | * Join this cluster to a DocumentDB global cluster. Immutable on create. |
| 100 | */ |
| 101 | globalClusterIdentifier?: string; |
| 102 | /** |
| 103 | * Master username. Immutable — forces replacement. |
| 104 | */ |
| 105 | masterUsername?: string; |
| 106 | /** |
| 107 | * Master password. In-place modify. |
| 108 | */ |
| 109 | masterUserPassword?: Redacted.Redacted<string>; |
| 110 | /** |
| 111 | * Let DocumentDB manage the master user password in Secrets Manager. |
| 112 | */ |
| 113 | manageMasterUserPassword?: boolean; |
| 114 | /** |
| 115 | * Rotate the managed master user password on the next reconcile. |
| 116 | */ |
| 117 | rotateMasterUserPassword?: boolean; |
| 118 | /** |
| 119 | * KMS key used to encrypt the managed master user secret. In-place modify. |
| 120 | */ |
| 121 | masterUserSecretKmsKeyId?: string; |
| 122 | /** |
| 123 | * Allow a major engine-version upgrade during a modify. Modify-only flag. |
| 124 | */ |
| 125 | allowMajorVersionUpgrade?: boolean; |
| 126 | /** |
| 127 | * User-defined tags. |
| 128 | */ |
| 129 | tags?: Record<string, string>; |
| 130 | } |
| 131 | |
| 132 | export interface DBCluster extends Resource< |
| 133 | "AWS.DocDB.DBCluster", |
| 134 | DBClusterProps, |
| 135 | { |
| 136 | /** The cluster identifier (unique per account/region). */ |
| 137 | dbClusterIdentifier: string; |
| 138 | /** The ARN of the cluster. */ |
| 139 | dbClusterArn: string; |
| 140 | /** The DB subnet group the cluster is deployed into. */ |
| 141 | dbSubnetGroupName: string | undefined; |
| 142 | /** The writer endpoint hostname of the cluster. */ |
| 143 | endpoint: string | undefined; |
| 144 | /** The load-balanced reader endpoint hostname. */ |
| 145 | readerEndpoint: string | undefined; |
| 146 | /** The port the cluster accepts connections on. */ |
| 147 | port: number | undefined; |
| 148 | /** The database engine (`docdb`). */ |
| 149 | engine: string; |
| 150 | /** The engine version running on the cluster. */ |
| 151 | engineVersion: string | undefined; |
| 152 | /** The current status of the cluster, e.g. `available`. */ |
| 153 | status: string | undefined; |
| 154 | /** The master (admin) username. */ |
| 155 | masterUsername: string | undefined; |
| 156 | /** ARN of the Secrets Manager secret holding the master credentials (when managed). */ |
| 157 | masterUserSecretArn: string | undefined; |
| 158 | /** The VPC security groups attached to the cluster. */ |
| 159 | vpcSecurityGroupIds: string[]; |
| 160 | /** Number of days automated backups are retained. */ |
| 161 | backupRetentionPeriod: number | undefined; |
| 162 | /** The daily window during which automated backups run. */ |
| 163 | preferredBackupWindow: string | undefined; |
| 164 | /** The weekly window during which maintenance can occur. */ |
| 165 | preferredMaintenanceWindow: string | undefined; |
| 166 | /** Whether cluster storage is encrypted at rest. */ |
| 167 | storageEncrypted: boolean | undefined; |
| 168 | /** The KMS key used for storage encryption. */ |
| 169 | kmsKeyId: string | undefined; |
| 170 | /** Whether deletion protection is enabled. */ |
| 171 | deletionProtection: boolean | undefined; |
| 172 | /** The instances that are members of the cluster. */ |
| 173 | dbClusterMembers: Array<{ |
| 174 | /** The identifier of the member instance. */ |
| 175 | dbInstanceIdentifier: string | undefined; |
| 176 | /** Whether this member is the cluster writer. */ |
| 177 | isClusterWriter: boolean | undefined; |
| 178 | /** The failover promotion tier of the member. */ |
| 179 | promotionTier: number | undefined; |
| 180 | }>; |
| 181 | /** The immutable region-unique resource ID of the cluster. */ |
| 182 | dbClusterResourceId: string | undefined; |
| 183 | /** The Route 53 hosted zone ID of the cluster endpoints. */ |
| 184 | hostedZoneId: string | undefined; |
| 185 | /** Whether the cluster has instances in multiple Availability Zones. */ |
| 186 | multiAZ: boolean | undefined; |
| 187 | /** The log types exported to CloudWatch Logs, e.g. `audit`, `profiler`. */ |
| 188 | enabledCloudwatchLogsExports: string[]; |
| 189 | /** When the cluster was created (ISO timestamp). */ |
| 190 | clusterCreateTime: string | undefined; |
| 191 | /** The storage type, e.g. `standard` or `iopt1`. */ |
| 192 | storageType: string | undefined; |
| 193 | /** The network type, e.g. `IPV4` or `DUAL`. */ |
| 194 | networkType: string | undefined; |
| 195 | /** The tags attached to the cluster. */ |
| 196 | tags: Record<string, string>; |
| 197 | }, |
| 198 | never, |
| 199 | Providers |
| 200 | > {} |
| 201 | |
| 202 | /** |
| 203 | * An Amazon DocumentDB (MongoDB-compatible) cluster. |
| 204 | * |
| 205 | * `DBCluster` owns the writer and reader endpoints and cluster-wide |
| 206 | * networking; instances are added via {@link DBInstance}. It can bootstrap |
| 207 | * master credentials directly or let DocumentDB manage them in Secrets Manager. |
| 208 | * Provisioning a cluster (and its first instance) takes several minutes. |
| 209 | * |
| 210 | * Mutable fields are reconciled in place against the observed cloud state; |
| 211 | * immutable fields (`engine`, `dbSubnetGroupName`, `storageEncrypted`, |
| 212 | * `kmsKeyId`, `globalClusterIdentifier`, `availabilityZones`, |
| 213 | * `masterUsername`) force a replacement. |
| 214 | * ### Creating a Cluster |
| 215 | * **Example:** DocumentDB cluster with a managed master secret |
| 216 | * ```typescript |
| 217 | * const cluster = yield* DBCluster("Docs", { |
| 218 | * dbSubnetGroupName: subnetGroup.dbSubnetGroupName, |
| 219 | * vpcSecurityGroupIds: [sg.groupId], |
| 220 | * masterUsername: "alchemy", |
| 221 | * manageMasterUserPassword: true, |
| 222 | * backupRetentionPeriod: "7 days", |
| 223 | * deletionProtection: false, |
| 224 | * }); |
| 225 | * ``` |
| 226 | * |
| 227 | * ### Logs & Encryption |
| 228 | * **Example:** Export audit logs and encrypt storage |
| 229 | * ```typescript |
| 230 | * const cluster = yield* DBCluster("Docs", { |
| 231 | * dbSubnetGroupName: subnetGroup.dbSubnetGroupName, |
| 232 | * masterUsername: "alchemy", |
| 233 | * masterUserPassword: Redacted.make("supersecret"), |
| 234 | * storageEncrypted: true, |
| 235 | * enableCloudwatchLogsExports: ["audit", "profiler"], |
| 236 | * }); |
| 237 | * ``` |
| 238 | * |
| 239 | * @resource |
| 240 | */ |
| 241 | export const DBCluster = Resource<DBCluster>("AWS.DocDB.DBCluster"); |
| 242 | |
| 243 | const toTagRecord = ( |
| 244 | tags: Array<{ Key?: string; Value?: string }> | undefined, |
| 245 | ): Record<string, string> => |
| 246 | Object.fromEntries( |
| 247 | (tags ?? []) |
| 248 | .filter( |
| 249 | (tag): tag is { Key: string; Value: string } => |
| 250 | typeof tag.Key === "string" && typeof tag.Value === "string", |
| 251 | ) |
| 252 | .map((tag) => [tag.Key, tag.Value]), |
| 253 | ); |
| 254 | |
| 255 | const toAttrs = ({ |
| 256 | cluster, |
| 257 | tags, |
| 258 | }: { |
| 259 | cluster: docdb.DBCluster; |
| 260 | tags: Record<string, string>; |
| 261 | }): DBCluster["Attributes"] => ({ |
| 262 | dbClusterIdentifier: cluster.DBClusterIdentifier ?? "", |
| 263 | dbClusterArn: cluster.DBClusterArn ?? "", |
| 264 | dbSubnetGroupName: cluster.DBSubnetGroup, |
| 265 | endpoint: cluster.Endpoint, |
| 266 | readerEndpoint: cluster.ReaderEndpoint, |
| 267 | port: cluster.Port, |
| 268 | engine: cluster.Engine ?? "docdb", |
| 269 | engineVersion: cluster.EngineVersion, |
| 270 | status: cluster.Status, |
| 271 | masterUsername: cluster.MasterUsername, |
| 272 | masterUserSecretArn: cluster.MasterUserSecret?.SecretArn, |
| 273 | vpcSecurityGroupIds: (cluster.VpcSecurityGroups ?? []).flatMap((group) => |
| 274 | group.VpcSecurityGroupId ? [group.VpcSecurityGroupId] : [], |
| 275 | ), |
| 276 | backupRetentionPeriod: cluster.BackupRetentionPeriod, |
| 277 | preferredBackupWindow: cluster.PreferredBackupWindow, |
| 278 | preferredMaintenanceWindow: cluster.PreferredMaintenanceWindow, |
| 279 | storageEncrypted: cluster.StorageEncrypted, |
| 280 | kmsKeyId: cluster.KmsKeyId, |
| 281 | deletionProtection: cluster.DeletionProtection, |
| 282 | dbClusterMembers: (cluster.DBClusterMembers ?? []).map((member) => ({ |
| 283 | dbInstanceIdentifier: member.DBInstanceIdentifier, |
| 284 | isClusterWriter: member.IsClusterWriter, |
| 285 | promotionTier: member.PromotionTier, |
| 286 | })), |
| 287 | dbClusterResourceId: cluster.DbClusterResourceId, |
| 288 | hostedZoneId: cluster.HostedZoneId, |
| 289 | multiAZ: cluster.MultiAZ, |
| 290 | enabledCloudwatchLogsExports: cluster.EnabledCloudwatchLogsExports ?? [], |
| 291 | clusterCreateTime: cluster.ClusterCreateTime?.toISOString(), |
| 292 | storageType: cluster.StorageType, |
| 293 | networkType: cluster.NetworkType, |
| 294 | tags, |
| 295 | }); |
| 296 | |
| 297 | /** |
| 298 | * Compute the CloudWatch Logs export delta. The modify API is delta-shaped |
| 299 | * (`EnableLogTypes`/`DisableLogTypes`), so it must NOT carry the full set. |
| 300 | * Returns `undefined` when there is no change. |
| 301 | */ |
| 302 | const logExportDelta = ( |
| 303 | observed: string[] | undefined, |
| 304 | desired: string[] | undefined, |
| 305 | ): docdb.CloudwatchLogsExportConfiguration | undefined => { |
| 306 | if (desired === undefined) return undefined; |
| 307 | const have = new Set(observed ?? []); |
| 308 | const want = new Set(desired); |
| 309 | const EnableLogTypes = [...want].filter((t) => !have.has(t)); |
| 310 | const DisableLogTypes = [...have].filter((t) => !want.has(t)); |
| 311 | if (EnableLogTypes.length === 0 && DisableLogTypes.length === 0) { |
| 312 | return undefined; |
| 313 | } |
| 314 | return { |
| 315 | ...(EnableLogTypes.length > 0 ? { EnableLogTypes } : {}), |
| 316 | ...(DisableLogTypes.length > 0 ? { DisableLogTypes } : {}), |
| 317 | }; |
| 318 | }; |
| 319 | |
| 320 | export const DBClusterProvider = () => |
| 321 | Provider.effect( |
| 322 | DBCluster, |
| 323 | Effect.gen(function* () { |
| 324 | const toIdentifier = (id: string, props: DBClusterProps) => |
| 325 | props.dbClusterIdentifier |
| 326 | ? Effect.succeed(props.dbClusterIdentifier) |
| 327 | : createPhysicalName({ id, maxLength: 63 }); |
| 328 | |
| 329 | const readCluster = Effect.fn(function* (clusterId: string) { |
| 330 | const response = yield* docdb |
| 331 | .describeDBClusters({ |
| 332 | DBClusterIdentifier: clusterId, |
| 333 | }) |
| 334 | .pipe(Effect.catchTag("DBClusterNotFoundFault", () => Effect.undefined)); |
| 335 | return response?.DBClusters?.[0]; |
| 336 | }); |
| 337 | |
| 338 | const readTags = Effect.fn(function* (arn: string | undefined) { |
| 339 | if (!arn) return {} as Record<string, string>; |
| 340 | const response = yield* docdb |
| 341 | .listTagsForResource({ ResourceName: arn }) |
| 342 | .pipe(Effect.catchTag("DBClusterNotFoundFault", () => Effect.undefined)); |
| 343 | return toTagRecord(response?.TagList); |
| 344 | }); |
| 345 | |
| 346 | // Bounded readiness wait. Gate on cluster `Status === "available"` so a |
| 347 | // follow-on `modifyDBCluster` doesn't hit `InvalidDBClusterStateFault`. |
| 348 | // Budgets ~10 min (60 * 10s) for slow provisioning. |
| 349 | const waitForCluster = Effect.fn(function* (clusterId: string) { |
| 350 | const readinessPolicy = Schedule.max([Schedule.fixed("10 seconds"), Schedule.recurs(60)]); |
| 351 | return yield* readCluster(clusterId).pipe( |
| 352 | Effect.flatMap((cluster) => { |
| 353 | if (!cluster?.DBClusterArn) { |
| 354 | return Effect.fail( |
| 355 | new DBClusterNotReady({ message: `DB cluster '${clusterId}' not found` }), |
| 356 | ); |
| 357 | } |
| 358 | if (cluster.Status !== "available") { |
| 359 | return Effect.fail( |
| 360 | new DBClusterNotReady({ |
| 361 | message: `DB cluster '${clusterId}' not available (status: ${cluster.Status})`, |
| 362 | }), |
| 363 | ); |
| 364 | } |
| 365 | return Effect.succeed(cluster); |
| 366 | }), |
| 367 | Effect.retry({ schedule: readinessPolicy }), |
| 368 | ); |
| 369 | }); |
| 370 | |
| 371 | return { |
| 372 | stables: ["dbClusterArn", "dbClusterIdentifier"], |
| 373 | // AWS account/region collection: exhaustively paginate |
| 374 | // `describeDBClusters` and map each cluster to the exact `read` |
| 375 | // Attributes shape. DocumentDB does not surface tags inline on the |
| 376 | // cluster, so — mirroring `DBSubnetGroup.list` — we emit an empty tag |
| 377 | // map rather than issuing a per-item `listTagsForResource` fan-out. |
| 378 | list: () => |
| 379 | docdb.describeDBClusters.pages({}).pipe( |
| 380 | Stream.runCollect, |
| 381 | Effect.map((chunk) => |
| 382 | Array.from(chunk).flatMap((page) => |
| 383 | (page.DBClusters ?? []).map((cluster) => toAttrs({ cluster, tags: {} })), |
| 384 | ), |
| 385 | ), |
| 386 | ), |
| 387 | diff: Effect.fn(function* ({ id, olds, news }) { |
| 388 | if (!isResolved(news)) return; |
| 389 | if ( |
| 390 | (yield* toIdentifier(id, olds ?? ({} as DBClusterProps))) !== |
| 391 | (yield* toIdentifier(id, news)) |
| 392 | ) { |
| 393 | return { action: "replace" } as const; |
| 394 | } |
| 395 | // Immutable props — any change forces a fresh cluster. |
| 396 | if ( |
| 397 | olds !== undefined && |
| 398 | ((olds.engine ?? "docdb") !== (news.engine ?? "docdb") || |
| 399 | olds.dbSubnetGroupName !== news.dbSubnetGroupName || |
| 400 | olds.storageEncrypted !== news.storageEncrypted || |
| 401 | olds.kmsKeyId !== news.kmsKeyId || |
| 402 | olds.masterUsername !== news.masterUsername || |
| 403 | olds.globalClusterIdentifier !== news.globalClusterIdentifier || |
| 404 | JSON.stringify(olds.availabilityZones ?? []) !== |
| 405 | JSON.stringify(news.availabilityZones ?? [])) |
| 406 | ) { |
| 407 | return { action: "replace" } as const; |
| 408 | } |
| 409 | }), |
| 410 | read: Effect.fn(function* ({ id, olds, output }) { |
| 411 | const identifier = |
| 412 | output?.dbClusterIdentifier ?? |
| 413 | (yield* toIdentifier(id, olds ?? ({} as DBClusterProps))); |
| 414 | const cluster = yield* readCluster(identifier); |
| 415 | if (!cluster?.DBClusterArn) { |
| 416 | return undefined; |
| 417 | } |
| 418 | const tags = yield* readTags(cluster.DBClusterArn); |
| 419 | return toAttrs({ cluster, tags }); |
| 420 | }), |
| 421 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 422 | const identifier = output?.dbClusterIdentifier ?? (yield* toIdentifier(id, news)); |
| 423 | const internalTags = yield* createInternalTags(id); |
| 424 | const desiredTags = { ...internalTags, ...news.tags }; |
| 425 | // Redacted end-to-end: distilled's `MasterUserPassword` is |
| 426 | // SensitiveString, so the Redacted value is passed through without |
| 427 | // unwrapping and never appears in traces. |
| 428 | const masterUserPassword = news.masterUserPassword; |
| 429 | |
| 430 | // Observe — fetch live cluster state. |
| 431 | let observed = yield* readCluster(identifier); |
| 432 | |
| 433 | // Ensure — create the cluster if it's missing. Tolerate |
| 434 | // `DBClusterAlreadyExistsFault` as a race with a peer reconciler. |
| 435 | if (!observed?.DBClusterArn) { |
| 436 | yield* docdb |
| 437 | .createDBCluster({ |
| 438 | DBClusterIdentifier: identifier, |
| 439 | Engine: news.engine ?? "docdb", |
| 440 | EngineVersion: news.engineVersion, |
| 441 | DBSubnetGroupName: news.dbSubnetGroupName, |
| 442 | DBClusterParameterGroupName: news.dbClusterParameterGroupName, |
| 443 | VpcSecurityGroupIds: news.vpcSecurityGroupIds, |
| 444 | Port: news.port, |
| 445 | AvailabilityZones: news.availabilityZones, |
| 446 | BackupRetentionPeriod: toWireDays(news.backupRetentionPeriod), |
| 447 | PreferredBackupWindow: news.preferredBackupWindow, |
| 448 | PreferredMaintenanceWindow: news.preferredMaintenanceWindow, |
| 449 | EnableCloudwatchLogsExports: news.enableCloudwatchLogsExports, |
| 450 | DeletionProtection: news.deletionProtection, |
| 451 | StorageEncrypted: news.storageEncrypted, |
| 452 | KmsKeyId: news.kmsKeyId, |
| 453 | StorageType: news.storageType, |
| 454 | NetworkType: news.networkType, |
| 455 | GlobalClusterIdentifier: news.globalClusterIdentifier, |
| 456 | MasterUsername: news.masterUsername, |
| 457 | MasterUserPassword: masterUserPassword, |
| 458 | ManageMasterUserPassword: news.manageMasterUserPassword, |
| 459 | MasterUserSecretKmsKeyId: news.masterUserSecretKmsKeyId, |
| 460 | Tags: Object.entries(desiredTags).map(([Key, Value]) => ({ |
| 461 | Key, |
| 462 | Value, |
| 463 | })), |
| 464 | }) |
| 465 | .pipe(Effect.catchTag("DBClusterAlreadyExistsFault", () => Effect.void)); |
| 466 | |
| 467 | observed = yield* waitForCluster(identifier); |
| 468 | } else { |
| 469 | // Wait for the cluster to settle before any modify so the call |
| 470 | // doesn't hit `InvalidDBClusterStateFault`. |
| 471 | observed = yield* waitForCluster(identifier); |
| 472 | |
| 473 | // syncCoreSettings — single `modifyDBCluster` carrying scalar |
| 474 | // in-place fields, only emitting a field when the desired value |
| 475 | // differs from the observed cloud state. |
| 476 | const core: docdb.ModifyDBClusterMessage = { |
| 477 | DBClusterIdentifier: identifier, |
| 478 | ApplyImmediately: true, |
| 479 | }; |
| 480 | let coreDirty = false; |
| 481 | const setIf = <K extends keyof docdb.ModifyDBClusterMessage>( |
| 482 | key: K, |
| 483 | desired: docdb.ModifyDBClusterMessage[K] | undefined, |
| 484 | observedValue: unknown, |
| 485 | ) => { |
| 486 | if (desired !== undefined && desired !== observedValue) { |
| 487 | core[key] = desired; |
| 488 | coreDirty = true; |
| 489 | } |
| 490 | }; |
| 491 | setIf("EngineVersion", news.engineVersion, observed.EngineVersion); |
| 492 | setIf("Port", news.port, observed.Port); |
| 493 | setIf("BackupRetentionPeriod", toWireDays(news.backupRetentionPeriod), observed.BackupRetentionPeriod); // prettier-ignore |
| 494 | setIf("PreferredBackupWindow", news.preferredBackupWindow, observed.PreferredBackupWindow); // prettier-ignore |
| 495 | setIf("PreferredMaintenanceWindow", news.preferredMaintenanceWindow, observed.PreferredMaintenanceWindow); // prettier-ignore |
| 496 | setIf("DeletionProtection", news.deletionProtection, observed.DeletionProtection); // prettier-ignore |
| 497 | setIf("StorageType", news.storageType, observed.StorageType); |
| 498 | setIf("NetworkType", news.networkType, observed.NetworkType); |
| 499 | setIf("DBClusterParameterGroupName", news.dbClusterParameterGroupName, observed.DBClusterParameterGroup); // prettier-ignore |
| 500 | setIf("MasterUserSecretKmsKeyId", news.masterUserSecretKmsKeyId, undefined); // prettier-ignore |
| 501 | if (news.vpcSecurityGroupIds !== undefined) { |
| 502 | core.VpcSecurityGroupIds = news.vpcSecurityGroupIds; |
| 503 | coreDirty = true; |
| 504 | } |
| 505 | if (news.allowMajorVersionUpgrade) { |
| 506 | core.AllowMajorVersionUpgrade = true; |
| 507 | } |
| 508 | // syncMasterPassword — rotation or explicit password update. |
| 509 | if (news.manageMasterUserPassword && news.rotateMasterUserPassword) { |
| 510 | core.RotateMasterUserPassword = true; |
| 511 | coreDirty = true; |
| 512 | } else if (masterUserPassword !== undefined) { |
| 513 | core.MasterUserPassword = masterUserPassword; |
| 514 | coreDirty = true; |
| 515 | } |
| 516 | if (coreDirty) { |
| 517 | yield* docdb.modifyDBCluster(core); |
| 518 | observed = yield* waitForCluster(identifier); |
| 519 | } |
| 520 | |
| 521 | // syncCloudwatchLogsExports — delta-shaped; separate call. |
| 522 | const logDelta = logExportDelta( |
| 523 | observed.EnabledCloudwatchLogsExports, |
| 524 | news.enableCloudwatchLogsExports, |
| 525 | ); |
| 526 | if (logDelta) { |
| 527 | yield* docdb.modifyDBCluster({ |
| 528 | DBClusterIdentifier: identifier, |
| 529 | CloudwatchLogsExportConfiguration: logDelta, |
| 530 | ApplyImmediately: true, |
| 531 | }); |
| 532 | observed = yield* waitForCluster(identifier); |
| 533 | } |
| 534 | } |
| 535 | |
| 536 | const dbClusterArn = observed.DBClusterArn ?? ""; |
| 537 | |
| 538 | // Sync tags — diff observed cloud tags against desired. |
| 539 | const observedTags = yield* readTags(dbClusterArn); |
| 540 | const { removed, upsert } = diffTags(observedTags, desiredTags); |
| 541 | if (upsert.length > 0 && dbClusterArn) { |
| 542 | yield* docdb.addTagsToResource({ |
| 543 | ResourceName: dbClusterArn, |
| 544 | Tags: upsert, |
| 545 | }); |
| 546 | } |
| 547 | if (removed.length > 0 && dbClusterArn) { |
| 548 | yield* docdb.removeTagsFromResource({ |
| 549 | ResourceName: dbClusterArn, |
| 550 | TagKeys: removed, |
| 551 | }); |
| 552 | } |
| 553 | |
| 554 | yield* session.note(dbClusterArn || identifier); |
| 555 | return toAttrs({ cluster: observed, tags: desiredTags }); |
| 556 | }), |
| 557 | delete: Effect.fn(function* ({ output }) { |
| 558 | yield* docdb |
| 559 | .deleteDBCluster({ |
| 560 | DBClusterIdentifier: output.dbClusterIdentifier, |
| 561 | SkipFinalSnapshot: true, |
| 562 | }) |
| 563 | .pipe(Effect.catchTag("DBClusterNotFoundFault", () => Effect.void)); |
| 564 | // Block until the cluster is fully gone. DocumentDB deletion is |
| 565 | // async; if we return while it is still `deleting`, a dependent |
| 566 | // (DBSubnetGroup or VPC) is torn down next and AWS rejects it. |
| 567 | yield* Effect.repeat( |
| 568 | docdb |
| 569 | .describeDBClusters({ |
| 570 | DBClusterIdentifier: output.dbClusterIdentifier, |
| 571 | }) |
| 572 | .pipe( |
| 573 | Effect.as(true), |
| 574 | Effect.catchTag("DBClusterNotFoundFault", () => Effect.succeed(false)), |
| 575 | ), |
| 576 | { |
| 577 | schedule: Schedule.max([Schedule.fixed("15 seconds"), Schedule.recurs(40)]), |
| 578 | until: (exists) => exists === false, |
| 579 | }, |
| 580 | ).pipe(Effect.catch(() => Effect.void)); |
| 581 | }), |
| 582 | }; |
| 583 | }), |
| 584 | ); |