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 * as Stream from "effect/Stream"; |
| 10 | import type { AccountID } from "../Environment.ts"; |
| 11 | import { AWSEnvironment } from "../Environment.ts"; |
| 12 | import type { Providers } from "../Providers.ts"; |
| 13 | import type { RegionID } from "../Region.ts"; |
| 14 | import { getDefaultVpcScope } from "./defaultVpcScope.ts"; |
| 15 | import type { VpcId } from "./Vpc.ts"; |
| 16 | |
| 17 | export type DhcpOptionsId<ID extends string = string> = `dopt-${ID}`; |
| 18 | |
| 19 | export type DhcpOptionsArn<ID extends DhcpOptionsId = DhcpOptionsId> = |
| 20 | `arn:aws:ec2:${RegionID}:${AccountID}:dhcp-options/${ID}`; |
| 21 | |
| 22 | export interface DhcpOptionsProps { |
| 23 | /** |
| 24 | * The domain name for hosts in the VPC (e.g. `example.internal`). Immutable — |
| 25 | * a DHCP options set cannot be edited, so any change replaces it. |
| 26 | */ |
| 27 | domainName?: string; |
| 28 | |
| 29 | /** |
| 30 | * The IP addresses (up to four) of the domain name servers, or |
| 31 | * `AmazonProvidedDNS`. Immutable. |
| 32 | */ |
| 33 | domainNameServers?: string[]; |
| 34 | |
| 35 | /** |
| 36 | * The IP addresses (up to four) of the NTP servers. Immutable. |
| 37 | */ |
| 38 | ntpServers?: string[]; |
| 39 | |
| 40 | /** |
| 41 | * The IP addresses (up to four) of the NetBIOS name servers. Immutable. |
| 42 | */ |
| 43 | netbiosNameServers?: string[]; |
| 44 | |
| 45 | /** |
| 46 | * The NetBIOS node type (1, 2, 4, or 8). AWS recommends 2. Immutable. |
| 47 | */ |
| 48 | netbiosNodeType?: "1" | "2" | "4" | "8"; |
| 49 | |
| 50 | /** |
| 51 | * The ID of a VPC to associate this DHCP options set with. When set, the VPC |
| 52 | * is associated on create/update; on delete (or when this is cleared) the VPC |
| 53 | * is re-associated with the account's default options set. Mutable. |
| 54 | */ |
| 55 | vpcId?: VpcId; |
| 56 | |
| 57 | /** |
| 58 | * Tags to assign to the DHCP options set. |
| 59 | */ |
| 60 | tags?: Record<string, string>; |
| 61 | } |
| 62 | |
| 63 | export interface DhcpOptions extends Resource< |
| 64 | "AWS.EC2.DhcpOptions", |
| 65 | DhcpOptionsProps, |
| 66 | { |
| 67 | /** |
| 68 | * The ID of the DHCP options set (prefixed `dopt-`). |
| 69 | */ |
| 70 | dhcpOptionsId: DhcpOptionsId; |
| 71 | |
| 72 | /** |
| 73 | * The Amazon Resource Name (ARN) of the DHCP options set. |
| 74 | */ |
| 75 | dhcpOptionsArn: DhcpOptionsArn; |
| 76 | |
| 77 | /** |
| 78 | * The AWS account ID of the DHCP options set owner. |
| 79 | */ |
| 80 | ownerId: string; |
| 81 | |
| 82 | /** |
| 83 | * The ID of the VPC this options set is associated with, if any. |
| 84 | */ |
| 85 | vpcId?: VpcId; |
| 86 | }, |
| 87 | never, |
| 88 | Providers |
| 89 | > {} |
| 90 | |
| 91 | /** |
| 92 | * A DHCP options set configures the DHCP parameters (domain name, DNS servers, |
| 93 | * NTP servers, NetBIOS settings) that a VPC hands out to the instances launched |
| 94 | * inside it. Attach a custom set to a VPC to override the AWS defaults — for |
| 95 | * example to point instances at your own DNS or an internal search domain. |
| 96 | * |
| 97 | * A DHCP options set is immutable: AWS provides no edit API, so changing any |
| 98 | * DHCP parameter replaces the set. Setting `vpcId` associates the set with a |
| 99 | * VPC; clearing it (or deleting the resource) re-associates the VPC with the |
| 100 | * account's default options set, since a set must be disassociated from every |
| 101 | * VPC before it can be deleted. |
| 102 | * |
| 103 | * ### Creating a DHCP Options Set |
| 104 | * **Example:** Custom DNS and Search Domain |
| 105 | * ```typescript |
| 106 | * const dhcp = yield* AWS.EC2.DhcpOptions("CorpDhcp", { |
| 107 | * domainName: "corp.internal", |
| 108 | * domainNameServers: ["10.0.0.2", "AmazonProvidedDNS"], |
| 109 | * vpcId: myVpc.vpcId, |
| 110 | * }); |
| 111 | * ``` |
| 112 | * Creates the options set and associates it with the VPC in one step. |
| 113 | * Instances launched into the VPC receive the `corp.internal` search domain and |
| 114 | * the listed DNS servers. |
| 115 | * |
| 116 | * **Example:** NTP and NetBIOS Configuration |
| 117 | * ```typescript |
| 118 | * const dhcp = yield* AWS.EC2.DhcpOptions("Dhcp", { |
| 119 | * ntpServers: ["169.254.169.123"], |
| 120 | * netbiosNameServers: ["10.0.0.5"], |
| 121 | * netbiosNodeType: "2", |
| 122 | * }); |
| 123 | * ``` |
| 124 | * Creates an unassociated options set that you can associate later by setting |
| 125 | * `vpcId`. |
| 126 | * |
| 127 | * @resource |
| 128 | */ |
| 129 | export const DhcpOptions = Resource<DhcpOptions>("AWS.EC2.DhcpOptions"); |
| 130 | |
| 131 | class DhcpOptionsStillVisible extends Data.TaggedError("DhcpOptionsStillVisible")<{ |
| 132 | dhcpOptionsId: string; |
| 133 | }> {} |
| 134 | |
| 135 | // Build the NewDhcpConfiguration list AWS expects from the flat props. |
| 136 | const buildConfigurations = (props: DhcpOptionsProps): ec2.NewDhcpConfiguration[] => { |
| 137 | const configs: ec2.NewDhcpConfiguration[] = []; |
| 138 | if (props.domainName !== undefined) { |
| 139 | configs.push({ Key: "domain-name", Values: [props.domainName] }); |
| 140 | } |
| 141 | if (props.domainNameServers !== undefined) { |
| 142 | configs.push({ |
| 143 | Key: "domain-name-servers", |
| 144 | Values: props.domainNameServers, |
| 145 | }); |
| 146 | } |
| 147 | if (props.ntpServers !== undefined) { |
| 148 | configs.push({ Key: "ntp-servers", Values: props.ntpServers }); |
| 149 | } |
| 150 | if (props.netbiosNameServers !== undefined) { |
| 151 | configs.push({ |
| 152 | Key: "netbios-name-servers", |
| 153 | Values: props.netbiosNameServers, |
| 154 | }); |
| 155 | } |
| 156 | if (props.netbiosNodeType !== undefined) { |
| 157 | configs.push({ |
| 158 | Key: "netbios-node-type", |
| 159 | Values: [props.netbiosNodeType], |
| 160 | }); |
| 161 | } |
| 162 | return configs; |
| 163 | }; |
| 164 | |
| 165 | export const DhcpOptionsProvider = () => |
| 166 | Provider.effect( |
| 167 | DhcpOptions, |
| 168 | Effect.gen(function* () { |
| 169 | const createTags = Effect.fn(function* (id: string, tags?: Record<string, string>) { |
| 170 | return { |
| 171 | Name: id, |
| 172 | ...(yield* createInternalTags(id)), |
| 173 | ...tags, |
| 174 | }; |
| 175 | }); |
| 176 | |
| 177 | const describeDhcpOptions = (dhcpOptionsId: string) => |
| 178 | ec2.describeDhcpOptions({ DhcpOptionsIds: [dhcpOptionsId] }).pipe( |
| 179 | Effect.map((r) => r.DhcpOptions?.[0]), |
| 180 | Effect.catchTags({ |
| 181 | "InvalidDhcpOptionID.NotFound": () => Effect.undefined, |
| 182 | "InvalidDhcpOptionsID.NotFound": () => Effect.undefined, |
| 183 | }), |
| 184 | ); |
| 185 | |
| 186 | const waitUntilDhcpOptionsGone = (dhcpOptionsId: string) => |
| 187 | describeDhcpOptions(dhcpOptionsId).pipe( |
| 188 | Effect.flatMap((options) => |
| 189 | options === undefined |
| 190 | ? Effect.void |
| 191 | : Effect.fail(new DhcpOptionsStillVisible({ dhcpOptionsId })), |
| 192 | ), |
| 193 | Effect.retry({ |
| 194 | while: (error) => error._tag === "DhcpOptionsStillVisible", |
| 195 | schedule: Schedule.max([Schedule.fixed(1000), Schedule.recurs(15)]), |
| 196 | }), |
| 197 | ); |
| 198 | |
| 199 | // Which VPC (if any) currently points at this options set. |
| 200 | const findAssociatedVpc = (dhcpOptionsId: string) => |
| 201 | ec2 |
| 202 | .describeVpcs({ |
| 203 | Filters: [{ Name: "dhcp-options-id", Values: [dhcpOptionsId] }], |
| 204 | }) |
| 205 | .pipe(Effect.map((r) => r.Vpcs?.[0]?.VpcId as VpcId | undefined)); |
| 206 | |
| 207 | const toAttrs = (opts: ec2.DhcpOptions, vpcId?: VpcId) => |
| 208 | AWSEnvironment.current.pipe( |
| 209 | Effect.map((env) => ({ |
| 210 | dhcpOptionsId: opts.DhcpOptionsId as DhcpOptionsId, |
| 211 | dhcpOptionsArn: |
| 212 | `arn:aws:ec2:${env.region}:${env.accountId}:dhcp-options/${opts.DhcpOptionsId}` as DhcpOptionsArn, |
| 213 | ownerId: opts.OwnerId!, |
| 214 | vpcId, |
| 215 | })), |
| 216 | ); |
| 217 | |
| 218 | return { |
| 219 | stables: ["dhcpOptionsId", "dhcpOptionsArn", "ownerId"], |
| 220 | |
| 221 | list: () => |
| 222 | Effect.gen(function* () { |
| 223 | const env = yield* AWSEnvironment.current; |
| 224 | // The options set the default VPC references is the account |
| 225 | // default AWS provisions; never census/nuke it. |
| 226 | const defaultVpc = yield* getDefaultVpcScope; |
| 227 | const items = yield* ec2.describeDhcpOptions.pages({}).pipe( |
| 228 | Stream.runCollect, |
| 229 | Effect.map((chunk) => |
| 230 | Array.from(chunk).flatMap((page) => |
| 231 | (page.DhcpOptions ?? []) |
| 232 | .filter( |
| 233 | (o): o is ec2.DhcpOptions & { DhcpOptionsId: string } => |
| 234 | o.DhcpOptionsId != null, |
| 235 | ) |
| 236 | .filter( |
| 237 | (o) => |
| 238 | defaultVpc.dhcpOptionsId === undefined || |
| 239 | o.DhcpOptionsId !== defaultVpc.dhcpOptionsId, |
| 240 | ) |
| 241 | .map((o) => ({ |
| 242 | dhcpOptionsId: o.DhcpOptionsId as DhcpOptionsId, |
| 243 | dhcpOptionsArn: |
| 244 | `arn:aws:ec2:${env.region}:${env.accountId}:dhcp-options/${o.DhcpOptionsId}` as DhcpOptionsArn, |
| 245 | ownerId: o.OwnerId!, |
| 246 | vpcId: undefined, |
| 247 | })), |
| 248 | ), |
| 249 | ), |
| 250 | ); |
| 251 | return items satisfies DhcpOptions["Attributes"][]; |
| 252 | }), |
| 253 | |
| 254 | read: Effect.fn(function* ({ output }) { |
| 255 | if (!output) return undefined; |
| 256 | const opts = yield* describeDhcpOptions(output.dhcpOptionsId); |
| 257 | if (!opts) return undefined; |
| 258 | const vpcId = yield* findAssociatedVpc(output.dhcpOptionsId); |
| 259 | return yield* toAttrs(opts, vpcId); |
| 260 | }), |
| 261 | |
| 262 | diff: Effect.fn(function* ({ news, olds }) { |
| 263 | if (!isResolved(news)) return; |
| 264 | // The DHCP configuration itself is immutable — a change replaces. |
| 265 | const eq = (a?: string[], b?: string[]) => |
| 266 | JSON.stringify(a ?? null) === JSON.stringify(b ?? null); |
| 267 | if ( |
| 268 | news.domainName !== olds.domainName || |
| 269 | !eq(news.domainNameServers, olds.domainNameServers) || |
| 270 | !eq(news.ntpServers, olds.ntpServers) || |
| 271 | !eq(news.netbiosNameServers, olds.netbiosNameServers) || |
| 272 | news.netbiosNodeType !== olds.netbiosNodeType |
| 273 | ) { |
| 274 | return { action: "replace" }; |
| 275 | } |
| 276 | // vpcId association and tags are mutable in place. |
| 277 | }), |
| 278 | |
| 279 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 280 | const desiredTags = yield* createTags(id, news.tags); |
| 281 | |
| 282 | // Observe — find the options set via the cached id, else create. |
| 283 | let opts: ec2.DhcpOptions | undefined; |
| 284 | if (output?.dhcpOptionsId) { |
| 285 | opts = yield* describeDhcpOptions(output.dhcpOptionsId); |
| 286 | } |
| 287 | |
| 288 | // Ensure — create if missing. |
| 289 | if (opts === undefined) { |
| 290 | yield* session.note("Creating DHCP options set..."); |
| 291 | const result = yield* ec2.createDhcpOptions({ |
| 292 | DhcpConfigurations: buildConfigurations(news), |
| 293 | TagSpecifications: [ |
| 294 | { |
| 295 | ResourceType: "dhcp-options", |
| 296 | Tags: createTagsList(desiredTags), |
| 297 | }, |
| 298 | ], |
| 299 | }); |
| 300 | opts = result.DhcpOptions!; |
| 301 | yield* session.note(`DHCP options set created: ${opts.DhcpOptionsId}`); |
| 302 | } |
| 303 | |
| 304 | const dhcpOptionsId = opts.DhcpOptionsId!; |
| 305 | |
| 306 | // Sync association — associate the desired VPC, and detach any VPC we |
| 307 | // previously associated that is no longer desired (re-point it at the |
| 308 | // default options set). |
| 309 | const previousVpc = output?.vpcId; |
| 310 | if (news.vpcId) { |
| 311 | yield* ec2.associateDhcpOptions({ |
| 312 | DhcpOptionsId: dhcpOptionsId, |
| 313 | VpcId: news.vpcId as string, |
| 314 | }); |
| 315 | } |
| 316 | if (previousVpc && previousVpc !== news.vpcId) { |
| 317 | yield* ec2.associateDhcpOptions({ |
| 318 | DhcpOptionsId: "default", |
| 319 | VpcId: previousVpc as string, |
| 320 | }); |
| 321 | } |
| 322 | |
| 323 | // Sync tags — observed cloud tags vs desired. |
| 324 | const currentTags = |
| 325 | (yield* ec2 |
| 326 | .describeTags({ |
| 327 | Filters: [ |
| 328 | { Name: "resource-id", Values: [dhcpOptionsId] }, |
| 329 | { Name: "resource-type", Values: ["dhcp-options"] }, |
| 330 | ], |
| 331 | }) |
| 332 | .pipe( |
| 333 | Effect.map( |
| 334 | (r) => |
| 335 | Object.fromEntries(r.Tags?.map((t) => [t.Key!, t.Value!]) ?? []) as Record< |
| 336 | string, |
| 337 | string |
| 338 | >, |
| 339 | ), |
| 340 | )) ?? {}; |
| 341 | const { removed, upsert } = diffTags(currentTags, desiredTags); |
| 342 | if (removed.length > 0) { |
| 343 | yield* ec2.deleteTags({ |
| 344 | Resources: [dhcpOptionsId], |
| 345 | Tags: removed.map((key) => ({ Key: key })), |
| 346 | }); |
| 347 | } |
| 348 | if (upsert.length > 0) { |
| 349 | yield* ec2.createTags({ |
| 350 | Resources: [dhcpOptionsId], |
| 351 | Tags: upsert, |
| 352 | }); |
| 353 | } |
| 354 | |
| 355 | return yield* toAttrs(opts, news.vpcId); |
| 356 | }), |
| 357 | |
| 358 | delete: Effect.fn(function* ({ output, session }) { |
| 359 | const dhcpOptionsId = output.dhcpOptionsId; |
| 360 | |
| 361 | // Disassociate any VPC first — a set cannot be deleted while attached. |
| 362 | if (output.vpcId) { |
| 363 | yield* session.note(`Restoring default DHCP options on ${output.vpcId}...`); |
| 364 | yield* ec2 |
| 365 | .associateDhcpOptions({ |
| 366 | DhcpOptionsId: "default", |
| 367 | VpcId: output.vpcId as string, |
| 368 | }) |
| 369 | .pipe(Effect.catchTag("InvalidVpcID.NotFound", () => Effect.void)); |
| 370 | } |
| 371 | |
| 372 | yield* session.note(`Deleting DHCP options set: ${dhcpOptionsId}`); |
| 373 | yield* ec2.deleteDhcpOptions({ DhcpOptionsId: dhcpOptionsId }).pipe( |
| 374 | Effect.catchTags({ |
| 375 | "InvalidDhcpOptionID.NotFound": () => Effect.void, |
| 376 | "InvalidDhcpOptionsID.NotFound": () => Effect.void, |
| 377 | }), |
| 378 | // A VPC association may still be clearing. |
| 379 | Effect.retry({ |
| 380 | while: (e: { _tag: string }) => e._tag === "DependencyViolation", |
| 381 | schedule: Schedule.max([Schedule.fixed(3000), Schedule.recurs(20)]), |
| 382 | }), |
| 383 | ); |
| 384 | yield* waitUntilDhcpOptionsGone(dhcpOptionsId); |
| 385 | }), |
| 386 | }; |
| 387 | }), |
| 388 | ); |