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 { Region } from "@distilled.cloud/aws/Region"; |
| 3 | import * as Namespace from "alchemy/Namespace"; |
| 4 | import * as Output from "alchemy/Output"; |
| 5 | import * as Data from "effect/Data"; |
| 6 | import * as Effect from "effect/Effect"; |
| 7 | import type { EIP as EIPResource } from "./EIP.ts"; |
| 8 | import { EIP } from "./EIP.ts"; |
| 9 | import type { InternetGateway as InternetGatewayResource } from "./InternetGateway.ts"; |
| 10 | import { InternetGateway } from "./InternetGateway.ts"; |
| 11 | import type { NatGateway as NatGatewayResource } from "./NatGateway.ts"; |
| 12 | import { NatGateway } from "./NatGateway.ts"; |
| 13 | import type { Route as RouteResource } from "./Route.ts"; |
| 14 | import { Route } from "./Route.ts"; |
| 15 | import type { RouteTable as RouteTableResource } from "./RouteTable.ts"; |
| 16 | import { RouteTable } from "./RouteTable.ts"; |
| 17 | import type { RouteTableAssociation as RouteTableAssociationResource } from "./RouteTableAssociation.ts"; |
| 18 | import { RouteTableAssociation } from "./RouteTableAssociation.ts"; |
| 19 | import type { Subnet as SubnetResource } from "./Subnet.ts"; |
| 20 | import { Subnet } from "./Subnet.ts"; |
| 21 | import type { Vpc as VpcResource } from "./Vpc.ts"; |
| 22 | import { Vpc } from "./Vpc.ts"; |
| 23 | import type { VpcEndpoint as VpcEndpointResource } from "./VpcEndpoint.ts"; |
| 24 | import { VpcEndpoint } from "./VpcEndpoint.ts"; |
| 25 | |
| 26 | export class NetworkInvalidProps extends Data.TaggedError("NetworkInvalidProps")<{ |
| 27 | readonly message: string; |
| 28 | readonly cause?: unknown; |
| 29 | }> {} |
| 30 | |
| 31 | export type NetworkNat = "none" | "single" | "per-az"; |
| 32 | |
| 33 | export type NetworkGatewayEndpoint = "s3" | "dynamodb"; |
| 34 | |
| 35 | export interface NetworkProps { |
| 36 | /** |
| 37 | * IPv4 CIDR block for the VPC. |
| 38 | * @example "10.42.0.0/16" |
| 39 | */ |
| 40 | cidrBlock: string; |
| 41 | |
| 42 | /** |
| 43 | * Number of Availability Zones to span or an explicit ordered list of zone names. |
| 44 | * Defaults to 2 available zones. |
| 45 | */ |
| 46 | availabilityZones?: number | string[]; |
| 47 | |
| 48 | /** |
| 49 | * NAT strategy for private subnets. |
| 50 | * - `"none"` keeps private subnets isolated |
| 51 | * - `"single"` creates one shared NAT gateway |
| 52 | * - `"per-az"` creates one NAT gateway per Availability Zone |
| 53 | * @default "none" |
| 54 | */ |
| 55 | nat?: NetworkNat; |
| 56 | |
| 57 | /** |
| 58 | * Gateway endpoints to attach to the private route tables. |
| 59 | * Supported in v1: S3 and DynamoDB. |
| 60 | */ |
| 61 | gatewayEndpoints?: NetworkGatewayEndpoint[]; |
| 62 | |
| 63 | /** |
| 64 | * Whether DNS resolution is supported for the VPC. |
| 65 | * @default true |
| 66 | */ |
| 67 | enableDnsSupport?: boolean; |
| 68 | |
| 69 | /** |
| 70 | * Whether instances launched in the VPC receive DNS hostnames. |
| 71 | * @default true |
| 72 | */ |
| 73 | enableDnsHostnames?: boolean; |
| 74 | |
| 75 | /** |
| 76 | * Tags to apply to all created resources. |
| 77 | */ |
| 78 | tags?: Record<string, string>; |
| 79 | } |
| 80 | |
| 81 | export interface NetworkResources { |
| 82 | availabilityZones: string[]; |
| 83 | vpc: VpcResource; |
| 84 | internetGateway?: InternetGatewayResource; |
| 85 | elasticIps: EIPResource[]; |
| 86 | natGateways: NatGatewayResource[]; |
| 87 | publicSubnets: SubnetResource[]; |
| 88 | privateSubnets: SubnetResource[]; |
| 89 | publicRouteTables: RouteTableResource[]; |
| 90 | privateRouteTables: RouteTableResource[]; |
| 91 | publicRoutes: RouteResource[]; |
| 92 | privateRoutes: RouteResource[]; |
| 93 | publicRouteAssociations: RouteTableAssociationResource[]; |
| 94 | privateRouteAssociations: RouteTableAssociationResource[]; |
| 95 | gatewayEndpoints: VpcEndpointResource[]; |
| 96 | vpcId: VpcResource["vpcId"]; |
| 97 | publicSubnetIds: Array<SubnetResource["subnetId"]>; |
| 98 | privateSubnetIds: Array<SubnetResource["subnetId"]>; |
| 99 | } |
| 100 | |
| 101 | export type Network = Effect.Success<ReturnType<typeof Network>>; |
| 102 | |
| 103 | /** |
| 104 | * Creates a production-shaped VPC network from the low-level EC2 primitives. |
| 105 | * |
| 106 | * `Network` is the ergonomic entry point for users who want a ready-to-use VPC |
| 107 | * layout without manually creating route tables, internet gateways, NAT |
| 108 | * gateways, and subnet associations by hand. |
| 109 | * |
| 110 | * The helper still returns the underlying canonical resources so callers can |
| 111 | * keep composing with raw `AWS.EC2.*` APIs when they need more control. |
| 112 | * **Example:** Minimal network |
| 113 | * ```typescript |
| 114 | * const network = yield* AWS.EC2.Network("AppNetwork", { |
| 115 | * cidrBlock: "10.42.0.0/16", |
| 116 | * }); |
| 117 | * ``` |
| 118 | * |
| 119 | * **Example:** ECS-ready network with shared NAT |
| 120 | * ```typescript |
| 121 | * const network = yield* AWS.EC2.Network("AppNetwork", { |
| 122 | * cidrBlock: "10.42.0.0/16", |
| 123 | * availabilityZones: 2, |
| 124 | * nat: "single", |
| 125 | * gatewayEndpoints: ["s3"], |
| 126 | * }); |
| 127 | * |
| 128 | * yield* AWS.ECS.Service("ApiService", { |
| 129 | * cluster, |
| 130 | * task: apiTask, |
| 131 | * vpcId: network.vpcId, |
| 132 | * subnets: network.publicSubnetIds, |
| 133 | * assignPublicIp: true, |
| 134 | * }); |
| 135 | * ``` |
| 136 | * |
| 137 | * @resource |
| 138 | */ |
| 139 | export const Network = (id: string, props: NetworkProps) => |
| 140 | Namespace.push( |
| 141 | id, |
| 142 | Effect.gen(function* () { |
| 143 | const availabilityZones = yield* resolveAvailabilityZones(props.availabilityZones); |
| 144 | const subnetCidrs = deriveSubnetCidrs(props.cidrBlock, availabilityZones.length); |
| 145 | const tags = props.tags; |
| 146 | |
| 147 | const vpc = yield* Vpc("Vpc", { |
| 148 | cidrBlock: props.cidrBlock, |
| 149 | enableDnsSupport: props.enableDnsSupport ?? true, |
| 150 | enableDnsHostnames: props.enableDnsHostnames ?? true, |
| 151 | tags, |
| 152 | }); |
| 153 | |
| 154 | const internetGateway = yield* InternetGateway("InternetGateway", { |
| 155 | vpcId: vpc.vpcId, |
| 156 | tags, |
| 157 | }); |
| 158 | |
| 159 | const publicSubnets: SubnetResource[] = []; |
| 160 | const privateSubnets: SubnetResource[] = []; |
| 161 | |
| 162 | for (const [index, availabilityZone] of availabilityZones.entries()) { |
| 163 | const publicSubnet = yield* Subnet(`PublicSubnet${index + 1}`, { |
| 164 | vpcId: vpc.vpcId, |
| 165 | cidrBlock: subnetCidrs.public[index], |
| 166 | availabilityZone, |
| 167 | mapPublicIpOnLaunch: true, |
| 168 | tags: { |
| 169 | // Kubernetes load-balancer subnet discovery (EKS Auto Mode and the |
| 170 | // AWS Load Balancer Controller both select subnets by this tag). |
| 171 | "kubernetes.io/role/elb": "1", |
| 172 | ...tags, |
| 173 | Tier: "public", |
| 174 | }, |
| 175 | }); |
| 176 | publicSubnets.push(publicSubnet); |
| 177 | |
| 178 | const privateSubnet = yield* Subnet(`PrivateSubnet${index + 1}`, { |
| 179 | vpcId: vpc.vpcId, |
| 180 | cidrBlock: subnetCidrs.private[index], |
| 181 | availabilityZone, |
| 182 | tags: { |
| 183 | // Internal load-balancer subnet discovery (see the public-subnet |
| 184 | // `kubernetes.io/role/elb` note above). |
| 185 | "kubernetes.io/role/internal-elb": "1", |
| 186 | ...tags, |
| 187 | Tier: "private", |
| 188 | }, |
| 189 | }); |
| 190 | privateSubnets.push(privateSubnet); |
| 191 | } |
| 192 | |
| 193 | const publicRouteTable = yield* RouteTable("PublicRouteTable", { |
| 194 | vpcId: vpc.vpcId, |
| 195 | tags: { |
| 196 | ...tags, |
| 197 | Tier: "public", |
| 198 | }, |
| 199 | }); |
| 200 | |
| 201 | const publicInternetRoute = yield* Route("PublicInternetRoute", { |
| 202 | routeTableId: publicRouteTable.routeTableId, |
| 203 | destinationCidrBlock: "0.0.0.0/0", |
| 204 | gatewayId: internetGateway.internetGatewayId, |
| 205 | }); |
| 206 | |
| 207 | const publicRouteAssociations: RouteTableAssociationResource[] = []; |
| 208 | |
| 209 | for (const [index, subnet] of publicSubnets.entries()) { |
| 210 | publicRouteAssociations.push( |
| 211 | yield* RouteTableAssociation(`PublicSubnetAssociation${index + 1}`, { |
| 212 | routeTableId: publicRouteTable.routeTableId, |
| 213 | subnetId: subnet.subnetId, |
| 214 | }), |
| 215 | ); |
| 216 | } |
| 217 | |
| 218 | // A "public subnet" is usable for public IPv4 only after both its |
| 219 | // route-table association and the route through the internet gateway |
| 220 | // exist. Preserve those dependencies in the IDs handed to NAT gateways |
| 221 | // and downstream resources. Besides preventing a launch/readiness race, |
| 222 | // this makes teardown order those consumers before the route and IGW; |
| 223 | // EC2 refuses to detach an IGW while a NAT gateway (or an instance) in |
| 224 | // the VPC still maps a public IPv4 address. |
| 225 | const publicSubnetIds = publicSubnets.map((subnet, index) => |
| 226 | Output.all( |
| 227 | subnet.subnetId, |
| 228 | publicRouteAssociations[index].associationId, |
| 229 | publicInternetRoute.routeTableId, |
| 230 | ).pipe(Output.map(([subnetId]) => subnetId)), |
| 231 | ); |
| 232 | |
| 233 | const nat = props.nat ?? "none"; |
| 234 | const elasticIps: EIPResource[] = []; |
| 235 | const natGateways: NatGatewayResource[] = []; |
| 236 | const privateRouteTables: RouteTableResource[] = []; |
| 237 | const privateRoutes: RouteResource[] = []; |
| 238 | const privateRouteAssociations: RouteTableAssociationResource[] = []; |
| 239 | |
| 240 | if (nat === "per-az") { |
| 241 | for (const index of publicSubnets.keys()) { |
| 242 | const eip = yield* EIP(`NatEip${index + 1}`, { |
| 243 | domain: "vpc", |
| 244 | tags, |
| 245 | }); |
| 246 | elasticIps.push(eip); |
| 247 | |
| 248 | const natGateway = yield* NatGateway(`NatGateway${index + 1}`, { |
| 249 | subnetId: publicSubnetIds[index], |
| 250 | allocationId: eip.allocationId, |
| 251 | connectivityType: "public", |
| 252 | tags, |
| 253 | }); |
| 254 | natGateways.push(natGateway); |
| 255 | |
| 256 | const privateRouteTable = yield* RouteTable(`PrivateRouteTable${index + 1}`, { |
| 257 | vpcId: vpc.vpcId, |
| 258 | tags: { |
| 259 | ...tags, |
| 260 | Tier: "private", |
| 261 | }, |
| 262 | }); |
| 263 | privateRouteTables.push(privateRouteTable); |
| 264 | |
| 265 | privateRoutes.push( |
| 266 | yield* Route(`PrivateInternetRoute${index + 1}`, { |
| 267 | routeTableId: privateRouteTable.routeTableId, |
| 268 | destinationCidrBlock: "0.0.0.0/0", |
| 269 | natGatewayId: natGateway.natGatewayId, |
| 270 | }), |
| 271 | ); |
| 272 | |
| 273 | privateRouteAssociations.push( |
| 274 | yield* RouteTableAssociation(`PrivateSubnetAssociation${index + 1}`, { |
| 275 | routeTableId: privateRouteTable.routeTableId, |
| 276 | subnetId: privateSubnets[index].subnetId, |
| 277 | }), |
| 278 | ); |
| 279 | } |
| 280 | } else { |
| 281 | const privateRouteTable = yield* RouteTable("PrivateRouteTable", { |
| 282 | vpcId: vpc.vpcId, |
| 283 | tags: { |
| 284 | ...tags, |
| 285 | Tier: "private", |
| 286 | }, |
| 287 | }); |
| 288 | privateRouteTables.push(privateRouteTable); |
| 289 | |
| 290 | if (nat === "single") { |
| 291 | const eip = yield* EIP("NatEip", { |
| 292 | domain: "vpc", |
| 293 | tags, |
| 294 | }); |
| 295 | elasticIps.push(eip); |
| 296 | |
| 297 | const natGateway = yield* NatGateway("NatGateway", { |
| 298 | subnetId: publicSubnetIds[0], |
| 299 | allocationId: eip.allocationId, |
| 300 | connectivityType: "public", |
| 301 | tags, |
| 302 | }); |
| 303 | natGateways.push(natGateway); |
| 304 | |
| 305 | privateRoutes.push( |
| 306 | yield* Route("PrivateInternetRoute", { |
| 307 | routeTableId: privateRouteTable.routeTableId, |
| 308 | destinationCidrBlock: "0.0.0.0/0", |
| 309 | natGatewayId: natGateway.natGatewayId, |
| 310 | }), |
| 311 | ); |
| 312 | } |
| 313 | |
| 314 | for (const [index, subnet] of privateSubnets.entries()) { |
| 315 | privateRouteAssociations.push( |
| 316 | yield* RouteTableAssociation(`PrivateSubnetAssociation${index + 1}`, { |
| 317 | routeTableId: privateRouteTable.routeTableId, |
| 318 | subnetId: subnet.subnetId, |
| 319 | }), |
| 320 | ); |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | const gatewayEndpoints: VpcEndpointResource[] = []; |
| 325 | const endpointServices = uniqueGatewayEndpoints(props.gatewayEndpoints); |
| 326 | if (endpointServices.length > 0) { |
| 327 | // Resolve the region lazily and via the `Region` service, which is |
| 328 | // provided both at deploy time and by the Lambda runtime. |
| 329 | // `AWSEnvironment` is deploy-time-only: this layer is re-executed at |
| 330 | // Function init, where `AWS::Environment` is not provided and |
| 331 | // resolving it crashes the runtime. |
| 332 | const region = yield* yield* Region; |
| 333 | for (const service of endpointServices) { |
| 334 | gatewayEndpoints.push( |
| 335 | yield* VpcEndpoint(`${toEndpointId(service)}Endpoint`, { |
| 336 | vpcId: vpc.vpcId, |
| 337 | serviceName: `com.amazonaws.${region}.${service}`, |
| 338 | vpcEndpointType: "Gateway", |
| 339 | routeTableIds: privateRouteTables.map((table) => table.routeTableId), |
| 340 | tags, |
| 341 | }), |
| 342 | ); |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | return { |
| 347 | availabilityZones, |
| 348 | vpc, |
| 349 | internetGateway, |
| 350 | elasticIps, |
| 351 | natGateways, |
| 352 | publicSubnets, |
| 353 | privateSubnets, |
| 354 | publicRouteTables: [publicRouteTable], |
| 355 | privateRouteTables, |
| 356 | publicRoutes: [publicInternetRoute], |
| 357 | privateRoutes, |
| 358 | publicRouteAssociations, |
| 359 | privateRouteAssociations, |
| 360 | gatewayEndpoints, |
| 361 | vpcId: vpc.vpcId, |
| 362 | publicSubnetIds, |
| 363 | privateSubnetIds: privateSubnets.map((subnet) => subnet.subnetId), |
| 364 | } satisfies NetworkResources; |
| 365 | }).pipe(Effect.orDie), |
| 366 | ); |
| 367 | |
| 368 | const resolveAvailabilityZones = (input?: number | string[]) => |
| 369 | Effect.gen(function* () { |
| 370 | if (Array.isArray(input)) { |
| 371 | if (input.length === 0) { |
| 372 | return yield* new NetworkInvalidProps({ |
| 373 | message: "EC2.Network requires at least one availability zone", |
| 374 | }); |
| 375 | } |
| 376 | if (new Set(input).size !== input.length) { |
| 377 | return yield* new NetworkInvalidProps({ |
| 378 | message: "EC2.Network availabilityZones must not contain duplicates", |
| 379 | }); |
| 380 | } |
| 381 | return input; |
| 382 | } |
| 383 | |
| 384 | const desiredCount = input ?? 2; |
| 385 | if (!Number.isInteger(desiredCount) || desiredCount <= 0) { |
| 386 | return yield* new NetworkInvalidProps({ |
| 387 | message: "EC2.Network availabilityZones count must be a positive integer", |
| 388 | }); |
| 389 | } |
| 390 | |
| 391 | if (globalThis.__ALCHEMY_RUNTIME__) { |
| 392 | // Inside a deployed Function this composition is re-executed at init, |
| 393 | // where every `yield* Subnet(...)` resolves its attributes from the |
| 394 | // injected environment — the zone names below only shape input props |
| 395 | // that the runtime ignores. Skip ec2:DescribeAvailabilityZones |
| 396 | // entirely: the function role does not (and should not) have that |
| 397 | // permission, so calling it at init crashes with UnauthorizedOperation. |
| 398 | const region = yield* yield* Region; |
| 399 | return Array.from( |
| 400 | { length: desiredCount }, |
| 401 | (_, index) => `${region}${String.fromCharCode(97 + index)}`, |
| 402 | ); |
| 403 | } |
| 404 | |
| 405 | const result = yield* ec2.describeAvailabilityZones({}); |
| 406 | const zones = (result.AvailabilityZones ?? []) |
| 407 | .filter((zone) => zone.State === "available" && zone.ZoneName) |
| 408 | .map((zone) => zone.ZoneName!) |
| 409 | .sort((a, b) => a.localeCompare(b)); |
| 410 | |
| 411 | if (zones.length < desiredCount) { |
| 412 | return yield* new NetworkInvalidProps({ |
| 413 | message: `EC2.Network requested ${desiredCount} availability zones, but only ${zones.length} are available`, |
| 414 | }); |
| 415 | } |
| 416 | |
| 417 | return zones.slice(0, desiredCount); |
| 418 | }); |
| 419 | |
| 420 | const deriveSubnetCidrs = (cidrBlock: string, azCount: number) => { |
| 421 | const [baseAddress, prefixText] = cidrBlock.split("/"); |
| 422 | const prefix = Number(prefixText); |
| 423 | if (!baseAddress || !Number.isInteger(prefix) || prefix < 0 || prefix > 28) { |
| 424 | throw new Error(`EC2.Network requires a valid IPv4 CIDR block, got '${cidrBlock}'`); |
| 425 | } |
| 426 | |
| 427 | const totalSubnets = azCount * 2; |
| 428 | const additionalBits = Math.ceil(Math.log2(totalSubnets)); |
| 429 | const subnetPrefix = Math.max(prefix + additionalBits, 24); |
| 430 | |
| 431 | if (subnetPrefix > 28) { |
| 432 | throw new Error( |
| 433 | `EC2.Network CIDR block '${cidrBlock}' is too small for ${totalSubnets} subnets`, |
| 434 | ); |
| 435 | } |
| 436 | |
| 437 | const subnetSize = 2 ** (32 - subnetPrefix); |
| 438 | const base = toNetworkAddress(baseAddress, prefix); |
| 439 | |
| 440 | return { |
| 441 | public: Array.from({ length: azCount }, (_, index) => |
| 442 | toCidr(base + subnetSize * index, subnetPrefix), |
| 443 | ), |
| 444 | private: Array.from({ length: azCount }, (_, index) => |
| 445 | toCidr(base + subnetSize * (index + azCount), subnetPrefix), |
| 446 | ), |
| 447 | }; |
| 448 | }; |
| 449 | |
| 450 | const toNetworkAddress = (ip: string, prefix: number) => { |
| 451 | const value = ipv4ToNumber(ip); |
| 452 | const blockSize = 2 ** (32 - prefix); |
| 453 | return Math.floor(value / blockSize) * blockSize; |
| 454 | }; |
| 455 | |
| 456 | const ipv4ToNumber = (ip: string) => { |
| 457 | const octets = ip.split(".").map((part) => Number(part)); |
| 458 | if ( |
| 459 | octets.length !== 4 || |
| 460 | octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255) |
| 461 | ) { |
| 462 | throw new Error(`Invalid IPv4 address '${ip}'`); |
| 463 | } |
| 464 | |
| 465 | return octets[0] * 256 ** 3 + octets[1] * 256 ** 2 + octets[2] * 256 + octets[3]; |
| 466 | }; |
| 467 | |
| 468 | const numberToIpv4 = (value: number) => |
| 469 | [ |
| 470 | Math.floor(value / 256 ** 3) % 256, |
| 471 | Math.floor(value / 256 ** 2) % 256, |
| 472 | Math.floor(value / 256) % 256, |
| 473 | value % 256, |
| 474 | ].join("."); |
| 475 | |
| 476 | const toCidr = (value: number, prefix: number) => `${numberToIpv4(value)}/${prefix}`; |
| 477 | |
| 478 | const uniqueGatewayEndpoints = (services: NetworkGatewayEndpoint[] = []) => [...new Set(services)]; |
| 479 | |
| 480 | const toEndpointId = (service: NetworkGatewayEndpoint) => (service === "s3" ? "S3" : "DynamoDb"); |