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

main
ts 75 lines 2.69 KB
Raw
1 import * as GCP from "@alchemy.run/gcp";
2 import type { TopicMessage } from "@alchemy.run/gcp/PubSub/TopicEventSource";
3 import * as Effect from "effect/Effect";
4 import * as HttpServerResponse from "effect/http/HttpServerResponse";
5 import * as Stream from "effect/Stream";
6
7 /** Marker object a consumer writes for one delivered message. */
8 export const markerFor = (messageId: string) => `markers/${messageId}.json`;
9
10 export const PushOrders = GCP.PubSub.Topic("PushOrders", {});
11 export const PullOrders = GCP.PubSub.Topic("PullOrders", {});
12 export const Markers = GCP.Storage.Bucket("TopicMarkers", {
13 location: "US-CENTRAL1",
14 forceDestroy: true,
15 });
16
17 const recordMessages =
18 (putObject: (request: { name: string; body: string }) => Effect.Effect<unknown, unknown, any>) =>
19 (messages: Stream.Stream<TopicMessage>) =>
20 messages.pipe(
21 Stream.runForEach(({ message, subscription }) =>
22 putObject({
23 name: markerFor(message.messageId ?? "unknown"),
24 body: JSON.stringify({
25 data: atob(message.data ?? ""),
26 attributes: message.attributes ?? {},
27 subscription,
28 }),
29 }).pipe(Effect.asVoid, Effect.orDie),
30 ),
31 );
32
33 /**
34 * Effect-native Cloud Run service consuming a topic over push. The
35 * service keeps the default IAM invoker check, so deliveries must carry a
36 * token Cloud Run accepts.
37 * Deployed from {@link ../TopicEventSource.test.ts}.
38 */
39 export class PushConsumer extends GCP.Function<PushConsumer>()(
40 "PushConsumer",
41 {
42 main: import.meta.url,
43 handler: "PushConsumer",
44 location: "us-central1",
45 },
46 Effect.gen(function* () {
47 const topic = yield* PushOrders;
48 const bucket = yield* Markers;
49 const putObject = yield* GCP.Storage.PutObject(bucket);
50 yield* GCP.PubSub.consumeTopicMessages(topic, recordMessages(putObject));
51 return {
52 fetch: Effect.succeed(HttpServerResponse.text("ok")),
53 };
54 }).pipe(Effect.provide(GCP.Run.TopicEventSource), Effect.provide(GCP.Storage.PutObjectHttp)),
55 ) {}
56
57 /**
58 * Effect-native Cloud Run worker pool consuming a topic with a pull loop.
59 * Deployed from {@link ../TopicEventSource.test.ts}.
60 */
61 export class PullConsumer extends GCP.Run.WorkerPool<PullConsumer>()(
62 "PullConsumer",
63 {
64 main: import.meta.url,
65 handler: "PullConsumer",
66 location: "us-central1",
67 scaling: { manualInstanceCount: 1 },
68 },
69 Effect.gen(function* () {
70 const topic = yield* PullOrders;
71 const bucket = yield* Markers;
72 const putObject = yield* GCP.Storage.PutObject(bucket);
73 yield* GCP.PubSub.consumeTopicMessages(topic, { maxMessages: 5 }, recordMessages(putObject));
74 }).pipe(Effect.provide(GCP.Run.TopicPullEventSource), Effect.provide(GCP.Storage.PutObjectHttp)),
75 ) {}