The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as ec2 from "@distilled.cloud/aws/ec2"; |
| 2 | import { isResolved } from "alchemy/Diff"; |
| 3 | import * as Provider from "alchemy/Provider"; |
| 4 | import { Resource } from "alchemy/Resource"; |
| 5 | import { createInternalTags, createTagsList, diffTags } from "alchemy/Tags"; |
| 6 | import * as Data from "effect/Data"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Schedule from "effect/Schedule"; |
| 9 | import type { AccountID } from "../Environment.ts"; |
| 10 | import { AWSEnvironment } from "../Environment.ts"; |
| 11 | import type { Providers } from "../Providers.ts"; |
| 12 | import type { RegionID } from "../Region.ts"; |
| 13 | |
| 14 | export class EIPUnexpectedResponse extends Data.TaggedError("EIPUnexpectedResponse")<{ |
| 15 | readonly message: string; |
| 16 | readonly cause?: unknown; |
| 17 | }> {} |
| 18 | |
| 19 | export type EIPArn = `arn:aws:ec2:${RegionID}:${AccountID}:elastic-ip/${AllocationId}`; |
| 20 | |
| 21 | export type AllocationId<ID extends string = string> = `eipalloc-${ID}`; |
| 22 | export const AllocationId = <ID extends string>(id: ID): ID & AllocationId<ID> => |
| 23 | `eipalloc-${id}` as ID & AllocationId<ID>; |
| 24 | |
| 25 | export interface EIPProps { |
| 26 | /** |
| 27 | * Indicates whether the Elastic IP address is for use with instances in a VPC or EC2-Classic. |
| 28 | * @default "vpc" |
| 29 | */ |
| 30 | domain?: "vpc" | "standard"; |
| 31 | |
| 32 | /** |
| 33 | * The ID of an address pool that you own. |
| 34 | * Use this parameter to let Amazon EC2 select an address from the address pool. |
| 35 | */ |
| 36 | publicIpv4Pool?: string; |
| 37 | |
| 38 | /** |
| 39 | * A unique set of Availability Zones, Local Zones, or Wavelength Zones |
| 40 | * from which AWS advertises IP addresses. |
| 41 | */ |
| 42 | networkBorderGroup?: string; |
| 43 | |
| 44 | /** |
| 45 | * The ID of a customer-owned address pool. |
| 46 | * Use this parameter to let Amazon EC2 select an address from the address pool. |
| 47 | */ |
| 48 | customerOwnedIpv4Pool?: string; |
| 49 | |
| 50 | /** |
| 51 | * Tags to assign to the Elastic IP. |
| 52 | * These will be merged with alchemy auto-tags. |
| 53 | */ |
| 54 | tags?: Record<string, string>; |
| 55 | } |
| 56 | |
| 57 | export interface EIP extends Resource< |
| 58 | "AWS.EC2.EIP", |
| 59 | EIPProps, |
| 60 | { |
| 61 | /** |
| 62 | * The allocation ID for the Elastic IP address. |
| 63 | */ |
| 64 | allocationId: AllocationId; |
| 65 | |
| 66 | /** |
| 67 | * The Amazon Resource Name (ARN) of the Elastic IP. |
| 68 | */ |
| 69 | eipArn: `arn:aws:ec2:${RegionID}:${AccountID}:elastic-ip/${string}`; |
| 70 | |
| 71 | /** |
| 72 | * The Elastic IP address. |
| 73 | */ |
| 74 | publicIp: string; |
| 75 | |
| 76 | /** |
| 77 | * The ID of an address pool. |
| 78 | */ |
| 79 | publicIpv4Pool?: string; |
| 80 | |
| 81 | /** |
| 82 | * Indicates whether the Elastic IP address is for use with instances in a VPC or EC2-Classic. |
| 83 | */ |
| 84 | domain: "vpc" | "standard"; |
| 85 | |
| 86 | /** |
| 87 | * The network border group. |
| 88 | */ |
| 89 | networkBorderGroup?: string; |
| 90 | |
| 91 | /** |
| 92 | * The customer-owned IP address. |
| 93 | */ |
| 94 | customerOwnedIp?: string; |
| 95 | |
| 96 | /** |
| 97 | * The ID of the customer-owned address pool. |
| 98 | */ |
| 99 | customerOwnedIpv4Pool?: string; |
| 100 | |
| 101 | /** |
| 102 | * The carrier IP address associated with the network interface. |
| 103 | */ |
| 104 | carrierIp?: string; |
| 105 | }, |
| 106 | never, |
| 107 | Providers |
| 108 | > {} |
| 109 | /** |
| 110 | * An Elastic IP address — a static, public IPv4 address allocated to your AWS |
| 111 | * account that you can attach to instances, network interfaces, or NAT |
| 112 | * gateways. |
| 113 | * |
| 114 | * Allocating an `EIP` reserves the address; you then reference its |
| 115 | * `allocationId` from the resource that should use it (for example a public |
| 116 | * `NatGateway`). The address is released back to AWS when the resource is |
| 117 | * destroyed. The pool-related properties (`publicIpv4Pool`, |
| 118 | * `networkBorderGroup`, `customerOwnedIpv4Pool`) are immutable and replace the |
| 119 | * address when changed. |
| 120 | * |
| 121 | * ### Allocating Elastic IPs |
| 122 | * By default an Elastic IP is allocated for use within a VPC (`domain: "vpc"`), |
| 123 | * which is the only domain available to modern accounts. |
| 124 | * **Example:** VPC-Scoped Elastic IP |
| 125 | * ```typescript |
| 126 | * const eip = yield* AWS.EC2.EIP("MyEip", { |
| 127 | * domain: "vpc", |
| 128 | * tags: { Name: "app-eip" }, |
| 129 | * }); |
| 130 | * ``` |
| 131 | * This reserves a standard, Amazon-owned public IPv4 address scoped to your VPC; |
| 132 | * `domain` defaults to `"vpc"`, so it can be omitted, and `tags` help you find |
| 133 | * the address in the console and on the bill. |
| 134 | * |
| 135 | * ### Bring-Your-Own-IP and Address Pools |
| 136 | * If you have onboarded an address range to AWS (BYOIP) or use Outposts, you can |
| 137 | * draw the address from a specific pool instead of Amazon's general pool. |
| 138 | * **Example:** Allocate from a Public IPv4 (BYOIP) Pool |
| 139 | * ```typescript |
| 140 | * const eip = yield* AWS.EC2.EIP("ByoipEip", { |
| 141 | * publicIpv4Pool: "ipv4pool-ec2-0abcdef1234567890", |
| 142 | * networkBorderGroup: "us-east-1", |
| 143 | * }); |
| 144 | * ``` |
| 145 | * `publicIpv4Pool` selects an address from a pool you own rather than a random |
| 146 | * Amazon address, and `networkBorderGroup` restricts which zone group AWS |
| 147 | * advertises it from (useful for Local and Wavelength Zones). |
| 148 | * |
| 149 | * **Example:** Allocate from a Customer-Owned Pool (Outposts) |
| 150 | * ```typescript |
| 151 | * const eip = yield* AWS.EC2.EIP("CoIpEip", { |
| 152 | * customerOwnedIpv4Pool: "ipv4pool-coip-0abcdef1234567890", |
| 153 | * }); |
| 154 | * ``` |
| 155 | * `customerOwnedIpv4Pool` pulls a customer-owned IP (CoIP) from an |
| 156 | * Outposts-associated pool, for workloads that must use your own on-premises |
| 157 | * address space. |
| 158 | * |
| 159 | * ### Using an Elastic IP |
| 160 | * **Example:** Attach to a NAT Gateway |
| 161 | * ```typescript |
| 162 | * const eip = yield* AWS.EC2.EIP("NatEip", {}); |
| 163 | * |
| 164 | * const natGateway = yield* AWS.EC2.NatGateway("NatGateway", { |
| 165 | * subnetId: publicSubnet.subnetId, |
| 166 | * allocationId: eip.allocationId, |
| 167 | * }); |
| 168 | * ``` |
| 169 | * Downstream resources consume the reserved address through its `allocationId`; |
| 170 | * here the EIP becomes the fixed public IP of a NAT gateway. |
| 171 | * |
| 172 | * @resource |
| 173 | */ |
| 174 | export const EIP = Resource<EIP>("AWS.EC2.EIP"); |
| 175 | |
| 176 | export const EIPProvider = () => |
| 177 | Provider.effect( |
| 178 | EIP, |
| 179 | Effect.gen(function* () { |
| 180 | const createTags = Effect.fn(function* (id: string, tags?: Record<string, string>) { |
| 181 | return { |
| 182 | Name: id, |
| 183 | ...(yield* createInternalTags(id)), |
| 184 | ...tags, |
| 185 | }; |
| 186 | }); |
| 187 | |
| 188 | return { |
| 189 | stables: ["allocationId", "eipArn", "publicIp"], |
| 190 | |
| 191 | list: () => |
| 192 | Effect.gen(function* () { |
| 193 | const { region, accountId } = yield* AWSEnvironment.current; |
| 194 | // describeAddresses is non-paginated and returns every Elastic IP |
| 195 | // in the account/region in a single response. |
| 196 | const result = yield* ec2.describeAddresses({}); |
| 197 | return (result.Addresses ?? []) |
| 198 | .filter((a): a is ec2.Address & { AllocationId: string } => a.AllocationId != null) |
| 199 | .map((address): EIP["Attributes"] => ({ |
| 200 | allocationId: address.AllocationId as AllocationId, |
| 201 | eipArn: |
| 202 | `arn:aws:ec2:${region}:${accountId}:elastic-ip/${address.AllocationId}` as EIPArn, |
| 203 | publicIp: address.PublicIp!, |
| 204 | publicIpv4Pool: address.PublicIpv4Pool, |
| 205 | domain: (address.Domain as "vpc" | "standard") ?? "vpc", |
| 206 | networkBorderGroup: address.NetworkBorderGroup, |
| 207 | customerOwnedIp: address.CustomerOwnedIp, |
| 208 | customerOwnedIpv4Pool: address.CustomerOwnedIpv4Pool, |
| 209 | carrierIp: address.CarrierIp, |
| 210 | })); |
| 211 | }), |
| 212 | |
| 213 | read: Effect.fn(function* ({ output }) { |
| 214 | const { region, accountId } = yield* AWSEnvironment.current; |
| 215 | |
| 216 | if (!output) return undefined; |
| 217 | const result = yield* ec2.describeAddresses({ |
| 218 | AllocationIds: [output.allocationId], |
| 219 | }); |
| 220 | |
| 221 | const address = result.Addresses?.[0]; |
| 222 | if (!address) { |
| 223 | return yield* new EIPUnexpectedResponse({ |
| 224 | message: `EIP ${output.allocationId} not found`, |
| 225 | }); |
| 226 | } |
| 227 | |
| 228 | return { |
| 229 | allocationId: address.AllocationId as AllocationId, |
| 230 | eipArn: |
| 231 | `arn:aws:ec2:${region}:${accountId}:elastic-ip/${address.AllocationId}` as EIPArn, |
| 232 | publicIp: address.PublicIp!, |
| 233 | publicIpv4Pool: address.PublicIpv4Pool, |
| 234 | domain: (address.Domain as "vpc" | "standard") ?? "vpc", |
| 235 | networkBorderGroup: address.NetworkBorderGroup, |
| 236 | customerOwnedIp: address.CustomerOwnedIp, |
| 237 | customerOwnedIpv4Pool: address.CustomerOwnedIpv4Pool, |
| 238 | carrierIp: address.CarrierIp, |
| 239 | } satisfies EIP["Attributes"]; |
| 240 | }), |
| 241 | |
| 242 | diff: Effect.fn(function* ({ news = {}, olds = {} }) { |
| 243 | if (!isResolved(news)) return; |
| 244 | // EIPs are immutable - any change to core properties requires replacement |
| 245 | if ( |
| 246 | news.publicIpv4Pool !== olds.publicIpv4Pool || |
| 247 | news.networkBorderGroup !== olds.networkBorderGroup || |
| 248 | news.customerOwnedIpv4Pool !== olds.customerOwnedIpv4Pool |
| 249 | ) { |
| 250 | return { action: "replace" }; |
| 251 | } |
| 252 | // Tags can be updated in-place |
| 253 | }), |
| 254 | |
| 255 | reconcile: Effect.fn(function* ({ id, news = {}, output, session }) { |
| 256 | const { region, accountId } = yield* AWSEnvironment.current; |
| 257 | |
| 258 | const desiredTags = yield* createTags(id, news.tags); |
| 259 | |
| 260 | // Observe — try to find an existing EIP via the cached allocationId. |
| 261 | // If it was released out-of-band, fall through to allocate. |
| 262 | let address: ec2.Address | undefined; |
| 263 | if (output?.allocationId) { |
| 264 | const lookup = yield* ec2 |
| 265 | .describeAddresses({ AllocationIds: [output.allocationId] }) |
| 266 | .pipe( |
| 267 | Effect.catchTag("InvalidAllocationID.NotFound", () => |
| 268 | Effect.succeed({ Addresses: [] }), |
| 269 | ), |
| 270 | ); |
| 271 | address = lookup.Addresses?.[0]; |
| 272 | } |
| 273 | |
| 274 | // Ensure — allocate a new EIP when none was observed. |
| 275 | if (address === undefined) { |
| 276 | yield* session.note("Allocating Elastic IP address..."); |
| 277 | const result = yield* ec2.allocateAddress({ |
| 278 | Domain: news.domain ?? "vpc", |
| 279 | PublicIpv4Pool: news.publicIpv4Pool, |
| 280 | NetworkBorderGroup: news.networkBorderGroup, |
| 281 | CustomerOwnedIpv4Pool: news.customerOwnedIpv4Pool, |
| 282 | TagSpecifications: [ |
| 283 | { |
| 284 | ResourceType: "elastic-ip", |
| 285 | Tags: createTagsList(desiredTags), |
| 286 | }, |
| 287 | ], |
| 288 | DryRun: false, |
| 289 | }); |
| 290 | const allocationId = result.AllocationId! as AllocationId; |
| 291 | yield* session.note(`Elastic IP allocated: ${allocationId}`); |
| 292 | const lookup = yield* ec2.describeAddresses({ |
| 293 | AllocationIds: [allocationId], |
| 294 | }); |
| 295 | address = lookup.Addresses?.[0]; |
| 296 | if (!address) { |
| 297 | return yield* new EIPUnexpectedResponse({ |
| 298 | message: `EIP ${allocationId} disappeared after allocation`, |
| 299 | }); |
| 300 | } |
| 301 | } |
| 302 | |
| 303 | const allocationId = address.AllocationId! as AllocationId; |
| 304 | |
| 305 | // Sync tags — observed cloud tags vs desired. |
| 306 | const currentTags = Object.fromEntries( |
| 307 | (address.Tags ?? []).map((t) => [t.Key!, t.Value!]), |
| 308 | ) as Record<string, string>; |
| 309 | const { removed, upsert } = diffTags(currentTags, desiredTags); |
| 310 | if (removed.length > 0) { |
| 311 | yield* ec2.deleteTags({ |
| 312 | Resources: [allocationId], |
| 313 | Tags: removed.map((key) => ({ Key: key })), |
| 314 | DryRun: false, |
| 315 | }); |
| 316 | } |
| 317 | if (upsert.length > 0) { |
| 318 | yield* ec2.createTags({ |
| 319 | Resources: [allocationId], |
| 320 | Tags: upsert, |
| 321 | DryRun: false, |
| 322 | }); |
| 323 | } |
| 324 | |
| 325 | return { |
| 326 | allocationId, |
| 327 | eipArn: `arn:aws:ec2:${region}:${accountId}:elastic-ip/${allocationId}` as EIPArn, |
| 328 | publicIp: address.PublicIp!, |
| 329 | publicIpv4Pool: address.PublicIpv4Pool, |
| 330 | domain: (address.Domain as "vpc" | "standard") ?? "vpc", |
| 331 | networkBorderGroup: address.NetworkBorderGroup, |
| 332 | customerOwnedIp: address.CustomerOwnedIp, |
| 333 | customerOwnedIpv4Pool: address.CustomerOwnedIpv4Pool, |
| 334 | carrierIp: address.CarrierIp, |
| 335 | } satisfies EIP["Attributes"]; |
| 336 | }), |
| 337 | |
| 338 | delete: Effect.fn(function* ({ output, session }) { |
| 339 | const allocationId = output.allocationId; |
| 340 | |
| 341 | yield* session.note(`Releasing Elastic IP: ${allocationId}`); |
| 342 | |
| 343 | yield* ec2 |
| 344 | .releaseAddress({ |
| 345 | AllocationId: allocationId, |
| 346 | DryRun: false, |
| 347 | }) |
| 348 | .pipe( |
| 349 | Effect.catchTags({ |
| 350 | "InvalidAllocationID.NotFound": () => Effect.void, |
| 351 | AuthFailure: () => Effect.void, |
| 352 | }), |
| 353 | Effect.tapError(Effect.logDebug), |
| 354 | // Retry when EIP is still in use (e.g., NAT Gateway being deleted) |
| 355 | Effect.retry({ |
| 356 | while: (e) => |
| 357 | // TODO(sam): not sure if the API will actually throw this |
| 358 | // e._tag === "DependencyViolation" || |
| 359 | // this throws if the address hasn't been disassociated from all resources |
| 360 | // we will retry it assuming that another resource provider is dissassociating it (e.g. a NAT Gateway resource is being deleted) |
| 361 | e._tag === "InvalidIPAddress.InUse", |
| 362 | schedule: Schedule.max([Schedule.exponential(1000, 1.5), Schedule.recurs(20)]).pipe( |
| 363 | Schedule.tap(({ attempt }) => |
| 364 | session.note(`EIP still in use, waiting for release... (attempt ${attempt})`), |
| 365 | ), |
| 366 | ), |
| 367 | }), |
| 368 | ); |
| 369 | |
| 370 | yield* session.note(`Elastic IP ${allocationId} released`); |
| 371 | }), |
| 372 | }; |
| 373 | }), |
| 374 | ); |