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

main
ts 70 lines 2.42 KB
Raw
1 import type * as sns from "@distilled.cloud/aws/sns";
2 import { makeBatchedSink } from "alchemy/Util/BatchedSink";
3 import * as Effect from "effect/Effect";
4 import * as Layer from "effect/Layer";
5 import * as AWSBindings from "../AWSBindings.ts";
6 import { PublishBatch } from "./PublishBatch.ts";
7 import type { Topic } from "./Topic.ts";
8 import { TopicSink, type TopicSinkEntry } from "./TopicSink.ts";
9
10 const encoder = new TextEncoder();
11
12 /**
13 * Select the original entries referenced by `Failed` results with the given
14 * `SenderFault` classification, preserving input order. The sink assigns
15 * `Id = String(index)` per call, so failed ids map back positionally.
16 */
17 const selectFailed = (
18 failed: readonly sns.BatchResultErrorEntry[] | undefined,
19 batch: readonly TopicSinkEntry[],
20 senderFault: boolean,
21 ): readonly TopicSinkEntry[] => {
22 if (failed === undefined || failed.length === 0) {
23 return [];
24 }
25 const indices = new Set(
26 failed.filter((entry) => entry.SenderFault === senderFault).map((entry) => Number(entry.Id)),
27 );
28 return batch.filter((_, index) => indices.has(index));
29 };
30
31 export const TopicSinkHttp = Layer.effect(
32 TopicSink,
33 Effect.gen(function* () {
34 const bind = yield* AWSBindings.Bind;
35 const publishBatch = yield* PublishBatch;
36
37 return Effect.fn(function* (topic: Topic) {
38 if (!globalThis.__ALCHEMY_RUNTIME__) {
39 yield* bind`AWS.SNS.TopicSink(${topic})`({
40 policyStatements: [
41 {
42 Effect: "Allow",
43 Action: ["sns:Publish"],
44 Resource: [topic.topicArn],
45 },
46 ],
47 });
48 }
49 const publish = yield* publishBatch(topic);
50
51 return makeBatchedSink<TopicSinkEntry, sns.PublishBatchResponse, sns.PublishBatchError>({
52 maxRecords: 10,
53 maxBytes: 262_144,
54 sizeOf: (entry) => encoder.encode(entry.Message).length,
55 send: (batch) =>
56 publish({
57 PublishBatchRequestEntries: batch.map((entry, index) => ({
58 ...entry,
59 Id: `${index}`,
60 })),
61 }),
62 // SenderFault=false failures (throttling, internal errors) are
63 // transient — re-submit them on the bounded schedule.
64 unprocessed: (out, batch) => selectFailed(out.Failed, batch, false),
65 // SenderFault=true failures are permanent — drop and surface.
66 rejected: (out, batch) => selectFailed(out.Failed, batch, true),
67 });
68 });
69 }),
70 );