@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, 04:45 UTC

main
ts 455 lines 16.6 KB
Raw
1 import * as ga from "@distilled.cloud/aws/global-accelerator";
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 } from "alchemy/Tags";
8 import * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import type { Providers } from "../Providers.ts";
11 import {
12 retryGaDeletion,
13 retryGaTransaction,
14 retryUntilAcceleratorDeletable,
15 retryUntilListenerDeletable,
16 withGaRegion,
17 } from "./common.ts";
18
19 export interface AcceleratorProps {
20 /**
21 * Name of the accelerator. Up to 64 characters; letters, digits, and
22 * hyphens only, and must not begin or end with a hyphen.
23 * @default ${app}-${id}-${stage}-${suffix}
24 */
25 name?: string;
26 /**
27 * The IP address type that the accelerator's static addresses use.
28 * `DUAL_STACK` assigns both IPv4 and IPv6 addresses.
29 * @default "IPV4"
30 */
31 ipAddressType?: "IPV4" | "DUAL_STACK";
32 /**
33 * Optionally specify one or two static IPv4 addresses from your own
34 * BYOIP address pools. Changing them replaces the accelerator.
35 * @default addresses assigned from Amazon's pool
36 */
37 ipAddresses?: string[];
38 /**
39 * Whether the accelerator accepts and routes traffic. A disabled
40 * accelerator keeps its static IP addresses but serves nothing.
41 * @default true
42 */
43 enabled?: boolean;
44 /**
45 * Publish flow logs describing the traffic the accelerator serves to an
46 * S3 bucket. The bucket must live in the same account and carry a bucket
47 * policy granting `delivery.logs.amazonaws.com` permission to
48 * `s3:PutObject` (and `s3:GetBucketAcl`). Omit to keep flow logs
49 * disabled.
50 * @default disabled
51 */
52 flowLogs?: FlowLogs;
53 /**
54 * Tags to apply to the accelerator. Merged with internal Alchemy tags.
55 */
56 tags?: Record<string, string>;
57 }
58
59 export interface FlowLogs {
60 /**
61 * Name of the S3 bucket flow logs are delivered to.
62 */
63 bucket: string;
64 /**
65 * Key prefix for the flow-log objects within the bucket.
66 * @default logs are delivered under `AWSLogs/` at the bucket root
67 */
68 prefix?: string;
69 }
70
71 export interface Accelerator extends Resource<
72 "AWS.GlobalAccelerator.Accelerator",
73 AcceleratorProps,
74 {
75 /** The ARN of the accelerator. */
76 acceleratorArn: string;
77 /** The name of the accelerator. */
78 name: string;
79 /** The DNS name that points to the accelerator's static IPv4 addresses. */
80 dnsName: string | undefined;
81 /** The DNS name for dual-stack (IPv4 + IPv6) accelerators. */
82 dualStackDnsName: string | undefined;
83 /** The static anycast IP addresses assigned to the accelerator. */
84 ipAddresses: string[];
85 /** The IP address type: `IPV4` or `DUAL_STACK`. */
86 ipAddressType: string;
87 /** Whether the accelerator accepts and routes traffic. */
88 enabled: boolean;
89 /** Deployment status: `DEPLOYED` or `IN_PROGRESS`. */
90 status: string;
91 /** Whether flow logs are published to S3. */
92 flowLogsEnabled: boolean;
93 /** The S3 bucket receiving flow logs, when enabled. */
94 flowLogsS3Bucket: string | undefined;
95 /** The S3 key prefix for flow logs, when enabled. */
96 flowLogsS3Prefix: string | undefined;
97 },
98 never,
99 Providers
100 > {}
101
102 /**
103 * An AWS Global Accelerator standard accelerator — two anycast static IP
104 * addresses that route client traffic over the AWS global network to the
105 * closest healthy regional endpoint.
106 *
107 * Accelerators are global resources (the control-plane API lives in
108 * us-west-2 regardless of your deployment region — alchemy pins it
109 * automatically). Attach `Listener`s to accept traffic and `EndpointGroup`s
110 * to route it to ALBs, NLBs, EC2 instances, or Elastic IPs per region.
111 * ### Creating Accelerators
112 * **Example:** Basic Accelerator
113 * ```typescript
114 * import * as GlobalAccelerator from "@alchemy.run/aws/GlobalAccelerator";
115 *
116 * const accelerator = yield* GlobalAccelerator.Accelerator("Edge");
117 * ```
118 *
119 * **Example:** Dual-Stack Accelerator
120 * ```typescript
121 * const accelerator = yield* GlobalAccelerator.Accelerator("Edge", {
122 * ipAddressType: "DUAL_STACK",
123 * });
124 * ```
125 *
126 * ### Flow Logs
127 * **Example:** Publish Flow Logs to S3
128 * ```typescript
129 * // the bucket policy must grant delivery.logs.amazonaws.com
130 * // s3:PutObject + s3:GetBucketAcl
131 * const accelerator = yield* GlobalAccelerator.Accelerator("Edge", {
132 * flowLogs: { bucket: logBucket.bucketName, prefix: "ga-flow-logs" },
133 * });
134 * ```
135 *
136 * ### Routing Traffic
137 * **Example:** Accelerator with Listener and Endpoint Group
138 * ```typescript
139 * const accelerator = yield* GlobalAccelerator.Accelerator("Edge");
140 * const listener = yield* GlobalAccelerator.Listener("Web", {
141 * acceleratorArn: accelerator.acceleratorArn,
142 * portRanges: [{ fromPort: 443, toPort: 443 }],
143 * protocol: "TCP",
144 * });
145 * yield* GlobalAccelerator.EndpointGroup("UsWest2", {
146 * listenerArn: listener.listenerArn,
147 * endpointGroupRegion: "us-west-2",
148 * endpoints: [{ endpointId: alb.loadBalancerArn }],
149 * });
150 * ```
151 *
152 * @resource
153 */
154 export const Accelerator = Resource<Accelerator>("AWS.GlobalAccelerator.Accelerator");
155
156 const createAcceleratorName = Effect.fn(function* (
157 id: string,
158 props: { name?: string | undefined },
159 ) {
160 return props.name ?? (yield* createPhysicalName({ id, maxLength: 64 }));
161 });
162
163 const toAttributes = (
164 a: ga.Accelerator,
165 acceleratorArn: string,
166 flowLogs?: ga.AcceleratorAttributes,
167 ) => ({
168 acceleratorArn,
169 name: a.Name ?? "",
170 dnsName: a.DnsName,
171 dualStackDnsName: a.DualStackDnsName,
172 ipAddresses: a.IpSets?.flatMap((set) => set.IpAddresses ?? []) ?? [],
173 ipAddressType: a.IpAddressType ?? "IPV4",
174 enabled: a.Enabled ?? true,
175 status: a.Status ?? "IN_PROGRESS",
176 flowLogsEnabled: flowLogs?.FlowLogsEnabled ?? false,
177 flowLogsS3Bucket: flowLogs?.FlowLogsS3Bucket,
178 flowLogsS3Prefix: flowLogs?.FlowLogsS3Prefix,
179 });
180
181 const describeAccelerator = Effect.fn(function* (acceleratorArn: string) {
182 return yield* withGaRegion(ga.describeAccelerator({ AcceleratorArn: acceleratorArn })).pipe(
183 Effect.map((r) => r.Accelerator),
184 Effect.catchTag("AcceleratorNotFoundException", () => Effect.undefined),
185 );
186 });
187
188 const describeFlowLogs = Effect.fn(function* (acceleratorArn: string) {
189 return yield* withGaRegion(
190 ga.describeAcceleratorAttributes({ AcceleratorArn: acceleratorArn }),
191 ).pipe(
192 Effect.map((r) => r.AcceleratorAttributes),
193 Effect.catchTag("AcceleratorNotFoundException", () => Effect.undefined),
194 );
195 });
196
197 const findAcceleratorByName = Effect.fn(function* (name: string) {
198 const accelerators = yield* withGaRegion(ga.listAccelerators.items({}).pipe(Stream.runCollect));
199 return Array.from(accelerators).find((a) => a.Name === name);
200 });
201
202 const fetchTags = Effect.fn(function* (resourceArn: string) {
203 return yield* withGaRegion(ga.listTagsForResource({ ResourceArn: resourceArn })).pipe(
204 Effect.map((r) => Object.fromEntries((r.Tags ?? []).map((t) => [t.Key, t.Value]))),
205 Effect.orElseSucceed(() => ({}) as Record<string, string>),
206 );
207 });
208
209 /**
210 * Global Accelerator's listener and endpoint-group resources are untagged
211 * children and cannot be enumerated independently by account-wide nuke.
212 * When nuke explicitly force-deletes an accelerator, discover and remove the
213 * complete child tree first. Normal stack destroy still relies on dependency
214 * ordering and deletes each child through its own provider.
215 */
216 const deleteAcceleratorChildren = Effect.fn(function* (acceleratorArn: string) {
217 const listeners = yield* withGaRegion(
218 ga.listListeners.items({ AcceleratorArn: acceleratorArn }).pipe(Stream.runCollect),
219 ).pipe(
220 Effect.map((chunk) => Array.from(chunk)),
221 Effect.catchTag("AcceleratorNotFoundException", () => Effect.succeed([] as ga.Listener[])),
222 );
223
224 // GA serializes mutations per accelerator. Keep this traversal sequential
225 // so deleting several children does not manufacture transaction conflicts.
226 yield* Effect.forEach(
227 listeners,
228 Effect.fn(function* (listener) {
229 if (!listener.ListenerArn) return;
230 const listenerArn = listener.ListenerArn;
231 const endpointGroups = yield* withGaRegion(
232 ga.listEndpointGroups.items({ ListenerArn: listenerArn }).pipe(Stream.runCollect),
233 ).pipe(
234 Effect.map((chunk) => Array.from(chunk)),
235 Effect.catchTag("ListenerNotFoundException", () =>
236 Effect.succeed([] as ga.EndpointGroup[]),
237 ),
238 );
239
240 yield* Effect.forEach(
241 endpointGroups,
242 (group) =>
243 group.EndpointGroupArn
244 ? ga
245 .deleteEndpointGroup({
246 EndpointGroupArn: group.EndpointGroupArn,
247 })
248 .pipe(
249 withGaRegion,
250 retryGaDeletion,
251 Effect.catchTag("EndpointGroupNotFoundException", () => Effect.void),
252 )
253 : Effect.void,
254 { discard: true },
255 );
256
257 // Endpoint-group detachment is asynchronous. The same bounded retry
258 // used by the child provider waits until the listener is deletable.
259 yield* ga.deleteListener({ ListenerArn: listenerArn }).pipe(
260 withGaRegion,
261 retryUntilListenerDeletable,
262 Effect.catchTag("ListenerNotFoundException", () => Effect.void),
263 );
264 }),
265 { discard: true },
266 );
267 });
268
269 export const AcceleratorProvider = () =>
270 Provider.succeed(Accelerator, {
271 stables: ["acceleratorArn", "dnsName", "dualStackDnsName", "ipAddresses"],
272 // Top-level, account-scoped collection: enumerate every accelerator.
273 list: () =>
274 withGaRegion(
275 ga.listAccelerators.items({}).pipe(
276 Stream.runCollect,
277 Effect.map((chunk) =>
278 Array.from(chunk)
279 .filter((a) => a.AcceleratorArn !== undefined)
280 .map((a) => toAttributes(a, a.AcceleratorArn!)),
281 ),
282 ),
283 ),
284 read: Effect.fn(function* ({ id, olds, output }) {
285 let live = output?.acceleratorArn
286 ? yield* describeAccelerator(output.acceleratorArn)
287 : undefined;
288 if (!live?.AcceleratorArn) {
289 // No cached ARN (or it vanished) — fall back to the deterministic
290 // physical name to recover from lost state / support adoption.
291 const name = yield* createAcceleratorName(id, olds ?? {});
292 live = yield* findAcceleratorByName(name);
293 }
294 if (!live?.AcceleratorArn) return undefined;
295 const flowLogs = yield* describeFlowLogs(live.AcceleratorArn);
296 const attrs = toAttributes(live, live.AcceleratorArn, flowLogs);
297 const tags = yield* fetchTags(live.AcceleratorArn);
298 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
299 }),
300 diff: Effect.fn(function* ({ id, news, olds }) {
301 if (!isResolved(news)) return undefined;
302 // Static BYOIP addresses are the accelerator's identity — changing
303 // them requires a replacement. Name, ipAddressType, and enabled are
304 // all mutable via updateAccelerator.
305 if (JSON.stringify(news.ipAddresses ?? []) !== JSON.stringify(olds.ipAddresses ?? [])) {
306 return { action: "replace" } as const;
307 }
308 const oldName = yield* createAcceleratorName(id, olds);
309 const newName = yield* createAcceleratorName(id, news);
310 if (oldName !== newName) {
311 // Renames are applied in place by reconcile.
312 return undefined;
313 }
314 }),
315 reconcile: Effect.fn(function* ({ id, news, output, instanceId, session }) {
316 const name = yield* createAcceleratorName(id, news);
317 const internalTags = yield* createInternalTags(id);
318 const desiredTags: Record<string, string> = {
319 ...news.tags,
320 ...internalTags,
321 };
322 const desiredEnabled = news.enabled ?? true;
323
324 // Observe — cached ARN first, deterministic name as fallback (covers
325 // create-then-persist-failure and adoption).
326 let live = output?.acceleratorArn
327 ? yield* describeAccelerator(output.acceleratorArn)
328 : undefined;
329 if (!live?.AcceleratorArn) {
330 live = yield* findAcceleratorByName(output?.name ?? name);
331 }
332
333 // Ensure — create if missing. The idempotency token (derived from the
334 // instance id) makes a crashed-and-retried create safe.
335 if (!live?.AcceleratorArn) {
336 live = yield* ga
337 .createAccelerator({
338 Name: name,
339 IpAddressType: news.ipAddressType,
340 IpAddresses: news.ipAddresses,
341 Enabled: desiredEnabled,
342 IdempotencyToken: instanceId,
343 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
344 Key,
345 Value,
346 })),
347 })
348 .pipe(
349 withGaRegion,
350 retryGaTransaction,
351 Effect.map((r) => r.Accelerator),
352 );
353 }
354 if (!live?.AcceleratorArn) {
355 return yield* Effect.die(new Error("CreateAccelerator returned no accelerator"));
356 }
357 const acceleratorArn = live.AcceleratorArn;
358
359 // Sync settings — diff observed vs desired, apply only the delta.
360 const update: ga.UpdateAcceleratorRequest = {
361 AcceleratorArn: acceleratorArn,
362 };
363 let dirty = false;
364 if ((live.Name ?? "") !== name) {
365 update.Name = name;
366 dirty = true;
367 }
368 if (news.ipAddressType !== undefined && live.IpAddressType !== news.ipAddressType) {
369 update.IpAddressType = news.ipAddressType;
370 dirty = true;
371 }
372 if ((live.Enabled ?? true) !== desiredEnabled) {
373 update.Enabled = desiredEnabled;
374 dirty = true;
375 }
376 if (dirty) {
377 const updated = yield* ga.updateAccelerator(update).pipe(
378 withGaRegion,
379 retryGaTransaction,
380 Effect.map((r) => r.Accelerator),
381 );
382 if (updated) live = updated;
383 }
384
385 // Sync flow logs — diff observed attributes against the desired
386 // flowLogs prop; only call updateAcceleratorAttributes on drift.
387 let flowLogs = yield* describeFlowLogs(acceleratorArn);
388 const desiredFlowLogsEnabled = news.flowLogs !== undefined;
389 const flowLogsDrift =
390 (flowLogs?.FlowLogsEnabled ?? false) !== desiredFlowLogsEnabled ||
391 (desiredFlowLogsEnabled &&
392 (flowLogs?.FlowLogsS3Bucket !== news.flowLogs!.bucket ||
393 (news.flowLogs!.prefix !== undefined &&
394 flowLogs?.FlowLogsS3Prefix !== news.flowLogs!.prefix)));
395 if (flowLogsDrift) {
396 flowLogs = yield* ga
397 .updateAcceleratorAttributes({
398 AcceleratorArn: acceleratorArn,
399 FlowLogsEnabled: desiredFlowLogsEnabled,
400 ...(desiredFlowLogsEnabled
401 ? {
402 FlowLogsS3Bucket: news.flowLogs!.bucket,
403 FlowLogsS3Prefix: news.flowLogs!.prefix,
404 }
405 : {}),
406 })
407 .pipe(
408 withGaRegion,
409 retryGaTransaction,
410 Effect.map((r) => r.AcceleratorAttributes),
411 );
412 }
413
414 // Sync tags against OBSERVED cloud tags so adoption converges.
415 const observedTags = yield* fetchTags(acceleratorArn);
416 const { upsert, removed } = diffTags(observedTags, desiredTags);
417 if (upsert.length > 0) {
418 yield* withGaRegion(ga.tagResource({ ResourceArn: acceleratorArn, Tags: upsert }));
419 }
420 if (removed.length > 0) {
421 yield* withGaRegion(ga.untagResource({ ResourceArn: acceleratorArn, TagKeys: removed }));
422 }
423
424 yield* session.note(acceleratorArn);
425 return toAttributes(live, acceleratorArn, flowLogs);
426 }),
427 delete: Effect.fn(function* ({ output, session, force }) {
428 const acceleratorArn = output.acceleratorArn;
429 if (force) {
430 yield* session.note("deleting accelerator listeners and endpoint groups");
431 yield* deleteAcceleratorChildren(acceleratorArn);
432 }
433 // An accelerator must be disabled before it can be deleted.
434 const exists = yield* ga
435 .updateAccelerator({
436 AcceleratorArn: acceleratorArn,
437 Enabled: false,
438 })
439 .pipe(
440 withGaRegion,
441 retryGaTransaction,
442 Effect.map(() => true),
443 Effect.catchTag("AcceleratorNotFoundException", () => Effect.succeed(false)),
444 );
445 if (!exists) return;
446 yield* session.note("waiting for accelerator to disable");
447 // The disable propagates asynchronously; deleteAccelerator rejects with
448 // AcceleratorNotDisabledException until it lands, so retry bounded.
449 yield* ga.deleteAccelerator({ AcceleratorArn: acceleratorArn }).pipe(
450 withGaRegion,
451 retryUntilAcceleratorDeletable,
452 Effect.catchTag("AcceleratorNotFoundException", () => Effect.void),
453 );
454 }),
455 });