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

main
ts 386 lines 13.7 KB
Raw
1 import * as ga from "@distilled.cloud/aws/global-accelerator";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import { toWireSeconds } from "alchemy/Util/Duration";
6 import type * as Duration from "effect/Duration";
7 import * as Effect from "effect/Effect";
8 import * as Stream from "effect/Stream";
9 import type { Providers } from "../Providers.ts";
10 import { retryGaDeletion, withGaRegion } from "./common.ts";
11
12 export interface EndpointConfiguration {
13 /**
14 * ID of the endpoint: an ALB or NLB ARN, an Elastic IP allocation ID, or
15 * an EC2 instance ID.
16 */
17 endpointId: string;
18 /**
19 * Relative traffic weight for this endpoint versus the other endpoints in
20 * the group (`0` - `255`).
21 * @default 128
22 */
23 weight?: number;
24 /**
25 * Preserve the client IP address through to the endpoint. Supported for
26 * ALB and EC2 instance endpoints.
27 * @default true for supported endpoint types
28 */
29 clientIPPreservationEnabled?: boolean;
30 /**
31 * ARN of the cross-account attachment authorizing this endpoint when it
32 * lives in another AWS account.
33 */
34 attachmentArn?: string;
35 }
36
37 export interface PortOverride {
38 /**
39 * The listener port to override.
40 */
41 listenerPort: number;
42 /**
43 * The endpoint port that traffic on the overridden listener port is
44 * routed to.
45 */
46 endpointPort: number;
47 }
48
49 export interface EndpointGroupProps {
50 /**
51 * ARN of the listener the endpoint group attaches to. Changing it
52 * replaces the endpoint group.
53 */
54 listenerArn: string;
55 /**
56 * The AWS Region where the endpoint group's endpoints live. One endpoint
57 * group per region per listener; changing it replaces the group.
58 */
59 endpointGroupRegion: string;
60 /**
61 * The endpoints (ALBs, NLBs, EC2 instances, Elastic IPs) traffic is
62 * routed to. Omitting it (or `[]`) keeps the group empty.
63 */
64 endpoints?: EndpointConfiguration[];
65 /**
66 * The percentage of the listener's traffic to send to this endpoint
67 * group (`0` - `100`), applied after location-based routing.
68 * @default 100
69 */
70 trafficDialPercentage?: number;
71 /**
72 * The port used for health checks.
73 * @default the first port of the listener's port ranges
74 */
75 healthCheckPort?: number;
76 /**
77 * The protocol used for health checks.
78 * @default "TCP"
79 */
80 healthCheckProtocol?: "TCP" | "HTTP" | "HTTPS";
81 /**
82 * The path for HTTP/HTTPS health checks.
83 * @default "/"
84 */
85 healthCheckPath?: string;
86 /**
87 * Time between health checks, e.g. `"10 seconds"` or
88 * `Duration.seconds(30)`. Rounded to whole seconds on the wire; the API
89 * accepts `10` or `30` seconds.
90 * @default "30 seconds"
91 */
92 healthCheckInterval?: Duration.Input;
93 /**
94 * Consecutive health-check successes/failures required to flip an
95 * endpoint healthy/unhealthy.
96 * @default 3
97 */
98 thresholdCount?: number;
99 /**
100 * Overrides routing specific listener ports to different endpoint ports.
101 */
102 portOverrides?: PortOverride[];
103 }
104
105 export interface EndpointGroup extends Resource<
106 "AWS.GlobalAccelerator.EndpointGroup",
107 EndpointGroupProps,
108 {
109 /** The ARN of the endpoint group. */
110 endpointGroupArn: string;
111 /** The ARN of the listener the endpoint group is attached to. */
112 listenerArn: string;
113 /** The AWS Region the group's endpoints live in. */
114 endpointGroupRegion: string;
115 /** The percentage of listener traffic dialed to this group. */
116 trafficDialPercentage: number;
117 /** The health-check protocol: `TCP`, `HTTP`, or `HTTPS`. */
118 healthCheckProtocol: string;
119 /** The port used for health checks. */
120 healthCheckPort: number | undefined;
121 /** The path used for HTTP/HTTPS health checks. */
122 healthCheckPath: string | undefined;
123 /** Seconds between health checks. */
124 healthCheckInterval: number;
125 /** Consecutive checks required to flip an endpoint's health state. */
126 thresholdCount: number;
127 /** The endpoints in the group with their observed health. */
128 endpoints: {
129 /** The endpoint's ID (ALB/NLB ARN, EIP allocation ID, or instance ID). */
130 endpointId: string | undefined;
131 /** Relative traffic weight of the endpoint. */
132 weight: number | undefined;
133 /** Observed health: `HEALTHY`, `UNHEALTHY`, or `INITIAL`. */
134 healthState: string | undefined;
135 /** Whether the client IP is preserved through to the endpoint. */
136 clientIPPreservationEnabled: boolean | undefined;
137 }[];
138 },
139 never,
140 Providers
141 > {}
142
143 /**
144 * A Global Accelerator endpoint group — the set of regional endpoints
145 * (ALBs, NLBs, EC2 instances, or Elastic IPs) that a listener routes
146 * traffic to in one AWS Region, with traffic-dial and health-check
147 * configuration.
148 *
149 * One endpoint group per region per listener. Everything except the
150 * listener and region is updatable in place.
151 * ### Creating Endpoint Groups
152 * **Example:** Route to an Application Load Balancer
153 * ```typescript
154 * const group = yield* GlobalAccelerator.EndpointGroup("UsWest2", {
155 * listenerArn: listener.listenerArn,
156 * endpointGroupRegion: "us-west-2",
157 * endpoints: [{ endpointId: alb.loadBalancerArn }],
158 * });
159 * ```
160 *
161 * **Example:** Weighted Endpoints with HTTP Health Checks
162 * ```typescript
163 * const group = yield* GlobalAccelerator.EndpointGroup("UsEast1", {
164 * listenerArn: listener.listenerArn,
165 * endpointGroupRegion: "us-east-1",
166 * endpoints: [
167 * { endpointId: blueAlb.loadBalancerArn, weight: 200 },
168 * { endpointId: greenAlb.loadBalancerArn, weight: 55 },
169 * ],
170 * healthCheckProtocol: "HTTP",
171 * healthCheckPath: "/health",
172 * healthCheckInterval: "10 seconds",
173 * });
174 * ```
175 *
176 * ### Traffic Management
177 * **Example:** Canary a Region with the Traffic Dial
178 * ```typescript
179 * const group = yield* GlobalAccelerator.EndpointGroup("Canary", {
180 * listenerArn: listener.listenerArn,
181 * endpointGroupRegion: "eu-west-1",
182 * trafficDialPercentage: 10,
183 * });
184 * ```
185 *
186 * @resource
187 */
188 export const EndpointGroup = Resource<EndpointGroup>("AWS.GlobalAccelerator.EndpointGroup");
189
190 // Endpoint-group ARNs embed the parent listener ARN:
191 // arn:...:accelerator/{id}/listener/{id}/endpoint-group/{id}
192 const listenerArnOf = (endpointGroupArn: string) => endpointGroupArn.split("/endpoint-group/")[0]!;
193
194 const toAttributes = (g: ga.EndpointGroup, endpointGroupArn: string) => ({
195 endpointGroupArn,
196 listenerArn: listenerArnOf(endpointGroupArn),
197 endpointGroupRegion: g.EndpointGroupRegion ?? "",
198 trafficDialPercentage: g.TrafficDialPercentage ?? 100,
199 healthCheckProtocol: g.HealthCheckProtocol ?? "TCP",
200 healthCheckPort: g.HealthCheckPort,
201 healthCheckPath: g.HealthCheckPath,
202 healthCheckInterval: g.HealthCheckIntervalSeconds ?? 30,
203 thresholdCount: g.ThresholdCount ?? 3,
204 endpoints: (g.EndpointDescriptions ?? []).map((d) => ({
205 endpointId: d.EndpointId,
206 weight: d.Weight,
207 healthState: d.HealthState,
208 clientIPPreservationEnabled: d.ClientIPPreservationEnabled,
209 })),
210 });
211
212 // The desired mutable configuration, shared by create and update. Defaults
213 // are applied explicitly so removing a prop converges back to the default.
214 const desiredConfig = (news: EndpointGroupProps) => ({
215 EndpointConfigurations: (news.endpoints ?? []).map((e) => ({
216 EndpointId: e.endpointId,
217 Weight: e.weight,
218 ClientIPPreservationEnabled: e.clientIPPreservationEnabled,
219 AttachmentArn: e.attachmentArn,
220 })),
221 TrafficDialPercentage: news.trafficDialPercentage ?? 100,
222 HealthCheckPort: news.healthCheckPort,
223 HealthCheckProtocol: news.healthCheckProtocol ?? "TCP",
224 HealthCheckPath: news.healthCheckPath,
225 HealthCheckIntervalSeconds: toWireSeconds(news.healthCheckInterval) ?? 30,
226 ThresholdCount: news.thresholdCount ?? 3,
227 PortOverrides: (news.portOverrides ?? []).map((o) => ({
228 ListenerPort: o.listenerPort,
229 EndpointPort: o.endpointPort,
230 })),
231 });
232
233 const normalizeOverrides = (overrides: ga.PortOverride[] | undefined) =>
234 JSON.stringify(
235 (overrides ?? [])
236 .map((o) => [o.ListenerPort ?? 0, o.EndpointPort ?? 0])
237 .sort((a, b) => a[0]! - b[0]!),
238 );
239
240 // Compare observed cloud state against the desired props for every aspect we
241 // manage. Fields the user never specified (healthCheckPort/path) fall back to
242 // service-computed defaults and are only compared when explicitly desired.
243 const hasDrift = (live: ga.EndpointGroup, news: EndpointGroupProps): boolean => {
244 if ((live.TrafficDialPercentage ?? 100) !== (news.trafficDialPercentage ?? 100)) {
245 return true;
246 }
247 if ((live.HealthCheckProtocol ?? "TCP") !== (news.healthCheckProtocol ?? "TCP")) {
248 return true;
249 }
250 if ((live.HealthCheckIntervalSeconds ?? 30) !== (toWireSeconds(news.healthCheckInterval) ?? 30)) {
251 return true;
252 }
253 if ((live.ThresholdCount ?? 3) !== (news.thresholdCount ?? 3)) return true;
254 if (news.healthCheckPort !== undefined && live.HealthCheckPort !== news.healthCheckPort) {
255 return true;
256 }
257 if (news.healthCheckPath !== undefined && live.HealthCheckPath !== news.healthCheckPath) {
258 return true;
259 }
260 if (
261 normalizeOverrides(live.PortOverrides) !== normalizeOverrides(desiredConfig(news).PortOverrides)
262 ) {
263 return true;
264 }
265 const observed = new Map((live.EndpointDescriptions ?? []).map((d) => [d.EndpointId ?? "", d]));
266 const desired = news.endpoints ?? [];
267 if (observed.size !== desired.length) return true;
268 for (const e of desired) {
269 const d = observed.get(e.endpointId);
270 if (!d) return true;
271 if (e.weight !== undefined && d.Weight !== e.weight) return true;
272 if (
273 e.clientIPPreservationEnabled !== undefined &&
274 d.ClientIPPreservationEnabled !== e.clientIPPreservationEnabled
275 ) {
276 return true;
277 }
278 }
279 return false;
280 };
281
282 const describeEndpointGroup = Effect.fn(function* (endpointGroupArn: string) {
283 return yield* withGaRegion(ga.describeEndpointGroup({ EndpointGroupArn: endpointGroupArn })).pipe(
284 Effect.map((r) => r.EndpointGroup),
285 Effect.catchTag("EndpointGroupNotFoundException", () => Effect.undefined),
286 );
287 });
288
289 // An endpoint group's natural identity is (listener, region) — GA allows at
290 // most one per region per listener, so this lookup is exact.
291 const findEndpointGroup = Effect.fn(function* (
292 listenerArn: string | undefined,
293 region: string | undefined,
294 ) {
295 if (!listenerArn || !region) return undefined;
296 const groups = yield* withGaRegion(
297 ga.listEndpointGroups.items({ ListenerArn: listenerArn }).pipe(Stream.runCollect),
298 ).pipe(
299 Effect.map((chunk) => Array.from(chunk)),
300 Effect.catchTag("ListenerNotFoundException", () => Effect.succeed([] as ga.EndpointGroup[])),
301 );
302 return groups.find((g) => g.EndpointGroupRegion === region);
303 });
304
305 export const EndpointGroupProvider = () =>
306 Provider.succeed(EndpointGroup, {
307 stables: ["endpointGroupArn", "listenerArn", "endpointGroupRegion"],
308 // Sub-resource keyed entirely by its parent listener (and untagged) —
309 // account-wide enumeration happens via the Accelerator resource.
310 list: () => Effect.succeed([]),
311 read: Effect.fn(function* ({ olds, output }) {
312 if (output?.endpointGroupArn) {
313 const live = yield* describeEndpointGroup(output.endpointGroupArn);
314 if (live) return toAttributes(live, output.endpointGroupArn);
315 }
316 const found = yield* findEndpointGroup(olds?.listenerArn, olds?.endpointGroupRegion);
317 if (!found?.EndpointGroupArn) return undefined;
318 return toAttributes(found, found.EndpointGroupArn);
319 }),
320 diff: Effect.fn(function* ({ news, olds }) {
321 if (!isResolved(news)) return undefined;
322 if (news.listenerArn !== olds.listenerArn) {
323 return { action: "replace" } as const;
324 }
325 if (news.endpointGroupRegion !== olds.endpointGroupRegion) {
326 return { action: "replace" } as const;
327 }
328 // everything else updates in place.
329 }),
330 reconcile: Effect.fn(function* ({ news, output, instanceId, session }) {
331 // Observe — cached ARN first, then the exact (listener, region) key.
332 let live = output?.endpointGroupArn
333 ? yield* describeEndpointGroup(output.endpointGroupArn)
334 : undefined;
335 if (!live?.EndpointGroupArn) {
336 live = yield* findEndpointGroup(news.listenerArn, news.endpointGroupRegion);
337 }
338
339 // Ensure — create if missing; a concurrent create for the same
340 // (listener, region) surfaces as AlreadyExists and we converge on it.
341 if (!live?.EndpointGroupArn) {
342 live = yield* withGaRegion(
343 ga.createEndpointGroup({
344 ListenerArn: news.listenerArn,
345 EndpointGroupRegion: news.endpointGroupRegion,
346 ...desiredConfig(news),
347 IdempotencyToken: instanceId,
348 }),
349 ).pipe(
350 Effect.map((r) => r.EndpointGroup),
351 Effect.catchTag("EndpointGroupAlreadyExistsException", () =>
352 findEndpointGroup(news.listenerArn, news.endpointGroupRegion),
353 ),
354 );
355 }
356 if (!live?.EndpointGroupArn) {
357 return yield* Effect.die(new Error("CreateEndpointGroup returned no endpoint group"));
358 }
359 const endpointGroupArn = live.EndpointGroupArn;
360
361 // Sync — one update with the full desired config when anything drifts.
362 if (hasDrift(live, news)) {
363 const updated = yield* withGaRegion(
364 ga.updateEndpointGroup({
365 EndpointGroupArn: endpointGroupArn,
366 ...desiredConfig(news),
367 }),
368 ).pipe(Effect.map((r) => r.EndpointGroup));
369 if (updated) live = updated;
370 }
371
372 yield* session.note(endpointGroupArn);
373 return toAttributes(live, endpointGroupArn);
374 }),
375 delete: Effect.fn(function* ({ output }) {
376 yield* ga
377 .deleteEndpointGroup({
378 EndpointGroupArn: output.endpointGroupArn,
379 })
380 .pipe(
381 withGaRegion,
382 retryGaDeletion,
383 Effect.catchTag("EndpointGroupNotFoundException", () => Effect.void),
384 );
385 }),
386 });