@devries-cameron20 / t3code Mirror · read-only
Fork 0

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, 03:37 UTC

main
ts 2,461 lines 99.3 KB
Raw
1 import {
2 diffMigrations,
3 migrationsAttrs,
4 migrationsInputOf,
5 stampedOf,
6 type MigrationsInput,
7 } from "@alchemy.run/sql/Migrations";
8 import * as ec2 from "@distilled.cloud/aws/ec2";
9 import * as rds from "@distilled.cloud/aws/rds";
10 import * as secretsmanager from "@distilled.cloud/aws/secrets-manager";
11 import { isResolved } from "alchemy/Diff";
12 import { createPhysicalName } from "alchemy/PhysicalName";
13 import * as Provider from "alchemy/Provider";
14 import { Resource } from "alchemy/Resource";
15 import { createInternalTags, diffTags } from "alchemy/Tags";
16 import { toWireDays, toWireSeconds } from "alchemy/Util/Duration";
17 import { sha256 } from "alchemy/Util/sha256";
18 import * as Data from "effect/Data";
19 import type * as Duration from "effect/Duration";
20 import * as Effect from "effect/Effect";
21 import * as Redacted from "effect/Redacted";
22 import * as Schedule from "effect/Schedule";
23 import * as Stream from "effect/Stream";
24 import {
25 normalizePolicyDocument,
26 stringifyPolicyDocument,
27 type PolicyDocument,
28 } from "../IAM/Policy.ts";
29 import { reapLogGroupsByPrefix } from "../Logs/reapLogGroups.ts";
30 import type { Providers } from "../Providers.ts";
31 import { runDBInstanceMigrations, type MigrationsTransport } from "./Migrations.ts";
32
33 export interface DBInstanceProps {
34 /**
35 * Instance identifier. If omitted, Alchemy generates one.
36 */
37 dbInstanceIdentifier?: string;
38 /**
39 * Aurora cluster the instance belongs to. When set, the instance is a
40 * cluster member and most storage/backup props are managed by the cluster.
41 * Replacing this forces a new instance.
42 */
43 dbClusterIdentifier?: string;
44 /**
45 * Instance class such as `db.serverless` or `db.t3.micro`.
46 */
47 dbInstanceClass: string;
48 /**
49 * Database engine, e.g. `mysql`, `postgres`, `aurora-postgresql`.
50 * Changing the engine forces replacement.
51 */
52 engine: string;
53 /**
54 * Optional engine version. Changed in place via `modifyDBInstance`.
55 */
56 engineVersion?: string;
57 /**
58 * Standalone (non-Aurora) database name created with the instance.
59 * Immutable — forces replacement.
60 */
61 dbName?: string;
62 /**
63 * Minimum allocated storage in GiB (standalone instances). RDS cannot
64 * shrink storage; omission/removal retains any larger existing allocation.
65 * Defaults to 100 GiB for io1/io2, 40 GiB for other RDS Custom storage,
66 * and 20 GiB otherwise. In-place increases request at least 10% growth.
67 * Cluster members inherit storage from their cluster.
68 */
69 allocatedStorage?: number;
70 /**
71 * Upper limit (GiB) for storage autoscaling on standalone instances.
72 * Omission or `0` disables autoscaling, including after adoption or drift.
73 * Disabling never shrinks allocated storage. RDS requires the current
74 * allocation as the modify request's reset value, not a zero ceiling.
75 * Not supported for cluster members or RDS Custom.
76 * @default 0
77 */
78 maxAllocatedStorage?: number;
79 /**
80 * Storage type: `gp2` | `gp3` | `io1` | `io2` | `standard`. Omission/removal
81 * selects gp3, including for existing instances. Magnetic (`standard`)
82 * storage is accepted only for existing instances; Db2 does not support gp2.
83 * AWS engine, instance-class, and regional restrictions still apply.
84 * Cluster members inherit storage from their cluster.
85 * @default "gp3"
86 */
87 storageType?: string;
88 /**
89 * Provisioned IOPS (io1/io2/gp3). Omission/removal selects a deterministic
90 * baseline, not the observed setting: gp3 uses 3000 IOPS, or 12000 for
91 * striped storage; io1/io2 use at least 1000. Allocation, autoscaling,
92 * engine, and declared throughput can raise that baseline.
93 * Small non-SQL Server gp3 volumes have fixed performance. AWS rate-limits
94 * changes and may require a storage-optimization cooldown.
95 */
96 iops?: number;
97 /**
98 * Storage throughput in MiBps (gp3 only). Omission/removal selects 125,
99 * or 500 for striped storage. MySQL/MariaDB IOPS can raise the baseline.
100 * gp3 is striped at 200 GiB for Oracle and 400 GiB for other engines,
101 * except SQL Server, which does not use the striped baseline.
102 */
103 storageThroughput?: number;
104 /**
105 * Master username (standalone instances). Immutable — forces replacement.
106 */
107 masterUsername?: string;
108 /**
109 * Master password (standalone instances). In-place modify.
110 */
111 masterUserPassword?: Redacted.Redacted<string>;
112 /**
113 * Let RDS manage the master user password in Secrets Manager.
114 */
115 manageMasterUserPassword?: boolean;
116 /**
117 * Rotate the managed master user password on the next reconcile.
118 */
119 rotateMasterUserPassword?: boolean;
120 /**
121 * KMS key used to encrypt the managed master user secret.
122 */
123 masterUserSecretKmsKeyId?: string;
124 /**
125 * Resource policy for this instance's RDS-managed master secret. Omission or
126 * removal deletes an existing policy, including after adoption or drift.
127 * RDS retains ownership of the secret value, rotation, and deletion.
128 * Requires Secrets Manager GetResourcePolicy, ValidateResourcePolicy,
129 * PutResourcePolicy, and DeleteResourcePolicy permissions. Declared policies
130 * are validated even on no-op plans; writes also use BlockPublicPolicy.
131 * Cluster-owned secrets and RDS Custom are not supported by this property.
132 */
133 masterUserSecretResourcePolicy?: PolicyDocument;
134 /**
135 * Standalone listener port. Omission/removal restores the engine default:
136 * PostgreSQL 5432, MySQL/MariaDB 3306, Oracle 1521, SQL Server 1433, Db2 50000.
137 * Unknown engines require an explicit port. RDS Custom supports creation
138 * with a port, but changing an existing Custom listener is not supported here.
139 * Ignored for Aurora and cluster members: configure the DBCluster port.
140 * Changes restart the database and are sent as `DBPortNumber` on modify.
141 */
142 port?: number;
143 /**
144 * Multi-AZ deployment (standalone instances). In-place modify.
145 */
146 multiAZ?: boolean;
147 /**
148 * Availability zone (standalone single-AZ). Immutable — forces replacement.
149 */
150 availabilityZone?: string;
151 /**
152 * Backup retention period (e.g. `"7 days"` or `Duration.days(7)`).
153 * Sent to the API in whole days. In-place modify.
154 */
155 backupRetentionPeriod?: Duration.Input;
156 /**
157 * Daily backup window, e.g. `07:00-09:00`. In-place modify.
158 */
159 preferredBackupWindow?: string;
160 /**
161 * Weekly maintenance window, e.g. `Mon:00:00-Mon:03:00`. In-place modify.
162 */
163 preferredMaintenanceWindow?: string;
164 /**
165 * Optional DB subnet group. Effectively immutable for an in-VPC instance.
166 */
167 dbSubnetGroupName?: string;
168 /**
169 * DB parameter group. Omission/removal restores `default.<engine-family>`.
170 * The family follows the requested version, otherwise the existing engine
171 * version, otherwise the regional default for a new instance. Aurora uses
172 * its cluster's version. Pending-reboot associations are returned without
173 * automatically rebooting. Unsupported on RDS Custom; Db2 BYOL requires
174 * an explicit group with IBM licensing IDs.
175 */
176 dbParameterGroupName?: string;
177 /**
178 * VPC security groups attached to the instance, compared as a set.
179 * Omission/removal restores the default group in the effective instance VPC:
180 * the declared subnet group's VPC, the existing instance VPC, or the regional
181 * default VPC for a new instance. An empty array is invalid.
182 * Resetting changes network access according to the default group's rules;
183 * it does not delete detached group resources. Ignored for cluster members,
184 * whose security groups are managed on DBCluster. Existing RDS Custom
185 * attachments cannot be changed through this provider.
186 */
187 vpcSecurityGroupIds?: string[];
188 /**
189 * Option group (MySQL/Oracle/SQL Server). In-place modify.
190 */
191 optionGroupName?: string;
192 /**
193 * License model, e.g. `license-included` | `bring-your-own-license`.
194 */
195 licenseModel?: string;
196 /**
197 * Whether storage is encrypted. Immutable — forces replacement.
198 */
199 storageEncrypted?: boolean;
200 /**
201 * KMS key for storage encryption. Immutable — forces replacement.
202 */
203 kmsKeyId?: string;
204 /**
205 * CA certificate identifier. In-place modify.
206 */
207 caCertificateIdentifier?: string;
208 /**
209 * Enable IAM database authentication. Omission/removal disables it, including
210 * after adoption or drift. Cluster members inherit their cluster's setting.
211 * Applying a change or a queued IAM change uses ApplyImmediately, which also
212 * applies unrelated pending RDS modifications. Supported on standalone
213 * PostgreSQL, MySQL, and MariaDB; unsupported on RDS Custom.
214 * @default false
215 */
216 enableIAMDatabaseAuthentication?: boolean;
217 /**
218 * Enable Performance Insights. In-place modify.
219 */
220 enablePerformanceInsights?: boolean;
221 /**
222 * KMS key for Performance Insights. In-place modify.
223 */
224 performanceInsightsKMSKeyId?: string;
225 /**
226 * Performance Insights retention (e.g. `"7 days"`). Sent to the API in
227 * whole days (valid: 7, 731, or month multiples).
228 */
229 performanceInsightsRetentionPeriod?: Duration.Input;
230 /**
231 * Enhanced-monitoring granularity (e.g. `"60 seconds"`). Sent to the API
232 * in whole seconds (valid: 0, 1, 5, 10, 15, 30, 60).
233 */
234 monitoringInterval?: Duration.Input;
235 /**
236 * IAM role ARN for enhanced monitoring. In-place modify.
237 */
238 monitoringRoleArn?: string;
239 /**
240 * Log types to export to CloudWatch Logs, compared as a set. Omission/removal
241 * disables all exports. Changes apply immediately without flushing unrelated
242 * pending modifications. Cluster members inherit their cluster's exports.
243 * Unsupported on RDS Custom.
244 * @default []
245 */
246 enableCloudwatchLogsExports?: string[];
247 /**
248 * Block accidental deletion. Omission/removal disables protection, including
249 * after adoption or drift. Ignored for cluster members: configure DBCluster.
250 * Aurora cluster protection does not prevent deleting individual instances.
251 * @default false
252 */
253 deletionProtection?: boolean;
254 /**
255 * Network type: `IPV4` | `DUAL`. Omission/removal restores IPv4. DUAL requires
256 * IPv6-enabled subnets. Ignored for cluster members: configure DBCluster.
257 * Changes apply immediately and can also apply unrelated pending RDS changes.
258 * @default "IPV4"
259 */
260 networkType?: string;
261 /**
262 * Allow a major engine-version upgrade during a modify. Modify-only flag.
263 */
264 allowMajorVersionUpgrade?: boolean;
265 /**
266 * Whether the instance has a public address. Omission/removal restores private
267 * access, including after adoption or drift. Also managed on Aurora instances;
268 * non-Aurora Multi-AZ cluster members inherit their cluster's configuration.
269 * Changes apply immediately without flushing unrelated pending modifications.
270 * @default false
271 */
272 publiclyAccessible?: boolean;
273 /**
274 * Promotion tier inside the cluster.
275 */
276 promotionTier?: number;
277 /**
278 * Auto minor version upgrades.
279 */
280 autoMinorVersionUpgrade?: boolean;
281 /**
282 * Copy tags to snapshots.
283 */
284 copyTagsToSnapshot?: boolean;
285 /**
286 * User-defined tags.
287 */
288 tags?: Record<string, string>;
289 /**
290 * Skip the final snapshot when the instance is deleted. Set `false` to
291 * have RDS take a final snapshot on teardown — belt-and-suspenders beyond
292 * `deletionProtection` for databases whose data must survive a deliberate
293 * destroy. Persisted into state so `delete` honors it without props.
294 * @default true
295 */
296 skipFinalSnapshot?: boolean;
297 /**
298 * Identifier for the final snapshot taken when `skipFinalSnapshot` is
299 * `false`. Defaults to `<instance-identifier>-final-<timestamp>` so
300 * repeated destroy/create cycles never collide on snapshot names.
301 */
302 finalDBSnapshotIdentifier?: string;
303 /**
304 * SQL migrations to apply on deploy, once this instance is available.
305 * Accepts a directory path, a `Drizzle.Schema` resource, or
306 * `{ dir, table? }`. Supports PostgreSQL, MySQL and MariaDB engines. On
307 * an Aurora cluster member the migrations target the cluster's database;
308 * declare them on one instance per cluster (the writer).
309 *
310 * Bookkeeping always lives in Alchemy's `__alchemy_migrations` table. A
311 * database previously migrated by drizzle-kit or Prisma is adopted by a
312 * one-way conversion on first deploy. Each migration commits with its
313 * bookkeeping row in one transaction; MySQL and MariaDB commit DDL
314 * implicitly, so their DDL is not rolled back if a later statement fails.
315 * Deleting the instance never touches the database.
316 */
317 migrations?: MigrationsInput;
318 /**
319 * How `migrations` reach the database: `"data-api"` (Aurora clusters with
320 * `enableHttpEndpoint: true`; the Data API runs one statement per call, so
321 * separate statements with `--> statement-breakpoint`), `"direct"` (a
322 * connection from the deploying machine, which needs a network route to
323 * the endpoint), or an `AWS.RDS.MigrationRunner` Lambda inside the VPC.
324 * @default "data-api" when the instance's Aurora cluster has the Data API enabled, otherwise "direct"
325 */
326 migrationsTransport?: MigrationsTransport;
327 /**
328 * ARN of the Secrets Manager secret (JSON with `username` and `password`)
329 * that `migrations` authenticate with.
330 * @default `masterUsername` + `masterUserPassword` when set (direct and Lambda transports), otherwise the RDS-managed master user secret
331 */
332 migrationsSecretArn?: string;
333 }
334
335 export interface DBInstance extends Resource<
336 "AWS.RDS.DBInstance",
337 DBInstanceProps,
338 {
339 /**
340 * Identifier of the instance.
341 */
342 dbInstanceIdentifier: string;
343 /**
344 * ARN of the instance.
345 */
346 dbInstanceArn: string;
347 /**
348 * Aurora cluster the instance belongs to, if any.
349 */
350 dbClusterIdentifier: string | undefined;
351 /**
352 * DNS address of the instance endpoint.
353 */
354 endpointAddress: string | undefined;
355 /**
356 * Port of the instance endpoint.
357 */
358 endpointPort: number | undefined;
359 /**
360 * Instance class (e.g. `db.serverless`, `db.t3.micro`).
361 */
362 dbInstanceClass: string | undefined;
363 /**
364 * Database engine.
365 */
366 engine: string | undefined;
367 /**
368 * Engine version in use.
369 */
370 engineVersion: string | undefined;
371 /**
372 * Status of the instance (e.g. `available`).
373 */
374 status: string | undefined;
375 /**
376 * Failover promotion tier inside the cluster.
377 */
378 promotionTier: number | undefined;
379 /**
380 * Whether the instance has a public address.
381 */
382 publiclyAccessible: boolean | undefined;
383 /**
384 * Subnet group the instance is placed in.
385 */
386 dbSubnetGroupName: string | undefined;
387 /**
388 * Parameter groups applied to the instance.
389 */
390 dbParameterGroupNames: string[];
391 /**
392 * Observed parameter-group apply statuses, including pending-reboot.
393 */
394 dbParameterGroupApplyStatuses: Record<string, string | undefined>;
395 /**
396 * Observed VPC security-group attachments, including cluster-owned groups.
397 */
398 vpcSecurityGroupIds: string[];
399 /**
400 * Observed VPC security-group application states, such as `active`.
401 */
402 vpcSecurityGroupStatuses: Record<string, string | undefined>;
403 /**
404 * Allocated storage in GiB.
405 */
406 allocatedStorage: number | undefined;
407 /**
408 * Storage autoscaling ceiling in GiB.
409 */
410 maxAllocatedStorage: number | undefined;
411 /**
412 * Storage type (e.g. `gp3`, `io1`, `aurora`).
413 */
414 storageType: string | undefined;
415 /**
416 * Provisioned IOPS.
417 */
418 iops: number | undefined;
419 /**
420 * Storage throughput in MiBps (gp3).
421 */
422 storageThroughput: number | undefined;
423 /**
424 * Whether the instance is Multi-AZ.
425 */
426 multiAZ: boolean | undefined;
427 /**
428 * Availability Zone of the instance.
429 */
430 availabilityZone: string | undefined;
431 /**
432 * Standby AZ for Multi-AZ deployments.
433 */
434 secondaryAvailabilityZone: string | undefined;
435 /**
436 * Backup retention period in days.
437 */
438 backupRetentionPeriod: number | undefined;
439 /**
440 * Daily backup window (`hh:mm-hh:mm` UTC).
441 */
442 preferredBackupWindow: string | undefined;
443 /**
444 * Weekly maintenance window.
445 */
446 preferredMaintenanceWindow: string | undefined;
447 /**
448 * KMS key used for storage encryption.
449 */
450 kmsKeyId: string | undefined;
451 /**
452 * Whether storage is encrypted.
453 */
454 storageEncrypted: boolean | undefined;
455 /**
456 * CA certificate identifier.
457 */
458 caCertificateIdentifier: string | undefined;
459 /**
460 * Whether IAM database authentication is enabled.
461 */
462 iamDatabaseAuthenticationEnabled: boolean | undefined;
463 /**
464 * Observed IAM authentication change awaiting application. A pending value
465 * is not evidence that authentication has changed on the database.
466 */
467 pendingIamDatabaseAuthenticationEnabled: boolean | undefined;
468 /**
469 * Whether Performance Insights is enabled.
470 */
471 performanceInsightsEnabled: boolean | undefined;
472 /**
473 * Enhanced-monitoring granularity in seconds.
474 */
475 monitoringInterval: number | undefined;
476 /**
477 * ARN of the enhanced-monitoring CloudWatch Logs stream.
478 */
479 enhancedMonitoringResourceArn: string | undefined;
480 /**
481 * Log types exported to CloudWatch Logs.
482 */
483 enabledCloudwatchLogsExports: string[];
484 /**
485 * Whether deletion protection is enabled.
486 */
487 deletionProtection: boolean | undefined;
488 /**
489 * Whether minor engine upgrades are applied automatically, as observed.
490 * Lets `alchemy drift` detect out-of-band changes.
491 */
492 autoMinorVersionUpgrade?: boolean;
493 /**
494 * Immutable region-unique instance resource ID (used in IAM auth ARNs).
495 */
496 dbiResourceId: string | undefined;
497 /**
498 * Master username.
499 */
500 masterUsername: string | undefined;
501 /**
502 * Whether the final snapshot is skipped on delete, persisted from the
503 * prop of the same name. `delete` receives only the stored attributes,
504 * never live props, so the snapshot decision must ride in state;
505 * `undefined` (older state without this attr) is treated as skip.
506 */
507 skipFinalSnapshot: boolean | undefined;
508 /**
509 * Identifier used for the final snapshot when `skipFinalSnapshot` is
510 * `false`, persisted from props so `delete` can name the snapshot without
511 * live props. `undefined` means `delete` falls back to the default
512 * `<instance-identifier>-final-<timestamp>` naming scheme.
513 */
514 finalDBSnapshotIdentifier: string | undefined;
515 /**
516 * Salted SHA-256 fingerprint of the last `masterUserPassword` this
517 * provider sent to RDS — `sha256(`${dbInstanceIdentifier}:${password}`)`,
518 * never the secret itself. Lets reconcile skip the `MasterUserPassword`
519 * modify (and the `resetting-master-credentials` cycle it triggers) when
520 * the configured password has not changed.
521 *
522 * Persisted `Redacted` because a password hash is still sensitive: an
523 * unsalted digest is vulnerable to rainbow-table lookup, so the state
524 * store must not surface it in plaintext (logs, `stringify`, dumps). The
525 * per-resource identifier salt additionally defeats precomputed tables;
526 * it is stable across a resource's life, so the fingerprint stays
527 * comparable across reconciles.
528 */
529 masterUserPasswordFingerprint: Redacted.Redacted<string> | undefined;
530 /**
531 * ARN of the Secrets Manager secret holding master credentials.
532 */
533 masterUserSecretArn: string | undefined;
534 /**
535 * Canonical policy observed during read or reconciliation. Undefined when
536 * there is no instance-managed secret or no resource policy. Inventory
537 * listing does not load policy metadata and leaves this attribute undefined.
538 */
539 masterUserSecretResourcePolicy: string | undefined;
540 /**
541 * Option group memberships.
542 */
543 optionGroupMemberships: string[];
544 /**
545 * License model.
546 */
547 licenseModel: string | undefined;
548 /**
549 * Configured database port.
550 */
551 dbInstancePort: number | undefined;
552 /**
553 * Network type (`IPV4` or `DUAL`).
554 */
555 networkType: string | undefined;
556 /**
557 * Tags on the instance.
558 */
559 tags: Record<string, string>;
560 /** Directory of the applied SQL migrations. */
561 migrationsDir: string | undefined;
562 /** Migration bookkeeping table. */
563 migrationsTable: string | undefined;
564 /** Applied migration content hashes. */
565 migrationsHashes: Record<string, string>;
566 },
567 never,
568 Providers
569 > {}
570
571 /**
572 * An RDS database instance — either a standalone (non-Aurora) database or a
573 * member of an Aurora `DBCluster`.
574 *
575 * Exposes the full storage, backup, monitoring, performance-insights,
576 * encryption, networking, and log-export surface of `createDBInstance` /
577 * `modifyDBInstance`. Mutable fields are reconciled in place against the
578 * observed cloud state; immutable fields (`engine`, `dbName`,
579 * `masterUsername`, `availabilityZone`, `storageEncrypted`, `kmsKeyId`,
580 * `dbSubnetGroupName`) force a replacement.
581 * ### Standalone Instance
582 * **Example:** A gp3 MySQL instance
583 * ```typescript
584 * const db = yield* DBInstance("Db", {
585 * engine: "mysql",
586 * dbInstanceClass: "db.t3.micro",
587 * allocatedStorage: 20,
588 * storageType: "gp3",
589 * masterUsername: "admin",
590 * masterUserPassword: Redacted.make("supersecret"),
591 * backupRetentionPeriod: "7 days",
592 * deletionProtection: false,
593 * });
594 * ```
595 *
596 * ### Storage Defaults
597 * Omitted storage settings describe desired defaults, including on existing
598 * instances: gp3 storage, a minimum allocation of 20 GiB, and the engine's
599 * baseline performance. RDS Custom defaults to 40 GiB; io1/io2 default to
600 * 100 GiB and at least 1000 IOPS. Only allocated capacity is a floor because
601 * RDS cannot shrink a database. Storage type and performance are reconciled
602 * even when the program is unchanged and the cloud settings have drifted.
603 *
604 * **Example:** PostgreSQL with default storage and autoscaling disabled
605 * ```typescript
606 * const db = yield* DBInstance("Db", {
607 * engine: "postgres",
608 * dbInstanceClass: "db.t3.micro",
609 * masterUsername: "admin",
610 * manageMasterUserPassword: true,
611 * });
612 * ```
613 *
614 * This starts with 20 GiB of gp3 storage, 3000 IOPS, and 125 MiBps. For small
615 * non-SQL Server gp3 volumes, these performance values are fixed and Alchemy
616 * omits the unsupported performance fields from AWS requests.
617 *
618 * ### Resetting Storage Performance
619 * Removing performance settings restores the baseline for the desired
620 * storage type, effective allocation, engine, and autoscaling limit. AWS
621 * requires coupled storage fields together on modifications; Alchemy sends
622 * the resolved allocation, type, supported performance fields, and ceiling
623 * in the same request. Existing database contents are retained.
624 *
625 * **Example:** Restore the PostgreSQL gp3 baseline at 400 GiB
626 * ```diff lang="typescript"
627 * const db = yield* DBInstance("Db", {
628 * engine: "postgres",
629 * dbInstanceClass: "db.t3.micro",
630 * masterUsername: "admin",
631 * manageMasterUserPassword: true,
632 * allocatedStorage: 400,
633 * - iops: 16000,
634 * - storageThroughput: 750,
635 * });
636 * ```
637 *
638 * At this allocation PostgreSQL uses striped gp3 storage, so removal requests
639 * 12000 IOPS and 500 MiBps. Removing `storageType: "gp2"` instead selects gp3
640 * without shrinking the allocation. Changes remain subject to AWS's storage
641 * optimization cooldown; redeploying cannot bypass that restriction.
642 *
643 * ### Storage Autoscaling
644 * `allocatedStorage` is a minimum, not a shrink target. RDS can increase the
645 * allocation but cannot reduce it in place. `maxAllocatedStorage` controls
646 * future automatic growth; omitting it or setting it to `0` disables autoscaling.
647 *
648 * **Example:** Start with 20 GiB and allow automatic growth to 100 GiB
649 * ```typescript
650 * const db = yield* DBInstance("Db", {
651 * engine: "postgres",
652 * dbInstanceClass: "db.t3.micro",
653 * masterUsername: "admin",
654 * manageMasterUserPassword: true,
655 * storageType: "gp2",
656 * allocatedStorage: 20,
657 * maxAllocatedStorage: 100,
658 * });
659 * ```
660 *
661 * If RDS grows this database to 30 GiB, redeploying keeps that capacity and the
662 * 100 GiB autoscaling limit. It does not attempt to shrink the database to 20 GiB.
663 * An externally changed autoscaling limit is reset to the declared value.
664 *
665 * ### Disabling Storage Autoscaling
666 * Removing `maxAllocatedStorage` resets autoscaling to its disabled default.
667 * Existing allocated storage and database contents remain intact.
668 *
669 * **Example:** Remove the autoscaling limit to disable future automatic growth
670 * ```diff lang="typescript"
671 * const db = yield* DBInstance("Db", {
672 * engine: "postgres",
673 * dbInstanceClass: "db.t3.micro",
674 * masterUsername: "admin",
675 * manageMasterUserPassword: true,
676 * storageType: "gp2",
677 * allocatedStorage: 20,
678 * - maxAllocatedStorage: 100,
679 * });
680 * ```
681 *
682 * `maxAllocatedStorage: 0` has the same behavior. Redeploying with either form
683 * also disables autoscaling if it was enabled outside Alchemy.
684 *
685 * ### Cluster Member
686 * **Example:** An Aurora writer instance
687 * ```typescript
688 * const writer = yield* DBInstance("Writer", {
689 * dbClusterIdentifier: cluster.dbClusterIdentifier,
690 * dbInstanceClass: "db.serverless",
691 * engine: "aurora-postgresql",
692 * });
693 * ```
694 *
695 * ### Listener Port Defaults
696 * Omitted listener ports select the database engine's default: PostgreSQL
697 * 5432, MySQL/MariaDB 3306, Oracle 1521, SQL Server 1433, and Db2 50000.
698 * Alchemy compares the actual endpoint port, including pending changes,
699 * rather than the separate `DbInstancePort` field returned by AWS.
700 *
701 * **Example:** PostgreSQL listening on its default port
702 * ```typescript
703 * const db = yield* DBInstance("Db", {
704 * engine: "postgres",
705 * dbInstanceClass: "db.t3.micro",
706 * masterUsername: "admin",
707 * manageMasterUserPassword: true,
708 * });
709 * ```
710 *
711 * ### Resetting the Listener Port
712 * Removing a custom port restores the engine default. Unchanged programs
713 * also detect and repair external listener changes. Port changes restart
714 * the database, including when restoring defaults after adoption.
715 *
716 * **Example:** Restore PostgreSQL's port 5432
717 * ```diff lang="typescript"
718 * const db = yield* DBInstance("Db", {
719 * engine: "postgres",
720 * dbInstanceClass: "db.t3.micro",
721 * masterUsername: "admin",
722 * manageMasterUserPassword: true,
723 * - port: 5433,
724 * });
725 * ```
726 *
727 * Aurora and other cluster members inherit their listener from `DBCluster`;
728 * instance `port` declarations are ignored. RDS Custom creation accepts a
729 * port, but an existing Custom instance that needs a listener change fails
730 * explicitly instead of silently retaining the wrong port or replacing data.
731 *
732 * ### Association Defaults
733 * Parameter and security-group associations are desired configuration.
734 * Omission selects a compatible engine default parameter group and the
735 * effective VPC's default security group, including during adoption.
736 * Existing database versions and VPC placement constrain those defaults;
737 * the currently attached groups are never used as fallback desired values.
738 *
739 * **Example:** Use default associations in a declared network
740 * ```typescript
741 * const db = yield* DBInstance("Db", {
742 * engine: "postgres",
743 * dbInstanceClass: "db.t3.micro",
744 * masterUsername: "admin",
745 * manageMasterUserPassword: true,
746 * dbSubnetGroupName: subnetGroup.dbSubnetGroupName,
747 * });
748 * ```
749 *
750 * ### Resetting Associations
751 * Removing declarations restores defaults. Unchanged programs also repair
752 * external attachment drift. Reordering or duplicating security-group IDs
753 * does not resend the association request.
754 *
755 * **Example:** Restore the engine and VPC default groups
756 * ```diff lang="typescript"
757 * const db = yield* DBInstance("Db", {
758 * engine: "postgres",
759 * dbInstanceClass: "db.t3.micro",
760 * masterUsername: "admin",
761 * manageMasterUserPassword: true,
762 * dbSubnetGroupName: subnetGroup.dbSubnetGroupName,
763 * - dbParameterGroupName: customParameters.dbParameterGroupName,
764 * - vpcSecurityGroupIds: [applicationGroup.groupId],
765 * });
766 * ```
767 *
768 * The default security group's rules determine network access after reset.
769 * Detached group resources remain intact. Parameter changes can require a
770 * reboot; `dbParameterGroupApplyStatuses` reports `pending-reboot` without
771 * automatically restarting the database. Aurora instance parameter groups
772 * remain instance-managed, while security groups belong to its cluster.
773 * Multi-AZ DB cluster associations are cluster-managed. RDS Custom cannot
774 * manage parameter groups or modify existing security-group attachments;
775 * Db2 BYOL requires an explicit parameter group with IBM licensing IDs.
776 *
777 * ### Security Defaults
778 * Omission is desired configuration, not permission to retain external state:
779 * IAM authentication, public access, and deletion protection default to false,
780 * network type to IPV4, and log exports to an empty set. Removal and unchanged
781 * declarations repair these settings after drift or adoption.
782 *
783 * **Example:** Enable IAM authentication and PostgreSQL log exports
784 * ```typescript
785 * const db = yield* DBInstance("Db", {
786 * engine: "postgres",
787 * dbInstanceClass: "db.t3.micro",
788 * masterUsername: "admin",
789 * manageMasterUserPassword: true,
790 * dbSubnetGroupName: subnetGroup.dbSubnetGroupName,
791 * enableIAMDatabaseAuthentication: true,
792 * enableCloudwatchLogsExports: ["postgresql"],
793 * });
794 * ```
795 *
796 * Removing the last two properties disables IAM authentication and log exports.
797 * Public access remains instance-managed for Aurora, while IAM authentication,
798 * deletion protection, network type, and exports belong to DBCluster. Requested
799 * or observed cluster membership suppresses instance writes to those settings.
800 * Non-Aurora Multi-AZ cluster members also inherit public accessibility.
801 *
802 * ### Pending Security Changes
803 * **Example:** Inspect applied and pending IAM authentication separately
804 * ```typescript
805 * return {
806 * enabled: db.iamDatabaseAuthenticationEnabled,
807 * pending: db.pendingIamDatabaseAuthenticationEnabled,
808 * securityGroupStatuses: db.vpcSecurityGroupStatuses,
809 * };
810 * ```
811 *
812 * Deployment waits for applied security settings and an operational instance.
813 * A matching queued IAM value is promoted with ApplyImmediately without
814 * resending the IAM field; an incompatible queued value is overwritten even
815 * when the applied value already matches. AWS has no selective queue flush:
816 * applying IAM or network-type changes immediately can apply unrelated pending
817 * modifications and cause downtime. Alchemy does not wait until maintenance.
818 * Network type has no field in AWS PendingModifiedValues, so an externally
819 * queued network change cannot be detected until it starts applying.
820 * Public access, deletion protection, and log exports use ApplyImmediately:false
821 * because AWS applies these immediately regardless of that flag. They do not
822 * flush the maintenance queue. Other declared updates retain their existing
823 * immediate-application behavior. Static parameter changes remain pending-reboot;
824 * Alchemy never calls RebootDBInstance automatically.
825 *
826 * ### Managed Master Secret Policy
827 * **Example:** Allow a role to read the RDS-managed master secret
828 * ```typescript
829 * const db = yield* DBInstance("Db", {
830 * engine: "postgres",
831 * dbInstanceClass: "db.t3.micro",
832 * masterUsername: "admin",
833 * manageMasterUserPassword: true,
834 * masterUserSecretResourcePolicy: {
835 * Version: "2012-10-17",
836 * Statement: [{
837 * Effect: "Allow",
838 * Principal: { AWS: reader.roleArn },
839 * Action: ["secretsmanager:GetSecretValue"],
840 * Resource: "*",
841 * }],
842 * },
843 * });
844 * ```
845 *
846 * Declared policies are checked with `ValidateResourcePolicy`, including
847 * unchanged plans, and writes additionally use `BlockPublicPolicy`. Once the
848 * managed secret exists, validation names it, so deployment requires
849 * `secretsmanager:ValidateResourcePolicy` and `secretsmanager:PutResourcePolicy`
850 * on that secret rather than on `*`. Before the first create, with no secret
851 * yet, validation runs without a target. Alchemy compares
852 * live policy metadata without reading secret values. RDS owns credential
853 * generation, rotation, and secret deletion. Only instance-managed secrets are
854 * supported; an Aurora or Multi-AZ cluster owns its own secret, and RDS Custom
855 * does not support managed credentials. Explicit denies can still obstruct the
856 * deployer's access or RDS rotation; policy validation is not a guarantee that
857 * every declared permission is operationally safe.
858 *
859 * ### Removing a Managed Secret Policy
860 * **Example:** Restore the default of no resource policy
861 * ```diff lang="typescript"
862 * const db = yield* DBInstance("Db", {
863 * engine: "postgres",
864 * dbInstanceClass: "db.t3.micro",
865 * masterUsername: "admin",
866 * manageMasterUserPassword: true,
867 * - masterUserSecretResourcePolicy: readerPolicy,
868 * });
869 * ```
870 *
871 * Omission or removal deletes the resource policy, including external policies
872 * discovered during adoption or unchanged-input drift detection. Identity-based
873 * IAM permissions still apply. The secret, its credentials, and RDS rotation
874 * remain intact. Deployment waits for policy readback before returning; managing
875 * an existing secret also requires `secretsmanager:GetResourcePolicy` and, when
876 * resetting a policy, `secretsmanager:DeleteResourcePolicy`.
877 *
878 * ### Readiness
879 * Deployment waits for an instance ARN and an operational status: `available`
880 * or `storage-optimization`. Storage optimization remains online and can
881 * continue for hours. Missing or pending observations retain the ten-minute
882 * provisioning budget; SDK failures keep their original typed errors rather
883 * than being retried by the readiness loop. Unknown statuses and blue/green
884 * `storage-initialization` remain bounded pending observations, never ready.
885 *
886 * **Example:** Return the ready database's status from a stack
887 * ```typescript
888 * const db = yield* DBInstance("Db", {
889 * engine: "postgres",
890 * dbInstanceClass: "db.t3.micro",
891 * masterUsername: "admin",
892 * manageMasterUserPassword: true,
893 * });
894 * return { status: db.status };
895 * ```
896 *
897 * States requiring intervention, including `stopped`, `storage-full`, and
898 * incompatible or failed configurations, fail with `DBInstanceReadinessBlocked`.
899 * Alchemy does not automatically start a stopped instance. Restore its
900 * operational state and deploy again. Unchanged declarations also check
901 * readiness, while storage, port, and association updates wait for both their
902 * requested values and an operational instance before returning.
903 *
904 * ### Migrations
905 * **Example:** Apply migrations from an Aurora cluster's writer
906 * ```typescript
907 * const cluster = yield* DBCluster("Cluster", {
908 * engine: "aurora-postgresql",
909 * databaseName: "app",
910 * enableHttpEndpoint: true,
911 * manageMasterUserPassword: true,
912 * masterUsername: "app",
913 * });
914 * const writer = yield* DBInstance("Writer", {
915 * dbClusterIdentifier: cluster.dbClusterIdentifier,
916 * dbInstanceClass: "db.serverless",
917 * engine: "aurora-postgresql",
918 * migrations: "./migrations",
919 * });
920 * ```
921 *
922 * Migrations run over the cluster's Data API once the instance is
923 * available, so the deploying machine needs no VPC access. Declare them on
924 * one instance per cluster.
925 *
926 * **Example:** Migrate a publicly reachable instance directly
927 * ```typescript
928 * const db = yield* DBInstance("Db", {
929 * engine: "postgres",
930 * dbInstanceClass: "db.t4g.micro",
931 * allocatedStorage: 20,
932 * dbName: "app",
933 * masterUsername: "app",
934 * manageMasterUserPassword: true,
935 * publiclyAccessible: true,
936 * migrations: "./migrations",
937 * migrationsTransport: "direct",
938 * });
939 * ```
940 *
941 * **Example:** Migrate a private instance through an in-VPC runner
942 * ```typescript
943 * const runner = yield* AWS.RDS.MigrationRunner("MigrationRunner", {
944 * subnetIds: network.privateSubnetIds,
945 * securityGroupIds: [runnerSecurityGroup.groupId],
946 * });
947 * const db = yield* DBInstance("Db", {
948 * engine: "mysql",
949 * dbInstanceClass: "db.t4g.micro",
950 * allocatedStorage: 20,
951 * dbName: "app",
952 * masterUsername: "app",
953 * manageMasterUserPassword: true,
954 * dbSubnetGroupName: subnetGroup.dbSubnetGroupName,
955 * vpcSecurityGroupIds: [databaseSecurityGroup.groupId],
956 * migrations: "./migrations",
957 * migrationsTransport: runner,
958 * });
959 * ```
960 *
961 * ### Monitoring & Logs
962 * **Example:** Enhanced monitoring + log export
963 * ```typescript
964 * const db = yield* DBInstance("Db", {
965 * engine: "postgres",
966 * dbInstanceClass: "db.t3.micro",
967 * allocatedStorage: 20,
968 * monitoringInterval: "60 seconds",
969 * monitoringRoleArn: monitoringRole.roleArn,
970 * enablePerformanceInsights: true,
971 * enableCloudwatchLogsExports: ["postgresql", "upgrade"],
972 * });
973 * ```
974 *
975 * @resource
976 */
977 export const DBInstance = Resource<DBInstance>("AWS.RDS.DBInstance");
978
979 const toTagRecord = (
980 tags: Array<{ Key?: string; Value?: string }> | undefined,
981 ): Record<string, string> =>
982 Object.fromEntries(
983 (tags ?? [])
984 .filter(
985 (tag): tag is { Key: string; Value: string } =>
986 typeof tag.Key === "string" && typeof tag.Value === "string",
987 )
988 .map((tag) => [tag.Key, tag.Value]),
989 );
990
991 /**
992 * Whether two optional master-password fingerprints match, compared by their
993 * underlying (`Redacted`-unwrapped) digest. A missing stored fingerprint
994 * counts as "does not match" so a pre-existing instance sends its password
995 * once, then records the fingerprint for subsequent reconciles.
996 */
997 const sameFingerprint = (
998 a: Redacted.Redacted<string> | undefined,
999 b: Redacted.Redacted<string> | undefined,
1000 ): boolean => a !== undefined && b !== undefined && Redacted.value(a) === Redacted.value(b);
1001
1002 const toAttrs = ({
1003 instance,
1004 tags,
1005 skipFinalSnapshot,
1006 finalDBSnapshotIdentifier,
1007 masterUserPasswordFingerprint,
1008 masterUserSecretResourcePolicy,
1009 migrations,
1010 }: {
1011 instance: rds.DBInstance;
1012 tags: Record<string, string>;
1013 skipFinalSnapshot?: boolean | undefined;
1014 finalDBSnapshotIdentifier?: string | undefined;
1015 masterUserPasswordFingerprint?: Redacted.Redacted<string> | undefined;
1016 masterUserSecretResourcePolicy?: string | undefined;
1017 migrations?: Pick<
1018 DBInstance["Attributes"],
1019 "migrationsDir" | "migrationsTable" | "migrationsHashes"
1020 >;
1021 }): DBInstance["Attributes"] => ({
1022 migrationsDir: migrations?.migrationsDir,
1023 migrationsTable: migrations?.migrationsTable,
1024 migrationsHashes: migrations?.migrationsHashes ?? {},
1025 skipFinalSnapshot,
1026 finalDBSnapshotIdentifier,
1027 masterUserPasswordFingerprint,
1028 dbInstanceIdentifier: instance.DBInstanceIdentifier ?? "",
1029 dbInstanceArn: instance.DBInstanceArn ?? "",
1030 dbClusterIdentifier: instance.DBClusterIdentifier,
1031 endpointAddress: instance.Endpoint?.Address,
1032 endpointPort: instance.Endpoint?.Port,
1033 dbInstanceClass: instance.DBInstanceClass,
1034 engine: instance.Engine,
1035 engineVersion: instance.EngineVersion,
1036 status: instance.DBInstanceStatus,
1037 promotionTier: instance.PromotionTier,
1038 publiclyAccessible: instance.PubliclyAccessible,
1039 dbSubnetGroupName: instance.DBSubnetGroup?.DBSubnetGroupName,
1040 dbParameterGroupNames: (instance.DBParameterGroups ?? []).flatMap((group) =>
1041 group.DBParameterGroupName ? [group.DBParameterGroupName] : [],
1042 ),
1043 dbParameterGroupApplyStatuses: Object.fromEntries(
1044 (instance.DBParameterGroups ?? []).flatMap((group) =>
1045 group.DBParameterGroupName ? [[group.DBParameterGroupName, group.ParameterApplyStatus]] : [],
1046 ),
1047 ),
1048 vpcSecurityGroupIds: (instance.VpcSecurityGroups ?? []).flatMap((group) =>
1049 group.VpcSecurityGroupId ? [group.VpcSecurityGroupId] : [],
1050 ),
1051 vpcSecurityGroupStatuses: Object.fromEntries(
1052 (instance.VpcSecurityGroups ?? []).flatMap((group) =>
1053 group.VpcSecurityGroupId ? [[group.VpcSecurityGroupId, group.Status]] : [],
1054 ),
1055 ),
1056 allocatedStorage: instance.AllocatedStorage,
1057 maxAllocatedStorage: instance.MaxAllocatedStorage,
1058 storageType: instance.StorageType,
1059 iops: instance.Iops,
1060 storageThroughput: instance.StorageThroughput,
1061 multiAZ: instance.MultiAZ,
1062 availabilityZone: instance.AvailabilityZone,
1063 secondaryAvailabilityZone: instance.SecondaryAvailabilityZone,
1064 backupRetentionPeriod: instance.BackupRetentionPeriod,
1065 preferredBackupWindow: instance.PreferredBackupWindow,
1066 preferredMaintenanceWindow: instance.PreferredMaintenanceWindow,
1067 kmsKeyId: instance.KmsKeyId,
1068 storageEncrypted: instance.StorageEncrypted,
1069 caCertificateIdentifier: instance.CACertificateIdentifier,
1070 iamDatabaseAuthenticationEnabled: instance.IAMDatabaseAuthenticationEnabled,
1071 pendingIamDatabaseAuthenticationEnabled:
1072 instance.PendingModifiedValues?.IAMDatabaseAuthenticationEnabled,
1073 performanceInsightsEnabled: instance.PerformanceInsightsEnabled,
1074 monitoringInterval: instance.MonitoringInterval,
1075 enhancedMonitoringResourceArn: instance.EnhancedMonitoringResourceArn,
1076 enabledCloudwatchLogsExports: instance.EnabledCloudwatchLogsExports ?? [],
1077 deletionProtection: instance.DeletionProtection,
1078 autoMinorVersionUpgrade: instance.AutoMinorVersionUpgrade,
1079 dbiResourceId: instance.DbiResourceId,
1080 masterUsername: instance.MasterUsername,
1081 masterUserSecretArn: instance.MasterUserSecret?.SecretArn,
1082 masterUserSecretResourcePolicy,
1083 optionGroupMemberships: (instance.OptionGroupMemberships ?? []).flatMap((membership) =>
1084 membership.OptionGroupName ? [membership.OptionGroupName] : [],
1085 ),
1086 licenseModel: instance.LicenseModel,
1087 dbInstancePort: instance.DbInstancePort,
1088 networkType: instance.NetworkType,
1089 tags,
1090 });
1091
1092 /**
1093 * Compute the CloudWatch Logs export delta. The modify API is delta-shaped
1094 * (`EnableLogTypes`/`DisableLogTypes`), so it must NOT carry the full set.
1095 * Returns `undefined` when there is no change.
1096 */
1097 const logExportDelta = (
1098 observed: string[] | undefined,
1099 desired: string[] | undefined,
1100 ): rds.CloudwatchLogsExportConfiguration | undefined => {
1101 if (desired === undefined) return undefined;
1102 const have = new Set(observed ?? []);
1103 const want = new Set(desired);
1104 const EnableLogTypes = [...want].filter((t) => !have.has(t));
1105 const DisableLogTypes = [...have].filter((t) => !want.has(t));
1106 if (EnableLogTypes.length === 0 && DisableLogTypes.length === 0) {
1107 return undefined;
1108 }
1109 return {
1110 ...(EnableLogTypes.length > 0 ? { EnableLogTypes } : {}),
1111 ...(DisableLogTypes.length > 0 ? { DisableLogTypes } : {}),
1112 };
1113 };
1114
1115 const sameMembers = (desired: readonly string[], observed: readonly (string | undefined)[]) => {
1116 const want = new Set(desired);
1117 const have = new Set(observed);
1118 return want.size === have.size && [...want].every((value) => have.has(value));
1119 };
1120
1121 const clusterOwnsConfiguration = (props: DBInstanceProps, observed?: rds.DBInstance) =>
1122 props.dbClusterIdentifier !== undefined ||
1123 observed?.DBClusterIdentifier !== undefined ||
1124 props.engine.startsWith("aurora") ||
1125 observed?.Engine?.startsWith("aurora") === true;
1126
1127 const securityConfiguration = (props: DBInstanceProps, observed?: rds.DBInstance) => {
1128 const clusterOwned = clusterOwnsConfiguration(props, observed);
1129 const custom =
1130 props.engine.startsWith("custom-") || observed?.Engine?.startsWith("custom-") === true;
1131 const supportsIam = ["postgres", "mysql", "mariadb"].includes(observed?.Engine ?? props.engine);
1132 return {
1133 publiclyAccessible:
1134 clusterOwned && !props.engine.startsWith("aurora") && !observed?.Engine?.startsWith("aurora")
1135 ? undefined
1136 : (props.publiclyAccessible ?? false),
1137 iamAuthentication: clusterOwned
1138 ? undefined
1139 : (props.enableIAMDatabaseAuthentication ?? (supportsIam ? false : undefined)),
1140 deletionProtection: clusterOwned ? undefined : (props.deletionProtection ?? false),
1141 networkType: clusterOwned ? undefined : (props.networkType ?? "IPV4"),
1142 logExports: clusterOwned
1143 ? undefined
1144 : (props.enableCloudwatchLogsExports ?? (custom ? undefined : [])),
1145 };
1146 };
1147
1148 type SecurityConfiguration = ReturnType<typeof securityConfiguration>;
1149
1150 const pendingLogExports = (instance: rds.DBInstance) =>
1151 instance.PendingModifiedValues?.PendingCloudwatchLogsExports;
1152
1153 const effectiveLogExports = (instance: rds.DBInstance) => {
1154 const exports = new Set(instance.EnabledCloudwatchLogsExports ?? []);
1155 for (const log of pendingLogExports(instance)?.LogTypesToDisable ?? []) {
1156 exports.delete(log);
1157 }
1158 for (const log of pendingLogExports(instance)?.LogTypesToEnable ?? []) {
1159 exports.add(log);
1160 }
1161 return [...exports];
1162 };
1163
1164 const iamConverged = (desired: SecurityConfiguration, instance: rds.DBInstance) =>
1165 desired.iamAuthentication === undefined ||
1166 (desired.iamAuthentication === instance.IAMDatabaseAuthenticationEnabled &&
1167 instance.PendingModifiedValues?.IAMDatabaseAuthenticationEnabled === undefined);
1168
1169 const securityConverged = (desired: SecurityConfiguration, instance: rds.DBInstance) =>
1170 iamConverged(desired, instance) &&
1171 (desired.publiclyAccessible === undefined ||
1172 desired.publiclyAccessible === instance.PubliclyAccessible) &&
1173 (desired.deletionProtection === undefined ||
1174 desired.deletionProtection === instance.DeletionProtection) &&
1175 (desired.networkType === undefined || desired.networkType === instance.NetworkType) &&
1176 (desired.logExports === undefined ||
1177 (sameMembers(desired.logExports, instance.EnabledCloudwatchLogsExports ?? []) &&
1178 (pendingLogExports(instance)?.LogTypesToEnable?.length ?? 0) === 0 &&
1179 (pendingLogExports(instance)?.LogTypesToDisable?.length ?? 0) === 0));
1180
1181 class DBInstanceSecurityPending extends Data.TaggedError("DBInstanceSecurityPending")<{
1182 instanceId: string;
1183 }> {
1184 override get message() {
1185 return `DB instance '${this.instanceId}' security configuration did not converge`;
1186 }
1187 }
1188
1189 class InvalidDBInstanceAssociations extends Data.TaggedError("InvalidDBInstanceAssociations")<{
1190 message: string;
1191 }> {}
1192
1193 const resolveAssociations = Effect.fn(function* (
1194 props: DBInstanceProps,
1195 observed?: rds.DBInstance,
1196 ) {
1197 const clusterIdentifier = props.dbClusterIdentifier ?? observed?.DBClusterIdentifier;
1198 const clusterOwned = clusterOwnsConfiguration(props, observed);
1199 const aurora =
1200 props.engine.startsWith("aurora") || observed?.Engine?.startsWith("aurora") === true;
1201 const custom = props.engine.startsWith("custom-");
1202 if (clusterOwned && !aurora) {
1203 if (props.dbParameterGroupName !== undefined) {
1204 return yield* new InvalidDBInstanceAssociations({
1205 message: "Multi-AZ DB cluster associations are managed on the cluster",
1206 });
1207 }
1208 return { dbParameterGroupName: undefined, vpcSecurityGroupIds: undefined };
1209 }
1210 if (
1211 props.engine.startsWith("db2-") &&
1212 props.dbParameterGroupName === undefined &&
1213 (props.licenseModel ?? observed?.LicenseModel ?? "bring-your-own-license") ===
1214 "bring-your-own-license"
1215 ) {
1216 return yield* new InvalidDBInstanceAssociations({
1217 message: "Db2 BYOL requires an explicit parameter group with IBM licensing IDs",
1218 });
1219 }
1220 let dbParameterGroupName = props.dbParameterGroupName;
1221 if (custom && dbParameterGroupName !== undefined) {
1222 return yield* new InvalidDBInstanceAssociations({
1223 message: "RDS Custom does not support DB parameter-group associations",
1224 });
1225 }
1226 if (!custom && dbParameterGroupName === undefined) {
1227 let engineVersion = props.engineVersion ?? observed?.EngineVersion;
1228 if (clusterIdentifier !== undefined) {
1229 engineVersion = (yield* rds.describeDBClusters({
1230 DBClusterIdentifier: clusterIdentifier,
1231 })).DBClusters?.[0]?.EngineVersion;
1232 if (!engineVersion) {
1233 return yield* new InvalidDBInstanceAssociations({
1234 message: "The DB cluster did not return an engine version",
1235 });
1236 }
1237 }
1238 const pages = yield* rds.describeDBEngineVersions
1239 .pages({
1240 Engine: props.engine,
1241 EngineVersion: engineVersion,
1242 DefaultOnly: engineVersion === undefined ? true : undefined,
1243 IncludeAll: engineVersion !== undefined ? true : undefined,
1244 })
1245 .pipe(Stream.runCollect);
1246 const families = new Set(
1247 pages.flatMap((page) =>
1248 (page.DBEngineVersions ?? []).map((version) => version.DBParameterGroupFamily),
1249 ),
1250 );
1251 const family = [...families][0];
1252 if (families.size !== 1 || !family) {
1253 return yield* new InvalidDBInstanceAssociations({
1254 message:
1255 "No unambiguous DB parameter group family; declare engineVersion or dbParameterGroupName",
1256 });
1257 }
1258 dbParameterGroupName = `default.${family}`;
1259 }
1260 if (clusterOwned) return { dbParameterGroupName, vpcSecurityGroupIds: undefined };
1261 let vpcSecurityGroupIds = props.vpcSecurityGroupIds;
1262 if (vpcSecurityGroupIds === undefined) {
1263 const vpcId =
1264 props.dbSubnetGroupName !== undefined
1265 ? (yield* rds.describeDBSubnetGroups({
1266 DBSubnetGroupName: props.dbSubnetGroupName,
1267 })).DBSubnetGroups?.[0]?.VpcId
1268 : (observed?.DBSubnetGroup?.VpcId ??
1269 (yield* ec2.describeVpcs({
1270 Filters: [{ Name: "is-default", Values: ["true"] }],
1271 })).Vpcs?.[0]?.VpcId);
1272 if (!vpcId) {
1273 return yield* new InvalidDBInstanceAssociations({
1274 message:
1275 "No VPC found for the DB instance; declare dbSubnetGroupName or provide a default VPC",
1276 });
1277 }
1278 const groups = yield* ec2.describeSecurityGroups({
1279 Filters: [
1280 { Name: "vpc-id", Values: [vpcId] },
1281 { Name: "group-name", Values: ["default"] },
1282 ],
1283 });
1284 vpcSecurityGroupIds = (groups.SecurityGroups ?? []).flatMap((group) =>
1285 group.GroupId ? [group.GroupId] : [],
1286 );
1287 if (vpcSecurityGroupIds.length !== 1) {
1288 return yield* new InvalidDBInstanceAssociations({
1289 message: `Expected one default security group in VPC '${vpcId}'`,
1290 });
1291 }
1292 }
1293 if (vpcSecurityGroupIds.length === 0) {
1294 return yield* new InvalidDBInstanceAssociations({
1295 message:
1296 "At least one VPC security group is required; omit vpcSecurityGroupIds to select the VPC default group",
1297 });
1298 }
1299 return {
1300 dbParameterGroupName,
1301 vpcSecurityGroupIds: [...new Set(vpcSecurityGroupIds)],
1302 };
1303 });
1304
1305 type Associations = Effect.Success<ReturnType<typeof resolveAssociations>>;
1306
1307 const parameterGroupMatches = (desired: Associations, instance: rds.DBInstance) =>
1308 desired.dbParameterGroupName === undefined ||
1309 sameMembers(
1310 [desired.dbParameterGroupName],
1311 (instance.DBParameterGroups ?? []).map((group) => group.DBParameterGroupName),
1312 );
1313
1314 const securityGroupsMatch = (desired: Associations, instance: rds.DBInstance) =>
1315 desired.vpcSecurityGroupIds === undefined ||
1316 sameMembers(
1317 desired.vpcSecurityGroupIds,
1318 (instance.VpcSecurityGroups ?? []).map((group) => group.VpcSecurityGroupId),
1319 );
1320
1321 const associationsConverged = (desired: Associations, instance: rds.DBInstance) =>
1322 parameterGroupMatches(desired, instance) &&
1323 (desired.dbParameterGroupName === undefined ||
1324 (instance.DBParameterGroups ?? []).every(
1325 (group) =>
1326 group.ParameterApplyStatus === "in-sync" || group.ParameterApplyStatus === "pending-reboot",
1327 )) &&
1328 securityGroupsMatch(desired, instance) &&
1329 (desired.vpcSecurityGroupIds === undefined ||
1330 (instance.VpcSecurityGroups ?? []).every((group) => group.Status === "active"));
1331
1332 class InvalidDBInstancePort extends Data.TaggedError("InvalidDBInstancePort")<{
1333 message: string;
1334 }> {}
1335
1336 const desiredInstancePort = Effect.fn(function* (
1337 props: DBInstanceProps,
1338 observed?: rds.DBInstance,
1339 ) {
1340 if (clusterOwnsConfiguration(props, observed)) {
1341 return undefined;
1342 }
1343 if (props.port !== undefined) {
1344 if (!Number.isInteger(props.port) || props.port < 1150 || props.port > 65535) {
1345 return yield* new InvalidDBInstancePort({
1346 message: "port must be an integer between 1150 and 65535",
1347 });
1348 }
1349 return props.port;
1350 }
1351 if (props.engine === "postgres") return 5432;
1352 if (props.engine === "mysql" || props.engine === "mariadb") return 3306;
1353 if (props.engine.startsWith("oracle-") || props.engine.startsWith("custom-oracle-")) return 1521;
1354 if (props.engine.startsWith("sqlserver-") || props.engine.startsWith("custom-sqlserver-"))
1355 return 1433;
1356 if (props.engine.startsWith("db2-")) return 50000;
1357 return yield* new InvalidDBInstancePort({
1358 message: `Declare port explicitly for engine '${props.engine}'`,
1359 });
1360 });
1361
1362 const portConverged = (instance: rds.DBInstance, port: number | undefined) =>
1363 port === undefined ||
1364 (instance.Endpoint?.Port === port && instance.PendingModifiedValues?.Port === undefined);
1365
1366 class InvalidDBInstanceStorage extends Data.TaggedError("InvalidDBInstanceStorage")<{
1367 message: string;
1368 }> {}
1369
1370 type StorageRequest = Required<
1371 Pick<rds.CreateDBInstanceMessage, "AllocatedStorage" | "StorageType">
1372 > &
1373 Pick<rds.CreateDBInstanceMessage, "Iops" | "StorageThroughput">;
1374
1375 interface DesiredStorage {
1376 request: StorageRequest;
1377 iops: number;
1378 throughput: number;
1379 }
1380
1381 const resolveStorage = Effect.fn(function* (props: DBInstanceProps, allocatedFloor = 0) {
1382 if (props.dbClusterIdentifier || props.engine.startsWith("aurora")) {
1383 if (
1384 props.allocatedStorage !== undefined ||
1385 props.storageType !== undefined ||
1386 props.iops !== undefined ||
1387 props.storageThroughput !== undefined
1388 ) {
1389 return yield* new InvalidDBInstanceStorage({
1390 message: "Configure cluster-owned storage on DBCluster, not DBInstance",
1391 });
1392 }
1393 return undefined;
1394 }
1395 const sqlServer = props.engine.includes("sqlserver-");
1396 const oracle = props.engine.includes("oracle-");
1397 const storageType = props.storageType ?? "gp3";
1398 const provisioned = storageType === "io1" || storageType === "io2";
1399 if (
1400 !["standard", "gp2", "gp3", "io1", "io2"].includes(storageType) ||
1401 (storageType === "standard" && allocatedFloor === 0) ||
1402 (storageType === "gp2" && props.engine.startsWith("db2-"))
1403 ) {
1404 return yield* new InvalidDBInstanceStorage({
1405 message: `Storage type '${storageType}' is not supported for '${props.engine}'`,
1406 });
1407 }
1408 const custom = props.engine.startsWith("custom-");
1409 const minimum = custom
1410 ? 40
1411 : sqlServer
1412 ? 20
1413 : provisioned
1414 ? 100
1415 : storageType === "standard"
1416 ? 5
1417 : 20;
1418 const requested = props.allocatedStorage ?? (provisioned ? 100 : custom ? 40 : 20);
1419 if (!Number.isInteger(requested) || requested <= 0) {
1420 return yield* new InvalidDBInstanceStorage({
1421 message: "allocatedStorage must be a positive integer",
1422 });
1423 }
1424 // An in-place increase must be at least ten percent of the current allocation.
1425 const allocation =
1426 requested > allocatedFloor && allocatedFloor > 0
1427 ? Math.max(requested, Math.ceil((allocatedFloor * 11) / 10))
1428 : Math.max(requested, allocatedFloor);
1429 if (allocation < minimum) {
1430 return yield* new InvalidDBInstanceStorage({
1431 message: `Effective allocated storage must be at least ${minimum} GiB for ${storageType}`,
1432 });
1433 }
1434 const ratioCapacity = Math.max(allocation, props.maxAllocatedStorage ?? 0);
1435 if (storageType !== "gp3") {
1436 if (props.storageThroughput !== undefined || (!provisioned && props.iops !== undefined)) {
1437 return yield* new InvalidDBInstanceStorage({
1438 message: `${storageType} does not support the declared IOPS/throughput settings`,
1439 });
1440 }
1441 const minimumIops = provisioned
1442 ? Math.max(1000, Math.ceil(ratioCapacity * (sqlServer && storageType === "io1" ? 1 : 0.5)))
1443 : 0;
1444 const iops = props.iops ?? minimumIops;
1445 const maximumIops = allocation * (storageType === "io1" ? 50 : 1000);
1446 if (provisioned && (!Number.isInteger(iops) || iops < minimumIops || iops > maximumIops)) {
1447 return yield* new InvalidDBInstanceStorage({
1448 message: `The allocation and autoscaling limit require ${storageType} IOPS between ${minimumIops} and ${maximumIops}`,
1449 });
1450 }
1451 return {
1452 request: {
1453 AllocatedStorage: allocation,
1454 StorageType: storageType,
1455 Iops: provisioned ? iops : undefined,
1456 },
1457 iops,
1458 throughput: 0,
1459 } satisfies DesiredStorage;
1460 }
1461 const striped = !sqlServer && allocation >= (oracle ? 200 : 400);
1462 const configurable = sqlServer || striped;
1463 const baselineIops = striped ? 12000 : 3000;
1464 const baselineThroughput = striped ? 500 : 125;
1465 const minimumIops = Math.max(
1466 baselineIops,
1467 sqlServer ? Math.ceil(ratioCapacity * 0.5) : 0,
1468 (props.storageThroughput ?? baselineThroughput) * 4,
1469 );
1470 const iops = props.iops ?? minimumIops;
1471 const minimumThroughput = Math.max(
1472 baselineThroughput,
1473 ["mysql", "mariadb"].includes(props.engine) ? Math.ceil(iops / 64) : 0,
1474 );
1475 const throughput = props.storageThroughput ?? minimumThroughput;
1476 if (
1477 !Number.isInteger(iops) ||
1478 iops < minimumIops ||
1479 !Number.isInteger(throughput) ||
1480 throughput < minimumThroughput ||
1481 throughput > iops * 0.25 ||
1482 (!configurable && (iops !== baselineIops || throughput !== baselineThroughput))
1483 ) {
1484 return yield* new InvalidDBInstanceStorage({
1485 message: configurable
1486 ? `gp3 requires at least ${minimumIops} IOPS and ${minimumThroughput} MiBps, with throughput <= IOPS / 4`
1487 : `Small ${props.engine} gp3 storage has fixed 3000 IOPS and 125 MiBps`,
1488 });
1489 }
1490 return {
1491 request: {
1492 AllocatedStorage: allocation,
1493 StorageType: storageType,
1494 Iops: configurable ? iops : undefined,
1495 StorageThroughput: configurable ? throughput : undefined,
1496 },
1497 iops,
1498 throughput,
1499 } satisfies DesiredStorage;
1500 });
1501
1502 const hasPendingStorage = (instance: rds.DBInstance) =>
1503 instance.PendingModifiedValues?.AllocatedStorage !== undefined ||
1504 instance.PendingModifiedValues?.StorageType !== undefined ||
1505 instance.PendingModifiedValues?.Iops !== undefined ||
1506 instance.PendingModifiedValues?.StorageThroughput !== undefined;
1507
1508 const storageConverged = (observed: rds.DBInstance, desired: DesiredStorage | undefined): boolean =>
1509 desired === undefined ||
1510 ((observed.AllocatedStorage ?? 0) >= desired.request.AllocatedStorage &&
1511 observed.StorageType === desired.request.StorageType &&
1512 (observed.Iops ?? 0) === desired.iops &&
1513 (observed.StorageThroughput ?? 0) === desired.throughput &&
1514 !hasPendingStorage(observed));
1515
1516 const toStorageConfiguration = Effect.fn(function* (props: DBInstanceProps) {
1517 const supportsAutoscaling =
1518 props.dbClusterIdentifier === undefined &&
1519 !props.engine.startsWith("aurora") &&
1520 !props.engine.startsWith("custom-");
1521 if (!supportsAutoscaling && props.maxAllocatedStorage !== undefined) {
1522 return yield* new InvalidDBInstanceStorage({
1523 message: "maxAllocatedStorage is not supported for cluster members or RDS Custom",
1524 });
1525 }
1526 const maxAllocatedStorage = supportsAutoscaling ? (props.maxAllocatedStorage ?? 0) : undefined;
1527 if (
1528 maxAllocatedStorage !== undefined &&
1529 (!Number.isInteger(maxAllocatedStorage) || maxAllocatedStorage < 0)
1530 ) {
1531 return yield* new InvalidDBInstanceStorage({
1532 message: "maxAllocatedStorage must be a nonnegative integer in GiB",
1533 });
1534 }
1535 return {
1536 allocatedStorage: props.dbClusterIdentifier === undefined ? props.allocatedStorage : undefined,
1537 maxAllocatedStorage,
1538 };
1539 });
1540
1541 type StorageConfiguration = Effect.Success<ReturnType<typeof toStorageConfiguration>>;
1542
1543 const allocationConverged = (desired: StorageConfiguration, observed: rds.DBInstance) =>
1544 desired.allocatedStorage === undefined ||
1545 (observed.AllocatedStorage !== undefined &&
1546 observed.AllocatedStorage >= desired.allocatedStorage);
1547
1548 const autoscalingConverged = (desired: StorageConfiguration, observed: rds.DBInstance) => {
1549 const ceiling = desired.maxAllocatedStorage;
1550 if (ceiling === undefined) return true;
1551 // RDS reports disabled autoscaling as zero; equality also prevents growth.
1552 if (ceiling === 0 || ceiling === observed.AllocatedStorage) {
1553 return (
1554 (observed.MaxAllocatedStorage ?? 0) === 0 ||
1555 observed.MaxAllocatedStorage === observed.AllocatedStorage
1556 );
1557 }
1558 return ceiling === observed.MaxAllocatedStorage;
1559 };
1560
1561 class InvalidDBInstanceSecretPolicy extends Data.TaggedError("InvalidDBInstanceSecretPolicy")<{
1562 message: string;
1563 }> {}
1564
1565 class DBInstanceManagedSecretMissing extends Data.TaggedError("DBInstanceManagedSecretMissing")<{
1566 instanceId: string;
1567 }> {
1568 override get message() {
1569 return `DB instance '${this.instanceId}' has no RDS-managed master secret for its resource policy`;
1570 }
1571 }
1572
1573 class DBInstanceSecretPolicyPending extends Data.TaggedError("DBInstanceSecretPolicyPending")<{
1574 instanceId: string;
1575 }> {
1576 override get message() {
1577 return `DB instance '${this.instanceId}' managed-secret resource policy has not propagated`;
1578 }
1579 }
1580
1581 class DBInstancePending extends Data.TaggedError("DBInstancePending")<{
1582 instanceId: string;
1583 status: string | undefined;
1584 }> {
1585 override get message() {
1586 return `DB instance '${this.instanceId}' is not ready (status: ${this.status ?? "not yet visible"})`;
1587 }
1588 }
1589
1590 class DBInstanceReadinessBlocked extends Data.TaggedError("DBInstanceReadinessBlocked")<{
1591 instanceId: string;
1592 status: string;
1593 }> {
1594 override get message() {
1595 return `DB instance '${this.instanceId}' requires intervention (status: ${this.status})`;
1596 }
1597 }
1598
1599 const blockedStatuses = new Set([
1600 "automation-paused",
1601 "delete-precheck",
1602 "deleted",
1603 "deleting",
1604 "failed",
1605 "inaccessible-encryption-credentials",
1606 "inaccessible-encryption-credentials-recoverable",
1607 "incompatible-create",
1608 "incompatible-network",
1609 "incompatible-option-group",
1610 "incompatible-parameters",
1611 "incompatible-restore",
1612 "insufficient-capacity",
1613 "restore-error",
1614 "stopped",
1615 "stopping",
1616 "storage-full",
1617 "unsupported-configuration",
1618 "upgrade-failed",
1619 ]);
1620
1621 const instanceReady = (
1622 instance: rds.DBInstance | undefined,
1623 ): instance is rds.DBInstance & { DBInstanceArn: string } =>
1624 !!instance?.DBInstanceArn &&
1625 (instance.DBInstanceStatus === "available" ||
1626 instance.DBInstanceStatus === "storage-optimization");
1627
1628 export const DBInstanceProvider = () =>
1629 Provider.effect(
1630 DBInstance,
1631 Effect.gen(function* () {
1632 const toIdentifier = (id: string, props: DBInstanceProps) =>
1633 props.dbInstanceIdentifier
1634 ? Effect.succeed(props.dbInstanceIdentifier)
1635 : createPhysicalName({ id, maxLength: 63 });
1636
1637 const readInstance = Effect.fn(function* (instanceId: string) {
1638 const response = yield* rds
1639 .describeDBInstances({
1640 DBInstanceIdentifier: instanceId,
1641 })
1642 .pipe(Effect.catchTag("DBInstanceNotFoundFault", () => Effect.undefined));
1643 return response?.DBInstances?.[0];
1644 });
1645
1646 const observeReadiness = Effect.fn(function* (instanceId: string) {
1647 const instance = yield* readInstance(instanceId);
1648 const status = instance?.DBInstanceStatus;
1649 if (status !== undefined && blockedStatuses.has(status)) {
1650 return yield* new DBInstanceReadinessBlocked({ instanceId, status });
1651 }
1652 return instance;
1653 });
1654
1655 // Storage optimization is online; provisioning retains its ten-minute budget.
1656 const waitForInstance = Effect.fn(function* (instanceId: string) {
1657 return yield* observeReadiness(instanceId).pipe(
1658 Effect.flatMap((instance) =>
1659 instanceReady(instance)
1660 ? Effect.succeed(instance)
1661 : Effect.fail(
1662 new DBInstancePending({
1663 instanceId,
1664 status: instance?.DBInstanceStatus,
1665 }),
1666 ),
1667 ),
1668 Effect.retry({
1669 while: (error) => error._tag === "DBInstancePending",
1670 schedule: Schedule.max([Schedule.fixed("10 seconds"), Schedule.recurs(60)]),
1671 }),
1672 );
1673 });
1674
1675 // RDS can keep reporting `available` for a few seconds after accepting
1676 // a modify, so `waitForInstance` may return before the previous change
1677 // starts and the next modify reaches a busy instance. Wait it out and
1678 // resend.
1679 const modifyInstance = Effect.fn(function* (
1680 instanceId: string,
1681 request: rds.ModifyDBInstanceMessage,
1682 ) {
1683 return yield* rds.modifyDBInstance(request).pipe(
1684 Effect.catchTag("InvalidDBInstanceStateFault", (error) =>
1685 waitForInstance(instanceId).pipe(Effect.andThen(Effect.fail(error))),
1686 ),
1687 Effect.retry({
1688 while: (error) => error._tag === "InvalidDBInstanceStateFault",
1689 schedule: Schedule.spaced("5 seconds"),
1690 times: 8,
1691 }),
1692 );
1693 });
1694
1695 const waitForSecurity = Effect.fn(function* (
1696 instanceId: string,
1697 desired: SecurityConfiguration,
1698 ) {
1699 const instance = yield* observeReadiness(instanceId).pipe(
1700 Effect.repeat({
1701 schedule: Schedule.min([
1702 Schedule.exponential("5 seconds"),
1703 Schedule.spaced("1 minute"),
1704 ]),
1705 times: 10,
1706 until: (instance) => instanceReady(instance) && securityConverged(desired, instance),
1707 }),
1708 );
1709 if (!instanceReady(instance) || !securityConverged(desired, instance)) {
1710 return yield* new DBInstanceSecurityPending({ instanceId });
1711 }
1712 return instance;
1713 });
1714
1715 const waitForAssociations = Effect.fn(function* (instanceId: string, desired: Associations) {
1716 const instance = yield* observeReadiness(instanceId).pipe(
1717 Effect.flatMap((instance) =>
1718 instance?.DBParameterGroups?.some(
1719 (group) => group.ParameterApplyStatus === "failed-to-apply",
1720 )
1721 ? Effect.fail(
1722 new InvalidDBInstanceAssociations({
1723 message: `DB instance '${instanceId}' parameter group failed to apply`,
1724 }),
1725 )
1726 : Effect.succeed(instance),
1727 ),
1728 Effect.repeat({
1729 schedule: Schedule.min([
1730 Schedule.exponential("5 seconds"),
1731 Schedule.spaced("1 minute"),
1732 ]),
1733 times: 10,
1734 until: (instance) =>
1735 instanceReady(instance) && associationsConverged(desired, instance),
1736 }),
1737 );
1738 if (!instanceReady(instance) || !associationsConverged(desired, instance)) {
1739 return yield* new InvalidDBInstanceAssociations({
1740 message: `DB instance '${instanceId}' associations did not converge`,
1741 });
1742 }
1743 return instance;
1744 });
1745
1746 const waitForPort = Effect.fn(function* (instanceId: string, port: number) {
1747 const instance = yield* observeReadiness(instanceId).pipe(
1748 Effect.repeat({
1749 schedule: Schedule.min([
1750 Schedule.exponential("5 seconds"),
1751 Schedule.spaced("1 minute"),
1752 ]),
1753 times: 10,
1754 until: (instance) => instanceReady(instance) && portConverged(instance, port),
1755 }),
1756 );
1757 if (!instanceReady(instance) || !portConverged(instance, port)) {
1758 return yield* new InvalidDBInstancePort({
1759 message: `DB instance '${instanceId}' listener did not converge (status: ${instance?.DBInstanceStatus}, desired: ${port}, observed: ${instance?.Endpoint?.Port}, pending: ${instance?.PendingModifiedValues?.Port})`,
1760 });
1761 }
1762 return instance;
1763 });
1764
1765 const waitForStorage = Effect.fn(function* (
1766 instanceId: string,
1767 converged: (instance: rds.DBInstance) => boolean,
1768 ) {
1769 // RDS can remain available while an accepted storage resize is pending.
1770 const instance = yield* observeReadiness(instanceId).pipe(
1771 Effect.repeat({
1772 schedule: Schedule.min([
1773 Schedule.exponential("5 seconds"),
1774 Schedule.spaced("1 minute"),
1775 ]),
1776 times: 10,
1777 until: (instance) => instanceReady(instance) && converged(instance),
1778 }),
1779 );
1780 if (!instanceReady(instance) || !converged(instance)) {
1781 return yield* new InvalidDBInstanceStorage({
1782 message: `DB instance '${instanceId}' storage did not converge (status: ${instance?.DBInstanceStatus}, allocated: ${instance?.AllocatedStorage}, maximum: ${instance?.MaxAllocatedStorage}, pending allocation: ${instance?.PendingModifiedValues?.AllocatedStorage})`,
1783 });
1784 }
1785 return instance;
1786 });
1787
1788 // ValidateResourcePolicy is authorized like PutResourcePolicy on its
1789 // target; without a SecretId the target is `*`, so an identity scoped to
1790 // the instance's own secret ARN is denied. Name the known secret.
1791 const validateMasterSecretPolicy = Effect.fn(function* (
1792 policy: PolicyDocument | undefined,
1793 secretArn?: string,
1794 ) {
1795 if (policy === undefined) return;
1796 const validation = yield* secretsmanager.validateResourcePolicy({
1797 ...(secretArn === undefined ? {} : { SecretId: secretArn }),
1798 ResourcePolicy: stringifyPolicyDocument(policy),
1799 });
1800 if (validation.PolicyValidationPassed !== true) {
1801 return yield* new InvalidDBInstanceSecretPolicy({
1802 message: `Managed-secret resource policy validation failed: ${(validation.ValidationErrors ?? []).map((error) => `${error.CheckName}: ${error.ErrorMessage}`).join("; ")}`,
1803 });
1804 }
1805 });
1806
1807 const readMasterSecretPolicy = Effect.fn(function* (secretArn: string) {
1808 const observed = yield* secretsmanager.getResourcePolicy({
1809 SecretId: secretArn,
1810 });
1811 return observed.ResourcePolicy === undefined
1812 ? undefined
1813 : normalizePolicyDocument(observed.ResourcePolicy);
1814 });
1815
1816 const readObservedSecretPolicy = (instance: rds.DBInstance) =>
1817 instance.MasterUserSecret?.SecretArn === undefined ||
1818 instance.DBClusterIdentifier !== undefined
1819 ? Effect.undefined
1820 : readMasterSecretPolicy(instance.MasterUserSecret.SecretArn).pipe(
1821 Effect.retry({
1822 while: (error) => error._tag === "ResourceNotFoundException",
1823 schedule: Schedule.fixed("5 seconds"),
1824 times: 10,
1825 }),
1826 );
1827
1828 const reconcileMasterSecretPolicy = Effect.fn(function* (
1829 instanceId: string,
1830 instance: rds.DBInstance,
1831 policy: PolicyDocument | undefined,
1832 ) {
1833 if (instance.DBClusterIdentifier !== undefined) {
1834 return { instance, policy: undefined };
1835 }
1836 if (instance.MasterUserSecret?.SecretArn === undefined && policy !== undefined) {
1837 instance = yield* readInstance(instanceId).pipe(
1838 Effect.flatMap((current) =>
1839 current?.MasterUserSecret?.SecretArn === undefined
1840 ? Effect.fail(new DBInstanceManagedSecretMissing({ instanceId }))
1841 : Effect.succeed(current),
1842 ),
1843 Effect.retry({
1844 while: (error) => error._tag === "DBInstanceManagedSecretMissing",
1845 schedule: Schedule.fixed("5 seconds"),
1846 times: 10,
1847 }),
1848 );
1849 }
1850 const secretArn = instance.MasterUserSecret?.SecretArn;
1851 if (secretArn === undefined) return { instance, policy: undefined };
1852 const desired = policy === undefined ? undefined : normalizePolicyDocument(policy);
1853 const observed = yield* readObservedSecretPolicy(instance);
1854 if (observed === desired) return { instance, policy: observed };
1855 const writePolicy =
1856 policy === undefined
1857 ? secretsmanager.deleteResourcePolicy({ SecretId: secretArn })
1858 : secretsmanager.putResourcePolicy({
1859 SecretId: secretArn,
1860 ResourcePolicy: stringifyPolicyDocument(policy),
1861 BlockPublicPolicy: true,
1862 });
1863 yield* writePolicy.pipe(
1864 Effect.retry({
1865 while: (error) => error._tag === "ResourceNotFoundException",
1866 schedule: Schedule.fixed("5 seconds"),
1867 times: 10,
1868 }),
1869 );
1870 // A missing secret is not evidence that its policy has been removed.
1871 const applied = yield* readMasterSecretPolicy(secretArn).pipe(
1872 Effect.flatMap((actual) =>
1873 actual === desired
1874 ? Effect.succeed(actual)
1875 : Effect.fail(new DBInstanceSecretPolicyPending({ instanceId })),
1876 ),
1877 Effect.retry({
1878 while: (error) =>
1879 error._tag === "DBInstanceSecretPolicyPending" ||
1880 error._tag === "ResourceNotFoundException",
1881 schedule: Schedule.fixed("5 seconds"),
1882 times: 10,
1883 }),
1884 );
1885 return { instance, policy: applied };
1886 });
1887
1888 return {
1889 stables: ["dbInstanceArn", "dbInstanceIdentifier"],
1890 // Pattern (a) AWS account/region collection: `describeDBInstances` is
1891 // paginated (items: "DBInstances") and returns each instance's
1892 // `TagList` inline, so we hydrate directly into the same shape `read`
1893 // produces — no per-item tag fetch needed. An empty/no-instances
1894 // account simply yields no pages. `DBInstanceNotFoundFault` is in the
1895 // op's typed error union; treat a stray one as "nothing to list".
1896 list: () =>
1897 rds.describeDBInstances.pages({}).pipe(
1898 Stream.runCollect,
1899 Effect.map((chunk) =>
1900 Array.from(chunk).flatMap((page) =>
1901 (page.DBInstances ?? [])
1902 .filter(
1903 (
1904 instance,
1905 ): instance is typeof instance & {
1906 DBInstanceArn: string;
1907 } => instance.DBInstanceArn != null,
1908 )
1909 .map((instance) =>
1910 toAttrs({
1911 instance,
1912 tags: toTagRecord(instance.TagList),
1913 }),
1914 ),
1915 ),
1916 ),
1917 Effect.catchTag("DBInstanceNotFoundFault", () =>
1918 Effect.succeed([] as DBInstance["Attributes"][]),
1919 ),
1920 ),
1921 diff: Effect.fn(function* ({ id, olds, news, output }) {
1922 if (!isResolved(news)) return undefined;
1923 yield* validateMasterSecretPolicy(
1924 news.masterUserSecretResourcePolicy,
1925 output?.masterUserSecretArn,
1926 );
1927 if (
1928 (yield* toIdentifier(id, olds ?? ({} as DBInstanceProps))) !==
1929 (yield* toIdentifier(id, news))
1930 ) {
1931 return { action: "replace" } as const;
1932 }
1933 // Immutable props — any change forces a fresh instance.
1934 if (
1935 olds !== undefined &&
1936 (olds.engine !== news.engine ||
1937 olds.dbName !== news.dbName ||
1938 olds.masterUsername !== news.masterUsername ||
1939 olds.availabilityZone !== news.availabilityZone ||
1940 olds.storageEncrypted !== news.storageEncrypted ||
1941 olds.kmsKeyId !== news.kmsKeyId ||
1942 olds.dbSubnetGroupName !== news.dbSubnetGroupName)
1943 ) {
1944 return { action: "replace" } as const;
1945 }
1946 const storage = yield* toStorageConfiguration(news);
1947 if (output !== undefined) {
1948 const instance = yield* readInstance(output.dbInstanceIdentifier);
1949 if (!instance?.DBInstanceArn) {
1950 return { action: "update", stables: [] } as const;
1951 }
1952 // The identifier names a different physical instance than the one
1953 // recorded, e.g. after a point-in-time restore renamed into place.
1954 // Nothing in the props changed, but the attributes did: reconcile
1955 // re-reads the instance so dependents see the new one.
1956 if (instance.DbiResourceId !== output.dbiResourceId) {
1957 return { action: "update" } as const;
1958 }
1959 if (!instanceReady(instance)) {
1960 return { action: "update" } as const;
1961 }
1962 const port = yield* desiredInstancePort(news, instance);
1963 const associations = yield* resolveAssociations(news, instance);
1964 const desiredStorage = yield* resolveStorage(news, instance.AllocatedStorage);
1965 if (
1966 !storageConverged(instance, desiredStorage) ||
1967 !autoscalingConverged(storage, instance) ||
1968 !portConverged(instance, port) ||
1969 !associationsConverged(associations, instance) ||
1970 !securityConverged(securityConfiguration(news, instance), instance) ||
1971 !Object.hasOwn(output, "vpcSecurityGroupStatuses") ||
1972 (news.masterUserSecretResourcePolicy !== undefined &&
1973 instance.MasterUserSecret?.SecretArn === undefined) ||
1974 (news.masterUserSecretResourcePolicy === undefined
1975 ? undefined
1976 : normalizePolicyDocument(news.masterUserSecretResourcePolicy)) !==
1977 (yield* readObservedSecretPolicy(instance))
1978 ) {
1979 return { action: "update" } as const;
1980 }
1981 }
1982 // After observation, so a vanished instance keeps `stables: []`.
1983 if (yield* diffMigrations({ news, output })) {
1984 return { action: "update" } as const;
1985 }
1986 }),
1987 read: Effect.fn(function* ({ id, olds, output }) {
1988 const identifier =
1989 output?.dbInstanceIdentifier ??
1990 (yield* toIdentifier(id, olds ?? { dbInstanceClass: "", engine: "" }));
1991 const instance = yield* readInstance(identifier);
1992 if (!instance?.DBInstanceArn) {
1993 return undefined;
1994 }
1995 return toAttrs({
1996 instance,
1997 tags: toTagRecord(instance.TagList),
1998 // Not observable from AWS — carry the stored deletion behavior
1999 // and last-sent fingerprint forward so a refresh drops neither.
2000 skipFinalSnapshot: output?.skipFinalSnapshot,
2001 finalDBSnapshotIdentifier: output?.finalDBSnapshotIdentifier,
2002 masterUserPasswordFingerprint: output?.masterUserPasswordFingerprint,
2003 masterUserSecretResourcePolicy: yield* readObservedSecretPolicy(instance),
2004 migrations: output,
2005 });
2006 }),
2007 reconcile: Effect.fn(function* ({ id, news, output, session }) {
2008 yield* validateMasterSecretPolicy(
2009 news.masterUserSecretResourcePolicy,
2010 output?.masterUserSecretArn,
2011 );
2012 const identifier = output?.dbInstanceIdentifier ?? (yield* toIdentifier(id, news));
2013 // AWS never returns the master password, so there is nothing to
2014 // observe-and-diff — fingerprint the configured value instead and
2015 // only send `MasterUserPassword` when the fingerprint changed.
2016 // Without this, every reconcile of an instance whose props carry a
2017 // password triggers a live `resetting-master-credentials` modify.
2018 // The hash is salted with the (stable) instance identifier so the
2019 // persisted digest is not rainbow-table-lookupable, and kept
2020 // `Redacted` so it never leaks in plaintext through state/logs.
2021 const passwordFingerprint =
2022 news.masterUserPassword !== undefined
2023 ? Redacted.make(
2024 yield* sha256(`${identifier}:${Redacted.value(news.masterUserPassword)}`),
2025 )
2026 : undefined;
2027 const internalTags = yield* createInternalTags(id);
2028 const desiredTags = { ...internalTags, ...news.tags };
2029 // Duration props → the exact wire units the RDS API expects.
2030 const backupRetentionDays = toWireDays(news.backupRetentionPeriod);
2031 const performanceInsightsRetentionDays = toWireDays(
2032 news.performanceInsightsRetentionPeriod,
2033 );
2034 const monitoringIntervalSeconds = toWireSeconds(news.monitoringInterval);
2035
2036 const storage = yield* toStorageConfiguration(news);
2037 // Observe — fetch live instance state.
2038 let observed = yield* observeReadiness(identifier);
2039 if (observed?.DBInstanceArn) {
2040 observed = yield* waitForInstance(identifier);
2041 }
2042 if (
2043 news.masterUserSecretResourcePolicy !== undefined &&
2044 (news.dbClusterIdentifier !== undefined ||
2045 news.engine.startsWith("custom-") ||
2046 observed?.DBClusterIdentifier !== undefined ||
2047 news.manageMasterUserPassword === false ||
2048 (!observed?.MasterUserSecret?.SecretArn && !news.manageMasterUserPassword))
2049 ) {
2050 return yield* new InvalidDBInstanceSecretPolicy({
2051 message:
2052 "A master secret resource policy requires an instance-managed secret; enable manageMasterUserPassword on a standalone DBInstance",
2053 });
2054 }
2055 let security = securityConfiguration(news, observed);
2056 let port = yield* desiredInstancePort(news, observed);
2057 let associations = yield* resolveAssociations(news, observed);
2058 let desiredStorage = yield* resolveStorage(news, observed?.AllocatedStorage);
2059
2060 // Ensure — create if missing. Tolerate
2061 // `DBInstanceAlreadyExistsFault` as a race with a peer reconciler.
2062 let created = false;
2063 if (!observed?.DBInstanceArn) {
2064 created = yield* rds
2065 .createDBInstance({
2066 DBInstanceIdentifier: identifier,
2067 DBClusterIdentifier: news.dbClusterIdentifier,
2068 DBInstanceClass: news.dbInstanceClass,
2069 Engine: news.engine,
2070 EngineVersion: news.engineVersion,
2071 DBName: news.dbName,
2072 ...desiredStorage?.request,
2073 // Omission at creation leaves autoscaling disabled.
2074 MaxAllocatedStorage: storage.maxAllocatedStorage || undefined,
2075 MasterUsername: news.masterUsername,
2076 MasterUserPassword: news.masterUserPassword,
2077 ManageMasterUserPassword: news.manageMasterUserPassword,
2078 MasterUserSecretKmsKeyId: news.masterUserSecretKmsKeyId,
2079 Port: port,
2080 MultiAZ: news.multiAZ,
2081 AvailabilityZone: news.availabilityZone,
2082 BackupRetentionPeriod: backupRetentionDays,
2083 PreferredBackupWindow: news.preferredBackupWindow,
2084 PreferredMaintenanceWindow: news.preferredMaintenanceWindow,
2085 DBSubnetGroupName: news.dbSubnetGroupName,
2086 DBParameterGroupName: associations.dbParameterGroupName,
2087 OptionGroupName: news.optionGroupName,
2088 LicenseModel: news.licenseModel,
2089 StorageEncrypted: news.storageEncrypted,
2090 KmsKeyId: news.kmsKeyId,
2091 CACertificateIdentifier: news.caCertificateIdentifier,
2092 EnableIAMDatabaseAuthentication: security.iamAuthentication,
2093 EnablePerformanceInsights: news.enablePerformanceInsights,
2094 PerformanceInsightsKMSKeyId: news.performanceInsightsKMSKeyId,
2095 PerformanceInsightsRetentionPeriod: performanceInsightsRetentionDays,
2096 MonitoringInterval: monitoringIntervalSeconds,
2097 MonitoringRoleArn: news.monitoringRoleArn,
2098 EnableCloudwatchLogsExports: security.logExports,
2099 DeletionProtection: security.deletionProtection,
2100 NetworkType: security.networkType,
2101 VpcSecurityGroupIds: associations.vpcSecurityGroupIds,
2102 PubliclyAccessible: security.publiclyAccessible,
2103 PromotionTier: news.promotionTier,
2104 AutoMinorVersionUpgrade: news.autoMinorVersionUpgrade,
2105 CopyTagsToSnapshot: news.copyTagsToSnapshot,
2106 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
2107 Key,
2108 Value,
2109 })),
2110 })
2111 .pipe(
2112 Effect.as(true),
2113 Effect.catchTag("DBInstanceAlreadyExistsFault", () => Effect.succeed(false)),
2114 );
2115
2116 observed = yield* waitForInstance(identifier);
2117 }
2118 if (!created) {
2119 if (hasPendingStorage(observed)) {
2120 observed = yield* waitForStorage(
2121 identifier,
2122 (instance) => !hasPendingStorage(instance),
2123 );
2124 }
2125 desiredStorage = yield* resolveStorage(news, observed.AllocatedStorage);
2126
2127 associations = yield* resolveAssociations(news, observed);
2128
2129 // syncCoreSettings — single `modifyDBInstance` carrying scalar
2130 // in-place fields. Only emit a field when the desired value differs
2131 // from the observed cloud state, to avoid spurious
2132 // `PendingModifiedValues`. The listener port is synchronized below.
2133 const core: rds.ModifyDBInstanceMessage = {
2134 DBInstanceIdentifier: identifier,
2135 ApplyImmediately: true,
2136 };
2137 let coreDirty = false;
2138 const setIf = <K extends keyof rds.ModifyDBInstanceMessage>(
2139 key: K,
2140 desired: rds.ModifyDBInstanceMessage[K] | undefined,
2141 observedValue: unknown,
2142 ) => {
2143 if (desired !== undefined && desired !== observedValue) {
2144 core[key] = desired;
2145 coreDirty = true;
2146 }
2147 };
2148 setIf("DBInstanceClass", news.dbInstanceClass, observed.DBInstanceClass); // prettier-ignore
2149 setIf("EngineVersion", news.engineVersion, observed.EngineVersion);
2150 if (desiredStorage && !storageConverged(observed, desiredStorage)) {
2151 Object.assign(core, desiredStorage.request);
2152 core.MaxAllocatedStorage =
2153 storage.maxAllocatedStorage === 0
2154 ? desiredStorage.request.AllocatedStorage
2155 : storage.maxAllocatedStorage;
2156 coreDirty = true;
2157 }
2158 setIf("MultiAZ", news.multiAZ, observed.MultiAZ);
2159 setIf("BackupRetentionPeriod", backupRetentionDays, observed.BackupRetentionPeriod); // prettier-ignore
2160 setIf("PreferredBackupWindow", news.preferredBackupWindow, observed.PreferredBackupWindow); // prettier-ignore
2161 setIf("PreferredMaintenanceWindow", news.preferredMaintenanceWindow, observed.PreferredMaintenanceWindow); // prettier-ignore
2162 setIf("OptionGroupName", news.optionGroupName, undefined);
2163 setIf("LicenseModel", news.licenseModel, observed.LicenseModel);
2164 setIf("CACertificateIdentifier", news.caCertificateIdentifier, observed.CACertificateIdentifier); // prettier-ignore
2165 setIf("EnablePerformanceInsights", news.enablePerformanceInsights, observed.PerformanceInsightsEnabled); // prettier-ignore
2166 setIf("PerformanceInsightsKMSKeyId", news.performanceInsightsKMSKeyId, observed.PerformanceInsightsKMSKeyId); // prettier-ignore
2167 setIf("PerformanceInsightsRetentionPeriod", performanceInsightsRetentionDays, observed.PerformanceInsightsRetentionPeriod); // prettier-ignore
2168 setIf("MonitoringInterval", monitoringIntervalSeconds, observed.MonitoringInterval); // prettier-ignore
2169 setIf("MonitoringRoleArn", news.monitoringRoleArn, observed.MonitoringRoleArn); // prettier-ignore
2170 if (!parameterGroupMatches(associations, observed)) {
2171 core.DBParameterGroupName = associations.dbParameterGroupName;
2172 coreDirty = true;
2173 }
2174 setIf("PromotionTier", news.promotionTier, observed.PromotionTier);
2175 setIf("AutoMinorVersionUpgrade", news.autoMinorVersionUpgrade, observed.AutoMinorVersionUpgrade); // prettier-ignore
2176 setIf("CopyTagsToSnapshot", news.copyTagsToSnapshot, observed.CopyTagsToSnapshot); // prettier-ignore
2177 if (!securityGroupsMatch(associations, observed)) {
2178 if (news.engine.startsWith("custom-")) {
2179 return yield* new InvalidDBInstanceAssociations({
2180 message:
2181 "Changing existing RDS Custom security-group associations through ModifyDBInstance is not supported",
2182 });
2183 }
2184 core.VpcSecurityGroupIds = associations.vpcSecurityGroupIds;
2185 coreDirty = true;
2186 }
2187 if (news.allowMajorVersionUpgrade) {
2188 core.AllowMajorVersionUpgrade = true;
2189 }
2190 // syncMasterPassword — rotation or explicit password update. The
2191 // explicit branch is fingerprint-guarded: send only when the
2192 // configured password actually changed (or was never
2193 // fingerprinted — pre-existing state sends once, then records).
2194 if (
2195 news.manageMasterUserPassword &&
2196 !observed.MasterUserSecret?.SecretArn &&
2197 !observed.DBClusterIdentifier
2198 ) {
2199 core.ManageMasterUserPassword = true;
2200 core.MasterUserSecretKmsKeyId = news.masterUserSecretKmsKeyId;
2201 coreDirty = true;
2202 }
2203 if (news.manageMasterUserPassword && news.rotateMasterUserPassword) {
2204 core.RotateMasterUserPassword = true;
2205 coreDirty = true;
2206 } else if (
2207 news.masterUserPassword !== undefined &&
2208 !sameFingerprint(passwordFingerprint, output?.masterUserPasswordFingerprint)
2209 ) {
2210 core.MasterUserPassword = news.masterUserPassword;
2211 coreDirty = true;
2212 }
2213 if (coreDirty) {
2214 yield* modifyInstance(identifier, core);
2215 observed = yield* waitForInstance(identifier);
2216 if (
2217 core.DBParameterGroupName !== undefined ||
2218 core.VpcSecurityGroupIds !== undefined
2219 ) {
2220 observed = yield* waitForAssociations(identifier, associations);
2221 }
2222 if (core.AllocatedStorage !== undefined) {
2223 observed = yield* waitForStorage(identifier, (instance) =>
2224 storageConverged(instance, desiredStorage),
2225 );
2226 }
2227 }
2228 }
2229
2230 if (hasPendingStorage(observed)) {
2231 observed = yield* waitForStorage(
2232 identifier,
2233 (instance) => !hasPendingStorage(instance),
2234 );
2235 }
2236 desiredStorage = yield* resolveStorage(news, observed.AllocatedStorage);
2237 if (desiredStorage && !storageConverged(observed, desiredStorage)) {
2238 yield* modifyInstance(identifier, {
2239 DBInstanceIdentifier: identifier,
2240 ...desiredStorage.request,
2241 MaxAllocatedStorage:
2242 storage.maxAllocatedStorage === 0
2243 ? desiredStorage.request.AllocatedStorage
2244 : storage.maxAllocatedStorage,
2245 ApplyImmediately: true,
2246 });
2247 observed = yield* waitForInstance(identifier);
2248 observed = yield* waitForStorage(identifier, (instance) =>
2249 storageConverged(instance, desiredStorage),
2250 );
2251 }
2252 if (!autoscalingConverged(storage, observed)) {
2253 const ceiling =
2254 storage.maxAllocatedStorage === 0
2255 ? observed.AllocatedStorage
2256 : storage.maxAllocatedStorage;
2257 if (ceiling === undefined) {
2258 return yield* new InvalidDBInstanceStorage({
2259 message: "RDS did not return the allocated storage needed to disable autoscaling",
2260 });
2261 }
2262 // AWS disables autoscaling when the ceiling equals live allocation.
2263 yield* modifyInstance(identifier, {
2264 DBInstanceIdentifier: identifier,
2265 MaxAllocatedStorage: ceiling,
2266 ApplyImmediately: true,
2267 });
2268 observed = yield* waitForStorage(
2269 identifier,
2270 (instance) =>
2271 allocationConverged(storage, instance) && autoscalingConverged(storage, instance),
2272 );
2273 }
2274
2275 port = yield* desiredInstancePort(news, observed);
2276 if (port !== undefined && !portConverged(observed, port)) {
2277 if (observed.PendingModifiedValues?.Port !== port) {
2278 if (news.engine.startsWith("custom-")) {
2279 return yield* new InvalidDBInstancePort({
2280 message:
2281 "Changing an existing RDS Custom listener through ModifyDBInstance is not supported",
2282 });
2283 }
2284 // Port changes restart immediately without applying unrelated pending settings.
2285 yield* modifyInstance(identifier, {
2286 DBInstanceIdentifier: identifier,
2287 DBPortNumber: port,
2288 ApplyImmediately: false,
2289 });
2290 }
2291 observed = yield* waitForPort(identifier, port);
2292 }
2293
2294 associations = yield* resolveAssociations(news, observed);
2295 if (!associationsConverged(associations, observed)) {
2296 const parameterChanged = !parameterGroupMatches(associations, observed);
2297 const securityChanged = !securityGroupsMatch(associations, observed);
2298 if (securityChanged && news.engine.startsWith("custom-")) {
2299 return yield* new InvalidDBInstanceAssociations({
2300 message:
2301 "Changing existing RDS Custom security-group associations through ModifyDBInstance is not supported",
2302 });
2303 }
2304 if (parameterChanged || securityChanged) {
2305 yield* modifyInstance(identifier, {
2306 DBInstanceIdentifier: identifier,
2307 DBParameterGroupName: parameterChanged
2308 ? associations.dbParameterGroupName
2309 : undefined,
2310 VpcSecurityGroupIds: securityChanged ? associations.vpcSecurityGroupIds : undefined,
2311 ApplyImmediately: true,
2312 });
2313 }
2314 observed = yield* waitForAssociations(identifier, associations);
2315 }
2316
2317 security = securityConfiguration(news, observed);
2318 const iamPending = observed.PendingModifiedValues?.IAMDatabaseAuthenticationEnabled;
2319 const iamChanged = !iamConverged(security, observed);
2320 const networkChanged =
2321 security.networkType !== undefined && security.networkType !== observed.NetworkType;
2322 if (iamChanged || networkChanged) {
2323 // IAM and network changes honor maintenance scheduling. AWS cannot
2324 // selectively apply one queued change without applying the rest.
2325 yield* modifyInstance(identifier, {
2326 DBInstanceIdentifier: identifier,
2327 EnableIAMDatabaseAuthentication:
2328 iamChanged && iamPending !== security.iamAuthentication
2329 ? security.iamAuthentication
2330 : undefined,
2331 NetworkType: networkChanged ? security.networkType : undefined,
2332 ApplyImmediately: true,
2333 });
2334 observed = yield* waitForInstance(identifier);
2335 }
2336
2337 const publicChanged =
2338 security.publiclyAccessible !== undefined &&
2339 security.publiclyAccessible !== observed.PubliclyAccessible;
2340 const protectionChanged =
2341 security.deletionProtection !== undefined &&
2342 security.deletionProtection !== observed.DeletionProtection;
2343 const logDelta = logExportDelta(effectiveLogExports(observed), security.logExports);
2344 if (publicChanged || protectionChanged || logDelta) {
2345 // These fields apply immediately even with false; leave unrelated
2346 // maintenance-window changes queued rather than flushing them.
2347 yield* modifyInstance(identifier, {
2348 DBInstanceIdentifier: identifier,
2349 PubliclyAccessible: publicChanged ? security.publiclyAccessible : undefined,
2350 DeletionProtection: protectionChanged ? security.deletionProtection : undefined,
2351 CloudwatchLogsExportConfiguration: logDelta,
2352 ApplyImmediately: false,
2353 });
2354 }
2355 observed = yield* waitForSecurity(identifier, security);
2356
2357 const dbInstanceArn = observed.DBInstanceArn ?? "";
2358
2359 // Sync tags — diff observed cloud tags against desired.
2360 const observedTags = toTagRecord(observed.TagList);
2361 const { removed, upsert } = diffTags(observedTags, desiredTags);
2362 if (upsert.length > 0 && dbInstanceArn) {
2363 yield* rds.addTagsToResource({
2364 ResourceName: dbInstanceArn,
2365 Tags: upsert,
2366 });
2367 }
2368 if (removed.length > 0 && dbInstanceArn) {
2369 yield* rds.removeTagsFromResource({
2370 ResourceName: dbInstanceArn,
2371 TagKeys: removed,
2372 });
2373 }
2374
2375 const managedSecret = yield* reconcileMasterSecretPolicy(
2376 identifier,
2377 observed,
2378 news.masterUserSecretResourcePolicy,
2379 );
2380 // Sync migrations — the shared pipeline skips already-applied ones.
2381 const migrationsInput = migrationsInputOf(news);
2382 const migrations = migrationsInput
2383 ? yield* runDBInstanceMigrations({
2384 instance: managedSecret.instance,
2385 input: migrationsInput,
2386 stamped: stampedOf(output),
2387 transport: news.migrationsTransport,
2388 secretArn: news.migrationsSecretArn,
2389 credentials:
2390 news.masterUsername && news.masterUserPassword
2391 ? { username: news.masterUsername, password: news.masterUserPassword }
2392 : undefined,
2393 })
2394 : undefined;
2395
2396 yield* session.note(dbInstanceArn || identifier);
2397 return toAttrs({
2398 instance: managedSecret.instance,
2399 tags: desiredTags,
2400 skipFinalSnapshot: news.skipFinalSnapshot,
2401 finalDBSnapshotIdentifier: news.finalDBSnapshotIdentifier,
2402 masterUserPasswordFingerprint: passwordFingerprint,
2403 masterUserSecretResourcePolicy: managedSecret.policy,
2404 migrations: migrationsAttrs({ input: migrationsInput, run: migrations, output }),
2405 });
2406 }),
2407 delete: Effect.fn(function* ({ output }) {
2408 // Default preserves the existing behavior (no final snapshot). When
2409 // the resource was declared with `skipFinalSnapshot: false`, take
2410 // one — timestamped by default so repeated destroy/create cycles
2411 // never collide on snapshot names.
2412 const skipFinalSnapshot = output.skipFinalSnapshot ?? true;
2413 const finalDBSnapshotIdentifier = skipFinalSnapshot
2414 ? undefined
2415 : (output.finalDBSnapshotIdentifier ??
2416 (yield* Effect.sync(
2417 () =>
2418 `${output.dbInstanceIdentifier}-final-${new Date()
2419 .toISOString()
2420 .replaceAll(/[:.]/g, "-")
2421 .toLowerCase()}`,
2422 )));
2423 yield* rds
2424 .deleteDBInstance({
2425 DBInstanceIdentifier: output.dbInstanceIdentifier,
2426 SkipFinalSnapshot: skipFinalSnapshot,
2427 FinalDBSnapshotIdentifier: finalDBSnapshotIdentifier,
2428 })
2429 .pipe(Effect.catchTag("DBInstanceNotFoundFault", () => Effect.void));
2430 // Block until the instance is fully gone. RDS deletion is async; if we
2431 // return while it is still `deleting`, a dependent (e.g. a
2432 // DBSubnetGroup or VPC) is torn down next and AWS rejects it with
2433 // `InvalidDBSubnetGroupStateFault: ... still using it`.
2434 yield* Effect.repeat(
2435 rds
2436 .describeDBInstances({
2437 DBInstanceIdentifier: output.dbInstanceIdentifier,
2438 })
2439 .pipe(
2440 Effect.as(true),
2441 Effect.catchTag("DBInstanceNotFoundFault", () => Effect.succeed(false)),
2442 ),
2443 {
2444 schedule: Schedule.max([
2445 Schedule.fixed("15 seconds"),
2446 // A final snapshot serializes before the delete, so give
2447 // that path a larger budget than the plain-delete wait.
2448 Schedule.recurs(skipFinalSnapshot ? 40 : 80),
2449 ]),
2450 until: (exists) => exists === false,
2451 },
2452 ).pipe(Effect.catch(() => Effect.void));
2453 // RDS creates `/aws/rds/instance/<id>/<logType>` for every
2454 // `enableCloudwatchLogsExports` type and never deletes them.
2455 yield* reapLogGroupsByPrefix(
2456 `/aws/rds/instance/${output.dbInstanceIdentifier.toLowerCase()}/`,
2457 );
2458 }),
2459 };
2460 }),
2461 );