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

main
ts 128 lines 4.55 KB
Raw
1 import * as pubsub from "@distilled.cloud/gcp/pubsub_v1";
2 import * as Effect from "effect/Effect";
3 import * as GCPBindings from "../GCPBindings.ts";
4 import { grantFor, type BindingIam } from "../HttpBinding.ts";
5 import type { PulledMessage, ReadSubscriptionClient } from "./ReadSubscription.ts";
6 import type { Subscription } from "./Subscription.ts";
7 import type { Topic } from "./Topic.ts";
8 import type { PublishMessage, WriteTopicClient } from "./WriteTopic.ts";
9
10 /**
11 * Shared HTTP scaffolding for the Pub/Sub `WriteTopic` / `ReadSubscription`
12 * bindings. NOT exported from `index.ts`.
13 */
14
15 export const writeTopicGrant: BindingIam = {
16 role: "roles/pubsub.publisher",
17 on: "pubsub.topic",
18 };
19
20 export const readSubscriptionGrant: BindingIam = {
21 role: "roles/pubsub.subscriber",
22 on: "pubsub.subscription",
23 };
24
25 const encode = (data: string | Uint8Array) =>
26 typeof data === "string"
27 ? Buffer.from(data, "utf8").toString("base64")
28 : Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString("base64");
29
30 const toPubsubMessage = (message: PublishMessage): pubsub.PubsubMessage => ({
31 data: encode(message.data),
32 attributes: message.attributes,
33 orderingKey: message.orderingKey,
34 });
35
36 const decode = (received: pubsub.ReceivedMessage): PulledMessage => {
37 const buffer = Buffer.from(received.message?.data ?? "", "base64");
38 return {
39 ...received,
40 ackId: received.ackId ?? "",
41 messageId: received.message?.messageId ?? "",
42 data: new Uint8Array(buffer),
43 text: buffer.toString("utf8"),
44 attributes: Object.fromEntries(
45 Object.entries(received.message?.attributes ?? {}).filter(
46 (entry): entry is [string, string] => entry[1] !== undefined,
47 ),
48 ),
49 };
50 };
51
52 export const makeWriteTopicBinding = Effect.gen(function* () {
53 const bind = yield* GCPBindings.Bind;
54 const publish = yield* GCPBindings.withCredentials(pubsub.publishProjectsTopics);
55 return Effect.fn(function* (topic: Topic) {
56 if (!globalThis.__ALCHEMY_RUNTIME__) {
57 yield* bind`GCP.PubSub.WriteTopic(${topic})`({
58 iam: [grantFor(writeTopicGrant, topic.name)],
59 });
60 }
61 const topicName = yield* topic.name;
62 const publishBatch = (messages: ReadonlyArray<PublishMessage>) =>
63 messages.length === 0
64 ? Effect.succeed<string[]>([])
65 : Effect.gen(function* () {
66 const body = yield* Effect.sync(() => ({
67 messages: messages.map(toPubsubMessage),
68 }));
69 const response = yield* publish({
70 topic: yield* topicName,
71 body,
72 });
73 return response.messageIds ?? [];
74 });
75 return {
76 publish: (message) => publishBatch([message]).pipe(Effect.map((ids) => ids[0] ?? "")),
77 publishBatch,
78 } satisfies WriteTopicClient;
79 });
80 });
81
82 export const makeReadSubscriptionBinding = Effect.gen(function* () {
83 const bind = yield* GCPBindings.Bind;
84 const pull = yield* GCPBindings.withCredentials(pubsub.pullProjectsSubscriptions);
85 const acknowledge = yield* GCPBindings.withCredentials(pubsub.acknowledgeProjectsSubscriptions);
86 const modifyAckDeadline = yield* GCPBindings.withCredentials(
87 pubsub.modifyAckDeadlineProjectsSubscriptions,
88 );
89 return Effect.fn(function* (subscription: Subscription) {
90 if (!globalThis.__ALCHEMY_RUNTIME__) {
91 yield* bind`GCP.PubSub.ReadSubscription(${subscription})`({
92 iam: [grantFor(readSubscriptionGrant, subscription.name)],
93 });
94 }
95 const subscriptionName = yield* subscription.name;
96 return {
97 pull: (options) =>
98 Effect.gen(function* () {
99 const response = yield* pull({
100 subscription: yield* subscriptionName,
101 body: {
102 maxMessages: options?.maxMessages ?? 10,
103 returnImmediately: options?.returnImmediately ?? false,
104 },
105 });
106 return yield* Effect.sync(() => (response.receivedMessages ?? []).map(decode));
107 }),
108 acknowledge: (ackIds) =>
109 ackIds.length === 0
110 ? Effect.void
111 : Effect.gen(function* () {
112 yield* acknowledge({
113 subscription: yield* subscriptionName,
114 body: { ackIds: [...ackIds] },
115 });
116 }),
117 modifyAckDeadline: (ackIds, seconds) =>
118 ackIds.length === 0
119 ? Effect.void
120 : Effect.gen(function* () {
121 yield* modifyAckDeadline({
122 subscription: yield* subscriptionName,
123 body: { ackIds: [...ackIds], ackDeadlineSeconds: seconds },
124 });
125 }),
126 } satisfies ReadSubscriptionClient;
127 });
128 });