@devries-cameron20 / t3code Mirror · read-only
Fork 0

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, 06:00 UTC

main
ts 511 lines 20.1 KB
Raw
1 import * as elbv2 from "@distilled.cloud/aws/elastic-load-balancing-v2";
2 import * as Data from "effect/Data";
3 import * as Effect from "effect/Effect";
4 import * as Schedule from "effect/Schedule";
5 import * as Stream from "effect/Stream";
6
7 /** Internal: the ALB is still visible after `deleteLoadBalancer`. */
8 class LoadBalancerStillDeleting extends Data.TaggedError("LoadBalancerStillDeleting")<{}> {}
9 import { deepEqual, isResolved } from "alchemy/Diff";
10 import type { Input } from "alchemy/Input";
11 import { createPhysicalName } from "alchemy/PhysicalName";
12 import * as Provider from "alchemy/Provider";
13 import { Resource } from "alchemy/Resource";
14 import { createInternalTags, diffTags } from "alchemy/Tags";
15 import type { SecurityGroupId } from "../EC2/SecurityGroup.ts";
16 import type { SubnetId } from "../EC2/Subnet.ts";
17 import type { AccountID } from "../Environment.ts";
18 import type { Providers } from "../Providers.ts";
19 import type { RegionID } from "../Region.ts";
20 import { attributeDelta, observedAttributes } from "./common.ts";
21 import { readElbTags } from "./internal.ts";
22
23 export type LoadBalancerName = string;
24 export type LoadBalancerArn =
25 `arn:aws:elasticloadbalancing:${RegionID}:${AccountID}:loadbalancer/${string}`;
26
27 export interface LoadBalancerProps {
28 /** The load balancer name. If omitted, a unique name is generated. Changing it replaces the load balancer. */
29 name?: string;
30 /**
31 * Whether the load balancer is internet-facing or internal. Changing it
32 * replaces the load balancer.
33 * @default "internet-facing"
34 */
35 scheme?: "internal" | "internet-facing";
36 /**
37 * The load balancer type. Changing it replaces the load balancer.
38 * @default "application"
39 */
40 type?: "application" | "network" | "gateway";
41 /**
42 * The subnets to attach. Mutually exclusive with {@link subnetMappings}.
43 * Updated in place via `setSubnets`.
44 */
45 subnets?: Input<SubnetId[]>;
46 /**
47 * Per-subnet mappings for static/EIP addresses (Network Load Balancers).
48 * Mutually exclusive with {@link subnets}. Updated in place via `setSubnets`.
49 */
50 subnetMappings?: {
51 subnetId: Input<SubnetId>;
52 /** The allocation ID of an Elastic IP (NLB). */
53 allocationId?: string;
54 /** A private IPv4 address from the subnet (internal NLB). */
55 privateIPv4Address?: string;
56 /** An IPv6 address from the subnet (dualstack NLB). */
57 iPv6Address?: string;
58 /** A source NAT IPv6 prefix. */
59 sourceNatIpv6Prefix?: string;
60 }[];
61 /** The security groups to attach. Updated in place via `setSecurityGroups`. */
62 securityGroups?: Input<SecurityGroupId[]>;
63 /** The IP address type (`ipv4`, `dualstack`, ...). Updated in place via `setIpAddressType`. */
64 ipAddressType?: string;
65 /** The ID of the customer-owned IPv4 pool (Outposts). Changing it replaces the load balancer. */
66 customerOwnedIpv4Pool?: string;
67 /** Whether to prefix-delegate IPv6 for source NAT (`on`/`off`). */
68 enablePrefixForIpv6SourceNat?: "on" | "off";
69 /**
70 * Whether to enforce security-group inbound rules on PrivateLink traffic
71 * (`on`/`off`). Carried by `setSecurityGroups`.
72 */
73 enforceSecurityGroupInboundRulesOnPrivateLinkTraffic?: "on" | "off";
74 /** Raw load-balancer attributes (idle timeout, deletion protection, access logs, ...). */
75 attributes?: Record<string, string>;
76 /** Tags to apply to the load balancer. */
77 tags?: Record<string, string>;
78 }
79
80 export interface LoadBalancer extends Resource<
81 "AWS.ELBv2.LoadBalancer",
82 LoadBalancerProps,
83 {
84 /** The ARN of the load balancer. */
85 loadBalancerArn: LoadBalancerArn;
86 /** The name of the load balancer. */
87 loadBalancerName: LoadBalancerName;
88 /** The public DNS name of the load balancer. */
89 dnsName: string;
90 /** The Route 53 hosted zone ID for alias records targeting the load balancer. */
91 canonicalHostedZoneId: string;
92 /** The ID of the VPC the load balancer resides in. */
93 vpcId: string;
94 /** Whether the load balancer is `internet-facing` or `internal`. */
95 scheme: string;
96 /** The load balancer type (`application`, `network`, or `gateway`). */
97 type: string;
98 /** The IDs of the security groups attached to the load balancer. */
99 securityGroups: string[];
100 /** The IDs of the subnets the load balancer spans. */
101 subnets: string[];
102 /** The tags applied to the load balancer. */
103 tags: Record<string, string>;
104 /**
105 * The live values of the keys declared in `attributes`. Undeclared
106 * attributes are left out so AWS defaults never register as drift.
107 */
108 attributes?: Record<string, string>;
109 },
110 never,
111 Providers
112 > {}
113
114 /**
115 * An ELBv2 (Application / Network / Gateway) load balancer.
116 * ### Creating a Load Balancer
117 * **Example:** Internet-facing Application Load Balancer
118 * ```typescript
119 * const lb = yield* LoadBalancer("web", {
120 * type: "application",
121 * scheme: "internet-facing",
122 * subnets: [subnet1.subnetId, subnet2.subnetId],
123 * securityGroups: [sg.groupId],
124 * });
125 * ```
126 *
127 * **Example:** Network Load Balancer with static EIPs
128 * ```typescript
129 * const nlb = yield* LoadBalancer("edge", {
130 * type: "network",
131 * scheme: "internet-facing",
132 * subnetMappings: [
133 * { subnetId: subnet1.subnetId, allocationId: eip1.allocationId },
134 * { subnetId: subnet2.subnetId, allocationId: eip2.allocationId },
135 * ],
136 * });
137 * ```
138 *
139 * ### Attributes
140 * **Example:** Idle timeout and deletion protection
141 * ```typescript
142 * const lb = yield* LoadBalancer("web", {
143 * type: "application",
144 * subnets: [subnet1.subnetId, subnet2.subnetId],
145 * attributes: {
146 * "idle_timeout.timeout_seconds": "120",
147 * "deletion_protection.enabled": "true",
148 * },
149 * });
150 * ```
151 *
152 * @resource
153 */
154 export const LoadBalancer = Resource<LoadBalancer>("AWS.ELBv2.LoadBalancer");
155
156 // ELB returns subnets and security groups in no fixed order (subnets follow
157 // availability zones), so Attributes hold them sorted for drift to compare.
158 const sortedSubnets = (lb: elbv2.LoadBalancer) =>
159 (lb.AvailabilityZones ?? []).flatMap((zone) => (zone.SubnetId ? [zone.SubnetId] : [])).sort();
160
161 const sortedSecurityGroups = (lb: elbv2.LoadBalancer) => [...(lb.SecurityGroups ?? [])].sort();
162
163 export const LoadBalancerProvider = () =>
164 Provider.effect(
165 LoadBalancer,
166 Effect.gen(function* () {
167 const toName = (id: string, props: { name?: string } = {}) =>
168 props.name
169 ? Effect.succeed(props.name)
170 : createPhysicalName({ id, maxLength: 32, lowercase: true });
171
172 // The observed values of the declared attribute keys; skips the call
173 // when nothing is declared.
174 const readAttributes = Effect.fn(function* (
175 loadBalancerArn: string,
176 declared: Record<string, string> | undefined,
177 ) {
178 if (!declared || Object.keys(declared).length === 0) return undefined;
179 const observed = yield* elbv2.describeLoadBalancerAttributes({
180 LoadBalancerArn: loadBalancerArn,
181 });
182 return observedAttributes(declared, observed.Attributes);
183 });
184
185 return {
186 stables: [
187 "loadBalancerArn",
188 "loadBalancerName",
189 "dnsName",
190 "canonicalHostedZoneId",
191 "vpcId",
192 ],
193 diff: Effect.fn(function* ({ id, olds, news }) {
194 if (!isResolved(news)) return;
195 const oldName = yield* toName(id, olds ?? {});
196 const newName = yield* toName(id, news ?? {});
197 if (oldName !== newName) {
198 return { action: "replace" } as const;
199 }
200 // Only scheme, type and customerOwnedIpv4Pool are immutable.
201 // subnets, securityGroups and ipAddressType are mutated in place
202 // during reconcile (setSubnets / setSecurityGroups / setIpAddressType).
203 if (
204 !deepEqual(
205 {
206 scheme: olds.scheme ?? "internet-facing",
207 type: olds.type ?? "application",
208 customerOwnedIpv4Pool: olds.customerOwnedIpv4Pool,
209 },
210 {
211 scheme: news.scheme ?? "internet-facing",
212 type: news.type ?? "application",
213 customerOwnedIpv4Pool: news.customerOwnedIpv4Pool,
214 },
215 )
216 ) {
217 return { action: "replace" } as const;
218 }
219 }),
220 read: Effect.fn(function* ({ olds, output }) {
221 if (!output) {
222 return undefined;
223 }
224 const described = yield* elbv2
225 .describeLoadBalancers({
226 LoadBalancerArns: [output.loadBalancerArn],
227 })
228 .pipe(Effect.catchTag("LoadBalancerNotFoundException", () => Effect.undefined));
229 const loadBalancer = described?.LoadBalancers?.[0];
230 if (!loadBalancer?.LoadBalancerArn) {
231 return undefined;
232 }
233 const attributes = yield* readAttributes(output.loadBalancerArn, olds?.attributes).pipe(
234 Effect.catchTag("LoadBalancerNotFoundException", () => Effect.succeed(null)),
235 );
236 if (attributes === null) {
237 return undefined;
238 }
239 const tags = yield* readElbTags(output.loadBalancerArn).pipe(
240 Effect.catchTag("LoadBalancerNotFoundException", () => Effect.undefined),
241 );
242 if (tags === undefined) {
243 return undefined;
244 }
245 return {
246 ...output,
247 tags,
248 dnsName: loadBalancer.DNSName!,
249 canonicalHostedZoneId: loadBalancer.CanonicalHostedZoneId!,
250 vpcId: loadBalancer.VpcId!,
251 scheme: loadBalancer.Scheme!,
252 type: loadBalancer.Type!,
253 securityGroups: sortedSecurityGroups(loadBalancer),
254 subnets: sortedSubnets(loadBalancer),
255 attributes,
256 };
257 }),
258 list: () =>
259 Effect.gen(function* () {
260 // Enumerate every load balancer in the account/region, paginating
261 // exhaustively.
262 const loadBalancers = yield* elbv2.describeLoadBalancers.pages({}).pipe(
263 Stream.runCollect,
264 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.LoadBalancers ?? [])),
265 );
266 const owned = loadBalancers.filter(
267 (lb): lb is elbv2.LoadBalancer & { LoadBalancerArn: string } =>
268 lb.LoadBalancerArn != null,
269 );
270 if (owned.length === 0) {
271 return [];
272 }
273
274 // describeTags accepts at most 20 ARNs per call, so batch.
275 const batches: (typeof owned)[] = [];
276 for (let i = 0; i < owned.length; i += 20) {
277 batches.push(owned.slice(i, i + 20));
278 }
279 const tagDescriptions = yield* Effect.forEach(
280 batches,
281 (batch) =>
282 elbv2
283 .describeTags({
284 ResourceArns: batch.map((lb) => lb.LoadBalancerArn),
285 })
286 .pipe(Effect.map((res) => res.TagDescriptions ?? [])),
287 { concurrency: 5 },
288 );
289 const tagsByArn = new Map(
290 tagDescriptions
291 .flat()
292 .flatMap((desc) =>
293 desc.ResourceArn
294 ? ([
295 [
296 desc.ResourceArn,
297 Object.fromEntries(
298 (desc.Tags ?? [])
299 .filter(
300 (t): t is { Key: string; Value: string } =>
301 typeof t.Key === "string" && typeof t.Value === "string",
302 )
303 .map((t) => [t.Key, t.Value]),
304 ),
305 ],
306 ] as const)
307 : [],
308 ),
309 );
310
311 return owned.map((lb) => ({
312 loadBalancerArn: lb.LoadBalancerArn as LoadBalancerArn,
313 loadBalancerName: lb.LoadBalancerName!,
314 dnsName: lb.DNSName!,
315 canonicalHostedZoneId: lb.CanonicalHostedZoneId!,
316 vpcId: lb.VpcId!,
317 scheme: lb.Scheme!,
318 type: lb.Type!,
319 securityGroups: sortedSecurityGroups(lb),
320 subnets: sortedSubnets(lb),
321 tags: tagsByArn.get(lb.LoadBalancerArn) ?? {},
322 }));
323 }),
324 reconcile: Effect.fn(function* ({ id, news, session }) {
325 const name = yield* toName(id, news);
326 const desiredTags = {
327 ...(yield* createInternalTags(id)),
328 ...news.tags,
329 };
330
331 // Observe — look up by deterministic name.
332 let described = yield* elbv2
333 .describeLoadBalancers({
334 Names: [name],
335 })
336 .pipe(Effect.catchTag("LoadBalancerNotFoundException", () => Effect.undefined));
337 let loadBalancer = described?.LoadBalancers?.[0];
338
339 const subnetMappings = news.subnetMappings?.map((m) => ({
340 SubnetId: m.subnetId as string,
341 AllocationId: m.allocationId,
342 PrivateIPv4Address: m.privateIPv4Address,
343 IPv6Address: m.iPv6Address,
344 SourceNatIpv6Prefix: m.sourceNatIpv6Prefix,
345 }));
346
347 // Ensure — create if missing. The replacement axes (scheme, type,
348 // customerOwnedIpv4Pool) are handled by diff so we don't need to
349 // deal with mismatches here.
350 if (!loadBalancer?.LoadBalancerArn) {
351 const created = yield* elbv2.createLoadBalancer({
352 Name: name,
353 Scheme: news.scheme ?? "internet-facing",
354 Type: news.type ?? "application",
355 Subnets: news.subnets as string[] | undefined,
356 SubnetMappings: subnetMappings,
357 SecurityGroups: news.securityGroups as string[] | undefined,
358 IpAddressType: news.ipAddressType,
359 CustomerOwnedIpv4Pool: news.customerOwnedIpv4Pool,
360 EnablePrefixForIpv6SourceNat: news.enablePrefixForIpv6SourceNat,
361 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
362 Key,
363 Value,
364 })),
365 });
366 loadBalancer = created.LoadBalancers?.[0];
367 if (!loadBalancer?.LoadBalancerArn) {
368 return yield* Effect.die(new Error("createLoadBalancer returned no load balancer"));
369 }
370 }
371
372 const loadBalancerArn = loadBalancer.LoadBalancerArn as LoadBalancerArn;
373
374 // Sync subnets — diff observed against desired. Only applies to
375 // application/network LBs that manage subnets in place.
376 const observedSubnets =
377 loadBalancer.AvailabilityZones?.flatMap((z) => (z.SubnetId ? [z.SubnetId] : [])) ?? [];
378 if (news.subnets) {
379 const desiredSubnets = news.subnets as string[];
380 if (!deepEqual([...observedSubnets].sort(), [...desiredSubnets].sort())) {
381 yield* elbv2.setSubnets({
382 LoadBalancerArn: loadBalancerArn,
383 Subnets: desiredSubnets,
384 });
385 }
386 } else if (subnetMappings) {
387 yield* elbv2.setSubnets({
388 LoadBalancerArn: loadBalancerArn,
389 SubnetMappings: subnetMappings,
390 });
391 }
392
393 // Sync security groups — diff observed against desired.
394 if (news.securityGroups) {
395 const observedSgs = loadBalancer.SecurityGroups ?? [];
396 const desiredSgs = news.securityGroups as string[];
397 if (
398 !deepEqual([...observedSgs].sort(), [...desiredSgs].sort()) ||
399 news.enforceSecurityGroupInboundRulesOnPrivateLinkTraffic
400 ) {
401 yield* elbv2.setSecurityGroups({
402 LoadBalancerArn: loadBalancerArn,
403 SecurityGroups: desiredSgs,
404 EnforceSecurityGroupInboundRulesOnPrivateLinkTraffic:
405 news.enforceSecurityGroupInboundRulesOnPrivateLinkTraffic,
406 });
407 }
408 }
409
410 // Sync IP address type — diff observed against desired.
411 if (news.ipAddressType && news.ipAddressType !== loadBalancer.IpAddressType) {
412 yield* elbv2.setIpAddressType({
413 LoadBalancerArn: loadBalancerArn,
414 IpAddressType: news.ipAddressType,
415 });
416 }
417
418 // Sync attributes — diff the observed values of the declared keys
419 // against desired and apply only the delta.
420 let attributes = yield* readAttributes(loadBalancerArn, news.attributes);
421 const attributeChanges = attributeDelta(news.attributes, attributes);
422 if (attributeChanges.length > 0) {
423 const modified = yield* elbv2.modifyLoadBalancerAttributes({
424 LoadBalancerArn: loadBalancerArn,
425 Attributes: attributeChanges,
426 });
427 attributes = {
428 ...attributes,
429 ...observedAttributes(news.attributes, modified.Attributes),
430 };
431 }
432
433 // Sync tags — diff observed cloud tags against desired.
434 const tagDescriptions = yield* elbv2.describeTags({
435 ResourceArns: [loadBalancerArn],
436 });
437 const observedTags = Object.fromEntries(
438 (tagDescriptions.TagDescriptions?.[0]?.Tags ?? [])
439 .filter(
440 (t): t is { Key: string; Value: string } =>
441 typeof t.Key === "string" && typeof t.Value === "string",
442 )
443 .map((t) => [t.Key, t.Value]),
444 );
445 const { removed, upsert } = diffTags(observedTags, desiredTags);
446 if (upsert.length > 0) {
447 yield* elbv2.addTags({
448 ResourceArns: [loadBalancerArn],
449 Tags: upsert,
450 });
451 }
452 if (removed.length > 0) {
453 yield* elbv2.removeTags({
454 ResourceArns: [loadBalancerArn],
455 TagKeys: removed,
456 });
457 }
458
459 // Re-read so subnets and security groups set above are reflected.
460 const final =
461 (yield* elbv2
462 .describeLoadBalancers({ LoadBalancerArns: [loadBalancerArn] })
463 .pipe(Effect.catchTag("LoadBalancerNotFoundException", () => Effect.undefined)))
464 ?.LoadBalancers?.[0] ?? loadBalancer;
465
466 yield* session.note(loadBalancerArn);
467 return {
468 loadBalancerArn,
469 loadBalancerName: final.LoadBalancerName!,
470 dnsName: final.DNSName!,
471 canonicalHostedZoneId: final.CanonicalHostedZoneId!,
472 vpcId: final.VpcId!,
473 scheme: final.Scheme!,
474 type: final.Type!,
475 securityGroups: sortedSecurityGroups(final),
476 subnets: sortedSubnets(final),
477 tags: desiredTags,
478 attributes,
479 };
480 }),
481 delete: Effect.fn(function* ({ output }) {
482 yield* elbv2
483 .deleteLoadBalancer({
484 LoadBalancerArn: output.loadBalancerArn,
485 })
486 .pipe(Effect.catchTag("LoadBalancerNotFoundException", () => Effect.void));
487
488 // `deleteLoadBalancer` returns immediately, but the ALB's ENIs
489 // linger for a minute or two afterwards and block deletion of any
490 // subnet or security group they occupy. Wait until the balancer is
491 // fully gone so downstream network resources tear down on the first
492 // attempt instead of spinning on dependency-violation retries.
493 yield* elbv2
494 .describeLoadBalancers({
495 LoadBalancerArns: [output.loadBalancerArn],
496 })
497 .pipe(
498 Effect.flatMap(() => Effect.fail(new LoadBalancerStillDeleting())),
499 Effect.catchTag("LoadBalancerNotFoundException", () => Effect.void),
500 Effect.retry({
501 while: (e) => e._tag === "LoadBalancerStillDeleting",
502 schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(48)]),
503 }),
504 // Best-effort: if it is somehow still visible after ~4 min, let
505 // the downstream deletes retry rather than fail the teardown.
506 Effect.catchTag("LoadBalancerStillDeleting", () => Effect.void),
507 );
508 }),
509 };
510 }),
511 );