The best way to control Claude Code, Codex and more from any computer or phone

main
ts 418 lines 15.1 KB
Raw
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 Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import * as Stream from "effect/Stream";
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 type PrefixListId<ID extends string = string> = `pl-${ID}`;
15 export const PrefixListId = <ID extends string>(id: ID): ID & PrefixListId<ID> =>
16 `pl-${id}` as ID & PrefixListId<ID>;
17
18 export type PrefixListArn<ID extends PrefixListId = PrefixListId> =
19 `arn:aws:ec2:${RegionID}:${AccountID}:prefix-list/${ID}`;
20
21 /**
22 * A single CIDR entry in a managed prefix list.
23 */
24 export interface PrefixListEntry {
25 /**
26 * The CIDR block for this entry. Must match the list's `addressFamily`
27 * (an IPv4 CIDR for `IPv4`, an IPv6 CIDR for `IPv6`).
28 */
29 cidr: string;
30 /**
31 * An optional description for the entry (up to 255 characters).
32 */
33 description?: string;
34 }
35
36 export interface PrefixListProps {
37 /**
38 * A name for the prefix list. If omitted, a unique name is generated from
39 * the app, stage, and logical ID. Up to 255 characters. Mutable.
40 */
41 prefixListName?: string;
42
43 /**
44 * The IP address family of the prefix list. Determines the CIDR format
45 * accepted in `entries`. Immutable — changing it replaces the list.
46 * @default "IPv4"
47 */
48 addressFamily?: "IPv4" | "IPv6";
49
50 /**
51 * The maximum number of entries the prefix list can hold. Required by AWS.
52 * Can be increased in place (not decreased) — a decrease replaces the list.
53 */
54 maxEntries: number;
55
56 /**
57 * The CIDR entries in the prefix list. Added/removed in place via versioned
58 * modifications.
59 * @default []
60 */
61 entries?: PrefixListEntry[];
62
63 /**
64 * Tags to assign to the prefix list.
65 */
66 tags?: Record<string, string>;
67 }
68
69 export interface PrefixList extends Resource<
70 "AWS.EC2.PrefixList",
71 PrefixListProps,
72 {
73 /**
74 * The ID of the prefix list (prefixed `pl-`).
75 */
76 prefixListId: PrefixListId;
77
78 /**
79 * The Amazon Resource Name (ARN) of the prefix list.
80 */
81 prefixListArn: PrefixListArn;
82
83 /**
84 * The name of the prefix list.
85 */
86 prefixListName: string;
87
88 /**
89 * The IP address family of the prefix list.
90 */
91 addressFamily: "IPv4" | "IPv6";
92
93 /**
94 * The maximum number of entries the prefix list can hold.
95 */
96 maxEntries: number;
97
98 /**
99 * The current version of the prefix list. Incremented on every entry
100 * modification.
101 */
102 version: number;
103
104 /**
105 * The AWS account ID of the prefix list owner.
106 */
107 ownerId: string;
108 },
109 never,
110 Providers
111 > {}
112
113 /**
114 * A managed prefix list is a named, reusable set of CIDR blocks that you
115 * reference by ID from security group rules and route tables. Instead of
116 * duplicating the same IP ranges across many rules, you maintain them in one
117 * place and every rule that references the list picks up changes automatically.
118 *
119 * The list is versioned: each entry modification bumps `version`, and AWS
120 * limits a list to `maxEntries` CIDRs (you provision headroom up front and can
121 * only grow it, never shrink it, in place). `addressFamily` fixes whether the
122 * list holds IPv4 or IPv6 CIDRs and is immutable.
123 *
124 * ### Creating a Prefix List
125 * **Example:** Basic IPv4 Prefix List
126 * ```typescript
127 * const corpNetworks = yield* AWS.EC2.PrefixList("CorpNetworks", {
128 * maxEntries: 10,
129 * entries: [
130 * { cidr: "10.0.0.0/16", description: "vpc-a" },
131 * { cidr: "10.1.0.0/16", description: "vpc-b" },
132 * ],
133 * });
134 * ```
135 * Creates a prefix list with two IPv4 CIDRs. The resulting `prefixListId`
136 * (prefixed `pl-`) can be referenced from security group rules and routes.
137 *
138 * **Example:** IPv6 Prefix List
139 * ```typescript
140 * const ipv6List = yield* AWS.EC2.PrefixList("Ipv6List", {
141 * addressFamily: "IPv6",
142 * maxEntries: 5,
143 * entries: [{ cidr: "2001:db8::/32" }],
144 * });
145 * ```
146 * `addressFamily: "IPv6"` makes the list accept IPv6 CIDRs. Because the family
147 * is intrinsic to the list, changing it later replaces the resource.
148 *
149 * ### Referencing a Prefix List from a Security Group Rule
150 * **Example:** Allow Inbound from a Prefix List
151 * ```typescript
152 * const corpNetworks = yield* AWS.EC2.PrefixList("CorpNetworks", {
153 * maxEntries: 10,
154 * entries: [{ cidr: "10.0.0.0/16" }],
155 * });
156 *
157 * const rule = yield* AWS.EC2.SecurityGroupRule("AllowCorp", {
158 * groupId: sg.groupId,
159 * type: "ingress",
160 * ipProtocol: "tcp",
161 * fromPort: 443,
162 * toPort: 443,
163 * prefixListId: corpNetworks.prefixListId,
164 * });
165 * ```
166 * The rule allows HTTPS from every CIDR in the list. Editing the list's
167 * `entries` updates what the rule permits without touching the rule itself.
168 *
169 * @resource
170 */
171 export const PrefixList = Resource<PrefixList>("AWS.EC2.PrefixList");
172
173 // A prefix list is stable (safe to modify/delete) only when its state ends in
174 // "-complete". "-in-progress" states are transient; "-failed" is terminal.
175 const isStableState = (state: string | undefined) =>
176 state === undefined || state.endsWith("-complete");
177
178 export const PrefixListProvider = () =>
179 Provider.effect(
180 PrefixList,
181 Effect.gen(function* () {
182 const createTags = Effect.fn(function* (id: string, tags?: Record<string, string>) {
183 return {
184 Name: id,
185 ...(yield* createInternalTags(id)),
186 ...tags,
187 };
188 });
189
190 const describePrefixList = (prefixListId: string) =>
191 ec2.describeManagedPrefixLists({ PrefixListIds: [prefixListId] }).pipe(
192 Effect.map((r) => r.PrefixLists?.[0]),
193 Effect.catchTag("InvalidPrefixListID.NotFound", () => Effect.undefined),
194 );
195
196 // Poll until the list leaves any "-in-progress" state.
197 const waitStable = (prefixListId: string) =>
198 describePrefixList(prefixListId).pipe(
199 Effect.flatMap((pl) =>
200 isStableState(pl?.State) ? Effect.succeed(pl) : Effect.fail(new PrefixListNotStable()),
201 ),
202 Effect.retry({
203 while: (e) => e instanceof PrefixListNotStable,
204 schedule: Schedule.max([Schedule.fixed(2000), Schedule.recurs(30)]),
205 }),
206 );
207
208 const getEntries = (prefixListId: string) =>
209 ec2.getManagedPrefixListEntries.pages({ PrefixListId: prefixListId }).pipe(
210 Stream.runCollect,
211 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Entries ?? [])),
212 );
213
214 const toAttrs = (pl: ec2.ManagedPrefixList) =>
215 AWSEnvironment.current.pipe(
216 Effect.map((env) => ({
217 prefixListId: pl.PrefixListId as PrefixListId,
218 prefixListArn:
219 (pl.PrefixListArn as PrefixListArn) ??
220 (`arn:aws:ec2:${env.region}:${env.accountId}:prefix-list/${pl.PrefixListId}` as PrefixListArn),
221 prefixListName: pl.PrefixListName!,
222 addressFamily: pl.AddressFamily as "IPv4" | "IPv6",
223 maxEntries: pl.MaxEntries!,
224 version: pl.Version!,
225 ownerId: pl.OwnerId!,
226 })),
227 );
228
229 return {
230 stables: ["prefixListId", "prefixListArn", "addressFamily", "ownerId"],
231
232 list: () =>
233 Effect.gen(function* () {
234 const env = yield* AWSEnvironment.current;
235 const items = yield* ec2.describeManagedPrefixLists.pages({}).pipe(
236 Stream.runCollect,
237 Effect.map((chunk) =>
238 Array.from(chunk).flatMap((page) =>
239 (page.PrefixLists ?? [])
240 // Skip AWS-managed lists (e.g. com.amazonaws.*), which
241 // are owned by "AWS" and have no PrefixListName we set.
242 .filter(
243 (
244 pl,
245 ): pl is ec2.ManagedPrefixList & {
246 PrefixListId: string;
247 } => pl.PrefixListId != null && pl.OwnerId !== "AWS",
248 )
249 .map((pl) => ({
250 prefixListId: pl.PrefixListId as PrefixListId,
251 prefixListArn:
252 (pl.PrefixListArn as PrefixListArn) ??
253 (`arn:aws:ec2:${env.region}:${env.accountId}:prefix-list/${pl.PrefixListId}` as PrefixListArn),
254 prefixListName: pl.PrefixListName!,
255 addressFamily: pl.AddressFamily as "IPv4" | "IPv6",
256 maxEntries: pl.MaxEntries!,
257 version: pl.Version!,
258 ownerId: pl.OwnerId!,
259 })),
260 ),
261 ),
262 );
263 return items satisfies PrefixList["Attributes"][];
264 }),
265
266 read: Effect.fn(function* ({ output }) {
267 if (!output) return undefined;
268 const pl = yield* describePrefixList(output.prefixListId);
269 if (!pl) return undefined;
270 return yield* toAttrs(pl);
271 }),
272
273 diff: Effect.fn(function* ({ news, olds }) {
274 if (!isResolved(news)) return;
275 const oldFamily = olds.addressFamily ?? "IPv4";
276 const newFamily = news.addressFamily ?? "IPv4";
277 if (oldFamily !== newFamily) {
278 return { action: "replace" };
279 }
280 // MaxEntries can only be increased in place; a decrease requires
281 // replacement.
282 if (news.maxEntries < olds.maxEntries) {
283 return { action: "replace" };
284 }
285 // prefixListName, maxEntries (increase), entries, tags → in-place.
286 }),
287
288 reconcile: Effect.fn(function* ({ id, news, output, session }) {
289 const desiredTags = yield* createTags(id, news.tags);
290 const desiredName = news.prefixListName ?? output?.prefixListName ?? id;
291 const desiredFamily = news.addressFamily ?? "IPv4";
292 const desiredEntries = news.entries ?? [];
293
294 // Observe — find the list via the cached id, else fall through.
295 let pl: ec2.ManagedPrefixList | undefined;
296 if (output?.prefixListId) {
297 pl = yield* describePrefixList(output.prefixListId);
298 }
299
300 // Ensure — create if missing.
301 if (pl === undefined) {
302 yield* session.note("Creating managed prefix list...");
303 const result = yield* ec2.createManagedPrefixList({
304 PrefixListName: desiredName,
305 AddressFamily: desiredFamily,
306 MaxEntries: news.maxEntries,
307 Entries: desiredEntries.map((e) => ({
308 Cidr: e.cidr,
309 Description: e.description,
310 })),
311 TagSpecifications: [
312 {
313 ResourceType: "prefix-list",
314 Tags: createTagsList(desiredTags),
315 },
316 ],
317 });
318 const created = result.PrefixList!;
319 yield* session.note(`Managed prefix list created: ${created.PrefixListId}`);
320 pl = yield* waitStable(created.PrefixListId!);
321 }
322
323 const prefixListId = pl!.PrefixListId!;
324
325 // Sync max-entries — an increase is a standalone modify (AWS forbids
326 // changing size and entries in the same call).
327 pl = yield* waitStable(prefixListId);
328 if ((pl?.MaxEntries ?? 0) < news.maxEntries) {
329 yield* session.note(`Increasing prefix list max entries to ${news.maxEntries}...`);
330 yield* ec2.modifyManagedPrefixList({
331 PrefixListId: prefixListId,
332 CurrentVersion: pl!.Version,
333 MaxEntries: news.maxEntries,
334 });
335 pl = yield* waitStable(prefixListId);
336 }
337
338 // Sync entries + name — diff observed entries against desired.
339 const currentEntries = yield* getEntries(prefixListId);
340 const currentByCidr = new Map(currentEntries.map((e) => [e.Cidr!, e.Description ?? ""]));
341 const desiredByCidr = new Map(desiredEntries.map((e) => [e.cidr, e.description ?? ""]));
342
343 const addEntries = desiredEntries
344 .filter(
345 (e) =>
346 !currentByCidr.has(e.cidr) || currentByCidr.get(e.cidr) !== (e.description ?? ""),
347 )
348 .map((e) => ({ Cidr: e.cidr, Description: e.description }));
349 const removeEntries = currentEntries
350 .filter((e) => !desiredByCidr.has(e.Cidr!))
351 .map((e) => ({ Cidr: e.Cidr! }));
352 const nameChanged = (pl?.PrefixListName ?? "") !== desiredName;
353
354 if (addEntries.length > 0 || removeEntries.length > 0 || nameChanged) {
355 yield* session.note("Updating managed prefix list entries...");
356 yield* ec2.modifyManagedPrefixList({
357 PrefixListId: prefixListId,
358 CurrentVersion: pl!.Version,
359 ...(nameChanged ? { PrefixListName: desiredName } : {}),
360 ...(addEntries.length > 0 ? { AddEntries: addEntries } : {}),
361 ...(removeEntries.length > 0 ? { RemoveEntries: removeEntries } : {}),
362 });
363 pl = yield* waitStable(prefixListId);
364 }
365
366 // Sync tags — observed cloud tags vs desired.
367 const currentTags =
368 (yield* ec2
369 .describeTags({
370 Filters: [
371 { Name: "resource-id", Values: [prefixListId] },
372 { Name: "resource-type", Values: ["prefix-list"] },
373 ],
374 })
375 .pipe(
376 Effect.map(
377 (r) =>
378 Object.fromEntries(r.Tags?.map((t) => [t.Key!, t.Value!]) ?? []) as Record<
379 string,
380 string
381 >,
382 ),
383 )) ?? {};
384 const { removed, upsert } = diffTags(currentTags, desiredTags);
385 if (removed.length > 0) {
386 yield* ec2.deleteTags({
387 Resources: [prefixListId],
388 Tags: removed.map((key) => ({ Key: key })),
389 });
390 }
391 if (upsert.length > 0) {
392 yield* ec2.createTags({ Resources: [prefixListId], Tags: upsert });
393 }
394
395 const final = yield* describePrefixList(prefixListId);
396 return yield* toAttrs(final!);
397 }),
398
399 delete: Effect.fn(function* ({ output, session }) {
400 const prefixListId = output.prefixListId;
401 yield* session.note(`Deleting managed prefix list: ${prefixListId}`);
402 yield* ec2.deleteManagedPrefixList({ PrefixListId: prefixListId }).pipe(
403 Effect.catchTag("InvalidPrefixListID.NotFound", () => Effect.void),
404 // Routes / SG rules still referencing the list surface as a
405 // DependencyViolation while they tear down.
406 Effect.retry({
407 while: (e: { _tag: string }) => e._tag === "DependencyViolation",
408 schedule: Schedule.max([Schedule.fixed(5000), Schedule.recurs(20)]),
409 }),
410 );
411 }),
412 };
413 }),
414 );
415
416 class PrefixListNotStable {
417 readonly _tag = "PrefixListNotStable";
418 }