@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 119 lines 4.14 KB
Raw
1 import type * as eventbridge from "@distilled.cloud/aws/eventbridge";
2 import * as Output from "alchemy/Output";
3 import { makeBatchedSink } from "alchemy/Util/BatchedSink";
4 import * as Effect from "effect/Effect";
5 import * as Layer from "effect/Layer";
6 import * as AWSBindings from "../AWSBindings.ts";
7 import { AWSEnvironment } from "../Environment.ts";
8 import { BusSink, type BusSinkEntry } from "./BusSink.ts";
9 import type { EventBus } from "./EventBus.ts";
10 import { PutEvents } from "./PutEvents.ts";
11
12 const encoder = new TextEncoder();
13
14 /**
15 * Approximate wire size of one entry, per AWS's documented calculation:
16 * 14 bytes if `Time` is specified, plus the UTF-8 byte lengths of `Source`,
17 * `DetailType`, `Detail`, and each entry in `Resources`.
18 */
19 const entrySize = (entry: BusSinkEntry): number => {
20 let size = entry.Time !== undefined ? 14 : 0;
21 if (entry.Source !== undefined) {
22 size += encoder.encode(entry.Source).length;
23 }
24 if (entry.DetailType !== undefined) {
25 size += encoder.encode(entry.DetailType).length;
26 }
27 if (entry.Detail !== undefined) {
28 size += encoder.encode(entry.Detail).length;
29 }
30 for (const resource of entry.Resources ?? []) {
31 size += encoder.encode(resource).length;
32 }
33 return size;
34 };
35
36 /**
37 * Per-entry error codes EventBridge documents as retryable. Every other
38 * `ErrorCode` (`MalformedDetail`, `AccessDeniedException`, ...) is permanent.
39 */
40 const TRANSIENT_ERROR_CODES: ReadonlySet<string> = new Set([
41 "ThrottlingException",
42 "InternalFailure",
43 ]);
44
45 /**
46 * Select the original entries whose positional `PutEventsResultEntry` carries
47 * an `ErrorCode` of the given transience, preserving input order (the result
48 * `Entries` array is aligned index-for-index with the request entries).
49 */
50 const selectFailed = (
51 out: eventbridge.PutEventsResponse,
52 batch: readonly BusSinkEntry[],
53 transient: boolean,
54 ): readonly BusSinkEntry[] => {
55 const results = out.Entries;
56 if (results === undefined || (out.FailedEntryCount ?? 0) === 0) {
57 return [];
58 }
59 return batch.filter((_, index) => {
60 const code = results[index]?.ErrorCode;
61 return code !== undefined && TRANSIENT_ERROR_CODES.has(code) === transient;
62 });
63 };
64
65 /**
66 * HTTP implementation of {@link BusSink}. At deploy time it grants
67 * `events:PutEvents` on the bound bus (or the default bus); at runtime it
68 * batches stream elements into `PutEvents` calls (10 entries / 256 KiB) with
69 * bounded retry of transient per-entry failures. Provide this layer on the
70 * Function using the sink.
71 */
72 export const BusSinkHttp = Layer.effect(
73 BusSink,
74 Effect.gen(function* () {
75 const bind = yield* AWSBindings.Bind;
76 const putEvents = yield* PutEvents;
77
78 return Effect.fn(function* (bus?: EventBus) {
79 if (!globalThis.__ALCHEMY_RUNTIME__) {
80 const { accountId, region } = yield* AWSEnvironment.current as unknown as Effect.Effect<{
81 accountId: string;
82 region: string;
83 }>;
84 // Pass the ARN as an unresolved Output — binding data is resolved
85 // by the engine before the host reconciles (see PutEventsHttp).
86 const resource = bus
87 ? Output.interpolate`${bus.eventBusArn}`
88 : (`arn:aws:events:${region}:${accountId}:event-bus/default` as const);
89
90 yield* bind`AWS.EventBridge.BusSink(${bus ?? "default"})`({
91 policyStatements: [
92 {
93 Effect: "Allow",
94 Action: ["events:PutEvents"],
95 Resource: [resource],
96 },
97 ],
98 });
99 }
100 const put = yield* putEvents(bus);
101 return makeBatchedSink<
102 BusSinkEntry,
103 eventbridge.PutEventsResponse,
104 eventbridge.PutEventsError
105 >({
106 maxRecords: 10,
107 maxBytes: 262_144,
108 sizeOf: entrySize,
109 send: (batch) => put({ Entries: [...batch] }),
110 // ThrottlingException / InternalFailure are transient — re-submit
111 // them on the bounded schedule.
112 unprocessed: (out, batch) => selectFailed(out, batch, true),
113 // Any other per-entry ErrorCode (e.g. MalformedDetail) is permanent —
114 // drop and surface.
115 rejected: (out, batch) => selectFailed(out, batch, false),
116 });
117 });
118 }),
119 );