@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 434 lines 16.5 KB
Raw
1 import * as eventbridge from "@distilled.cloud/aws/eventbridge";
2 import { Region as AwsRegion } from "@distilled.cloud/aws/Region";
3 import { Unowned } from "alchemy/AdoptPolicy";
4 import { isResolved } from "alchemy/Diff";
5 import { createPhysicalName } from "alchemy/PhysicalName";
6 import * as Provider from "alchemy/Provider";
7 import { Resource } from "alchemy/Resource";
8 import { createInternalTags, createTagsList, diffTags, hasAlchemyTags } from "alchemy/Tags";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11 import { AWSEnvironment, type AccountID } from "../Environment.ts";
12 import type { Providers } from "../Providers.ts";
13 import type { RegionID } from "../Region.ts";
14 import type { QueueArn } from "../SQS/Queue.ts";
15
16 export type { IncludeDetail, Level, LogConfig } from "@distilled.cloud/aws/eventbridge";
17
18 export type EventBusName = string;
19 export type EventBusArn = `arn:aws:events:${RegionID}:${AccountID}:event-bus/${EventBusName}`;
20
21 export interface EventBusDeadLetterConfig {
22 /** ARN of the SQS queue used as the dead-letter queue. */
23 Arn?: QueueArn;
24 }
25
26 export interface EventBusProps {
27 /**
28 * Name of the event bus. Must match [/\.\-_A-Za-z0-9]+, 1-256 characters.
29 * If omitted, a unique name will be generated.
30 * Cannot be "default" — use the default event bus by omitting eventBusName on rules.
31 */
32 name?: EventBusName;
33
34 /**
35 * The partner event source to associate with this event bus.
36 * Only used when creating a partner event bus.
37 */
38 eventSourceName?: string;
39
40 /**
41 * Description of the event bus.
42 */
43 description?: string;
44
45 /**
46 * The identifier of the KMS customer managed key for EventBridge to use
47 * to encrypt events on this event bus.
48 */
49 kmsKeyIdentifier?: string;
50
51 /**
52 * Dead-letter queue configuration for undeliverable events.
53 */
54 deadLetterConfig?: EventBusDeadLetterConfig;
55
56 /**
57 * Logging configuration for the event bus.
58 */
59 logConfig?: eventbridge.LogConfig;
60
61 /**
62 * Whether to delete any rules remaining on the bus (removing their
63 * targets first) when the bus is destroyed. Rules managed by the same
64 * stack are always deleted before the bus by the engine, and AWS-managed
65 * rules (e.g. the hidden archival rule an Archive leaves behind while
66 * AWS's async cleanup lags) are always force-swept; `forceDestroy`
67 * additionally sweeps rules created out-of-band (or leaked by an
68 * interrupted deploy), which would otherwise block bus deletion with
69 * `EventBusHasRules` forever.
70 * @default false
71 */
72 forceDestroy?: boolean;
73
74 /**
75 * Tags to assign to the event bus.
76 */
77 tags?: Record<string, string>;
78
79 /**
80 * AWS region to create the event bus in. Defaults to the stack's region.
81 * Set it to place the secondary bus of a global {@link Endpoint} in its
82 * failover region. Changing the region replaces the event bus.
83 */
84 region?: string;
85 }
86
87 /** The region segment of an event bus ARN. */
88 const regionOfEventBusArn = (arn: string) => arn.split(":")[3];
89
90 /** Run EventBridge calls in `region`, or the ambient region when omitted. */
91 const inRegion =
92 (region: string | undefined) =>
93 <A, E, R>(effect: Effect.Effect<A, E, R>) =>
94 region === undefined
95 ? effect
96 : effect.pipe(Effect.provideService(AwsRegion, Effect.succeed(region as RegionID)));
97
98 /**
99 * An Amazon EventBridge event bus for receiving and routing events.
100 * ### Creating Event Buses
101 * **Example:** Custom Event Bus
102 * ```typescript
103 * const bus = yield* EventBus("MyAppEvents", {
104 * description: "Custom event bus for my application",
105 * });
106 * ```
107 *
108 * **Example:** Event Bus with Dead Letter Queue
109 * ```typescript
110 * const bus = yield* EventBus("ReliableBus", {
111 * deadLetterConfig: {
112 * Arn: yield* dlq.queueArn,
113 * },
114 * });
115 * ```
116 *
117 * **Example:** Event Bus in Another Region
118 * ```typescript
119 * const secondary = yield* EventBus("SecondaryBus", {
120 * name: "orders",
121 * region: "us-east-2",
122 * });
123 * ```
124 *
125 * **Example:** Event Bus with KMS Encryption
126 * ```typescript
127 * const bus = yield* EventBus("EncryptedBus", {
128 * kmsKeyIdentifier: yield* key.keyArn(),
129 * });
130 * ```
131 *
132 * @resource
133 */
134 export interface EventBus extends Resource<
135 "AWS.EventBridge.EventBus",
136 EventBusProps,
137 {
138 /** The name of the event bus. */
139 eventBusName: EventBusName;
140 /** The ARN of the event bus. */
141 eventBusArn: EventBusArn;
142 /** Description of the event bus, if set. */
143 description?: string;
144 },
145 never,
146 Providers
147 > {}
148 export const EventBus = Resource<EventBus>("AWS.EventBridge.EventBus");
149
150 export const EventBusProvider = () =>
151 Provider.effect(
152 EventBus,
153 Effect.gen(function* () {
154 const createEventBusName = (id: string, props: { name?: string } = {}) =>
155 Effect.gen(function* () {
156 if (props.name) {
157 return props.name;
158 }
159 return yield* createPhysicalName({
160 id,
161 maxLength: 256,
162 });
163 });
164
165 return {
166 stables: ["eventBusName", "eventBusArn"],
167 diff: Effect.fn(function* ({ id, news, olds }) {
168 if (!isResolved(news)) return;
169 const oldName = yield* createEventBusName(id, olds);
170 const newName = yield* createEventBusName(id, news);
171 if (oldName !== newName) {
172 return { action: "replace" } as const;
173 }
174 if ((olds.eventSourceName ?? "") !== (news.eventSourceName ?? "")) {
175 return { action: "replace" } as const;
176 }
177 const { region } = yield* AWSEnvironment.current;
178 if ((olds.region ?? region) !== (news.region ?? region)) {
179 return { action: "replace" } as const;
180 }
181 }),
182 read: Effect.fn(function* ({ id, olds, output }) {
183 const eventBusName = output?.eventBusName ?? (yield* createEventBusName(id, olds ?? {}));
184 const region = output ? regionOfEventBusArn(output.eventBusArn) : olds?.region;
185 return yield* inRegion(region)(
186 Effect.gen(function* () {
187 const described = yield* eventbridge
188 .describeEventBus({
189 Name: eventBusName,
190 })
191 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
192
193 if (!described?.Arn || !described.Name) {
194 return undefined;
195 }
196
197 const { Tags } = yield* eventbridge.listTagsForResource({
198 ResourceARN: described.Arn,
199 });
200 const attrs = {
201 eventBusName: described.Name,
202 eventBusArn: described.Arn as EventBusArn,
203 description: described.Description,
204 };
205 return (yield* hasAlchemyTags(id, Tags ?? [])) ? attrs : Unowned(attrs);
206 }),
207 );
208 }),
209 list: () =>
210 Effect.gen(function* () {
211 // Enumerate every event bus in the ambient account/region via
212 // manual NextToken pagination (listEventBuses is not a paginated
213 // distilled op). The AWS-managed `default` bus is excluded — the
214 // EventBus resource cannot manage it (name "default" is reserved).
215 const attrs: {
216 eventBusName: EventBusName;
217 eventBusArn: EventBusArn;
218 description?: string;
219 }[] = [];
220 let nextToken: string | undefined;
221 do {
222 const page = yield* eventbridge.listEventBuses({
223 NextToken: nextToken,
224 });
225 for (const bus of page.EventBuses ?? []) {
226 if (!bus.Name || !bus.Arn || bus.Name === "default") {
227 continue;
228 }
229 attrs.push({
230 eventBusName: bus.Name,
231 eventBusArn: bus.Arn as EventBusArn,
232 description: bus.Description,
233 });
234 }
235 nextToken = page.NextToken;
236 } while (nextToken);
237 return attrs;
238 }),
239 reconcile: Effect.fn(function* ({ id, news = {}, output, session }) {
240 return yield* inRegion(news.region)(
241 Effect.gen(function* () {
242 const env = yield* AWSEnvironment.current;
243 const { accountId } = env;
244 const region = news.region ?? env.region;
245 const eventBusName = output?.eventBusName ?? (yield* createEventBusName(id, news));
246 const eventBusArn = (output?.eventBusArn ??
247 `arn:aws:events:${region}:${accountId}:event-bus/${eventBusName}`) as EventBusArn;
248 const internalTags = yield* createInternalTags(id);
249 const desiredTags = {
250 ...internalTags,
251 ...(news.tags as Record<string, string> | undefined),
252 };
253
254 // Observe — fetch live cloud state. We don't trust `output`
255 // blindly: a bus deleted out of band shows up as missing and we
256 // recreate. Foreign-tagged buses have already been screened by
257 // `read` upstream.
258 let described = yield* eventbridge
259 .describeEventBus({
260 Name: eventBusName,
261 })
262 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
263
264 // Ensure — create the bus if missing. Tolerate
265 // `ResourceAlreadyExistsException` as a race with a peer
266 // reconciler: re-read and continue with the sync path.
267 if (!described?.Arn) {
268 yield* eventbridge
269 .createEventBus({
270 Name: eventBusName,
271 EventSourceName: news.eventSourceName,
272 Description: news.description,
273 KmsKeyIdentifier: news.kmsKeyIdentifier as string | undefined,
274 DeadLetterConfig: news.deadLetterConfig
275 ? { Arn: news.deadLetterConfig.Arn as string | undefined }
276 : undefined,
277 LogConfig: news.logConfig,
278 Tags: createTagsList(desiredTags),
279 })
280 .pipe(Effect.catchTag("ResourceAlreadyExistsException", () => Effect.void));
281
282 described = yield* eventbridge
283 .describeEventBus({
284 Name: eventBusName,
285 })
286 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
287 }
288
289 // Sync mutable bus configuration — `updateEventBus` overwrites
290 // `description`, KMS key, DLQ, and log config in one shot, so we
291 // call it unconditionally (idempotent for matching values).
292 yield* eventbridge.updateEventBus({
293 Name: eventBusName,
294 Description: news.description,
295 KmsKeyIdentifier: news.kmsKeyIdentifier as string | undefined,
296 DeadLetterConfig: news.deadLetterConfig
297 ? { Arn: news.deadLetterConfig.Arn as string | undefined }
298 : undefined,
299 LogConfig: news.logConfig,
300 });
301
302 // Sync tags — diff observed cloud tags against desired. Adoption
303 // may bring us a bus with its own tag set; diffing against the
304 // freshly-fetched tags lets the reconciler converge regardless.
305 const observedTagsList = yield* eventbridge
306 .listTagsForResource({
307 ResourceARN: eventBusArn,
308 })
309 .pipe(Effect.map((r) => r.Tags ?? []));
310 const observedTags: Record<string, string> = {};
311 for (const tag of observedTagsList) {
312 if (tag.Key && tag.Value !== undefined) {
313 observedTags[tag.Key] = tag.Value;
314 }
315 }
316 const { removed, upsert } = diffTags(observedTags, desiredTags);
317
318 if (removed.length > 0) {
319 yield* eventbridge.untagResource({
320 ResourceARN: eventBusArn,
321 TagKeys: removed,
322 });
323 }
324
325 if (upsert.length > 0) {
326 yield* eventbridge.tagResource({
327 ResourceARN: eventBusArn,
328 Tags: upsert,
329 });
330 }
331
332 yield* session.note(eventBusArn);
333 return {
334 eventBusName,
335 eventBusArn,
336 description: news.description,
337 };
338 }),
339 );
340 }),
341 delete: Effect.fn(function* ({ olds = {}, output }) {
342 return yield* inRegion(regionOfEventBusArn(output.eventBusArn))(
343 Effect.gen(function* () {
344 const eventBusName = output.eventBusName;
345
346 // Rules the engine knows about are deleted first (they depend on
347 // the bus), but AWS-managed rules can linger: deleting an archive
348 // removes its hidden archival rule *asynchronously*, sometimes
349 // minutes later, during which deleteEventBus keeps failing with
350 // EventBusHasRules. Sweep remaining rules with Force (required for
351 // managed rules) instead of waiting out AWS's async cleanup:
352 // AWS-managed rules (`ManagedBy` set) are always swept; rules
353 // created out-of-band by the user are only swept when
354 // `forceDestroy` is enabled.
355 yield* Effect.gen(function* () {
356 let nextToken: string | undefined;
357 do {
358 const page = yield* eventbridge.listRules({
359 EventBusName: eventBusName,
360 NextToken: nextToken,
361 });
362 for (const rule of page.Rules ?? []) {
363 if (!rule.Name) continue;
364 if (!rule.ManagedBy && !olds.forceDestroy) continue;
365 const targets = yield* eventbridge
366 .listTargetsByRule({
367 Rule: rule.Name,
368 EventBusName: eventBusName,
369 })
370 .pipe(
371 Effect.catchTag("ResourceNotFoundException", () =>
372 Effect.succeed({ Targets: [] }),
373 ),
374 );
375 const targetIds = (targets.Targets ?? []).map((t) => t.Id);
376 if (targetIds.length > 0) {
377 yield* eventbridge
378 .removeTargets({
379 Rule: rule.Name,
380 EventBusName: eventBusName,
381 Ids: targetIds,
382 Force: true,
383 })
384 .pipe(
385 Effect.catchTag(
386 ["ResourceNotFoundException", "ManagedRuleException"],
387 () => Effect.void,
388 ),
389 );
390 }
391 yield* eventbridge
392 .deleteRule({
393 Name: rule.Name,
394 EventBusName: eventBusName,
395 Force: true,
396 })
397 .pipe(
398 Effect.catchTag(
399 ["ResourceNotFoundException", "ManagedRuleException"],
400 () => Effect.void,
401 ),
402 );
403 }
404 nextToken = page.NextToken;
405 } while (nextToken);
406 }).pipe(
407 // Bus already gone (or vanishes mid-sweep) — nothing to sweep.
408 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
409 );
410
411 // The sweep and EventBridge's own bookkeeping are eventually
412 // consistent — a just-deleted rule can still count against the bus
413 // for a few seconds. Retry the typed dependency violation on a
414 // bounded schedule.
415 yield* eventbridge
416 .deleteEventBus({
417 Name: eventBusName,
418 })
419 .pipe(
420 Effect.retry({
421 while: (e): boolean => e._tag === "EventBusHasRules",
422 schedule: Schedule.spaced("3 seconds"),
423 times: 10,
424 }),
425 // Bus already gone (deleted out-of-band, or a previous
426 // destroy partially succeeded) — delete is idempotent.
427 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
428 );
429 }),
430 );
431 }),
432 };
433 }),
434 );