@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, 06:00 UTC

main
ts 889 lines 32.9 KB
Raw
1 import * as rds from "@distilled.cloud/aws/rds";
2 import * as secretsmanager from "@distilled.cloud/aws/secrets-manager";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { createInternalTags, diffTags } from "alchemy/Tags";
8 import { toWireDays, toWireSeconds } from "alchemy/Util/Duration";
9 import * as Data from "effect/Data";
10 import type * as Duration from "effect/Duration";
11 import * as Effect from "effect/Effect";
12 import * as Redacted from "effect/Redacted";
13 import * as Schedule from "effect/Schedule";
14 import * as Stream from "effect/Stream";
15 import { reapLogGroupsByPrefix } from "../Logs/reapLogGroups.ts";
16 import type { Providers } from "../Providers.ts";
17
18 export class RDSDBClusterNotReady extends Data.TaggedError("RDSDBClusterNotReady")<{
19 readonly message: string;
20 readonly cause?: unknown;
21 }> {}
22
23 export interface DBClusterProps {
24 /**
25 * Cluster identifier. If omitted, Alchemy generates one.
26 */
27 dbClusterIdentifier?: string;
28 /**
29 * Aurora engine, such as `aurora-postgresql`.
30 */
31 engine: string;
32 /**
33 * Optional engine version.
34 */
35 engineVersion?: string;
36 /**
37 * Optional database name created with the cluster.
38 */
39 databaseName?: string;
40 /**
41 * Subnet group used by the cluster.
42 */
43 dbSubnetGroupName?: string;
44 /**
45 * Cluster parameter group name.
46 */
47 dbClusterParameterGroupName?: string;
48 /**
49 * Security groups attached to the cluster.
50 */
51 vpcSecurityGroupIds?: string[];
52 /**
53 * Optional listener port.
54 */
55 port?: number;
56 /**
57 * Enable IAM database authentication.
58 */
59 enableIAMDatabaseAuthentication?: boolean;
60 /**
61 * Enable Aurora Data API / HTTP endpoint support.
62 */
63 enableHttpEndpoint?: boolean;
64 /**
65 * Engine mode, for example `provisioned` or `serverless`.
66 * Changing it forces replacement unless `AllowEngineModeChange` applies.
67 */
68 engineMode?: string;
69 /**
70 * Serverless v2 scaling configuration.
71 */
72 serverlessV2ScalingConfiguration?: rds.ServerlessV2ScalingConfiguration;
73 /**
74 * Serverless v1 scaling configuration. In-place modify.
75 */
76 scalingConfiguration?: rds.ScalingConfiguration;
77 /**
78 * Availability zones for cluster placement. Immutable — forces replacement.
79 */
80 availabilityZones?: string[];
81 /**
82 * Backup retention period (e.g. `"7 days"` or `Duration.days(7)`).
83 * Sent to the API in whole days. In-place modify.
84 */
85 backupRetentionPeriod?: Duration.Input;
86 /**
87 * Daily backup window, e.g. `07:00-09:00`. In-place modify.
88 */
89 preferredBackupWindow?: string;
90 /**
91 * Weekly maintenance window, e.g. `Mon:00:00-Mon:03:00`. In-place modify.
92 */
93 preferredMaintenanceWindow?: string;
94 /**
95 * Backtrack window (Aurora MySQL only), e.g. `"1 hour"`. Sent to the API
96 * in whole seconds. In-place modify.
97 */
98 backtrackWindow?: Duration.Input;
99 /**
100 * Option group name. In-place modify.
101 */
102 optionGroupName?: string;
103 /**
104 * Log types to export to CloudWatch Logs. Diffed against observed state and
105 * applied via the delta-shaped `CloudwatchLogsExportConfiguration` on modify.
106 */
107 enableCloudwatchLogsExports?: string[];
108 /**
109 * Auto minor version upgrade. In-place modify.
110 */
111 autoMinorVersionUpgrade?: boolean;
112 /**
113 * Allow a major engine-version upgrade during a modify. Modify-only flag.
114 */
115 allowMajorVersionUpgrade?: boolean;
116 /**
117 * Enhanced-monitoring granularity (e.g. `"60 seconds"`). Sent to the API
118 * in whole seconds (valid: 0, 1, 5, 10, 15, 30, 60). In-place modify.
119 */
120 monitoringInterval?: Duration.Input;
121 /**
122 * IAM role ARN for enhanced monitoring. In-place modify.
123 */
124 monitoringRoleArn?: string;
125 /**
126 * Enable Performance Insights. In-place modify.
127 */
128 enablePerformanceInsights?: boolean;
129 /**
130 * KMS key for Performance Insights. In-place modify.
131 */
132 performanceInsightsKMSKeyId?: string;
133 /**
134 * Performance Insights retention (e.g. `"7 days"`). Sent to the API in
135 * whole days (valid: 7, 731, or month multiples). In-place modify.
136 */
137 performanceInsightsRetentionPeriod?: Duration.Input;
138 /**
139 * Network type: `IPV4` | `DUAL`. In-place modify.
140 */
141 networkType?: string;
142 /**
143 * CA certificate identifier. In-place modify.
144 */
145 caCertificateIdentifier?: string;
146 /**
147 * KMS key used to encrypt the managed master user secret. In-place modify.
148 */
149 masterUserSecretKmsKeyId?: string;
150 /**
151 * Rotate the managed master user password on the next reconcile.
152 */
153 rotateMasterUserPassword?: boolean;
154 /**
155 * Enable global write forwarding (secondary regions of a global cluster).
156 */
157 enableGlobalWriteForwarding?: boolean;
158 /**
159 * Enable local write forwarding (Aurora reader endpoints). In-place modify.
160 */
161 enableLocalWriteForwarding?: boolean;
162 /**
163 * Join this cluster to an Aurora global cluster. Immutable on create.
164 */
165 globalClusterIdentifier?: string;
166 /**
167 * Instance class for a provisioned multi-AZ cluster. In-place modify.
168 */
169 dbClusterInstanceClass?: string;
170 /**
171 * Allocated storage (GiB) for a provisioned multi-AZ cluster. In-place.
172 */
173 allocatedStorage?: number;
174 /**
175 * Storage type (provisioned multi-AZ cluster). In-place modify.
176 */
177 storageType?: string;
178 /**
179 * Provisioned IOPS (provisioned multi-AZ cluster). In-place modify.
180 */
181 iops?: number;
182 /**
183 * Whether a provisioned cluster is publicly reachable. In-place modify.
184 */
185 publiclyAccessible?: boolean;
186 /**
187 * Engine lifecycle support setting. Immutable — forces replacement.
188 */
189 engineLifecycleSupport?: string;
190 /**
191 * Whether to copy tags to snapshots.
192 */
193 copyTagsToSnapshot?: boolean;
194 /**
195 * Whether to block accidental deletion.
196 */
197 deletionProtection?: boolean;
198 /**
199 * Whether the storage is encrypted. Immutable — forces replacement.
200 */
201 storageEncrypted?: boolean;
202 /**
203 * Optional KMS key used for storage encryption. Immutable — forces replace.
204 */
205 kmsKeyId?: string;
206 /**
207 * Let RDS manage the master user password in Secrets Manager.
208 */
209 manageMasterUserPassword?: boolean;
210 /**
211 * Explicit master username when not deriving credentials from a secret.
212 */
213 masterUsername?: string;
214 /**
215 * Explicit master password when not deriving credentials from a secret.
216 */
217 masterUserPassword?: Redacted.Redacted<string>;
218 /**
219 * Existing Secrets Manager secret ARN whose JSON payload contains
220 * `username` and `password`.
221 */
222 masterUserSecretArn?: string;
223 /**
224 * User-defined tags.
225 */
226 tags?: Record<string, string>;
227 }
228
229 export interface DBCluster extends Resource<
230 "AWS.RDS.DBCluster",
231 DBClusterProps,
232 {
233 /**
234 * Identifier of the cluster.
235 */
236 dbClusterIdentifier: string;
237 /**
238 * ARN of the cluster.
239 */
240 dbClusterArn: string;
241 /**
242 * Subnet group the cluster is placed in.
243 */
244 dbSubnetGroupName: string | undefined;
245 /**
246 * Writer endpoint DNS address.
247 */
248 endpoint: string | undefined;
249 /**
250 * Load-balanced reader endpoint DNS address.
251 */
252 readerEndpoint: string | undefined;
253 /**
254 * Port the database listens on.
255 */
256 port: number | undefined;
257 /**
258 * Database engine (e.g. `aurora-postgresql`).
259 */
260 engine: string;
261 /**
262 * Engine version in use.
263 */
264 engineVersion: string | undefined;
265 /**
266 * Status of the cluster (e.g. `available`).
267 */
268 status: string | undefined;
269 /**
270 * Name of the initial database.
271 */
272 databaseName: string | undefined;
273 /**
274 * Master username.
275 */
276 masterUsername: string | undefined;
277 /**
278 * ARN of the Secrets Manager secret holding master credentials.
279 */
280 masterUserSecretArn: string | undefined;
281 /**
282 * Security groups attached to the cluster.
283 */
284 vpcSecurityGroupIds: string[];
285 /**
286 * Whether the Data API HTTP endpoint is enabled.
287 */
288 httpEndpointEnabled: boolean | undefined;
289 /**
290 * Allocated storage in GiB (provisioned engines).
291 */
292 allocatedStorage: number | undefined;
293 /**
294 * Backup retention period in days.
295 */
296 backupRetentionPeriod: number | undefined;
297 /**
298 * Daily backup window (`hh:mm-hh:mm` UTC).
299 */
300 preferredBackupWindow: string | undefined;
301 /**
302 * Weekly maintenance window.
303 */
304 preferredMaintenanceWindow: string | undefined;
305 /**
306 * Whether storage is encrypted.
307 */
308 storageEncrypted: boolean | undefined;
309 /**
310 * KMS key used for storage encryption.
311 */
312 kmsKeyId: string | undefined;
313 /**
314 * Whether deletion protection is enabled.
315 */
316 deletionProtection: boolean | undefined;
317 /**
318 * Whether IAM database authentication is enabled.
319 */
320 iamDatabaseAuthenticationEnabled: boolean | undefined;
321 /**
322 * Engine mode (e.g. `provisioned`).
323 */
324 engineMode: string | undefined;
325 /**
326 * Member instances with their writer flag and promotion tier.
327 */
328 dbClusterMembers: Array<{
329 dbInstanceIdentifier: string | undefined;
330 isClusterWriter: boolean | undefined;
331 promotionTier: number | undefined;
332 }>;
333 /**
334 * Immutable region-unique cluster resource ID (used in IAM auth ARNs).
335 */
336 dbClusterResourceId: string | undefined;
337 /**
338 * Route 53 hosted zone ID of the cluster endpoints.
339 */
340 hostedZoneId: string | undefined;
341 /**
342 * Whether the cluster has instances in multiple AZs.
343 */
344 multiAZ: boolean | undefined;
345 /**
346 * Log types exported to CloudWatch Logs.
347 */
348 enabledCloudwatchLogsExports: string[];
349 /**
350 * Whether cluster tags are copied to snapshots.
351 */
352 copyTagsToSnapshot: boolean | undefined;
353 /**
354 * Time the cluster was created (ISO 8601).
355 */
356 clusterCreateTime: string | undefined;
357 /**
358 * Serverless v2 platform version.
359 */
360 serverlessV2PlatformVersion: string | undefined;
361 /**
362 * Enhanced-monitoring granularity in seconds.
363 */
364 monitoringInterval: number | undefined;
365 /**
366 * Whether Performance Insights is enabled.
367 */
368 performanceInsightsEnabled: boolean | undefined;
369 /**
370 * Instance class for Multi-AZ DB clusters.
371 */
372 dbClusterInstanceClass: string | undefined;
373 /**
374 * Storage type (e.g. `aurora`, `aurora-iopt1`).
375 */
376 storageType: string | undefined;
377 /**
378 * Provisioned IOPS (Multi-AZ DB clusters).
379 */
380 iops: number | undefined;
381 /**
382 * Network type (`IPV4` or `DUAL`).
383 */
384 networkType: string | undefined;
385 /**
386 * Custom endpoint ARNs associated with the cluster.
387 */
388 customEndpoints: string[];
389 /**
390 * Tags on the cluster.
391 */
392 tags: Record<string, string>;
393 },
394 never,
395 Providers
396 > {}
397
398 /**
399 * An Aurora DB cluster.
400 *
401 * `DBCluster` owns the writer and reader endpoints, cluster-wide networking,
402 * and Data API enablement. It can bootstrap master credentials directly or by
403 * reading a Secrets Manager secret that contains `username` and `password`.
404 *
405 * It exposes the full backup, maintenance, monitoring, performance-insights,
406 * encryption, scaling, and log-export surface of `createDBCluster` /
407 * `modifyDBCluster`. Mutable fields are reconciled in place against the
408 * observed cloud state; immutable fields (`engine`, `databaseName`,
409 * `dbSubnetGroupName`, `storageEncrypted`, `kmsKeyId`, `engineMode`,
410 * `globalClusterIdentifier`, `availabilityZones`, `engineLifecycleSupport`)
411 * force a replacement.
412 * ### Serverless v2 Cluster
413 * **Example:** Aurora Postgres serverless-v2
414 * ```typescript
415 * const cluster = yield* DBCluster("Cluster", {
416 * engine: "aurora-postgresql",
417 * engineMode: "provisioned",
418 * serverlessV2ScalingConfiguration: { MinCapacity: 0.5, MaxCapacity: 4 },
419 * manageMasterUserPassword: true,
420 * masterUsername: "alchemy",
421 * backupRetentionPeriod: "7 days",
422 * deletionProtection: false,
423 * });
424 * ```
425 *
426 * ### Logs & Monitoring
427 * **Example:** Export logs and enable Performance Insights
428 * ```typescript
429 * const cluster = yield* DBCluster("Cluster", {
430 * engine: "aurora-postgresql",
431 * enableCloudwatchLogsExports: ["postgresql"],
432 * enablePerformanceInsights: true,
433 * monitoringInterval: "60 seconds",
434 * monitoringRoleArn: monitoringRole.roleArn,
435 * });
436 * ```
437 *
438 * @resource
439 */
440 export const DBCluster = Resource<DBCluster>("AWS.RDS.DBCluster");
441
442 const toTagRecord = (
443 tags: Array<{ Key?: string; Value?: string }> | undefined,
444 ): Record<string, string> =>
445 Object.fromEntries(
446 (tags ?? [])
447 .filter(
448 (tag): tag is { Key: string; Value: string } =>
449 typeof tag.Key === "string" && typeof tag.Value === "string",
450 )
451 .map((tag) => [tag.Key, tag.Value]),
452 );
453
454 const resolveMasterCredentials = (props: DBClusterProps) =>
455 Effect.gen(function* () {
456 if (props.masterUserSecretArn) {
457 const value = yield* secretsmanager.getSecretValue({
458 SecretId: props.masterUserSecretArn,
459 });
460 const secretString = value.SecretString
461 ? typeof value.SecretString === "string"
462 ? value.SecretString
463 : Redacted.value(value.SecretString)
464 : undefined;
465 const secret = secretString
466 ? (JSON.parse(secretString) as {
467 username?: string;
468 password?: string;
469 })
470 : {};
471 return {
472 MasterUsername: props.masterUsername ?? secret.username,
473 MasterUserPassword: props.masterUserPassword ?? secret.password,
474 };
475 }
476
477 return {
478 MasterUsername: props.masterUsername,
479 MasterUserPassword: props.masterUserPassword,
480 };
481 });
482
483 const toAttrs = ({
484 cluster,
485 tags,
486 }: {
487 cluster: rds.DBCluster;
488 tags: Record<string, string>;
489 }): DBCluster["Attributes"] => ({
490 dbClusterIdentifier: cluster.DBClusterIdentifier ?? "",
491 dbClusterArn: cluster.DBClusterArn ?? "",
492 dbSubnetGroupName: cluster.DBSubnetGroup,
493 endpoint: cluster.Endpoint,
494 readerEndpoint: cluster.ReaderEndpoint,
495 port: cluster.Port,
496 engine: cluster.Engine ?? "",
497 engineVersion: cluster.EngineVersion,
498 status: cluster.Status,
499 databaseName: cluster.DatabaseName,
500 masterUsername: cluster.MasterUsername,
501 masterUserSecretArn: cluster.MasterUserSecret?.SecretArn,
502 vpcSecurityGroupIds: (cluster.VpcSecurityGroups ?? []).flatMap((group) =>
503 group.VpcSecurityGroupId ? [group.VpcSecurityGroupId] : [],
504 ),
505 httpEndpointEnabled: cluster.HttpEndpointEnabled,
506 allocatedStorage: cluster.AllocatedStorage,
507 backupRetentionPeriod: cluster.BackupRetentionPeriod,
508 preferredBackupWindow: cluster.PreferredBackupWindow,
509 preferredMaintenanceWindow: cluster.PreferredMaintenanceWindow,
510 storageEncrypted: cluster.StorageEncrypted,
511 kmsKeyId: cluster.KmsKeyId,
512 deletionProtection: cluster.DeletionProtection,
513 iamDatabaseAuthenticationEnabled: cluster.IAMDatabaseAuthenticationEnabled,
514 engineMode: cluster.EngineMode,
515 dbClusterMembers: (cluster.DBClusterMembers ?? []).map((member) => ({
516 dbInstanceIdentifier: member.DBInstanceIdentifier,
517 isClusterWriter: member.IsClusterWriter,
518 promotionTier: member.PromotionTier,
519 })),
520 dbClusterResourceId: cluster.DbClusterResourceId,
521 hostedZoneId: cluster.HostedZoneId,
522 multiAZ: cluster.MultiAZ,
523 enabledCloudwatchLogsExports: cluster.EnabledCloudwatchLogsExports ?? [],
524 copyTagsToSnapshot: cluster.CopyTagsToSnapshot,
525 clusterCreateTime: cluster.ClusterCreateTime?.toISOString(),
526 serverlessV2PlatformVersion: cluster.ServerlessV2PlatformVersion,
527 monitoringInterval: cluster.MonitoringInterval,
528 performanceInsightsEnabled: cluster.PerformanceInsightsEnabled,
529 dbClusterInstanceClass: cluster.DBClusterInstanceClass,
530 storageType: cluster.StorageType,
531 iops: cluster.Iops,
532 networkType: cluster.NetworkType,
533 customEndpoints: cluster.CustomEndpoints ?? [],
534 tags,
535 });
536
537 /**
538 * Compute the CloudWatch Logs export delta. The modify API is delta-shaped
539 * (`EnableLogTypes`/`DisableLogTypes`), so it must NOT carry the full set.
540 * Returns `undefined` when there is no change.
541 */
542 const logExportDelta = (
543 observed: string[] | undefined,
544 desired: string[] | undefined,
545 ): rds.CloudwatchLogsExportConfiguration | undefined => {
546 if (desired === undefined) return undefined;
547 const have = new Set(observed ?? []);
548 const want = new Set(desired);
549 const EnableLogTypes = [...want].filter((t) => !have.has(t));
550 const DisableLogTypes = [...have].filter((t) => !want.has(t));
551 if (EnableLogTypes.length === 0 && DisableLogTypes.length === 0) {
552 return undefined;
553 }
554 return {
555 ...(EnableLogTypes.length > 0 ? { EnableLogTypes } : {}),
556 ...(DisableLogTypes.length > 0 ? { DisableLogTypes } : {}),
557 };
558 };
559
560 export const DBClusterProvider = () =>
561 Provider.effect(
562 DBCluster,
563 Effect.gen(function* () {
564 const toIdentifier = (id: string, props: DBClusterProps) =>
565 props.dbClusterIdentifier
566 ? Effect.succeed(props.dbClusterIdentifier)
567 : createPhysicalName({ id, maxLength: 63 });
568
569 const readCluster = Effect.fn(function* (clusterId: string) {
570 const response = yield* rds
571 .describeDBClusters({
572 DBClusterIdentifier: clusterId,
573 })
574 .pipe(Effect.catchTag("DBClusterNotFoundFault", () => Effect.undefined));
575 return response?.DBClusters?.[0];
576 });
577
578 // Bounded readiness wait. Gate on cluster `Status === "available"` so a
579 // follow-on `modifyDBCluster` doesn't hit `InvalidDBClusterStateFault`.
580 // Budgets ~10 min (60 * 10s) for slow provisioning. `requireAvailable:
581 // false` only waits for the ARN to appear.
582 const waitForCluster = Effect.fn(function* (
583 clusterId: string,
584 { requireAvailable = true }: { requireAvailable?: boolean } = {},
585 ) {
586 const readinessPolicy = Schedule.max([Schedule.fixed("10 seconds"), Schedule.recurs(60)]);
587 return yield* readCluster(clusterId).pipe(
588 Effect.flatMap((cluster) => {
589 if (!cluster?.DBClusterArn) {
590 return Effect.fail(
591 new RDSDBClusterNotReady({ message: `DB cluster '${clusterId}' not found` }),
592 );
593 }
594 if (requireAvailable && cluster.Status !== "available") {
595 return Effect.fail(
596 new RDSDBClusterNotReady({
597 message: `DB cluster '${clusterId}' not available (status: ${cluster.Status})`,
598 }),
599 );
600 }
601 return Effect.succeed(cluster);
602 }),
603 Effect.retry({ schedule: readinessPolicy }),
604 );
605 });
606
607 return {
608 stables: ["dbClusterArn", "dbClusterIdentifier"],
609 // AWS account/region collection (pattern a): exhaustively paginate
610 // `describeDBClusters` and map each cluster to the exact `read`
611 // Attributes shape. Tags come inline on `DBCluster.TagList`, so no
612 // per-item `listTagsForResource` hydration is needed (matching `read`).
613 list: () =>
614 rds.describeDBClusters.pages({}).pipe(
615 Stream.runCollect,
616 Effect.map((chunk) =>
617 Array.from(chunk).flatMap((page) =>
618 (page.DBClusters ?? []).map((cluster) =>
619 toAttrs({
620 cluster,
621 tags: toTagRecord(cluster.TagList),
622 }),
623 ),
624 ),
625 ),
626 ),
627 diff: Effect.fn(function* ({ id, olds, news }) {
628 if (!isResolved(news)) return;
629 if (
630 (yield* toIdentifier(id, olds ?? ({} as DBClusterProps))) !==
631 (yield* toIdentifier(id, news))
632 ) {
633 return { action: "replace" } as const;
634 }
635 // Immutable props — any change forces a fresh cluster.
636 if (
637 olds !== undefined &&
638 (olds.engine !== news.engine ||
639 olds.databaseName !== news.databaseName ||
640 olds.dbSubnetGroupName !== news.dbSubnetGroupName ||
641 olds.storageEncrypted !== news.storageEncrypted ||
642 olds.kmsKeyId !== news.kmsKeyId ||
643 olds.engineMode !== news.engineMode ||
644 olds.globalClusterIdentifier !== news.globalClusterIdentifier ||
645 olds.engineLifecycleSupport !== news.engineLifecycleSupport ||
646 JSON.stringify(olds.availabilityZones ?? []) !==
647 JSON.stringify(news.availabilityZones ?? []))
648 ) {
649 return { action: "replace" } as const;
650 }
651 }),
652 read: Effect.fn(function* ({ id, olds, output }) {
653 const identifier =
654 output?.dbClusterIdentifier ??
655 (yield* toIdentifier(id, olds ?? ({ engine: "" } as DBClusterProps)));
656 const cluster = yield* readCluster(identifier);
657 if (!cluster?.DBClusterArn) {
658 return undefined;
659 }
660 return toAttrs({
661 cluster,
662 tags: toTagRecord(cluster.TagList),
663 });
664 }),
665 reconcile: Effect.fn(function* ({ id, news, output, session }) {
666 const identifier = output?.dbClusterIdentifier ?? (yield* toIdentifier(id, news));
667 const internalTags = yield* createInternalTags(id);
668 const desiredTags = { ...internalTags, ...news.tags };
669 const credentials = yield* resolveMasterCredentials(news);
670 // Duration props → the exact wire units the RDS API expects.
671 const backupRetentionDays = toWireDays(news.backupRetentionPeriod);
672 const backtrackWindowSeconds = toWireSeconds(news.backtrackWindow);
673 const monitoringIntervalSeconds = toWireSeconds(news.monitoringInterval);
674 const performanceInsightsRetentionDays = toWireDays(
675 news.performanceInsightsRetentionPeriod,
676 );
677
678 // Observe — fetch live cluster state. We never trust `output`
679 // blindly: the cluster may have been deleted out-of-band, or this
680 // may be a first-time reconcile after adoption.
681 let observed = yield* readCluster(identifier);
682
683 // Ensure — create the cluster if it's missing. Tolerate
684 // `DBClusterAlreadyExistsFault` as a race with a peer reconciler
685 // (e.g. retry after state-persistence failure).
686 if (!observed?.DBClusterArn) {
687 yield* rds
688 .createDBCluster({
689 DBClusterIdentifier: identifier,
690 Engine: news.engine,
691 EngineVersion: news.engineVersion,
692 DatabaseName: news.databaseName,
693 DBSubnetGroupName: news.dbSubnetGroupName,
694 DBClusterParameterGroupName: news.dbClusterParameterGroupName,
695 VpcSecurityGroupIds: news.vpcSecurityGroupIds,
696 Port: news.port,
697 AvailabilityZones: news.availabilityZones,
698 BackupRetentionPeriod: backupRetentionDays,
699 PreferredBackupWindow: news.preferredBackupWindow,
700 PreferredMaintenanceWindow: news.preferredMaintenanceWindow,
701 BacktrackWindow: backtrackWindowSeconds,
702 OptionGroupName: news.optionGroupName,
703 EnableCloudwatchLogsExports: news.enableCloudwatchLogsExports,
704 EnableIAMDatabaseAuthentication: news.enableIAMDatabaseAuthentication,
705 EnableHttpEndpoint: news.enableHttpEndpoint,
706 EngineMode: news.engineMode,
707 ScalingConfiguration: news.scalingConfiguration,
708 ServerlessV2ScalingConfiguration: news.serverlessV2ScalingConfiguration,
709 AutoMinorVersionUpgrade: news.autoMinorVersionUpgrade,
710 MonitoringInterval: monitoringIntervalSeconds,
711 MonitoringRoleArn: news.monitoringRoleArn,
712 EnablePerformanceInsights: news.enablePerformanceInsights,
713 PerformanceInsightsKMSKeyId: news.performanceInsightsKMSKeyId,
714 PerformanceInsightsRetentionPeriod: performanceInsightsRetentionDays,
715 NetworkType: news.networkType,
716 CACertificateIdentifier: news.caCertificateIdentifier,
717 MasterUserSecretKmsKeyId: news.masterUserSecretKmsKeyId,
718 EnableGlobalWriteForwarding: news.enableGlobalWriteForwarding,
719 EnableLocalWriteForwarding: news.enableLocalWriteForwarding,
720 GlobalClusterIdentifier: news.globalClusterIdentifier,
721 DBClusterInstanceClass: news.dbClusterInstanceClass,
722 AllocatedStorage: news.allocatedStorage,
723 StorageType: news.storageType,
724 Iops: news.iops,
725 PubliclyAccessible: news.publiclyAccessible,
726 EngineLifecycleSupport: news.engineLifecycleSupport,
727 CopyTagsToSnapshot: news.copyTagsToSnapshot,
728 DeletionProtection: news.deletionProtection,
729 StorageEncrypted: news.storageEncrypted,
730 KmsKeyId: news.kmsKeyId,
731 ManageMasterUserPassword: news.manageMasterUserPassword,
732 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
733 Key,
734 Value,
735 })),
736 ...credentials,
737 })
738 .pipe(Effect.catchTag("DBClusterAlreadyExistsFault", () => Effect.void));
739
740 observed = yield* waitForCluster(identifier);
741 } else {
742 // Wait for the cluster to settle before any modify so the call
743 // doesn't hit `InvalidDBClusterStateFault`.
744 observed = yield* waitForCluster(identifier);
745
746 // syncCoreSettings — single `modifyDBCluster` carrying scalar
747 // in-place fields, only emitting a field when the desired value
748 // differs from the observed cloud state.
749 const core: rds.ModifyDBClusterMessage = {
750 DBClusterIdentifier: identifier,
751 ApplyImmediately: true,
752 };
753 let coreDirty = false;
754 const setIf = <K extends keyof rds.ModifyDBClusterMessage>(
755 key: K,
756 desired: rds.ModifyDBClusterMessage[K] | undefined,
757 observedValue: unknown,
758 ) => {
759 if (desired !== undefined && desired !== observedValue) {
760 core[key] = desired;
761 coreDirty = true;
762 }
763 };
764 setIf("EngineVersion", news.engineVersion, observed.EngineVersion);
765 setIf("Port", news.port, observed.Port);
766 setIf("BackupRetentionPeriod", backupRetentionDays, observed.BackupRetentionPeriod); // prettier-ignore
767 setIf("PreferredBackupWindow", news.preferredBackupWindow, observed.PreferredBackupWindow); // prettier-ignore
768 setIf("PreferredMaintenanceWindow", news.preferredMaintenanceWindow, observed.PreferredMaintenanceWindow); // prettier-ignore
769 setIf("BacktrackWindow", backtrackWindowSeconds, observed.BacktrackWindow); // prettier-ignore
770 setIf("DeletionProtection", news.deletionProtection, observed.DeletionProtection); // prettier-ignore
771 setIf("CopyTagsToSnapshot", news.copyTagsToSnapshot, observed.CopyTagsToSnapshot); // prettier-ignore
772 setIf("EnableIAMDatabaseAuthentication", news.enableIAMDatabaseAuthentication, observed.IAMDatabaseAuthenticationEnabled); // prettier-ignore
773 setIf("EnableHttpEndpoint", news.enableHttpEndpoint, observed.HttpEndpointEnabled); // prettier-ignore
774 setIf("AutoMinorVersionUpgrade", news.autoMinorVersionUpgrade, observed.AutoMinorVersionUpgrade); // prettier-ignore
775 setIf("MonitoringInterval", monitoringIntervalSeconds, observed.MonitoringInterval); // prettier-ignore
776 setIf("MonitoringRoleArn", news.monitoringRoleArn, observed.MonitoringRoleArn); // prettier-ignore
777 setIf("EnablePerformanceInsights", news.enablePerformanceInsights, observed.PerformanceInsightsEnabled); // prettier-ignore
778 setIf("PerformanceInsightsKMSKeyId", news.performanceInsightsKMSKeyId, observed.PerformanceInsightsKMSKeyId); // prettier-ignore
779 setIf("PerformanceInsightsRetentionPeriod", performanceInsightsRetentionDays, observed.PerformanceInsightsRetentionPeriod); // prettier-ignore
780 setIf("NetworkType", news.networkType, observed.NetworkType);
781 setIf("DBClusterInstanceClass", news.dbClusterInstanceClass, observed.DBClusterInstanceClass); // prettier-ignore
782 setIf("AllocatedStorage", news.allocatedStorage, observed.AllocatedStorage); // prettier-ignore
783 setIf("StorageType", news.storageType, observed.StorageType);
784 setIf("Iops", news.iops, observed.Iops);
785 setIf("OptionGroupName", news.optionGroupName, undefined);
786 setIf("DBClusterParameterGroupName", news.dbClusterParameterGroupName, observed.DBClusterParameterGroup); // prettier-ignore
787 setIf("EnableGlobalWriteForwarding", news.enableGlobalWriteForwarding, undefined); // prettier-ignore
788 setIf("EnableLocalWriteForwarding", news.enableLocalWriteForwarding, undefined); // prettier-ignore
789 setIf("CACertificateIdentifier", news.caCertificateIdentifier, undefined); // prettier-ignore
790 if (news.scalingConfiguration !== undefined) {
791 core.ScalingConfiguration = news.scalingConfiguration;
792 coreDirty = true;
793 }
794 if (news.serverlessV2ScalingConfiguration !== undefined) {
795 core.ServerlessV2ScalingConfiguration = news.serverlessV2ScalingConfiguration;
796 coreDirty = true;
797 }
798 if (news.vpcSecurityGroupIds !== undefined) {
799 core.VpcSecurityGroupIds = news.vpcSecurityGroupIds;
800 coreDirty = true;
801 }
802 if (news.allowMajorVersionUpgrade) {
803 core.AllowMajorVersionUpgrade = true;
804 }
805 // syncMasterPassword — rotation or explicit password update.
806 if (news.manageMasterUserPassword && news.rotateMasterUserPassword) {
807 core.RotateMasterUserPassword = true;
808 coreDirty = true;
809 } else if (credentials.MasterUserPassword !== undefined) {
810 core.MasterUserPassword = credentials.MasterUserPassword;
811 coreDirty = true;
812 }
813 if (coreDirty) {
814 yield* rds.modifyDBCluster(core);
815 observed = yield* waitForCluster(identifier);
816 }
817
818 // syncCloudwatchLogsExports — delta-shaped; separate call.
819 const logDelta = logExportDelta(
820 observed.EnabledCloudwatchLogsExports,
821 news.enableCloudwatchLogsExports,
822 );
823 if (logDelta) {
824 yield* rds.modifyDBCluster({
825 DBClusterIdentifier: identifier,
826 CloudwatchLogsExportConfiguration: logDelta,
827 ApplyImmediately: true,
828 });
829 observed = yield* waitForCluster(identifier);
830 }
831 }
832
833 const dbClusterArn = observed.DBClusterArn ?? "";
834
835 // Sync tags — diff observed cloud tags against desired so the
836 // reconciler converges regardless of what was on the resource
837 // before (initial create, adoption, or drift).
838 const observedTags = toTagRecord(observed.TagList);
839 const { removed, upsert } = diffTags(observedTags, desiredTags);
840 if (upsert.length > 0 && dbClusterArn) {
841 yield* rds.addTagsToResource({
842 ResourceName: dbClusterArn,
843 Tags: upsert,
844 });
845 }
846 if (removed.length > 0 && dbClusterArn) {
847 yield* rds.removeTagsFromResource({
848 ResourceName: dbClusterArn,
849 TagKeys: removed,
850 });
851 }
852
853 yield* session.note(dbClusterArn || identifier);
854 return toAttrs({ cluster: observed, tags: desiredTags });
855 }),
856 delete: Effect.fn(function* ({ output }) {
857 yield* rds
858 .deleteDBCluster({
859 DBClusterIdentifier: output.dbClusterIdentifier,
860 SkipFinalSnapshot: true,
861 })
862 .pipe(Effect.catchTag("DBClusterNotFoundFault", () => Effect.void));
863 // Block until the cluster is fully gone. RDS deletion is async; if we
864 // return while it is still `deleting`, a dependent (e.g. a
865 // DBSubnetGroup or VPC) is torn down next and AWS rejects it with
866 // `InvalidDBSubnetGroupStateFault: ... still using it`.
867 yield* Effect.repeat(
868 rds
869 .describeDBClusters({
870 DBClusterIdentifier: output.dbClusterIdentifier,
871 })
872 .pipe(
873 Effect.as(true),
874 Effect.catchTag("DBClusterNotFoundFault", () => Effect.succeed(false)),
875 ),
876 {
877 schedule: Schedule.max([Schedule.fixed("15 seconds"), Schedule.recurs(40)]),
878 until: (exists) => exists === false,
879 },
880 ).pipe(Effect.catch(() => Effect.void));
881 // RDS creates `/aws/rds/cluster/<id>/<logType>` for every
882 // `enableCloudwatchLogsExports` type and never deletes them.
883 yield* reapLogGroupsByPrefix(
884 `/aws/rds/cluster/${output.dbClusterIdentifier.toLowerCase()}/`,
885 );
886 }),
887 };
888 }),
889 );