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 * as iam from "@distilled.cloud/aws/iam"; |
| 3 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 4 | import { isResolved } from "alchemy/Diff"; |
| 5 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 6 | import * as Provider from "alchemy/Provider"; |
| 7 | import { Resource } from "alchemy/Resource"; |
| 8 | import { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags"; |
| 9 | import * as Data from "effect/Data"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import * as Schedule from "effect/Schedule"; |
| 12 | import * as Stream from "effect/Stream"; |
| 13 | import { AWSEnvironment } from "../Environment.ts"; |
| 14 | import type { Providers } from "../Providers.ts"; |
| 15 | |
| 16 | export class ReplicationSubnetGroupUnexpectedResponse extends Data.TaggedError( |
| 17 | "ReplicationSubnetGroupUnexpectedResponse", |
| 18 | )<{ |
| 19 | readonly message: string; |
| 20 | readonly cause?: unknown; |
| 21 | }> {} |
| 22 | |
| 23 | export interface ReplicationSubnetGroupProps { |
| 24 | /** |
| 25 | * Subnet-group identifier. Must be lowercase, 1-255 characters, and cannot |
| 26 | * be the reserved value `default`. If omitted, a deterministic physical |
| 27 | * name is generated. Changing it replaces the subnet group. |
| 28 | */ |
| 29 | replicationSubnetGroupIdentifier?: string; |
| 30 | /** |
| 31 | * Human-readable description of the subnet group. |
| 32 | */ |
| 33 | description?: string; |
| 34 | /** |
| 35 | * VPC subnet IDs the replication instance can be placed in. Must span at |
| 36 | * least two Availability Zones. |
| 37 | */ |
| 38 | subnetIds: string[]; |
| 39 | /** |
| 40 | * User-defined tags for the subnet group. |
| 41 | */ |
| 42 | tags?: Record<string, string>; |
| 43 | } |
| 44 | |
| 45 | export interface ReplicationSubnetGroup extends Resource< |
| 46 | "AWS.DMS.ReplicationSubnetGroup", |
| 47 | ReplicationSubnetGroupProps, |
| 48 | { |
| 49 | /** The subnet group identifier (unique per account/region). */ |
| 50 | replicationSubnetGroupIdentifier: string; |
| 51 | /** The ARN of the replication subnet group. */ |
| 52 | replicationSubnetGroupArn: string; |
| 53 | /** The VPC the subnets belong to. */ |
| 54 | vpcId: string | undefined; |
| 55 | /** The IDs of the subnets in the group. */ |
| 56 | subnetIds: string[]; |
| 57 | /** The current status of the subnet group, e.g. `Complete`. */ |
| 58 | status: string | undefined; |
| 59 | /** The tags attached to the subnet group. */ |
| 60 | tags: Record<string, string>; |
| 61 | }, |
| 62 | never, |
| 63 | Providers |
| 64 | > {} |
| 65 | |
| 66 | /** |
| 67 | * A DMS replication subnet group — the set of VPC subnets a replication |
| 68 | * instance can be launched into. Must cover at least two Availability Zones. |
| 69 | * Free and fast to create. |
| 70 | * ### Creating a Subnet Group |
| 71 | * **Example:** Two-AZ Subnet Group |
| 72 | * ```typescript |
| 73 | * const subnetGroup = yield* ReplicationSubnetGroup("Migration", { |
| 74 | * description: "DMS replication subnets", |
| 75 | * subnetIds: [subnetA.subnetId, subnetB.subnetId], |
| 76 | * }); |
| 77 | * ``` |
| 78 | * |
| 79 | * @resource |
| 80 | */ |
| 81 | export const ReplicationSubnetGroup = Resource<ReplicationSubnetGroup>( |
| 82 | "AWS.DMS.ReplicationSubnetGroup", |
| 83 | ); |
| 84 | |
| 85 | const toTagRecord = ( |
| 86 | tags: Array<{ Key?: string; Value?: string }> | undefined, |
| 87 | ): Record<string, string> => |
| 88 | Object.fromEntries( |
| 89 | (tags ?? []) |
| 90 | .filter( |
| 91 | (tag): tag is { Key: string; Value: string } => |
| 92 | typeof tag.Key === "string" && typeof tag.Value === "string", |
| 93 | ) |
| 94 | .map((tag) => [tag.Key, tag.Value]), |
| 95 | ); |
| 96 | |
| 97 | const sameStringSet = ( |
| 98 | a: readonly string[] | undefined, |
| 99 | b: readonly string[] | undefined, |
| 100 | ): boolean => { |
| 101 | const left = [...(a ?? [])].sort(); |
| 102 | const right = [...(b ?? [])].sort(); |
| 103 | return left.length === right.length && left.every((v, i) => v === right[i]); |
| 104 | }; |
| 105 | |
| 106 | const DMS_VPC_ROLE_NAME = "dms-vpc-role"; |
| 107 | const DMS_VPC_POLICY_ARN = "arn:aws:iam::aws:policy/service-role/AmazonDMSVPCManagementRole"; |
| 108 | const DMS_VPC_ROLE_OWNER_TAG = { |
| 109 | Key: "alchemy::managed-by", |
| 110 | Value: "AWS.DMS.ReplicationSubnetGroup", |
| 111 | } as const; |
| 112 | |
| 113 | export const ReplicationSubnetGroupProvider = () => |
| 114 | Provider.effect( |
| 115 | ReplicationSubnetGroup, |
| 116 | Effect.gen(function* () { |
| 117 | const toName = (id: string, props: ReplicationSubnetGroupProps) => |
| 118 | props.replicationSubnetGroupIdentifier |
| 119 | ? Effect.succeed(props.replicationSubnetGroupIdentifier) |
| 120 | : createPhysicalName({ id, maxLength: 200, lowercase: true }); |
| 121 | |
| 122 | // Subnet-group ARNs deterministically embed the identifier, so we build |
| 123 | // them rather than reading one back (describe returns no ARN). |
| 124 | const toArn = Effect.fn(function* (identifier: string) { |
| 125 | const { accountId, region } = yield* AWSEnvironment.current; |
| 126 | return `arn:aws:dms:${region}:${accountId}:subgrp:${identifier}`; |
| 127 | }); |
| 128 | |
| 129 | const findGroup = Effect.fn(function* (identifier: string) { |
| 130 | const response = yield* dms |
| 131 | .describeReplicationSubnetGroups({ |
| 132 | Filters: [{ Name: "replication-subnet-group-id", Values: [identifier] }], |
| 133 | }) |
| 134 | .pipe(Effect.catchTag("ResourceNotFoundFault", () => Effect.undefined)); |
| 135 | return response?.ReplicationSubnetGroups?.[0]; |
| 136 | }); |
| 137 | |
| 138 | // DMS requires the account-wide `dms-vpc-role` (trusting |
| 139 | // dms.amazonaws.com with the AmazonDMSVPCManagementRole managed policy) |
| 140 | // before any VPC-touching operation. The console creates it implicitly; |
| 141 | // API callers must ensure it. Tag only roles created by this provider so |
| 142 | // deletion can distinguish our helper from pre-existing account |
| 143 | // infrastructure with the same AWS-mandated name. |
| 144 | const ensureDmsVpcRole = Effect.gen(function* () { |
| 145 | yield* iam |
| 146 | .createRole({ |
| 147 | RoleName: DMS_VPC_ROLE_NAME, |
| 148 | AssumeRolePolicyDocument: JSON.stringify({ |
| 149 | Version: "2012-10-17", |
| 150 | Statement: [ |
| 151 | { |
| 152 | Effect: "Allow", |
| 153 | Principal: { Service: "dms.amazonaws.com" }, |
| 154 | Action: "sts:AssumeRole", |
| 155 | }, |
| 156 | ], |
| 157 | }), |
| 158 | Tags: [DMS_VPC_ROLE_OWNER_TAG], |
| 159 | }) |
| 160 | .pipe(Effect.catchTag("EntityAlreadyExistsException", () => Effect.void)); |
| 161 | // Idempotent — attaching an already-attached managed policy is a no-op. |
| 162 | yield* iam.attachRolePolicy({ |
| 163 | RoleName: DMS_VPC_ROLE_NAME, |
| 164 | PolicyArn: DMS_VPC_POLICY_ARN, |
| 165 | }); |
| 166 | }).pipe( |
| 167 | // A concurrent last-subnet-group delete can remove the shared helper |
| 168 | // between create/get and policy attachment. Re-observe and ensure it |
| 169 | // again instead of surfacing a cross-test race. |
| 170 | Effect.retry({ |
| 171 | while: (error) => |
| 172 | error._tag === "NoSuchEntityException" || |
| 173 | error._tag === "ConcurrentModificationException" || |
| 174 | error._tag === "LimitExceededException" || |
| 175 | error._tag === "ServiceFailureException", |
| 176 | schedule: Schedule.max([Schedule.fixed("1 second"), Schedule.recurs(10)]), |
| 177 | }), |
| 178 | ); |
| 179 | |
| 180 | const deleteOwnedDmsVpcRoleIfUnused = Effect.gen(function* () { |
| 181 | // Bound the whole observe/detach/delete loop to 30 seconds. Every pass |
| 182 | // rechecks DMS first, so a concurrent subnet-group create protects the |
| 183 | // role and takes responsibility for deleting it later. |
| 184 | for (let attempt = 0; attempt < 30; attempt++) { |
| 185 | const groups = yield* dms.describeReplicationSubnetGroups({}); |
| 186 | if ((groups.ReplicationSubnetGroups ?? []).length > 0) return; |
| 187 | |
| 188 | const tags = yield* iam |
| 189 | .listRoleTags({ RoleName: DMS_VPC_ROLE_NAME }) |
| 190 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.undefined)); |
| 191 | if (tags === undefined) return; |
| 192 | const owned = (tags.Tags ?? []).some( |
| 193 | (tag) => |
| 194 | tag.Key === DMS_VPC_ROLE_OWNER_TAG.Key && tag.Value === DMS_VPC_ROLE_OWNER_TAG.Value, |
| 195 | ); |
| 196 | if (!owned) return; |
| 197 | |
| 198 | const deleted = yield* Effect.gen(function* () { |
| 199 | yield* iam |
| 200 | .detachRolePolicy({ |
| 201 | RoleName: DMS_VPC_ROLE_NAME, |
| 202 | PolicyArn: DMS_VPC_POLICY_ARN, |
| 203 | }) |
| 204 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)); |
| 205 | yield* iam |
| 206 | .deleteRole({ RoleName: DMS_VPC_ROLE_NAME }) |
| 207 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)); |
| 208 | return true; |
| 209 | }).pipe( |
| 210 | Effect.catchTag( |
| 211 | [ |
| 212 | "ConcurrentModificationException", |
| 213 | "DeleteConflictException", |
| 214 | "LimitExceededException", |
| 215 | "ServiceFailureException", |
| 216 | ], |
| 217 | () => Effect.succeed(false), |
| 218 | ), |
| 219 | ); |
| 220 | if (!deleted) { |
| 221 | yield* Effect.sleep("1 second"); |
| 222 | continue; |
| 223 | } |
| 224 | |
| 225 | const remaining = yield* iam |
| 226 | .getRole({ RoleName: DMS_VPC_ROLE_NAME }) |
| 227 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.undefined)); |
| 228 | if (remaining === undefined) return; |
| 229 | yield* Effect.sleep("1 second"); |
| 230 | } |
| 231 | return yield* Effect.die( |
| 232 | new Error( |
| 233 | `IAM role ${DMS_VPC_ROLE_NAME} remained observable 30 seconds after the last DMS subnet group was deleted`, |
| 234 | ), |
| 235 | ); |
| 236 | }); |
| 237 | |
| 238 | const readTags = Effect.fn(function* (arn: string) { |
| 239 | const response = yield* dms |
| 240 | .listTagsForResource({ ResourceArn: arn }) |
| 241 | .pipe(Effect.orElseSucceed(() => undefined)); |
| 242 | return toTagRecord(response?.TagList); |
| 243 | }); |
| 244 | |
| 245 | const toAttrs = Effect.fn(function* (group: dms.ReplicationSubnetGroup) { |
| 246 | const identifier = group.ReplicationSubnetGroupIdentifier; |
| 247 | if (!identifier) { |
| 248 | return yield* new ReplicationSubnetGroupUnexpectedResponse({ |
| 249 | message: "DMS replication subnet group is missing its identifier", |
| 250 | }); |
| 251 | } |
| 252 | const arn = yield* toArn(identifier); |
| 253 | return { |
| 254 | replicationSubnetGroupIdentifier: identifier, |
| 255 | replicationSubnetGroupArn: arn, |
| 256 | vpcId: group.VpcId, |
| 257 | subnetIds: (group.Subnets ?? []) |
| 258 | .map((s) => s.SubnetIdentifier) |
| 259 | .filter((s): s is string => typeof s === "string"), |
| 260 | status: group.SubnetGroupStatus, |
| 261 | tags: yield* readTags(arn), |
| 262 | }; |
| 263 | }); |
| 264 | |
| 265 | return { |
| 266 | stables: ["replicationSubnetGroupIdentifier", "replicationSubnetGroupArn"], |
| 267 | |
| 268 | diff: Effect.fn(function* ({ id, olds, news }) { |
| 269 | if (!isResolved(news)) return undefined; |
| 270 | if ( |
| 271 | (yield* toName(id, olds ?? ({ subnetIds: [] } as ReplicationSubnetGroupProps))) !== |
| 272 | (yield* toName(id, news)) |
| 273 | ) { |
| 274 | return { action: "replace" } as const; |
| 275 | } |
| 276 | }), |
| 277 | |
| 278 | read: Effect.fn(function* ({ id, olds, output }) { |
| 279 | const name = |
| 280 | output?.replicationSubnetGroupIdentifier ?? |
| 281 | (yield* toName(id, olds ?? ({ subnetIds: [] } as ReplicationSubnetGroupProps))); |
| 282 | const group = yield* findGroup(name); |
| 283 | if (!group?.ReplicationSubnetGroupIdentifier) return undefined; |
| 284 | const attrs = yield* toAttrs(group); |
| 285 | return (yield* hasAlchemyTags(id, attrs.tags)) ? attrs : Unowned(attrs); |
| 286 | }), |
| 287 | |
| 288 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 289 | const name = output?.replicationSubnetGroupIdentifier ?? (yield* toName(id, news)); |
| 290 | const internalTags = yield* createInternalTags(id); |
| 291 | const desiredTags = { ...internalTags, ...news.tags }; |
| 292 | const description = news.description ?? "Managed by Alchemy"; |
| 293 | |
| 294 | // 1. Observe — cloud state is authoritative. |
| 295 | let observed = yield* findGroup(name); |
| 296 | |
| 297 | // 2. Ensure — create if missing; tolerate AlreadyExists as a race. |
| 298 | if (observed === undefined) { |
| 299 | yield* ensureDmsVpcRole; |
| 300 | yield* dms |
| 301 | .createReplicationSubnetGroup({ |
| 302 | ReplicationSubnetGroupIdentifier: name, |
| 303 | ReplicationSubnetGroupDescription: description, |
| 304 | SubnetIds: news.subnetIds, |
| 305 | Tags: Object.entries(desiredTags).map(([Key, Value]) => ({ |
| 306 | Key, |
| 307 | Value, |
| 308 | })), |
| 309 | }) |
| 310 | .pipe( |
| 311 | // A freshly-created dms-vpc-role takes a few seconds to |
| 312 | // propagate to DMS, which surfaces as AccessDeniedFault |
| 313 | // ("The IAM Role ... is not configured properly"). |
| 314 | Effect.catchTag("AccessDeniedFault", (error) => |
| 315 | ensureDmsVpcRole.pipe(Effect.andThen(Effect.fail(error))), |
| 316 | ), |
| 317 | Effect.retry({ |
| 318 | while: (e) => e._tag === "AccessDeniedFault", |
| 319 | schedule: Schedule.spaced("5 seconds"), |
| 320 | times: 10, |
| 321 | }), |
| 322 | Effect.catchTag("ResourceAlreadyExistsFault", () => Effect.void), |
| 323 | ); |
| 324 | observed = yield* findGroup(name); |
| 325 | } else { |
| 326 | // 3. Sync — modify description / subnet set in place when they drift. |
| 327 | const observedSubnets = (observed.Subnets ?? []) |
| 328 | .map((s) => s.SubnetIdentifier) |
| 329 | .filter((s): s is string => typeof s === "string"); |
| 330 | if ( |
| 331 | description !== observed.ReplicationSubnetGroupDescription || |
| 332 | !sameStringSet(news.subnetIds, observedSubnets) |
| 333 | ) { |
| 334 | yield* dms.modifyReplicationSubnetGroup({ |
| 335 | ReplicationSubnetGroupIdentifier: name, |
| 336 | ReplicationSubnetGroupDescription: description, |
| 337 | SubnetIds: news.subnetIds, |
| 338 | }); |
| 339 | observed = yield* findGroup(name); |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | if (!observed?.ReplicationSubnetGroupIdentifier) { |
| 344 | return yield* new ReplicationSubnetGroupUnexpectedResponse({ |
| 345 | message: `DMS replication subnet group '${name}' not found after reconcile`, |
| 346 | }); |
| 347 | } |
| 348 | |
| 349 | // 3b. Sync tags — diff against OBSERVED cloud tags. |
| 350 | const arn = yield* toArn(name); |
| 351 | const observedTags = yield* readTags(arn); |
| 352 | const { upsert, removed } = diffTags(observedTags, desiredTags); |
| 353 | if (upsert.length > 0) { |
| 354 | yield* dms.addTagsToResource({ ResourceArn: arn, Tags: upsert }); |
| 355 | } |
| 356 | if (removed.length > 0) { |
| 357 | yield* dms.removeTagsFromResource({ |
| 358 | ResourceArn: arn, |
| 359 | TagKeys: removed, |
| 360 | }); |
| 361 | } |
| 362 | |
| 363 | yield* session.note(name); |
| 364 | return yield* toAttrs(observed); |
| 365 | }), |
| 366 | |
| 367 | delete: Effect.fn(function* ({ output }) { |
| 368 | yield* dms |
| 369 | .deleteReplicationSubnetGroup({ |
| 370 | ReplicationSubnetGroupIdentifier: output.replicationSubnetGroupIdentifier, |
| 371 | }) |
| 372 | .pipe(Effect.catchTag("ResourceNotFoundFault", () => Effect.void)); |
| 373 | |
| 374 | // Observe actual absence before discarding state or considering the |
| 375 | // shared helper unused. DMS deletion is eventually consistent. |
| 376 | for (let attempt = 0; attempt < 30; attempt++) { |
| 377 | if ((yield* findGroup(output.replicationSubnetGroupIdentifier)) === undefined) { |
| 378 | yield* deleteOwnedDmsVpcRoleIfUnused; |
| 379 | return; |
| 380 | } |
| 381 | yield* Effect.sleep("1 second"); |
| 382 | } |
| 383 | return yield* Effect.die( |
| 384 | new Error( |
| 385 | `DMS replication subnet group ${output.replicationSubnetGroupIdentifier} remained observable 30 seconds after delete`, |
| 386 | ), |
| 387 | ); |
| 388 | }), |
| 389 | |
| 390 | list: () => |
| 391 | dms.describeReplicationSubnetGroups.pages({}).pipe( |
| 392 | Stream.runCollect, |
| 393 | Effect.map((chunk) => |
| 394 | Array.from(chunk).flatMap((page) => |
| 395 | (page.ReplicationSubnetGroups ?? []).filter( |
| 396 | (group) => group.ReplicationSubnetGroupIdentifier !== undefined, |
| 397 | ), |
| 398 | ), |
| 399 | ), |
| 400 | Effect.flatMap(Effect.forEach((group) => toAttrs(group), { concurrency: 4 })), |
| 401 | ), |
| 402 | }; |
| 403 | }), |
| 404 | ); |