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

main
ts 87 lines 2.82 KB
Raw
1 import * as queues from "@distilled.cloud/cloudflare/queues";
2 import * as Effect from "effect/Effect";
3 import * as Layer from "effect/Layer";
4 import { authorizeWith } from "../HttpClientUtils.ts";
5 import {
6 makeHttpQueueBinding,
7 makeQueueHttpScope,
8 toQueueSendError,
9 type QueueAuth,
10 } from "./QueueHttp.ts";
11 import { SendError, type SendMessage } from "./QueueTypes.ts";
12 import { WriteQueue, type WriteQueueClient } from "./WriteQueue.ts";
13
14 /**
15 * HTTP-backed implementation of the {@link WriteQueue} service.
16 *
17 * It creates a scoped {@link AccountApiToken} with the `Queues Write`
18 * permission and pushes messages via the Cloudflare Queues bulk-push
19 * HTTP API (`POST /messages/batch`). The bulk endpoint takes the raw
20 * JSON value as the message `body` (the single-message endpoint
21 * expects a pre-encoded string), so it round-trips arbitrary
22 * JSON-serializable payloads the same way the native producer binding
23 * does — `send` is just a batch of one.
24 */
25 export const WriteQueueHttp = Layer.effect(
26 WriteQueue,
27 Effect.suspend(() =>
28 makeHttpQueueBinding({
29 permissionGroups: ["Queues Write"],
30 makeClient: (token, queueId) =>
31 makeWriteQueueHttpClient(
32 { authorize: authorizeWith(token), accountId: token.accountId },
33 queueId,
34 ),
35 }),
36 ),
37 );
38
39 /** Convert a message into the Cloudflare bulk-push `messages[]` shape. */
40 const toMessage = (message: SendMessage) =>
41 message.contentType === "text"
42 ? {
43 body: typeof message.body === "string" ? message.body : String(message.body),
44 contentType: "text" as const,
45 }
46 : { body: message.body, contentType: "json" as const };
47
48 /**
49 * Build the producer client over the Queues bulk-push HTTP API.
50 *
51 * Shared by {@link WriteQueueHttp} (scoped token auth) and
52 * `WriteQueueLocal` (current-credentials auth) — they differ only in the
53 * {@link QueueAuth} they inject.
54 */
55 export const makeWriteQueueHttpClient = (
56 auth: QueueAuth,
57 queueId: Effect.Effect<string>,
58 ): WriteQueueClient => {
59 const scope = makeQueueHttpScope(auth, queueId);
60
61 const push = (messages: ReadonlyArray<SendMessage>) =>
62 scope.pipe(
63 Effect.flatMap(({ accountId, queueId }) =>
64 auth.authorize(
65 queues.bulkPushMessages({
66 accountId,
67 queueId,
68 messages: messages.map(toMessage),
69 }),
70 ),
71 ),
72 Effect.mapError(toQueueSendError),
73 Effect.asVoid,
74 );
75
76 return {
77 raw: Effect.die(
78 new SendError({
79 message: "Queue HTTP client does not expose a native Queue binding; use send/sendBatch.",
80 cause: new Error("unsupported"),
81 }),
82 ),
83 send: (body: unknown, options?: { contentType?: "json" | "text" }) =>
84 push([{ body, contentType: options?.contentType }]),
85 sendBatch: (messages: ReadonlyArray<SendMessage>) => push(messages),
86 };
87 };