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

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