The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import * as dms from "@distilled.cloud/aws/database-migration-service"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 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, hasAlchemyTags } from "alchemy/Tags"; |
| 8 | import * as Data from "effect/Data"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import * as Schedule from "effect/Schedule"; |
| 11 | import * as Stream from "effect/Stream"; |
| 12 | import type { Providers } from "../Providers.ts"; |
| 13 | |
| 14 | export class ReplicationInstanceNotReady extends Data.TaggedError("ReplicationInstanceNotReady")<{ |
| 15 | readonly message: string; |
| 16 | readonly cause?: unknown; |
| 17 | }> {} |
| 18 | |
| 19 | export class ReplicationInstanceUnexpectedResponse extends Data.TaggedError( |
| 20 | "ReplicationInstanceUnexpectedResponse", |
| 21 | )<{ |
| 22 | readonly message: string; |
| 23 | readonly cause?: unknown; |
| 24 | }> {} |
| 25 | |
| 26 | export interface ReplicationInstanceProps { |
| 27 | /** |
| 28 | * Replication-instance identifier. Must be lowercase, 1-63 characters, |
| 29 | * begin with a letter, and contain only letters, digits, and hyphens. If |
| 30 | * omitted, a deterministic physical name is generated. Changing it replaces |
| 31 | * the instance. |
| 32 | */ |
| 33 | replicationInstanceIdentifier?: string; |
| 34 | /** |
| 35 | * Compute and memory class, e.g. `"dms.t3.small"`, `"dms.c5.large"`. |
| 36 | */ |
| 37 | replicationInstanceClass: string; |
| 38 | /** |
| 39 | * Storage in gigabytes allocated to the replication instance. |
| 40 | * @default service-chosen for the instance class |
| 41 | */ |
| 42 | allocatedStorage?: number; |
| 43 | /** |
| 44 | * VPC security group IDs controlling network access to the instance. |
| 45 | */ |
| 46 | vpcSecurityGroupIds?: string[]; |
| 47 | /** |
| 48 | * Availability Zone the instance is created in. Changing it replaces the |
| 49 | * instance. |
| 50 | */ |
| 51 | availabilityZone?: string; |
| 52 | /** |
| 53 | * Subnet group the instance is placed in. Changing it replaces the |
| 54 | * instance. |
| 55 | */ |
| 56 | replicationSubnetGroupIdentifier?: string; |
| 57 | /** |
| 58 | * Weekly maintenance window in `ddd:hh24:mi-ddd:hh24:mi` (UTC) format. |
| 59 | */ |
| 60 | preferredMaintenanceWindow?: string; |
| 61 | /** |
| 62 | * Whether to provision the instance across multiple Availability Zones. |
| 63 | * @default false |
| 64 | */ |
| 65 | multiAZ?: boolean; |
| 66 | /** |
| 67 | * DMS engine version. |
| 68 | * @default latest |
| 69 | */ |
| 70 | engineVersion?: string; |
| 71 | /** |
| 72 | * Whether minor engine upgrades are applied automatically during the |
| 73 | * maintenance window. |
| 74 | * @default true |
| 75 | */ |
| 76 | autoMinorVersionUpgrade?: boolean; |
| 77 | /** |
| 78 | * Customer-managed KMS key for storage encryption. Changing it replaces the |
| 79 | * instance. |
| 80 | * @default AWS-owned DMS key |
| 81 | */ |
| 82 | kmsKeyId?: string; |
| 83 | /** |
| 84 | * Whether the instance gets a public IP address. Changing it replaces the |
| 85 | * instance. |
| 86 | * @default true |
| 87 | */ |
| 88 | publiclyAccessible?: boolean; |
| 89 | /** |
| 90 | * Network type: `"IPV4"`, `"IPV6"`, or `"DUAL"`. Changing it replaces the |
| 91 | * instance. |
| 92 | */ |
| 93 | networkType?: string; |
| 94 | /** |
| 95 | * User-defined tags for the instance. |
| 96 | */ |
| 97 | tags?: Record<string, string>; |
| 98 | } |
| 99 | |
| 100 | export interface ReplicationInstance extends Resource< |
| 101 | "AWS.DMS.ReplicationInstance", |
| 102 | ReplicationInstanceProps, |
| 103 | { |
| 104 | /** The replication instance identifier (unique per account/region). */ |
| 105 | replicationInstanceIdentifier: string; |
| 106 | /** The ARN of the replication instance. */ |
| 107 | replicationInstanceArn: string; |
| 108 | /** The compute class of the instance, e.g. `dms.t3.small`. */ |
| 109 | replicationInstanceClass: string; |
| 110 | /** The current status of the instance, e.g. `available`. */ |
| 111 | status: string | undefined; |
| 112 | /** The DMS engine version running on the instance. */ |
| 113 | engineVersion: string | undefined; |
| 114 | /** The private IP addresses of the instance. */ |
| 115 | privateIpAddresses: string[]; |
| 116 | /** The public IP addresses of the instance (when publicly accessible). */ |
| 117 | publicIpAddresses: string[]; |
| 118 | /** The tags attached to the replication instance. */ |
| 119 | tags: Record<string, string>; |
| 120 | }, |
| 121 | never, |
| 122 | Providers |
| 123 | > {} |
| 124 | |
| 125 | /** |
| 126 | * A DMS replication instance — the managed compute that runs migration and |
| 127 | * replication tasks. Provisioning takes several minutes and the instance is |
| 128 | * billed hourly while it exists, so create it only when a migration is |
| 129 | * running and destroy it promptly. |
| 130 | * ### Creating a Replication Instance |
| 131 | * **Example:** Small Instance in a Subnet Group |
| 132 | * ```typescript |
| 133 | * const instance = yield* ReplicationInstance("Migration", { |
| 134 | * replicationInstanceClass: "dms.t3.small", |
| 135 | * allocatedStorage: 50, |
| 136 | * replicationSubnetGroupIdentifier: subnetGroup.replicationSubnetGroupIdentifier, |
| 137 | * publiclyAccessible: false, |
| 138 | * }); |
| 139 | * ``` |
| 140 | * |
| 141 | * @resource |
| 142 | */ |
| 143 | export const ReplicationInstance = Resource<ReplicationInstance>("AWS.DMS.ReplicationInstance"); |
| 144 | |
| 145 | const toTagRecord = ( |
| 146 | tags: Array<{ Key?: string; Value?: string }> | undefined, |
| 147 | ): Record<string, string> => |
| 148 | Object.fromEntries( |
| 149 | (tags ?? []) |
| 150 | .filter( |
| 151 | (tag): tag is { Key: string; Value: string } => |
| 152 | typeof tag.Key === "string" && typeof tag.Value === "string", |
| 153 | ) |
| 154 | .map((tag) => [tag.Key, tag.Value]), |
| 155 | ); |
| 156 | |
| 157 | export const ReplicationInstanceProvider = () => |
| 158 | Provider.effect( |
| 159 | ReplicationInstance, |
| 160 | Effect.gen(function* () { |
| 161 | const toName = (id: string, props: ReplicationInstanceProps) => |
| 162 | props.replicationInstanceIdentifier |
| 163 | ? Effect.succeed(props.replicationInstanceIdentifier) |
| 164 | : createPhysicalName({ id, maxLength: 60, lowercase: true }); |
| 165 | |
| 166 | const findInstance = Effect.fn(function* (identifier: string) { |
| 167 | const response = yield* dms |
| 168 | .describeReplicationInstances({ |
| 169 | Filters: [{ Name: "replication-instance-id", Values: [identifier] }], |
| 170 | }) |
| 171 | .pipe(Effect.catchTag("ResourceNotFoundFault", () => Effect.undefined)); |
| 172 | return response?.ReplicationInstances?.[0]; |
| 173 | }); |
| 174 | |
| 175 | const readTags = Effect.fn(function* (arn: string) { |
| 176 | const response = yield* dms |
| 177 | .listTagsForResource({ ResourceArn: arn }) |
| 178 | .pipe(Effect.orElseSucceed(() => undefined)); |
| 179 | return toTagRecord(response?.TagList); |
| 180 | }); |
| 181 | |
| 182 | // Provisioning and modifications both surface as a transitional status; |
| 183 | // budget ~15 minutes (15s x 60) for the instance to become available. |
| 184 | const waitForInstance = Effect.fn(function* (identifier: string) { |
| 185 | const readinessPolicy = Schedule.max([Schedule.fixed("15 seconds"), Schedule.recurs(60)]); |
| 186 | return yield* findInstance(identifier).pipe( |
| 187 | Effect.flatMap((instance) => { |
| 188 | if (!instance?.ReplicationInstanceArn) { |
| 189 | return Effect.fail( |
| 190 | new ReplicationInstanceNotReady({ |
| 191 | message: `DMS replication instance '${identifier}' not found`, |
| 192 | }), |
| 193 | ); |
| 194 | } |
| 195 | if (instance.ReplicationInstanceStatus !== "available") { |
| 196 | return Effect.fail( |
| 197 | new ReplicationInstanceNotReady({ |
| 198 | message: `DMS replication instance '${identifier}' not available (status: ${instance.ReplicationInstanceStatus})`, |
| 199 | }), |
| 200 | ); |
| 201 | } |
| 202 | return Effect.succeed(instance); |
| 203 | }), |
| 204 | Effect.retry({ schedule: readinessPolicy }), |
| 205 | ); |
| 206 | }); |
| 207 | |
| 208 | const toAttrs = Effect.fn(function* (instance: dms.ReplicationInstance) { |
| 209 | const identifier = instance.ReplicationInstanceIdentifier; |
| 210 | if (!identifier || !instance.ReplicationInstanceArn) { |
| 211 | return yield* new ReplicationInstanceUnexpectedResponse({ |
| 212 | message: `DMS replication instance '${identifier}' is missing its identifier or ARN`, |
| 213 | }); |
| 214 | } |
| 215 | return { |
| 216 | replicationInstanceIdentifier: identifier, |
| 217 | replicationInstanceArn: instance.ReplicationInstanceArn, |
| 218 | replicationInstanceClass: instance.ReplicationInstanceClass ?? "", |
| 219 | status: instance.ReplicationInstanceStatus, |
| 220 | engineVersion: instance.EngineVersion, |
| 221 | privateIpAddresses: [...(instance.ReplicationInstancePrivateIpAddresses ?? [])], |
| 222 | publicIpAddresses: [...(instance.ReplicationInstancePublicIpAddresses ?? [])], |
| 223 | tags: yield* readTags(instance.ReplicationInstanceArn), |
| 224 | }; |
| 225 | }); |
| 226 | |
| 227 | return { |
| 228 | stables: ["replicationInstanceIdentifier", "replicationInstanceArn"], |
| 229 | |
| 230 | diff: Effect.fn(function* ({ id, olds, news }) { |
| 231 | if (!isResolved(news)) return undefined; |
| 232 | if ( |
| 233 | (yield* toName( |
| 234 | id, |
| 235 | olds ?? |
| 236 | ({ |
| 237 | replicationInstanceClass: "", |
| 238 | } as ReplicationInstanceProps), |
| 239 | )) !== (yield* toName(id, news)) |
| 240 | ) { |
| 241 | return { action: "replace" } as const; |
| 242 | } |
| 243 | // Create-only properties force a replacement. |
| 244 | if ((news.publiclyAccessible ?? undefined) !== (olds?.publiclyAccessible ?? undefined)) { |
| 245 | return { action: "replace" } as const; |
| 246 | } |
| 247 | if ((news.kmsKeyId ?? undefined) !== (olds?.kmsKeyId ?? undefined)) { |
| 248 | return { action: "replace" } as const; |
| 249 | } |
| 250 | if ((news.availabilityZone ?? undefined) !== (olds?.availabilityZone ?? undefined)) { |
| 251 | return { action: "replace" } as const; |
| 252 | } |
| 253 | if ( |
| 254 | (news.replicationSubnetGroupIdentifier ?? undefined) !== |
| 255 | (olds?.replicationSubnetGroupIdentifier ?? undefined) |
| 256 | ) { |
| 257 | return { action: "replace" } as const; |
| 258 | } |
| 259 | if ((news.networkType ?? undefined) !== (olds?.networkType ?? undefined)) { |
| 260 | return { action: "replace" } as const; |
| 261 | } |
| 262 | }), |
| 263 | |
| 264 | read: Effect.fn(function* ({ id, olds, output }) { |
| 265 | const name = |
| 266 | output?.replicationInstanceIdentifier ?? |
| 267 | (yield* toName( |
| 268 | id, |
| 269 | olds ?? |
| 270 | ({ |
| 271 | replicationInstanceClass: "", |
| 272 | } as ReplicationInstanceProps), |
| 273 | )); |
| 274 | const instance = yield* findInstance(name); |
| 275 | if (!instance?.ReplicationInstanceArn) return undefined; |
| 276 | const attrs = yield* toAttrs(instance); |
| 277 | return (yield* hasAlchemyTags(id, attrs.tags)) ? attrs : Unowned(attrs); |
| 278 | }), |
| 279 | |
| 280 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 281 | const name = output?.replicationInstanceIdentifier ?? (yield* toName(id, news)); |
| 282 | const internalTags = yield* createInternalTags(id); |
| 283 | const desiredTags = { ...internalTags, ...news.tags }; |
| 284 | |
| 285 | // 1. Observe — cloud state is authoritative. |
| 286 | let observed = yield* findInstance(name); |
| 287 | |
| 288 | // 2. Ensure — create if missing; tolerate AlreadyExists as a race. |
| 289 | if (observed === undefined) { |
| 290 | yield* dms |
| 291 | .createReplicationInstance({ |
| 292 | ReplicationInstanceIdentifier: name, |
| 293 | ReplicationInstanceClass: news.replicationInstanceClass, |
| 294 | AllocatedStorage: news.allocatedStorage, |
| 295 | VpcSecurityGroupIds: news.vpcSecurityGroupIds, |
| 296 | AvailabilityZone: news.availabilityZone, |
| 297 | ReplicationSubnetGroupIdentifier: news.replicationSubnetGroupIdentifier, |
| 298 | PreferredMaintenanceWindow: news.preferredMaintenanceWindow, |
| 299 | MultiAZ: news.multiAZ, |
| 300 | EngineVersion: news.engineVersion, |
| 301 | AutoMinorVersionUpgrade: news.autoMinorVersionUpgrade, |
| 302 | KmsKeyId: news.kmsKeyId, |
| 303 | PubliclyAccessible: news.publiclyAccessible, |
| 304 | NetworkType: news.networkType, |
| 305 | Tags: Object.entries(desiredTags).map(([Key, Value]) => ({ |
| 306 | Key, |
| 307 | Value, |
| 308 | })), |
| 309 | }) |
| 310 | .pipe(Effect.catchTag("ResourceAlreadyExistsFault", () => Effect.void)); |
| 311 | } |
| 312 | |
| 313 | // Wait for availability so sync/modify calls don't hit |
| 314 | // InvalidResourceStateFault. |
| 315 | observed = yield* waitForInstance(name); |
| 316 | |
| 317 | // 3. Sync — compute the modify delta from OBSERVED state. Immutable |
| 318 | // properties are handled by diff (replacement), so only mutable |
| 319 | // aspects are compared here. |
| 320 | const modify: dms.ModifyReplicationInstanceMessage = { |
| 321 | ReplicationInstanceArn: observed.ReplicationInstanceArn!, |
| 322 | ApplyImmediately: true, |
| 323 | }; |
| 324 | let dirty = false; |
| 325 | if (news.replicationInstanceClass !== observed.ReplicationInstanceClass) { |
| 326 | modify.ReplicationInstanceClass = news.replicationInstanceClass; |
| 327 | dirty = true; |
| 328 | } |
| 329 | if ( |
| 330 | news.allocatedStorage !== undefined && |
| 331 | news.allocatedStorage !== observed.AllocatedStorage |
| 332 | ) { |
| 333 | modify.AllocatedStorage = news.allocatedStorage; |
| 334 | dirty = true; |
| 335 | } |
| 336 | if (news.multiAZ !== undefined && news.multiAZ !== observed.MultiAZ) { |
| 337 | modify.MultiAZ = news.multiAZ; |
| 338 | dirty = true; |
| 339 | } |
| 340 | if (news.engineVersion !== undefined && news.engineVersion !== observed.EngineVersion) { |
| 341 | modify.EngineVersion = news.engineVersion; |
| 342 | modify.AllowMajorVersionUpgrade = true; |
| 343 | dirty = true; |
| 344 | } |
| 345 | if ( |
| 346 | news.preferredMaintenanceWindow !== undefined && |
| 347 | news.preferredMaintenanceWindow !== observed.PreferredMaintenanceWindow |
| 348 | ) { |
| 349 | modify.PreferredMaintenanceWindow = news.preferredMaintenanceWindow; |
| 350 | dirty = true; |
| 351 | } |
| 352 | |
| 353 | if (dirty) { |
| 354 | yield* dms.modifyReplicationInstance(modify); |
| 355 | observed = yield* waitForInstance(name); |
| 356 | } |
| 357 | |
| 358 | // 3b. Sync tags — diff against OBSERVED cloud tags. |
| 359 | const arn = observed.ReplicationInstanceArn!; |
| 360 | const observedTags = yield* readTags(arn); |
| 361 | const { upsert, removed } = diffTags(observedTags, desiredTags); |
| 362 | if (upsert.length > 0) { |
| 363 | yield* dms.addTagsToResource({ ResourceArn: arn, Tags: upsert }); |
| 364 | } |
| 365 | if (removed.length > 0) { |
| 366 | yield* dms.removeTagsFromResource({ |
| 367 | ResourceArn: arn, |
| 368 | TagKeys: removed, |
| 369 | }); |
| 370 | } |
| 371 | |
| 372 | yield* session.note(name); |
| 373 | return yield* toAttrs(observed); |
| 374 | }), |
| 375 | |
| 376 | delete: Effect.fn(function* ({ output }) { |
| 377 | // Converge to "gone", not just "delete requested": a `deleting` |
| 378 | // instance still holds its replication subnet group, so deleting |
| 379 | // the group right after fails with InvalidResourceStateFault |
| 380 | // ("Cannot delete the subnet group ... because at least one |
| 381 | // replication instance ... is using it"). Each attempt observes the |
| 382 | // instance; a mid-create/modify instance rejects deletion with |
| 383 | // InvalidResourceStateFault until it settles, so retry then too. |
| 384 | // Instance deletion takes ~5-10 minutes; budget ~15 min (15s x 60). |
| 385 | yield* Effect.gen(function* () { |
| 386 | const instance = yield* findInstance(output.replicationInstanceIdentifier); |
| 387 | if (instance === undefined) return; |
| 388 | if (instance.ReplicationInstanceStatus !== "deleting") { |
| 389 | yield* dms |
| 390 | .deleteReplicationInstance({ |
| 391 | ReplicationInstanceArn: output.replicationInstanceArn, |
| 392 | }) |
| 393 | .pipe( |
| 394 | Effect.catchTags({ |
| 395 | ResourceNotFoundFault: () => Effect.void, |
| 396 | InvalidResourceStateFault: () => Effect.void, |
| 397 | }), |
| 398 | ); |
| 399 | } |
| 400 | return yield* new ReplicationInstanceNotReady({ |
| 401 | message: `DMS replication instance '${output.replicationInstanceIdentifier}' still exists (status: ${instance.ReplicationInstanceStatus})`, |
| 402 | }); |
| 403 | }).pipe( |
| 404 | Effect.retry({ |
| 405 | schedule: Schedule.max([Schedule.fixed("15 seconds"), Schedule.recurs(60)]), |
| 406 | }), |
| 407 | ); |
| 408 | }), |
| 409 | |
| 410 | list: () => |
| 411 | dms.describeReplicationInstances.pages({}).pipe( |
| 412 | Stream.runCollect, |
| 413 | Effect.map((chunk) => |
| 414 | Array.from(chunk).flatMap((page) => |
| 415 | (page.ReplicationInstances ?? []).filter( |
| 416 | (instance) => |
| 417 | instance.ReplicationInstanceIdentifier !== undefined && |
| 418 | instance.ReplicationInstanceArn !== undefined, |
| 419 | ), |
| 420 | ), |
| 421 | ), |
| 422 | Effect.flatMap( |
| 423 | Effect.forEach((instance) => toAttrs(instance), { |
| 424 | concurrency: 4, |
| 425 | }), |
| 426 | ), |
| 427 | ), |
| 428 | }; |
| 429 | }), |
| 430 | ); |