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
| 1 | import * as neptune from "@distilled.cloud/aws/neptune"; |
| 2 | import { isResolved } from "alchemy/Diff"; |
| 3 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 4 | import * as Provider from "alchemy/Provider"; |
| 5 | import { Resource } from "alchemy/Resource"; |
| 6 | import { createInternalTags, diffTags } from "alchemy/Tags"; |
| 7 | import { toWireDays } from "alchemy/Util/Duration"; |
| 8 | import * as Data from "effect/Data"; |
| 9 | import type * as Duration from "effect/Duration"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import * as Schedule from "effect/Schedule"; |
| 12 | import * as Stream from "effect/Stream"; |
| 13 | import type { Providers } from "../Providers.ts"; |
| 14 | |
| 15 | export class NeptuneDBClusterNotReady extends Data.TaggedError("NeptuneDBClusterNotReady")<{ |
| 16 | readonly message: string; |
| 17 | readonly cause?: unknown; |
| 18 | }> {} |
| 19 | |
| 20 | export interface ServerlessV2ScalingConfiguration { |
| 21 | /** |
| 22 | * Minimum Neptune Capacity Units (NCUs), e.g. `1`. |
| 23 | */ |
| 24 | minCapacity?: number; |
| 25 | /** |
| 26 | * Maximum Neptune Capacity Units (NCUs), e.g. `2.5`. |
| 27 | */ |
| 28 | maxCapacity?: number; |
| 29 | } |
| 30 | |
| 31 | export interface DBClusterProps { |
| 32 | /** |
| 33 | * Cluster identifier. If omitted, Alchemy generates one. |
| 34 | */ |
| 35 | dbClusterIdentifier?: string; |
| 36 | /** |
| 37 | * Database engine. Neptune only supports `neptune`. |
| 38 | * Changing it forces replacement. |
| 39 | * @default "neptune" |
| 40 | */ |
| 41 | engine?: string; |
| 42 | /** |
| 43 | * Optional engine version, e.g. `1.4.5.0`. Changed in place via |
| 44 | * `modifyDBCluster` (may require `allowMajorVersionUpgrade`). |
| 45 | */ |
| 46 | engineVersion?: string; |
| 47 | /** |
| 48 | * Subnet group the cluster is placed into. Neptune is VPC-only, so this |
| 49 | * is effectively required. Immutable — forces replacement. |
| 50 | */ |
| 51 | dbSubnetGroupName?: string; |
| 52 | /** |
| 53 | * Cluster parameter group name. In-place modify. |
| 54 | */ |
| 55 | dbClusterParameterGroupName?: string; |
| 56 | /** |
| 57 | * Security groups attached to the cluster. In-place modify. |
| 58 | */ |
| 59 | vpcSecurityGroupIds?: string[]; |
| 60 | /** |
| 61 | * Listener port. |
| 62 | * @default 8182 |
| 63 | */ |
| 64 | port?: number; |
| 65 | /** |
| 66 | * Availability zones for cluster placement. Immutable — forces replacement. |
| 67 | */ |
| 68 | availabilityZones?: string[]; |
| 69 | /** |
| 70 | * Backup retention period (1-35 days, e.g. `"7 days"` or |
| 71 | * `Duration.days(7)`). Sent to the API in whole days. In-place modify. |
| 72 | */ |
| 73 | backupRetentionPeriod?: Duration.Input; |
| 74 | /** |
| 75 | * Daily backup window, e.g. `07:00-09:00`. In-place modify. |
| 76 | */ |
| 77 | preferredBackupWindow?: string; |
| 78 | /** |
| 79 | * Weekly maintenance window, e.g. `Mon:00:00-Mon:03:00`. In-place modify. |
| 80 | */ |
| 81 | preferredMaintenanceWindow?: string; |
| 82 | /** |
| 83 | * Log types to export to CloudWatch Logs (`audit`, `slowquery`). Diffed |
| 84 | * against observed state and applied via the delta-shaped |
| 85 | * `CloudwatchLogsExportConfiguration` on modify. |
| 86 | */ |
| 87 | enableCloudwatchLogsExports?: string[]; |
| 88 | /** |
| 89 | * Enable IAM database authentication (SigV4-signed data-plane requests). |
| 90 | * In-place modify. |
| 91 | */ |
| 92 | enableIAMDatabaseAuthentication?: boolean; |
| 93 | /** |
| 94 | * Serverless v2 (NCU-based) scaling configuration. Required when using |
| 95 | * `db.serverless` instances. In-place modify. |
| 96 | */ |
| 97 | serverlessV2ScalingConfiguration?: ServerlessV2ScalingConfiguration; |
| 98 | /** |
| 99 | * Block accidental deletion. In-place modify. |
| 100 | */ |
| 101 | deletionProtection?: boolean; |
| 102 | /** |
| 103 | * Whether the storage is encrypted. Immutable — forces replacement. |
| 104 | */ |
| 105 | storageEncrypted?: boolean; |
| 106 | /** |
| 107 | * Optional KMS key used for storage encryption. Immutable — forces replace. |
| 108 | */ |
| 109 | kmsKeyId?: string; |
| 110 | /** |
| 111 | * Storage type, `standard` | `iopt1`. In-place modify. |
| 112 | */ |
| 113 | storageType?: string; |
| 114 | /** |
| 115 | * Copy tags to snapshots. In-place modify. |
| 116 | */ |
| 117 | copyTagsToSnapshot?: boolean; |
| 118 | /** |
| 119 | * Join this cluster to a Neptune global database. Immutable on create. |
| 120 | */ |
| 121 | globalClusterIdentifier?: string; |
| 122 | /** |
| 123 | * Allow a major engine-version upgrade during a modify. Modify-only flag. |
| 124 | */ |
| 125 | allowMajorVersionUpgrade?: boolean; |
| 126 | /** |
| 127 | * IAM roles to associate with the cluster — e.g. an S3 read role for the |
| 128 | * Neptune bulk loader, or a SageMaker role for Neptune ML (set |
| 129 | * `featureName` where the feature requires it). Reconciled in place by |
| 130 | * diffing the observed cloud associations against this list via |
| 131 | * `addRoleToDBCluster`/`removeRoleFromDBCluster`. |
| 132 | */ |
| 133 | associatedRoles?: Array<{ |
| 134 | /** ARN of the IAM role to associate. */ |
| 135 | roleArn: string; |
| 136 | /** Neptune feature the role is scoped to (omit for the default). */ |
| 137 | featureName?: string; |
| 138 | }>; |
| 139 | /** |
| 140 | * User-defined tags. |
| 141 | */ |
| 142 | tags?: Record<string, string>; |
| 143 | } |
| 144 | |
| 145 | export interface DBCluster extends Resource< |
| 146 | "AWS.Neptune.DBCluster", |
| 147 | DBClusterProps, |
| 148 | { |
| 149 | /** Identifier of the cluster. */ |
| 150 | dbClusterIdentifier: string; |
| 151 | /** ARN of the cluster. */ |
| 152 | dbClusterArn: string; |
| 153 | /** Name of the subnet group the cluster is placed in. */ |
| 154 | dbSubnetGroupName: string | undefined; |
| 155 | /** Name of the attached cluster parameter group. */ |
| 156 | dbClusterParameterGroupName: string | undefined; |
| 157 | /** Writer (cluster) endpoint host name. */ |
| 158 | endpoint: string | undefined; |
| 159 | /** Load-balanced reader endpoint host name. */ |
| 160 | readerEndpoint: string | undefined; |
| 161 | /** Port the cluster listens on (default 8182). */ |
| 162 | port: number | undefined; |
| 163 | /** Database engine (`neptune`). */ |
| 164 | engine: string; |
| 165 | /** Running engine version. */ |
| 166 | engineVersion: string | undefined; |
| 167 | /** Current lifecycle status (e.g. `creating`, `available`). */ |
| 168 | status: string | undefined; |
| 169 | /** IDs of the VPC security groups attached to the cluster. */ |
| 170 | vpcSecurityGroupIds: string[]; |
| 171 | /** Automated backup retention period, in days. */ |
| 172 | backupRetentionPeriod: number | undefined; |
| 173 | /** Daily window during which automated backups are taken. */ |
| 174 | preferredBackupWindow: string | undefined; |
| 175 | /** Weekly window during which maintenance may occur. */ |
| 176 | preferredMaintenanceWindow: string | undefined; |
| 177 | /** Whether storage is encrypted at rest. */ |
| 178 | storageEncrypted: boolean | undefined; |
| 179 | /** KMS key encrypting the cluster's storage. */ |
| 180 | kmsKeyId: string | undefined; |
| 181 | /** Whether deletion protection is enabled. */ |
| 182 | deletionProtection: boolean | undefined; |
| 183 | /** Whether IAM database authentication is enabled. */ |
| 184 | iamDatabaseAuthenticationEnabled: boolean | undefined; |
| 185 | /** IAM roles associated with the cluster (bulk loader, Neptune ML). */ |
| 186 | associatedRoles: Array<{ |
| 187 | /** ARN of the associated IAM role. */ |
| 188 | roleArn: string | undefined; |
| 189 | /** Neptune feature the role is scoped to. */ |
| 190 | featureName: string | undefined; |
| 191 | /** Association status (`ACTIVE`, `PENDING`, `INVALID`). */ |
| 192 | status: string | undefined; |
| 193 | }>; |
| 194 | /** Serverless v2 (NCU) scaling range, if configured. */ |
| 195 | serverlessV2ScalingConfiguration: |
| 196 | | { minCapacity: number | undefined; maxCapacity: number | undefined } |
| 197 | | undefined; |
| 198 | /** Instances that are members of the cluster. */ |
| 199 | dbClusterMembers: Array<{ |
| 200 | /** Identifier of the member instance. */ |
| 201 | dbInstanceIdentifier: string | undefined; |
| 202 | /** Whether the member is the cluster's writer. */ |
| 203 | isClusterWriter: boolean | undefined; |
| 204 | /** Failover promotion priority of the member. */ |
| 205 | promotionTier: number | undefined; |
| 206 | }>; |
| 207 | /** Immutable, region-unique identifier of the cluster. */ |
| 208 | dbClusterResourceId: string | undefined; |
| 209 | /** Route 53 hosted zone id of the cluster endpoints. */ |
| 210 | hostedZoneId: string | undefined; |
| 211 | /** Whether the cluster has instances in multiple Availability Zones. */ |
| 212 | multiAZ: boolean | undefined; |
| 213 | /** Log types exported to CloudWatch Logs (e.g. `audit`). */ |
| 214 | enabledCloudwatchLogsExports: string[]; |
| 215 | /** Creation time of the cluster (ISO 8601). */ |
| 216 | clusterCreateTime: string | undefined; |
| 217 | /** Storage type (`standard` or `iopt1`). */ |
| 218 | storageType: string | undefined; |
| 219 | /** Whether cluster tags are copied to snapshots. */ |
| 220 | copyTagsToSnapshot: boolean | undefined; |
| 221 | /** Tags on the cluster (user + internal Alchemy tags). */ |
| 222 | tags: Record<string, string>; |
| 223 | }, |
| 224 | never, |
| 225 | Providers |
| 226 | > {} |
| 227 | |
| 228 | /** |
| 229 | * An Amazon Neptune graph database cluster. |
| 230 | * |
| 231 | * `DBCluster` owns the writer and reader endpoints and cluster-wide |
| 232 | * networking; compute is added via {@link DBInstance}. Neptune serves |
| 233 | * Gremlin, openCypher, and SPARQL over the cluster endpoint (default port |
| 234 | * 8182) and is reachable only from inside the VPC. Provisioning a cluster |
| 235 | * plus its first instance takes ~10 minutes. |
| 236 | * |
| 237 | * Mutable fields are reconciled in place against the observed cloud state; |
| 238 | * immutable fields (`engine`, `dbSubnetGroupName`, `storageEncrypted`, |
| 239 | * `kmsKeyId`, `globalClusterIdentifier`, `availabilityZones`) force a |
| 240 | * replacement. |
| 241 | * ### Creating a Cluster |
| 242 | * **Example:** Neptune cluster with IAM auth |
| 243 | * ```typescript |
| 244 | * const cluster = yield* DBCluster("Graph", { |
| 245 | * dbSubnetGroupName: subnetGroup.dbSubnetGroupName, |
| 246 | * vpcSecurityGroupIds: [sg.groupId], |
| 247 | * enableIAMDatabaseAuthentication: true, |
| 248 | * backupRetentionPeriod: "1 day", |
| 249 | * deletionProtection: false, |
| 250 | * }); |
| 251 | * ``` |
| 252 | * |
| 253 | * ### Serverless |
| 254 | * **Example:** Serverless v2 cluster (pair with a `db.serverless` instance) |
| 255 | * ```typescript |
| 256 | * const cluster = yield* DBCluster("Graph", { |
| 257 | * dbSubnetGroupName: subnetGroup.dbSubnetGroupName, |
| 258 | * serverlessV2ScalingConfiguration: { |
| 259 | * minCapacity: 1, |
| 260 | * maxCapacity: 2.5, |
| 261 | * }, |
| 262 | * }); |
| 263 | * ``` |
| 264 | * |
| 265 | * @resource |
| 266 | */ |
| 267 | export const DBCluster = Resource<DBCluster>("AWS.Neptune.DBCluster"); |
| 268 | |
| 269 | const toTagRecord = ( |
| 270 | tags: Array<{ Key?: string; Value?: string }> | undefined, |
| 271 | ): Record<string, string> => |
| 272 | Object.fromEntries( |
| 273 | (tags ?? []) |
| 274 | .filter( |
| 275 | (tag): tag is { Key: string; Value: string } => |
| 276 | typeof tag.Key === "string" && typeof tag.Value === "string", |
| 277 | ) |
| 278 | .map((tag) => [tag.Key, tag.Value]), |
| 279 | ); |
| 280 | |
| 281 | const toAttrs = ({ |
| 282 | cluster, |
| 283 | tags, |
| 284 | }: { |
| 285 | cluster: neptune.DBCluster; |
| 286 | tags: Record<string, string>; |
| 287 | }): DBCluster["Attributes"] => ({ |
| 288 | dbClusterIdentifier: cluster.DBClusterIdentifier ?? "", |
| 289 | dbClusterArn: cluster.DBClusterArn ?? "", |
| 290 | dbSubnetGroupName: cluster.DBSubnetGroup, |
| 291 | dbClusterParameterGroupName: cluster.DBClusterParameterGroup, |
| 292 | endpoint: cluster.Endpoint, |
| 293 | readerEndpoint: cluster.ReaderEndpoint, |
| 294 | port: cluster.Port, |
| 295 | engine: cluster.Engine ?? "neptune", |
| 296 | engineVersion: cluster.EngineVersion, |
| 297 | status: cluster.Status, |
| 298 | vpcSecurityGroupIds: (cluster.VpcSecurityGroups ?? []).flatMap((group) => |
| 299 | group.VpcSecurityGroupId ? [group.VpcSecurityGroupId] : [], |
| 300 | ), |
| 301 | backupRetentionPeriod: cluster.BackupRetentionPeriod, |
| 302 | preferredBackupWindow: cluster.PreferredBackupWindow, |
| 303 | preferredMaintenanceWindow: cluster.PreferredMaintenanceWindow, |
| 304 | storageEncrypted: cluster.StorageEncrypted, |
| 305 | kmsKeyId: cluster.KmsKeyId, |
| 306 | deletionProtection: cluster.DeletionProtection, |
| 307 | iamDatabaseAuthenticationEnabled: cluster.IAMDatabaseAuthenticationEnabled, |
| 308 | associatedRoles: (cluster.AssociatedRoles ?? []).map((role) => ({ |
| 309 | roleArn: role.RoleArn, |
| 310 | featureName: role.FeatureName, |
| 311 | status: role.Status, |
| 312 | })), |
| 313 | serverlessV2ScalingConfiguration: cluster.ServerlessV2ScalingConfiguration |
| 314 | ? { |
| 315 | minCapacity: cluster.ServerlessV2ScalingConfiguration.MinCapacity, |
| 316 | maxCapacity: cluster.ServerlessV2ScalingConfiguration.MaxCapacity, |
| 317 | } |
| 318 | : undefined, |
| 319 | dbClusterMembers: (cluster.DBClusterMembers ?? []).map((member) => ({ |
| 320 | dbInstanceIdentifier: member.DBInstanceIdentifier, |
| 321 | isClusterWriter: member.IsClusterWriter, |
| 322 | promotionTier: member.PromotionTier, |
| 323 | })), |
| 324 | dbClusterResourceId: cluster.DbClusterResourceId, |
| 325 | hostedZoneId: cluster.HostedZoneId, |
| 326 | multiAZ: cluster.MultiAZ, |
| 327 | enabledCloudwatchLogsExports: cluster.EnabledCloudwatchLogsExports ?? [], |
| 328 | clusterCreateTime: cluster.ClusterCreateTime?.toISOString(), |
| 329 | storageType: cluster.StorageType, |
| 330 | copyTagsToSnapshot: cluster.CopyTagsToSnapshot, |
| 331 | tags, |
| 332 | }); |
| 333 | |
| 334 | /** |
| 335 | * Compute the CloudWatch Logs export delta. The modify API is delta-shaped |
| 336 | * (`EnableLogTypes`/`DisableLogTypes`), so it must NOT carry the full set. |
| 337 | * Returns `undefined` when there is no change. |
| 338 | */ |
| 339 | const logExportDelta = ( |
| 340 | observed: string[] | undefined, |
| 341 | desired: string[] | undefined, |
| 342 | ): neptune.CloudwatchLogsExportConfiguration | undefined => { |
| 343 | if (desired === undefined) return undefined; |
| 344 | const have = new Set(observed ?? []); |
| 345 | const want = new Set(desired); |
| 346 | const EnableLogTypes = [...want].filter((t) => !have.has(t)); |
| 347 | const DisableLogTypes = [...have].filter((t) => !want.has(t)); |
| 348 | if (EnableLogTypes.length === 0 && DisableLogTypes.length === 0) { |
| 349 | return undefined; |
| 350 | } |
| 351 | return { |
| 352 | ...(EnableLogTypes.length > 0 ? { EnableLogTypes } : {}), |
| 353 | ...(DisableLogTypes.length > 0 ? { DisableLogTypes } : {}), |
| 354 | }; |
| 355 | }; |
| 356 | |
| 357 | export const DBClusterProvider = () => |
| 358 | Provider.effect( |
| 359 | DBCluster, |
| 360 | Effect.gen(function* () { |
| 361 | const toIdentifier = (id: string, props: DBClusterProps) => |
| 362 | props.dbClusterIdentifier |
| 363 | ? Effect.succeed(props.dbClusterIdentifier) |
| 364 | : createPhysicalName({ id, maxLength: 63 }); |
| 365 | |
| 366 | const readCluster = Effect.fn(function* (clusterId: string) { |
| 367 | const response = yield* neptune |
| 368 | .describeDBClusters({ |
| 369 | DBClusterIdentifier: clusterId, |
| 370 | }) |
| 371 | .pipe(Effect.catchTag("DBClusterNotFoundFault", () => Effect.undefined)); |
| 372 | return response?.DBClusters?.[0]; |
| 373 | }); |
| 374 | |
| 375 | const readTags = Effect.fn(function* (arn: string | undefined) { |
| 376 | if (!arn) return {} as Record<string, string>; |
| 377 | const response = yield* neptune |
| 378 | .listTagsForResource({ ResourceName: arn }) |
| 379 | .pipe(Effect.catchTag("DBClusterNotFoundFault", () => Effect.undefined)); |
| 380 | return toTagRecord(response?.TagList); |
| 381 | }); |
| 382 | |
| 383 | // Bounded readiness wait. Gate on cluster `Status === "available"` so a |
| 384 | // follow-on `modifyDBCluster` doesn't hit `InvalidDBClusterStateFault`. |
| 385 | // Budgets ~10 min (60 * 10s) for slow provisioning. |
| 386 | const waitForCluster = Effect.fn(function* (clusterId: string) { |
| 387 | const readinessPolicy = Schedule.max([Schedule.fixed("10 seconds"), Schedule.recurs(60)]); |
| 388 | return yield* readCluster(clusterId).pipe( |
| 389 | Effect.flatMap((cluster) => { |
| 390 | if (!cluster?.DBClusterArn) { |
| 391 | return Effect.fail( |
| 392 | new NeptuneDBClusterNotReady({ message: `DB cluster '${clusterId}' not found` }), |
| 393 | ); |
| 394 | } |
| 395 | if (cluster.Status !== "available") { |
| 396 | return Effect.fail( |
| 397 | new NeptuneDBClusterNotReady({ |
| 398 | message: `DB cluster '${clusterId}' not available (status: ${cluster.Status})`, |
| 399 | }), |
| 400 | ); |
| 401 | } |
| 402 | return Effect.succeed(cluster); |
| 403 | }), |
| 404 | Effect.retry({ schedule: readinessPolicy }), |
| 405 | ); |
| 406 | }); |
| 407 | |
| 408 | return { |
| 409 | stables: ["dbClusterArn", "dbClusterIdentifier"], |
| 410 | // AWS account/region collection: the RDS-family control plane serves |
| 411 | // clusters for every engine (RDS, DocumentDB, Neptune), so filter to |
| 412 | // `engine = neptune`. Tags are not surfaced inline — mirror |
| 413 | // `DBSubnetGroup.list` and emit an empty tag map rather than a |
| 414 | // per-item `listTagsForResource` fan-out. |
| 415 | list: () => |
| 416 | neptune.describeDBClusters |
| 417 | .pages({ Filters: [{ Name: "engine", Values: ["neptune"] }] }) |
| 418 | .pipe( |
| 419 | Stream.runCollect, |
| 420 | Effect.map((chunk) => |
| 421 | Array.from(chunk).flatMap((page) => |
| 422 | (page.DBClusters ?? []).map((cluster) => toAttrs({ cluster, tags: {} })), |
| 423 | ), |
| 424 | ), |
| 425 | ), |
| 426 | diff: Effect.fn(function* ({ id, olds, news }) { |
| 427 | if (!isResolved(news)) return; |
| 428 | if ( |
| 429 | (yield* toIdentifier(id, olds ?? ({} as DBClusterProps))) !== |
| 430 | (yield* toIdentifier(id, news)) |
| 431 | ) { |
| 432 | return { action: "replace" } as const; |
| 433 | } |
| 434 | // Immutable props — any change forces a fresh cluster. |
| 435 | if ( |
| 436 | olds !== undefined && |
| 437 | ((olds.engine ?? "neptune") !== (news.engine ?? "neptune") || |
| 438 | olds.dbSubnetGroupName !== news.dbSubnetGroupName || |
| 439 | olds.storageEncrypted !== news.storageEncrypted || |
| 440 | olds.kmsKeyId !== news.kmsKeyId || |
| 441 | olds.globalClusterIdentifier !== news.globalClusterIdentifier || |
| 442 | JSON.stringify(olds.availabilityZones ?? []) !== |
| 443 | JSON.stringify(news.availabilityZones ?? [])) |
| 444 | ) { |
| 445 | return { action: "replace" } as const; |
| 446 | } |
| 447 | }), |
| 448 | read: Effect.fn(function* ({ id, olds, output }) { |
| 449 | const identifier = |
| 450 | output?.dbClusterIdentifier ?? |
| 451 | (yield* toIdentifier(id, olds ?? ({} as DBClusterProps))); |
| 452 | const cluster = yield* readCluster(identifier); |
| 453 | if (!cluster?.DBClusterArn) { |
| 454 | return undefined; |
| 455 | } |
| 456 | const tags = yield* readTags(cluster.DBClusterArn); |
| 457 | return toAttrs({ cluster, tags }); |
| 458 | }), |
| 459 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 460 | const identifier = output?.dbClusterIdentifier ?? (yield* toIdentifier(id, news)); |
| 461 | const internalTags = yield* createInternalTags(id); |
| 462 | const desiredTags = { ...internalTags, ...news.tags }; |
| 463 | // The wire field is whole days. |
| 464 | const backupRetentionDays = toWireDays(news.backupRetentionPeriod); |
| 465 | |
| 466 | // Observe — fetch live cluster state. |
| 467 | let observed = yield* readCluster(identifier); |
| 468 | |
| 469 | // Ensure — create the cluster if it's missing. Tolerate |
| 470 | // `DBClusterAlreadyExistsFault` as a race with a peer reconciler. |
| 471 | if (!observed?.DBClusterArn) { |
| 472 | yield* neptune |
| 473 | .createDBCluster({ |
| 474 | DBClusterIdentifier: identifier, |
| 475 | Engine: news.engine ?? "neptune", |
| 476 | EngineVersion: news.engineVersion, |
| 477 | DBSubnetGroupName: news.dbSubnetGroupName, |
| 478 | DBClusterParameterGroupName: news.dbClusterParameterGroupName, |
| 479 | VpcSecurityGroupIds: news.vpcSecurityGroupIds, |
| 480 | Port: news.port, |
| 481 | AvailabilityZones: news.availabilityZones, |
| 482 | BackupRetentionPeriod: backupRetentionDays, |
| 483 | PreferredBackupWindow: news.preferredBackupWindow, |
| 484 | PreferredMaintenanceWindow: news.preferredMaintenanceWindow, |
| 485 | EnableCloudwatchLogsExports: news.enableCloudwatchLogsExports, |
| 486 | EnableIAMDatabaseAuthentication: news.enableIAMDatabaseAuthentication, |
| 487 | ServerlessV2ScalingConfiguration: news.serverlessV2ScalingConfiguration |
| 488 | ? { |
| 489 | MinCapacity: news.serverlessV2ScalingConfiguration.minCapacity, |
| 490 | MaxCapacity: news.serverlessV2ScalingConfiguration.maxCapacity, |
| 491 | } |
| 492 | : undefined, |
| 493 | DeletionProtection: news.deletionProtection, |
| 494 | StorageEncrypted: news.storageEncrypted, |
| 495 | KmsKeyId: news.kmsKeyId, |
| 496 | StorageType: news.storageType, |
| 497 | CopyTagsToSnapshot: news.copyTagsToSnapshot, |
| 498 | GlobalClusterIdentifier: news.globalClusterIdentifier, |
| 499 | Tags: Object.entries(desiredTags).map(([Key, Value]) => ({ |
| 500 | Key, |
| 501 | Value, |
| 502 | })), |
| 503 | }) |
| 504 | .pipe(Effect.catchTag("DBClusterAlreadyExistsFault", () => Effect.void)); |
| 505 | |
| 506 | observed = yield* waitForCluster(identifier); |
| 507 | } else { |
| 508 | // Wait for the cluster to settle before any modify so the call |
| 509 | // doesn't hit `InvalidDBClusterStateFault`. |
| 510 | observed = yield* waitForCluster(identifier); |
| 511 | |
| 512 | // syncCoreSettings — single `modifyDBCluster` carrying scalar |
| 513 | // in-place fields, only emitting a field when the desired value |
| 514 | // differs from the observed cloud state. |
| 515 | const core: neptune.ModifyDBClusterMessage = { |
| 516 | DBClusterIdentifier: identifier, |
| 517 | ApplyImmediately: true, |
| 518 | }; |
| 519 | let coreDirty = false; |
| 520 | const setIf = <K extends keyof neptune.ModifyDBClusterMessage>( |
| 521 | key: K, |
| 522 | desired: neptune.ModifyDBClusterMessage[K] | undefined, |
| 523 | observedValue: unknown, |
| 524 | ) => { |
| 525 | if (desired !== undefined && desired !== observedValue) { |
| 526 | core[key] = desired; |
| 527 | coreDirty = true; |
| 528 | } |
| 529 | }; |
| 530 | setIf("EngineVersion", news.engineVersion, observed.EngineVersion); |
| 531 | setIf("Port", news.port, observed.Port); |
| 532 | setIf("BackupRetentionPeriod", backupRetentionDays, observed.BackupRetentionPeriod); // prettier-ignore |
| 533 | setIf("PreferredBackupWindow", news.preferredBackupWindow, observed.PreferredBackupWindow); // prettier-ignore |
| 534 | setIf("PreferredMaintenanceWindow", news.preferredMaintenanceWindow, observed.PreferredMaintenanceWindow); // prettier-ignore |
| 535 | setIf("DeletionProtection", news.deletionProtection, observed.DeletionProtection); // prettier-ignore |
| 536 | setIf("StorageType", news.storageType, observed.StorageType); |
| 537 | setIf("CopyTagsToSnapshot", news.copyTagsToSnapshot, observed.CopyTagsToSnapshot); // prettier-ignore |
| 538 | setIf("EnableIAMDatabaseAuthentication", news.enableIAMDatabaseAuthentication, observed.IAMDatabaseAuthenticationEnabled); // prettier-ignore |
| 539 | setIf("DBClusterParameterGroupName", news.dbClusterParameterGroupName, observed.DBClusterParameterGroup); // prettier-ignore |
| 540 | if (news.vpcSecurityGroupIds !== undefined) { |
| 541 | const observedGroups = (observed.VpcSecurityGroups ?? []) |
| 542 | .flatMap((g) => (g.VpcSecurityGroupId ? [g.VpcSecurityGroupId] : [])) |
| 543 | .sort(); |
| 544 | if ( |
| 545 | JSON.stringify(observedGroups) !== |
| 546 | JSON.stringify([...news.vpcSecurityGroupIds].sort()) |
| 547 | ) { |
| 548 | core.VpcSecurityGroupIds = news.vpcSecurityGroupIds; |
| 549 | coreDirty = true; |
| 550 | } |
| 551 | } |
| 552 | if (news.serverlessV2ScalingConfiguration !== undefined) { |
| 553 | const observedScaling = observed.ServerlessV2ScalingConfiguration; |
| 554 | if ( |
| 555 | observedScaling?.MinCapacity !== |
| 556 | news.serverlessV2ScalingConfiguration.minCapacity || |
| 557 | observedScaling?.MaxCapacity !== news.serverlessV2ScalingConfiguration.maxCapacity |
| 558 | ) { |
| 559 | core.ServerlessV2ScalingConfiguration = { |
| 560 | MinCapacity: news.serverlessV2ScalingConfiguration.minCapacity, |
| 561 | MaxCapacity: news.serverlessV2ScalingConfiguration.maxCapacity, |
| 562 | }; |
| 563 | coreDirty = true; |
| 564 | } |
| 565 | } |
| 566 | if (news.allowMajorVersionUpgrade) { |
| 567 | core.AllowMajorVersionUpgrade = true; |
| 568 | } |
| 569 | if (coreDirty) { |
| 570 | yield* neptune.modifyDBCluster(core); |
| 571 | observed = yield* waitForCluster(identifier); |
| 572 | } |
| 573 | |
| 574 | // syncCloudwatchLogsExports — delta-shaped; separate call. |
| 575 | const logDelta = logExportDelta( |
| 576 | observed.EnabledCloudwatchLogsExports, |
| 577 | news.enableCloudwatchLogsExports, |
| 578 | ); |
| 579 | if (logDelta) { |
| 580 | yield* neptune.modifyDBCluster({ |
| 581 | DBClusterIdentifier: identifier, |
| 582 | CloudwatchLogsExportConfiguration: logDelta, |
| 583 | ApplyImmediately: true, |
| 584 | }); |
| 585 | observed = yield* waitForCluster(identifier); |
| 586 | } |
| 587 | } |
| 588 | |
| 589 | // Sync associated IAM roles — diff observed cloud associations |
| 590 | // against desired. Only runs when the prop is set, so clusters |
| 591 | // that don't manage roles through Alchemy are left untouched. |
| 592 | if (news.associatedRoles !== undefined) { |
| 593 | const roleKey = (roleArn: string | undefined, featureName: string | undefined) => |
| 594 | `${roleArn ?? ""}|${featureName ?? ""}`; |
| 595 | const observedRoles = observed.AssociatedRoles ?? []; |
| 596 | const observedKeys = new Set( |
| 597 | observedRoles.map((role) => roleKey(role.RoleArn, role.FeatureName)), |
| 598 | ); |
| 599 | const desiredKeys = new Set( |
| 600 | news.associatedRoles.map((role) => roleKey(role.roleArn, role.featureName)), |
| 601 | ); |
| 602 | for (const role of news.associatedRoles) { |
| 603 | if (!observedKeys.has(roleKey(role.roleArn, role.featureName))) { |
| 604 | yield* neptune |
| 605 | .addRoleToDBCluster({ |
| 606 | DBClusterIdentifier: identifier, |
| 607 | RoleArn: role.roleArn, |
| 608 | FeatureName: role.featureName, |
| 609 | }) |
| 610 | .pipe(Effect.catchTag("DBClusterRoleAlreadyExistsFault", () => Effect.void)); |
| 611 | } |
| 612 | } |
| 613 | for (const role of observedRoles) { |
| 614 | if ( |
| 615 | role.RoleArn !== undefined && |
| 616 | !desiredKeys.has(roleKey(role.RoleArn, role.FeatureName)) |
| 617 | ) { |
| 618 | yield* neptune |
| 619 | .removeRoleFromDBCluster({ |
| 620 | DBClusterIdentifier: identifier, |
| 621 | RoleArn: role.RoleArn, |
| 622 | FeatureName: role.FeatureName, |
| 623 | }) |
| 624 | .pipe(Effect.catchTag("DBClusterRoleNotFoundFault", () => Effect.void)); |
| 625 | } |
| 626 | } |
| 627 | // Re-observe so the returned attributes carry the fresh |
| 628 | // associations. |
| 629 | observed = (yield* readCluster(identifier)) ?? observed; |
| 630 | } |
| 631 | |
| 632 | const dbClusterArn = observed.DBClusterArn ?? ""; |
| 633 | |
| 634 | // Sync tags — diff observed cloud tags against desired. |
| 635 | const observedTags = yield* readTags(dbClusterArn); |
| 636 | const { removed, upsert } = diffTags(observedTags, desiredTags); |
| 637 | if (upsert.length > 0 && dbClusterArn) { |
| 638 | yield* neptune.addTagsToResource({ |
| 639 | ResourceName: dbClusterArn, |
| 640 | Tags: upsert, |
| 641 | }); |
| 642 | } |
| 643 | if (removed.length > 0 && dbClusterArn) { |
| 644 | yield* neptune.removeTagsFromResource({ |
| 645 | ResourceName: dbClusterArn, |
| 646 | TagKeys: removed, |
| 647 | }); |
| 648 | } |
| 649 | |
| 650 | yield* session.note(dbClusterArn || identifier); |
| 651 | return toAttrs({ cluster: observed, tags: desiredTags }); |
| 652 | }), |
| 653 | delete: Effect.fn(function* ({ output }) { |
| 654 | yield* neptune |
| 655 | .deleteDBCluster({ |
| 656 | DBClusterIdentifier: output.dbClusterIdentifier, |
| 657 | SkipFinalSnapshot: true, |
| 658 | }) |
| 659 | .pipe(Effect.catchTag("DBClusterNotFoundFault", () => Effect.void)); |
| 660 | // Block until the cluster is fully gone. Neptune deletion is async; |
| 661 | // if we return while it is still `deleting`, a dependent |
| 662 | // (DBSubnetGroup or VPC) is torn down next and AWS rejects it. |
| 663 | yield* Effect.repeat( |
| 664 | neptune |
| 665 | .describeDBClusters({ |
| 666 | DBClusterIdentifier: output.dbClusterIdentifier, |
| 667 | }) |
| 668 | .pipe( |
| 669 | Effect.as(true), |
| 670 | Effect.catchTag("DBClusterNotFoundFault", () => Effect.succeed(false)), |
| 671 | ), |
| 672 | { |
| 673 | schedule: Schedule.max([Schedule.fixed("15 seconds"), Schedule.recurs(40)]), |
| 674 | until: (exists) => exists === false, |
| 675 | }, |
| 676 | ).pipe(Effect.catch(() => Effect.void)); |
| 677 | }), |
| 678 | }; |
| 679 | }), |
| 680 | ); |