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

main
ts 487 lines 19.6 KB
Raw
1 import * as elbv2 from "@distilled.cloud/aws/elastic-load-balancing-v2";
2 import { deepEqual, isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, diffTags } from "alchemy/Tags";
7 import { toSeconds } from "alchemy/Util/Duration";
8 import type * as Duration from "effect/Duration";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12 import type { AccountID } from "../Environment.ts";
13 import { plainJson } from "../internal/Observe.ts";
14 import type { Providers } from "../Providers.ts";
15 import type { RegionID } from "../Region.ts";
16 import { attributeDelta, observedAttributes } from "./common.ts";
17 import { readElbTags } from "./internal.ts";
18
19 export type TargetGroupName = string;
20 export type TargetGroupArn =
21 `arn:aws:elasticloadbalancing:${RegionID}:${AccountID}:targetgroup/${string}`;
22
23 export interface TargetGroupProps {
24 /** The target group name. If omitted, a unique name is generated. Changing it replaces the target group. */
25 name?: string;
26 /** The VPC the targets live in. Not required for `lambda` targets. Changing it replaces the target group. */
27 vpcId?: string;
28 /** The port on which targets receive traffic. Changing it replaces the target group. */
29 port?: number;
30 /**
31 * The protocol for routing traffic to targets. Changing it replaces the
32 * target group.
33 * @default "HTTP"
34 */
35 protocol?: "HTTP" | "HTTPS" | "TCP" | "UDP" | "TCP_UDP" | "TLS" | "GENEVE";
36 /**
37 * The application protocol version. Use `GRPC` for gRPC, `HTTP2` for HTTP/2.
38 * Changing it replaces the target group.
39 */
40 protocolVersion?: "HTTP1" | "HTTP2" | "GRPC";
41 /**
42 * The target type. Changing it replaces the target group.
43 * @default "ip"
44 */
45 targetType?: "ip" | "instance" | "lambda" | "alb";
46 /** The IP address type (`ipv4`/`ipv6`). Changing it replaces the target group. */
47 ipAddressType?: "ipv4" | "ipv6";
48 /** The health-check path (HTTP/HTTPS). Updated in place. */
49 healthCheckPath?: string;
50 /** The health-check port. Updated in place. */
51 healthCheckPort?: string;
52 /** The health-check protocol. Updated in place. */
53 healthCheckProtocol?: string;
54 /** Whether health checks are enabled. Updated in place. */
55 healthCheckEnabled?: boolean;
56 /** The approximate interval between health checks — e.g. `"15 seconds"`. Sent to AWS as whole seconds. Updated in place. */
57 healthCheckInterval?: Duration.Input;
58 /** The amount of time to wait for a health-check response — e.g. `"5 seconds"`. Sent to AWS as whole seconds. Updated in place. */
59 healthCheckTimeout?: Duration.Input;
60 /** The number of consecutive successes before a target is healthy. Updated in place. */
61 healthyThresholdCount?: number;
62 /** The number of consecutive failures before a target is unhealthy. Updated in place. */
63 unhealthyThresholdCount?: number;
64 /** The HTTP/gRPC codes used to determine a healthy response. Updated in place. */
65 matcher?: { HttpCode?: string; GrpcCode?: string };
66 /** Raw target-group attributes (deregistration delay, stickiness, slow start, ...). */
67 attributes?: Record<string, string>;
68 /** Tags to apply to the target group. */
69 tags?: Record<string, string>;
70 }
71
72 export interface TargetGroup extends Resource<
73 "AWS.ELBv2.TargetGroup",
74 TargetGroupProps,
75 {
76 /** The ARN of the target group. */
77 targetGroupArn: TargetGroupArn;
78 /** The name of the target group. */
79 targetGroupName: TargetGroupName;
80 /** Undefined for `lambda` target groups (they have no port). */
81 port: number | undefined;
82 /** Undefined for `lambda` target groups (they have no protocol). */
83 protocol: string | undefined;
84 /** The target type (`instance`, `ip`, `lambda`, or `alb`). */
85 targetType: string;
86 /** Undefined for `lambda` target groups (they are not VPC-scoped). */
87 vpcId: string | undefined;
88 /** The tags applied to the target group. */
89 tags: Record<string, string>;
90 /**
91 * The live values of the keys declared in `attributes`. Undeclared
92 * attributes are left out so AWS defaults never register as drift.
93 */
94 attributes?: Record<string, string>;
95 /**
96 * The health-check settings the props declare, as observed. Lets
97 * `alchemy drift` detect out-of-band changes.
98 */
99 healthCheck?: Partial<HealthCheckSettings>;
100 },
101 never,
102 Providers
103 > {}
104
105 /**
106 * An ELBv2 target group. A target group routes requests to one or more
107 * registered targets (instances, IPs, Lambda functions, or another ALB) using
108 * the configured protocol and port, and runs health checks against them.
109 * ### Creating a Target Group
110 * **Example:** HTTP target group
111 * ```typescript
112 * const tg = yield* TargetGroup("web", {
113 * vpcId: vpc.vpcId,
114 * port: 80,
115 * protocol: "HTTP",
116 * targetType: "ip",
117 * });
118 * ```
119 *
120 * **Example:** Lambda target group
121 * ```typescript
122 * // No vpc/port/protocol — the target is a Lambda function.
123 * const tg = yield* TargetGroup("fn", {
124 * targetType: "lambda",
125 * });
126 * ```
127 *
128 * **Example:** gRPC target group
129 * ```typescript
130 * const tg = yield* TargetGroup("grpc", {
131 * vpcId: vpc.vpcId,
132 * port: 50051,
133 * protocol: "HTTP",
134 * protocolVersion: "GRPC",
135 * matcher: { GrpcCode: "0" },
136 * });
137 * ```
138 *
139 * ### Health Checks
140 * **Example:** Custom health-check thresholds
141 * ```typescript
142 * const tg = yield* TargetGroup("api", {
143 * vpcId: vpc.vpcId,
144 * port: 8080,
145 * protocol: "HTTP",
146 * healthCheckPath: "/healthz",
147 * healthCheckInterval: "15 seconds",
148 * healthyThresholdCount: 3,
149 * unhealthyThresholdCount: 3,
150 * });
151 * ```
152 *
153 * @resource
154 */
155 export const TargetGroup = Resource<TargetGroup>("AWS.ELBv2.TargetGroup");
156
157 type HealthCheckSettings = Pick<
158 elbv2.TargetGroup,
159 | "HealthCheckPath"
160 | "HealthCheckPort"
161 | "HealthCheckProtocol"
162 | "HealthCheckEnabled"
163 | "HealthCheckIntervalSeconds"
164 | "HealthCheckTimeoutSeconds"
165 | "HealthyThresholdCount"
166 | "UnhealthyThresholdCount"
167 | "Matcher"
168 >;
169
170 /**
171 * The health-check settings reconcile converges (those the props declare),
172 * taken from `settings`. `read` and `reconcile` share it so a converged
173 * target group reads unchanged.
174 */
175 const observeHealthCheck = (
176 settings: HealthCheckSettings,
177 props: TargetGroupProps | undefined,
178 ): Partial<HealthCheckSettings> =>
179 plainJson({
180 HealthCheckPath: props?.healthCheckPath === undefined ? undefined : settings.HealthCheckPath,
181 HealthCheckPort: props?.healthCheckPort === undefined ? undefined : settings.HealthCheckPort,
182 HealthCheckProtocol:
183 props?.healthCheckProtocol === undefined ? undefined : settings.HealthCheckProtocol,
184 HealthCheckEnabled:
185 props?.healthCheckEnabled === undefined ? undefined : settings.HealthCheckEnabled,
186 HealthCheckIntervalSeconds:
187 props?.healthCheckInterval === undefined ? undefined : settings.HealthCheckIntervalSeconds,
188 HealthCheckTimeoutSeconds:
189 props?.healthCheckTimeout === undefined ? undefined : settings.HealthCheckTimeoutSeconds,
190 HealthyThresholdCount:
191 props?.healthyThresholdCount === undefined ? undefined : settings.HealthyThresholdCount,
192 UnhealthyThresholdCount:
193 props?.unhealthyThresholdCount === undefined ? undefined : settings.UnhealthyThresholdCount,
194 Matcher: props?.matcher === undefined ? undefined : settings.Matcher,
195 });
196
197 export const TargetGroupProvider = () =>
198 Provider.effect(
199 TargetGroup,
200 Effect.gen(function* () {
201 const toName = (id: string, props: { name?: string } = {}) =>
202 props.name
203 ? Effect.succeed(props.name)
204 : createPhysicalName({ id, maxLength: 32, lowercase: true });
205
206 // The observed values of the declared attribute keys; skips the call
207 // when nothing is declared.
208 const readAttributes = Effect.fn(function* (
209 targetGroupArn: string,
210 declared: Record<string, string> | undefined,
211 ) {
212 if (!declared || Object.keys(declared).length === 0) return undefined;
213 const observed = yield* elbv2.describeTargetGroupAttributes({
214 TargetGroupArn: targetGroupArn,
215 });
216 return observedAttributes(declared, observed.Attributes);
217 });
218
219 return {
220 stables: ["targetGroupArn", "targetGroupName", "vpcId"],
221 diff: Effect.fn(function* ({ id, olds, news }) {
222 if (!isResolved(news)) return;
223 if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) {
224 return { action: "replace" } as const;
225 }
226 if (
227 !deepEqual(
228 {
229 vpcId: olds.vpcId,
230 protocol: olds.protocol ?? "HTTP",
231 protocolVersion: olds.protocolVersion,
232 port: olds.port,
233 targetType: olds.targetType ?? "ip",
234 ipAddressType: olds.ipAddressType,
235 },
236 {
237 vpcId: news.vpcId,
238 protocol: news.protocol ?? "HTTP",
239 protocolVersion: news.protocolVersion,
240 port: news.port,
241 targetType: news.targetType ?? "ip",
242 ipAddressType: news.ipAddressType,
243 },
244 )
245 ) {
246 return { action: "replace" } as const;
247 }
248 }),
249 read: Effect.fn(function* ({ olds, output }) {
250 if (!output) {
251 return undefined;
252 }
253 const described = yield* elbv2
254 .describeTargetGroups({
255 TargetGroupArns: [output.targetGroupArn],
256 })
257 .pipe(Effect.catchTag("TargetGroupNotFoundException", () => Effect.undefined));
258 const targetGroup = described?.TargetGroups?.[0];
259 if (!targetGroup?.TargetGroupArn) {
260 return undefined;
261 }
262 const attributes = yield* readAttributes(output.targetGroupArn, olds?.attributes).pipe(
263 Effect.catchTag("TargetGroupNotFoundException", () => Effect.succeed(null)),
264 );
265 if (attributes === null) {
266 return undefined;
267 }
268 const tags = yield* readElbTags(output.targetGroupArn).pipe(
269 Effect.catchTag("TargetGroupNotFoundException", () => Effect.undefined),
270 );
271 if (tags === undefined) {
272 return undefined;
273 }
274 return {
275 ...output,
276 port: targetGroup.Port,
277 protocol: targetGroup.Protocol,
278 targetType: targetGroup.TargetType!,
279 vpcId: targetGroup.VpcId,
280 tags,
281 attributes,
282 healthCheck: observeHealthCheck(targetGroup, olds),
283 };
284 }),
285 // Target groups are account/region-scoped. Exhaustively paginate
286 // describeTargetGroups, then fetch tags per group (Attributes carry
287 // them) to produce the same shape `read` returns.
288 list: () =>
289 Effect.gen(function* () {
290 const targetGroups = yield* elbv2.describeTargetGroups.pages({}).pipe(
291 Stream.runCollect,
292 Effect.map((chunk) =>
293 Array.from(chunk).flatMap((page) =>
294 (page.TargetGroups ?? []).filter(
295 (tg): tg is elbv2.TargetGroup & { TargetGroupArn: string } =>
296 tg.TargetGroupArn != null,
297 ),
298 ),
299 ),
300 );
301 return yield* Effect.forEach(
302 targetGroups,
303 (tg) =>
304 Effect.gen(function* () {
305 const tagDescriptions = yield* elbv2
306 .describeTags({ ResourceArns: [tg.TargetGroupArn] })
307 .pipe(Effect.catchTag("TargetGroupNotFoundException", () => Effect.undefined));
308 const tags = Object.fromEntries(
309 (tagDescriptions?.TagDescriptions?.[0]?.Tags ?? [])
310 .filter(
311 (t): t is { Key: string; Value: string } =>
312 typeof t.Key === "string" && typeof t.Value === "string",
313 )
314 .map((t) => [t.Key, t.Value]),
315 );
316 return {
317 targetGroupArn: tg.TargetGroupArn as TargetGroupArn,
318 targetGroupName: tg.TargetGroupName!,
319 port: tg.Port,
320 protocol: tg.Protocol,
321 targetType: tg.TargetType!,
322 vpcId: tg.VpcId,
323 tags,
324 };
325 }),
326 { concurrency: 10 },
327 );
328 }),
329 reconcile: Effect.fn(function* ({ id, news, session }) {
330 const name = yield* toName(id, news);
331 const desiredTags = {
332 ...(yield* createInternalTags(id)),
333 ...news.tags,
334 };
335
336 // Observe — look up by deterministic name.
337 let described = yield* elbv2
338 .describeTargetGroups({
339 Names: [name],
340 })
341 .pipe(Effect.catchTag("TargetGroupNotFoundException", () => Effect.undefined));
342 let targetGroup = described?.TargetGroups?.[0];
343
344 // Ensure — create if missing. Stable axes (vpcId, port, protocol,
345 // targetType) are handled by diff so we don't deal with mismatch.
346 // Lambda target groups have no port/protocol/VPC — the API rejects
347 // those members, so omit them entirely.
348 const isLambdaTarget = news.targetType === "lambda";
349 if (!targetGroup?.TargetGroupArn) {
350 const created = yield* elbv2.createTargetGroup({
351 Name: name,
352 Port: isLambdaTarget ? undefined : news.port,
353 Protocol: isLambdaTarget ? undefined : (news.protocol ?? "HTTP"),
354 ProtocolVersion: isLambdaTarget ? undefined : news.protocolVersion,
355 VpcId: isLambdaTarget ? undefined : news.vpcId,
356 TargetType: news.targetType ?? "ip",
357 IpAddressType: isLambdaTarget ? undefined : news.ipAddressType,
358 HealthCheckPath: news.healthCheckPath,
359 HealthCheckPort: news.healthCheckPort,
360 HealthCheckProtocol: news.healthCheckProtocol,
361 HealthCheckEnabled: news.healthCheckEnabled,
362 HealthCheckIntervalSeconds: toSeconds(news.healthCheckInterval),
363 HealthCheckTimeoutSeconds: toSeconds(news.healthCheckTimeout),
364 HealthyThresholdCount: news.healthyThresholdCount,
365 UnhealthyThresholdCount: news.unhealthyThresholdCount,
366 Matcher: news.matcher,
367 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
368 Key,
369 Value,
370 })),
371 });
372 targetGroup = created.TargetGroups?.[0];
373 if (!targetGroup?.TargetGroupArn) {
374 return yield* Effect.die(new Error("createTargetGroup returned no target group"));
375 }
376 }
377
378 const targetGroupArn = targetGroup.TargetGroupArn as TargetGroupArn;
379
380 // Sync health check — diff observed against desired; only call
381 // modifyTargetGroup when a health-check field actually changed.
382 const observedHc = {
383 HealthCheckPath: targetGroup.HealthCheckPath,
384 HealthCheckPort: targetGroup.HealthCheckPort,
385 HealthCheckProtocol: targetGroup.HealthCheckProtocol,
386 HealthCheckEnabled: targetGroup.HealthCheckEnabled,
387 HealthCheckIntervalSeconds: targetGroup.HealthCheckIntervalSeconds,
388 HealthCheckTimeoutSeconds: targetGroup.HealthCheckTimeoutSeconds,
389 HealthyThresholdCount: targetGroup.HealthyThresholdCount,
390 UnhealthyThresholdCount: targetGroup.UnhealthyThresholdCount,
391 Matcher: targetGroup.Matcher,
392 };
393 const desiredHc = {
394 HealthCheckPath: news.healthCheckPath ?? observedHc.HealthCheckPath,
395 HealthCheckPort: news.healthCheckPort ?? observedHc.HealthCheckPort,
396 HealthCheckProtocol: news.healthCheckProtocol ?? observedHc.HealthCheckProtocol,
397 HealthCheckEnabled: news.healthCheckEnabled ?? observedHc.HealthCheckEnabled,
398 HealthCheckIntervalSeconds:
399 toSeconds(news.healthCheckInterval) ?? observedHc.HealthCheckIntervalSeconds,
400 HealthCheckTimeoutSeconds:
401 toSeconds(news.healthCheckTimeout) ?? observedHc.HealthCheckTimeoutSeconds,
402 HealthyThresholdCount: news.healthyThresholdCount ?? observedHc.HealthyThresholdCount,
403 UnhealthyThresholdCount:
404 news.unhealthyThresholdCount ?? observedHc.UnhealthyThresholdCount,
405 Matcher: news.matcher ?? observedHc.Matcher,
406 };
407 if (!deepEqual(observedHc, desiredHc)) {
408 yield* elbv2.modifyTargetGroup({
409 TargetGroupArn: targetGroupArn,
410 ...desiredHc,
411 });
412 }
413
414 // Sync attributes — diff the observed values of the declared keys
415 // against desired and apply only the delta.
416 let attributes = yield* readAttributes(targetGroupArn, news.attributes);
417 const attributeChanges = attributeDelta(news.attributes, attributes);
418 if (attributeChanges.length > 0) {
419 const modified = yield* elbv2.modifyTargetGroupAttributes({
420 TargetGroupArn: targetGroupArn,
421 Attributes: attributeChanges,
422 });
423 attributes = {
424 ...attributes,
425 ...observedAttributes(news.attributes, modified.Attributes),
426 };
427 }
428
429 // Sync tags — diff observed cloud tags against desired.
430 const tagDescriptions = yield* elbv2.describeTags({
431 ResourceArns: [targetGroupArn],
432 });
433 const observedTags = Object.fromEntries(
434 (tagDescriptions.TagDescriptions?.[0]?.Tags ?? [])
435 .filter(
436 (t): t is { Key: string; Value: string } =>
437 typeof t.Key === "string" && typeof t.Value === "string",
438 )
439 .map((t) => [t.Key, t.Value]),
440 );
441 const { removed, upsert } = diffTags(observedTags, desiredTags);
442 if (upsert.length > 0) {
443 yield* elbv2.addTags({
444 ResourceArns: [targetGroupArn],
445 Tags: upsert,
446 });
447 }
448 if (removed.length > 0) {
449 yield* elbv2.removeTags({
450 ResourceArns: [targetGroupArn],
451 TagKeys: removed,
452 });
453 }
454
455 yield* session.note(targetGroupArn);
456 return {
457 targetGroupArn,
458 targetGroupName: targetGroup.TargetGroupName!,
459 port: targetGroup.Port,
460 protocol: targetGroup.Protocol,
461 targetType: targetGroup.TargetType!,
462 vpcId: targetGroup.VpcId,
463 tags: desiredTags,
464 attributes,
465 healthCheck: observeHealthCheck(desiredHc, news),
466 };
467 }),
468 delete: Effect.fn(function* ({ output }) {
469 // deleteTargetGroup is idempotent on a missing target group (returns
470 // success). It only fails with ResourceInUseException while a
471 // listener/rule still references it — retry briefly for the
472 // eventual-consistency window after the dependents are removed.
473 yield* elbv2
474 .deleteTargetGroup({
475 TargetGroupArn: output.targetGroupArn,
476 })
477 .pipe(
478 Effect.retry({
479 while: (e) => e._tag === "ResourceInUseException",
480 schedule: Schedule.max([Schedule.spaced("3 seconds"), Schedule.recurs(8)]),
481 }),
482 Effect.catchTag("ResourceInUseException", () => Effect.void),
483 );
484 }),
485 };
486 }),
487 );