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

main
ts 527 lines 18.7 KB
Raw
1 import * as vpclattice from "@distilled.cloud/aws/vpc-lattice";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { createInternalTags, diffTags, hasAlchemyTags, tagRecord } from "alchemy/Tags";
8 import { toWireSeconds } from "alchemy/Util/Duration";
9 import * as Data from "effect/Data";
10 import type * as Duration from "effect/Duration";
11 import * as Effect from "effect/Effect";
12 import * as Schedule from "effect/Schedule";
13 import * as Stream from "effect/Stream";
14 import type { Providers } from "../Providers.ts";
15 import { retryOnConflict, waitUntilAbsent, waitUntilStable } from "./internal.ts";
16
17 export class VpcLatticeTargetGroupUnexpectedResponse extends Data.TaggedError(
18 "VpcLatticeTargetGroupUnexpectedResponse",
19 )<{
20 readonly message: string;
21 readonly cause?: unknown;
22 }> {}
23
24 /**
25 * The kind of compute a target group routes to.
26 */
27 export type TargetGroupType = "IP" | "LAMBDA" | "INSTANCE" | "ALB";
28
29 /**
30 * A target registered with a target group: an IP address, EC2 instance ID,
31 * ALB ARN, or Lambda function ARN depending on the group's `type`.
32 */
33 export interface TargetGroupTarget {
34 /**
35 * The target identifier: IP address (`IP`), instance ID (`INSTANCE`),
36 * load balancer ARN (`ALB`), or Lambda function ARN (`LAMBDA`).
37 */
38 id: string;
39 /**
40 * Port the target listens on. Not applicable to `LAMBDA` targets.
41 */
42 port?: number;
43 }
44
45 /**
46 * Health check configuration for `IP` and `INSTANCE` target groups.
47 */
48 export interface TargetGroupHealthCheck {
49 /**
50 * Whether health checking is enabled.
51 */
52 enabled?: boolean;
53 /**
54 * Protocol used for health check requests (`HTTP` or `HTTPS`).
55 */
56 protocol?: string;
57 /**
58 * Protocol version used for health check requests (`HTTP1` or `HTTP2`).
59 */
60 protocolVersion?: string;
61 /**
62 * Port used for health checks. Defaults to the target's port.
63 */
64 port?: number;
65 /**
66 * Destination path for health check requests.
67 * @default "/"
68 */
69 path?: string;
70 /**
71 * Approximate time between health checks of an individual target, e.g.
72 * `"30 seconds"` (a bare number is milliseconds). Rounded to whole seconds
73 * on the wire.
74 */
75 healthCheckInterval?: Duration.Input;
76 /**
77 * Time to wait before a health check request is considered failed, e.g.
78 * `"5 seconds"` (a bare number is milliseconds). Rounded to whole seconds
79 * on the wire.
80 */
81 healthCheckTimeout?: Duration.Input;
82 /**
83 * Consecutive successful checks required before an unhealthy target is
84 * considered healthy.
85 */
86 healthyThresholdCount?: number;
87 /**
88 * Consecutive failed checks required before a healthy target is considered
89 * unhealthy.
90 */
91 unhealthyThresholdCount?: number;
92 /**
93 * HTTP status codes counted as a healthy response, e.g. `{ httpCode: "200-299" }`.
94 */
95 matcher?: { httpCode: string };
96 }
97
98 export interface TargetGroupProps {
99 /**
100 * Name of the target group. If omitted, a unique name is generated.
101 * Immutable — changing it replaces the resource.
102 */
103 name?: string;
104 /**
105 * The kind of targets the group routes to. Immutable — changing it replaces
106 * the resource.
107 */
108 type: TargetGroupType;
109 /**
110 * Port the targets listen on. Required for every type except `LAMBDA`.
111 * Immutable — changing it replaces the resource.
112 */
113 port?: number;
114 /**
115 * Protocol used to route traffic to the targets (`HTTP`, `HTTPS`, or
116 * `TCP`). Not applicable to `LAMBDA`. Immutable — changing it replaces the
117 * resource.
118 */
119 protocol?: string;
120 /**
121 * Protocol version (`HTTP1`, `HTTP2`, or `GRPC`). Not applicable to
122 * `LAMBDA`. Immutable — changing it replaces the resource.
123 * @default "HTTP1"
124 */
125 protocolVersion?: string;
126 /**
127 * IP address type of the targets (`IPV4` or `IPV6`). `IP` type only.
128 * Immutable — changing it replaces the resource.
129 * @default "IPV4"
130 */
131 ipAddressType?: string;
132 /**
133 * ID of the VPC the targets live in. Required for every type except
134 * `LAMBDA`. Immutable — changing it replaces the resource.
135 */
136 vpcIdentifier?: string;
137 /**
138 * Version of the event structure a `LAMBDA` target receives (`V1` or
139 * `V2`). Immutable — changing it replaces the resource.
140 * @default "V1"
141 */
142 lambdaEventStructureVersion?: string;
143 /**
144 * Health check configuration. Mutable for `IP` and `INSTANCE` groups; not
145 * applicable to `LAMBDA` and `ALB`.
146 */
147 healthCheck?: TargetGroupHealthCheck;
148 /**
149 * Targets to keep registered with the group. Reconciled against the
150 * observed registrations: missing targets are registered and extra ones
151 * are deregistered.
152 */
153 targets?: TargetGroupTarget[];
154 /**
155 * User-defined tags to apply to the target group.
156 */
157 tags?: Record<string, string>;
158 }
159
160 export interface TargetGroup extends Resource<
161 "AWS.VpcLattice.TargetGroup",
162 TargetGroupProps,
163 {
164 /**
165 * Service-assigned unique ID of the target group.
166 */
167 targetGroupId: string;
168 /**
169 * ARN of the target group.
170 */
171 targetGroupArn: string;
172 /**
173 * Physical name of the target group.
174 */
175 name: string;
176 /**
177 * The kind of targets the group routes to.
178 */
179 type: TargetGroupType;
180 /**
181 * Current lifecycle status (e.g. `ACTIVE`).
182 */
183 status: string;
184 /**
185 * Current tags reported for the target group.
186 */
187 tags: Record<string, string>;
188 },
189 never,
190 Providers
191 > {}
192
193 /**
194 * An Amazon VPC Lattice target group — the collection of compute targets
195 * (IPs, EC2 instances, ALBs, or Lambda functions) that a lattice service's
196 * listeners and rules forward traffic to.
197 *
198 * ### Creating Target Groups
199 * **Example:** Lambda Target Group
200 * ```typescript
201 * const targets = yield* TargetGroup("ApiTargets", {
202 * type: "LAMBDA",
203 * targets: [{ id: fn.functionArn }],
204 * });
205 * ```
206 *
207 * **Example:** IP Target Group with Health Check
208 * ```typescript
209 * const targets = yield* TargetGroup("BackendTargets", {
210 * type: "IP",
211 * port: 80,
212 * protocol: "HTTP",
213 * vpcIdentifier: vpc.vpcId,
214 * healthCheck: {
215 * enabled: true,
216 * path: "/health",
217 * healthCheckInterval: "30 seconds",
218 * healthCheckTimeout: "5 seconds",
219 * },
220 * targets: [{ id: "10.0.1.10", port: 80 }],
221 * });
222 * ```
223 *
224 * @resource
225 */
226 export const TargetGroup = Resource<TargetGroup>("AWS.VpcLattice.TargetGroup");
227
228 const toWireHealthCheck = (healthCheck: TargetGroupHealthCheck): vpclattice.HealthCheckConfig => ({
229 enabled: healthCheck.enabled,
230 protocol: healthCheck.protocol,
231 protocolVersion: healthCheck.protocolVersion,
232 port: healthCheck.port,
233 path: healthCheck.path,
234 healthCheckIntervalSeconds: toWireSeconds(healthCheck.healthCheckInterval),
235 healthCheckTimeoutSeconds: toWireSeconds(healthCheck.healthCheckTimeout),
236 healthyThresholdCount: healthCheck.healthyThresholdCount,
237 unhealthyThresholdCount: healthCheck.unhealthyThresholdCount,
238 matcher: healthCheck.matcher,
239 });
240
241 const targetKey = (t: { id?: string; port?: number }) => `${t.id ?? ""}#${t.port ?? ""}`;
242
243 /**
244 * RegisterTargets reports per-target failures in `unsuccessful` instead of
245 * throwing. Tagged so callers (e.g. `delete`'s not-found tolerance) can keep
246 * using `Effect.catchTag` on the fully typed error union.
247 */
248 class TargetRegistrationFailed extends Data.TaggedError("AWS.VpcLattice.TargetRegistrationFailed")<{
249 targetGroupId: string;
250 unsuccessful: vpclattice.TargetFailure[];
251 }> {
252 override get message() {
253 return `Failed to register targets with target group ${this.targetGroupId}: ${JSON.stringify(this.unsuccessful)}`;
254 }
255 }
256
257 export const TargetGroupProvider = () =>
258 Provider.effect(
259 TargetGroup,
260 Effect.gen(function* () {
261 const toName = (id: string, props: { name?: string } = {}) =>
262 props.name
263 ? Effect.succeed(props.name)
264 : createPhysicalName({ id, maxLength: 63, lowercase: true });
265
266 const observe = (targetGroupIdentifier: string) =>
267 vpclattice
268 .getTargetGroup({ targetGroupIdentifier })
269 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
270
271 const findByName = (name: string) =>
272 vpclattice.listTargetGroups.pages({}).pipe(
273 Stream.runCollect,
274 Effect.map((chunk) =>
275 Array.from(chunk)
276 .flatMap((page) => page.items ?? [])
277 .find((t) => t.name === name),
278 ),
279 Effect.flatMap((summary) => (summary?.id ? observe(summary.id) : Effect.undefined)),
280 );
281
282 const syncTags = Effect.fn(function* (arn: string, desiredTags: Record<string, string>) {
283 const listed = yield* vpclattice.listTagsForResource({
284 resourceArn: arn,
285 });
286 const { removed, upsert } = diffTags(tagRecord(listed.tags), desiredTags);
287 if (upsert.length > 0) {
288 yield* vpclattice.tagResource({
289 resourceArn: arn,
290 tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
291 });
292 }
293 if (removed.length > 0) {
294 yield* vpclattice.untagResource({
295 resourceArn: arn,
296 tagKeys: removed,
297 });
298 }
299 });
300
301 const syncTargets = Effect.fn(function* (
302 targetGroupId: string,
303 desired: TargetGroupTarget[],
304 ) {
305 const observed = yield* vpclattice.listTargets
306 .pages({ targetGroupIdentifier: targetGroupId })
307 .pipe(
308 Stream.runCollect,
309 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.items ?? [])),
310 );
311 const desiredKeys = new Set(desired.map(targetKey));
312 const observedKeys = new Set(observed.map(targetKey));
313 // DRAINING targets are already being deregistered — leave them alone.
314 const toRemove = observed.filter(
315 (t): t is typeof t & { id: string } =>
316 t.id != null && !desiredKeys.has(targetKey(t)) && t.status !== "DRAINING",
317 );
318 const toAdd = desired.filter((t) => !observedKeys.has(targetKey(t)));
319 if (toRemove.length > 0) {
320 yield* vpclattice.deregisterTargets({
321 targetGroupIdentifier: targetGroupId,
322 targets: toRemove.map((t) => ({ id: t.id, port: t.port })),
323 });
324 }
325 if (toAdd.length > 0) {
326 // Partial failures are reported in `unsuccessful`, not thrown.
327 const result = yield* retryOnConflict(
328 vpclattice.registerTargets({
329 targetGroupIdentifier: targetGroupId,
330 targets: toAdd,
331 }),
332 );
333 const unsuccessful = result.unsuccessful ?? [];
334 if (unsuccessful.length > 0) {
335 return yield* new TargetRegistrationFailed({ targetGroupId, unsuccessful });
336 }
337 }
338 });
339
340 return {
341 stables: ["targetGroupId", "targetGroupArn", "name", "type"],
342 diff: Effect.fn(function* ({ id, olds, news }) {
343 if (!isResolved(news)) return;
344 if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) {
345 return { action: "replace" } as const;
346 }
347 // Everything except healthCheck, targets, and tags is fixed at
348 // creation time.
349 if (
350 olds?.type !== news.type ||
351 (olds?.port ?? undefined) !== news.port ||
352 (olds?.protocol ?? undefined) !== news.protocol ||
353 (olds?.protocolVersion ?? undefined) !== news.protocolVersion ||
354 (olds?.ipAddressType ?? undefined) !== news.ipAddressType ||
355 (olds?.vpcIdentifier ?? undefined) !== news.vpcIdentifier ||
356 (olds?.lambdaEventStructureVersion ?? undefined) !== news.lambdaEventStructureVersion
357 ) {
358 return { action: "replace" } as const;
359 }
360 }),
361 read: Effect.fn(function* ({ id, olds, output }) {
362 const group = output?.targetGroupId
363 ? yield* observe(output.targetGroupId)
364 : yield* findByName(yield* toName(id, olds ?? {}));
365 if (!group?.arn || !group.id) return undefined;
366 const listed = yield* vpclattice.listTagsForResource({
367 resourceArn: group.arn,
368 });
369 const attrs = {
370 targetGroupId: group.id,
371 targetGroupArn: group.arn,
372 name: group.name!,
373 type: (group.type as TargetGroupType) ?? "IP",
374 status: group.status ?? "UNKNOWN",
375 tags: tagRecord(listed.tags),
376 };
377 return (yield* hasAlchemyTags(id, listed.tags)) ? attrs : Unowned(attrs);
378 }),
379 reconcile: Effect.fn(function* ({ id, news, output, session }) {
380 const name = yield* toName(id, news);
381 const internalTags = yield* createInternalTags(id);
382 const desiredTags = { ...internalTags, ...news.tags };
383
384 // Observe — prefer the stable id cache, fall back to name lookup.
385 let group = output?.targetGroupId
386 ? yield* observe(output.targetGroupId)
387 : yield* findByName(name);
388
389 // Ensure — create if missing.
390 if (!group?.arn || !group.id) {
391 const created = yield* vpclattice
392 .createTargetGroup({
393 name,
394 type: news.type,
395 config:
396 news.type === "LAMBDA" && news.lambdaEventStructureVersion === undefined
397 ? undefined
398 : {
399 port: news.port,
400 protocol: news.protocol,
401 protocolVersion: news.protocolVersion,
402 ipAddressType: news.ipAddressType,
403 vpcIdentifier: news.vpcIdentifier,
404 lambdaEventStructureVersion: news.lambdaEventStructureVersion,
405 healthCheck: news.healthCheck
406 ? toWireHealthCheck(news.healthCheck)
407 : undefined,
408 },
409 })
410 .pipe(Effect.catchTag("ConflictException", () => findByName(name)));
411 if (!created?.arn || !created.id) {
412 return yield* new VpcLatticeTargetGroupUnexpectedResponse({
413 message: `Failed to create target group ${name}`,
414 });
415 }
416 group = yield* observe(created.id);
417 if (!group?.arn || !group.id) {
418 group = { id: created.id, arn: created.arn };
419 }
420 }
421 const targetGroupId = group.id;
422 const targetGroupArn = group.arn;
423 if (!targetGroupId || !targetGroupArn) {
424 return yield* new VpcLatticeTargetGroupUnexpectedResponse({
425 message: `Target group ${name} is missing its id/arn`,
426 });
427 }
428
429 // Target groups reject updates while CREATE_IN_PROGRESS.
430 const stable = yield* waitUntilStable(observe(targetGroupId));
431
432 // Sync health check — the only mutable setting (IP/INSTANCE only).
433 if (news.healthCheck !== undefined) {
434 const desired = toWireHealthCheck(news.healthCheck);
435 const observedHealthCheck = stable?.config?.healthCheck ?? {};
436 const drifted = (
437 Object.entries(desired) as [keyof vpclattice.HealthCheckConfig, unknown][]
438 ).some(
439 ([key, value]) =>
440 value !== undefined &&
441 JSON.stringify(observedHealthCheck[key]) !== JSON.stringify(value),
442 );
443 if (drifted) {
444 yield* retryOnConflict(
445 vpclattice.updateTargetGroup({
446 targetGroupIdentifier: targetGroupId,
447 healthCheck: desired,
448 }),
449 );
450 }
451 }
452
453 // Sync targets — register missing, deregister extras.
454 yield* syncTargets(targetGroupId, news.targets ?? []);
455
456 yield* syncTags(targetGroupArn, desiredTags);
457
458 const final = yield* observe(targetGroupId);
459 yield* session.note(targetGroupArn);
460 return {
461 targetGroupId,
462 targetGroupArn,
463 name,
464 type: news.type,
465 status: final?.status ?? stable?.status ?? "ACTIVE",
466 tags: desiredTags,
467 };
468 }),
469 list: () =>
470 Effect.gen(function* () {
471 const summaries = yield* vpclattice.listTargetGroups.pages({}).pipe(
472 Stream.runCollect,
473 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.items ?? [])),
474 );
475 return yield* Effect.forEach(
476 summaries.filter(
477 (s): s is typeof s & { id: string; arn: string } => s.id != null && s.arn != null,
478 ),
479 (summary) =>
480 Effect.gen(function* () {
481 const listed = yield* vpclattice.listTagsForResource({
482 resourceArn: summary.arn,
483 });
484 return {
485 targetGroupId: summary.id,
486 targetGroupArn: summary.arn,
487 name: summary.name!,
488 type: (summary.type as TargetGroupType) ?? "IP",
489 status: summary.status ?? "UNKNOWN",
490 tags: tagRecord(listed.tags),
491 };
492 }),
493 { concurrency: 10 },
494 );
495 }),
496 delete: Effect.fn(function* ({ output }) {
497 // Deregister any remaining targets first so the group doesn't sit
498 // in a draining conflict while deleting.
499 yield* syncTargets(output.targetGroupId, []).pipe(
500 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
501 );
502 // Deregistered targets sit in DRAINING for a while and
503 // DeleteTargetGroup rejects with `ConflictException: TargetGroup
504 // has targets registered with it` until they are gone. Wait
505 // (bounded) for the drain to complete.
506 yield* Effect.repeat(
507 vpclattice.listTargets({ targetGroupIdentifier: output.targetGroupId }).pipe(
508 Effect.map((r) => r.items.length),
509 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed(0)),
510 ),
511 {
512 schedule: Schedule.max([Schedule.spaced("3 seconds"), Schedule.recurs(15)]),
513 until: (remaining): boolean => remaining === 0,
514 },
515 );
516 yield* retryOnConflict(
517 vpclattice.deleteTargetGroup({
518 targetGroupIdentifier: output.targetGroupId,
519 }),
520 ).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
521 // Deletion is asynchronous while targets drain; wait until the
522 // group is actually gone so dependent VPC deletes don't conflict.
523 yield* waitUntilAbsent(observe(output.targetGroupId));
524 }),
525 };
526 }),
527 );