@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 251 lines 9.14 KB
Raw
1 import * as elbv2 from "@distilled.cloud/aws/elastic-load-balancing-v2";
2 import { isResolved } from "alchemy/Diff";
3 import type { Input } from "alchemy/Input";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import * as Stream from "effect/Stream";
9 import type { Providers } from "../Providers.ts";
10 import { type TargetGroup, type TargetGroupArn } from "./TargetGroup.ts";
11
12 export interface TargetGroupAttachmentProps {
13 /** The target group to register the target with. Changing it replaces the attachment. */
14 targetGroupArn: Input<TargetGroupArn> | TargetGroup;
15 /**
16 * The target ID: an instance ID (`instance` target type), an IP address
17 * (`ip`), a Lambda function ARN (`lambda`), or an ALB ARN (`alb`). Changing
18 * it replaces the attachment.
19 */
20 targetId: string;
21 /**
22 * The port on which the target receives traffic. Defaults to the target
23 * group port. Not applicable to `lambda` targets. Changing it replaces the
24 * attachment.
25 */
26 port?: number;
27 /**
28 * The Availability Zone of the target. Set to `all` to register an IP
29 * target outside the target group's VPC (e.g. an on-prem address). Changing
30 * it replaces the attachment.
31 */
32 availabilityZone?: string;
33 }
34
35 export interface TargetGroupAttachment extends Resource<
36 "AWS.ELBv2.TargetGroupAttachment",
37 TargetGroupAttachmentProps,
38 {
39 /** The ARN of the target group the target is registered with. */
40 targetGroupArn: TargetGroupArn;
41 /** The registered target: an instance ID, IP address, or Lambda/ALB ARN. */
42 targetId: string;
43 /** The port the target receives traffic on, if applicable. */
44 port: number | undefined;
45 /** The Availability Zone the target was registered in, if specified. */
46 availabilityZone: string | undefined;
47 },
48 never,
49 Providers
50 > {}
51
52 /**
53 * Registers a single target (instance, IP address, Lambda function, or ALB)
54 * with an ELBv2 target group. ECS services register their own tasks, so this
55 * resource matters for Lambda-behind-ALB, EC2 instances, and static IPs.
56 *
57 * For `lambda` targets, the Lambda function's resource policy must allow
58 * `elasticloadbalancing.amazonaws.com` to invoke it, scoped to the target
59 * group ARN — create a {@link Permission} first. The provider retries the
60 * registration briefly while that permission propagates.
61 * ### Registering Targets
62 * **Example:** Lambda function target
63 * ```typescript
64 * const tg = yield* TargetGroup("fn", { targetType: "lambda" });
65 * yield* Lambda.Permission("AlbInvoke", {
66 * action: "lambda:InvokeFunction",
67 * functionName: fn.functionArn.as<string>(),
68 * principal: "elasticloadbalancing.amazonaws.com",
69 * sourceArn: tg.targetGroupArn.as<string>(),
70 * });
71 * yield* TargetGroupAttachment("fn-target", {
72 * targetGroupArn: tg.targetGroupArn,
73 * targetId: fn.functionArn.as<string>(),
74 * });
75 * ```
76 *
77 * **Example:** IP address target
78 * ```typescript
79 * yield* TargetGroupAttachment("ip-target", {
80 * targetGroupArn: tg.targetGroupArn,
81 * targetId: "10.0.1.15",
82 * port: 8080,
83 * });
84 * ```
85 *
86 * **Example:** EC2 instance target
87 * ```typescript
88 * yield* TargetGroupAttachment("instance-target", {
89 * targetGroupArn: tg.targetGroupArn,
90 * targetId: instance.instanceId,
91 * port: 80,
92 * });
93 * ```
94 *
95 * @resource
96 */
97 export const TargetGroupAttachment = Resource<TargetGroupAttachment>(
98 "AWS.ELBv2.TargetGroupAttachment",
99 );
100
101 // Registering a Lambda target validates that the function's resource policy
102 // grants elasticloadbalancing.amazonaws.com invoke permission. The Permission
103 // resource is often created in the same deploy with no data dependency on the
104 // attachment, so registerTargets can run before the policy lands. ELB surfaces
105 // the missing-permission case as either `InvalidTargetException` or an
106 // empty-message `AccessDeniedException` (both members of the registerTargets
107 // error union — AccessDeniedException via CommonErrors), so retry both briefly
108 // while IAM propagates. Explicitly typed so `Retry.Return`'s conditional type
109 // never leaks into declaration emit.
110 const retryThroughPermissionPropagation = <A, E extends { _tag: string }, R>(
111 self: Effect.Effect<A, E, R>,
112 ): Effect.Effect<A, E, R> =>
113 Effect.retry(self, {
114 while: (e) => e._tag === "InvalidTargetException" || e._tag === "AccessDeniedException",
115 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(15)]),
116 });
117
118 const wireTarget = (props: {
119 targetId: string;
120 port?: number;
121 availabilityZone?: string;
122 }): elbv2.TargetDescription => ({
123 Id: props.targetId,
124 Port: props.port,
125 AvailabilityZone: props.availabilityZone,
126 });
127
128 export const TargetGroupAttachmentProvider = () =>
129 Provider.succeed(TargetGroupAttachment, {
130 stables: ["targetGroupArn", "targetId", "port", "availabilityZone"],
131 diff: Effect.fn(function* ({ olds, news }) {
132 if (!isResolved(news)) return;
133 // Registration has no mutable aspect — every change is a replacement.
134 if (
135 olds.targetGroupArn !== news.targetGroupArn ||
136 olds.targetId !== news.targetId ||
137 olds.port !== news.port ||
138 olds.availabilityZone !== news.availabilityZone
139 ) {
140 return { action: "replace" } as const;
141 }
142 }),
143 read: Effect.fn(function* ({ output }) {
144 if (!output) {
145 return undefined;
146 }
147 // describeTargetHealth without an explicit Targets filter lists only
148 // registered targets, so presence in the response means registered.
149 const health = yield* elbv2
150 .describeTargetHealth({ TargetGroupArn: output.targetGroupArn })
151 .pipe(Effect.catchTag(["TargetGroupNotFoundException"], () => Effect.undefined));
152 const registered = health?.TargetHealthDescriptions?.some(
153 (d) =>
154 d.Target?.Id === output.targetId &&
155 (output.port === undefined || d.Target?.Port === output.port),
156 );
157 return registered ? output : undefined;
158 }),
159 // Attachments belong to a target group. Enumerate every target group,
160 // then every registered target.
161 list: Effect.fn(function* () {
162 const targetGroupArns = yield* elbv2.describeTargetGroups.pages({}).pipe(
163 Stream.runCollect,
164 Effect.map((chunk) =>
165 Array.from(chunk).flatMap((page) =>
166 (page.TargetGroups ?? []).flatMap((tg) =>
167 tg.TargetGroupArn ? [tg.TargetGroupArn as TargetGroupArn] : [],
168 ),
169 ),
170 ),
171 );
172 const rows = yield* Effect.forEach(
173 targetGroupArns,
174 (targetGroupArn) =>
175 elbv2.describeTargetHealth({ TargetGroupArn: targetGroupArn }).pipe(
176 Effect.map((health) =>
177 (health.TargetHealthDescriptions ?? []).flatMap((d) =>
178 d.Target?.Id
179 ? [
180 {
181 targetGroupArn,
182 targetId: d.Target.Id,
183 port: d.Target.Port,
184 availabilityZone: d.Target.AvailabilityZone,
185 },
186 ]
187 : [],
188 ),
189 ),
190 // The group may vanish between enumeration and health lookup.
191 Effect.catchTag(["TargetGroupNotFoundException"], () => Effect.succeed([])),
192 ),
193 { concurrency: 10 },
194 );
195 const result: TargetGroupAttachment["Attributes"][] = rows.flat();
196 return result;
197 }),
198 reconcile: Effect.fn(function* ({ news, session }) {
199 const targetGroupArn = news.targetGroupArn as TargetGroupArn;
200 const target = wireTarget(news);
201
202 // Observe — is the target already registered?
203 const health = yield* elbv2
204 .describeTargetHealth({ TargetGroupArn: targetGroupArn })
205 .pipe(Effect.catchTag(["InvalidTargetException"], () => Effect.undefined));
206 const registered = health?.TargetHealthDescriptions?.some(
207 (d) =>
208 d.Target?.Id === news.targetId &&
209 (news.port === undefined || d.Target?.Port === news.port),
210 );
211
212 // Ensure — registerTargets is an idempotent put, but skip the call
213 // (and its permission-propagation retry) when already registered.
214 if (!registered) {
215 yield* retryThroughPermissionPropagation(
216 elbv2.registerTargets({
217 TargetGroupArn: targetGroupArn,
218 Targets: [target],
219 }),
220 );
221 }
222
223 yield* session.note(`${news.targetId} -> ${targetGroupArn}`);
224 return {
225 targetGroupArn,
226 targetId: news.targetId,
227 port: news.port,
228 availabilityZone: news.availabilityZone,
229 };
230 }),
231 delete: Effect.fn(function* ({ output }) {
232 yield* elbv2
233 .deregisterTargets({
234 TargetGroupArn: output.targetGroupArn,
235 Targets: [
236 wireTarget({
237 targetId: output.targetId,
238 port: output.port,
239 availabilityZone: output.availabilityZone,
240 }),
241 ],
242 })
243 .pipe(
244 // Already deregistered / group already deleted.
245 Effect.catchTag(
246 ["InvalidTargetException", "TargetGroupNotFoundException"],
247 () => Effect.void,
248 ),
249 );
250 }),
251 });