@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 126 lines 4.28 KB
Raw
1 import * as Namespace from "alchemy/Namespace";
2 import * as Output from "alchemy/Output";
3 import * as Effect from "effect/Effect";
4 import * as HttpServerResponse from "effect/http/HttpServerResponse";
5 import * as Layer from "effect/Layer";
6 import * as Stream from "effect/Stream";
7 import { Subscription } from "../PubSub/Subscription.ts";
8 import type { Topic } from "../PubSub/Topic.ts";
9 import {
10 TopicEventSource as PubSubTopicEventSource,
11 type TopicEventSourceProps,
12 type TopicEventSourceService,
13 type TopicMessage,
14 } from "../PubSub/TopicEventSource.ts";
15 import {
16 deliveryAudience,
17 grantSelfInvoker,
18 hostEndpoint,
19 listenForDeliveries,
20 pathSegment,
21 pushHost,
22 } from "../PushDelivery.ts";
23
24 /**
25 * Subscription `deadLetterPolicy` and `retryPolicy` for the event source's
26 * props. Dead-lettering defaults to a backoff so its attempts span more
27 * than a transient failure.
28 */
29 const deliveryPolicyOf = (props: TopicEventSourceProps) => ({
30 deadLetterPolicy:
31 props.deadLetter === undefined
32 ? undefined
33 : {
34 deadLetterTopic: props.deadLetter.topic.name,
35 maxDeliveryAttempts: props.deadLetter.maxDeliveryAttempts ?? 5,
36 },
37 retryPolicy:
38 props.retryPolicy ??
39 (props.deadLetter === undefined
40 ? undefined
41 : { minimumBackoff: "10s", maximumBackoff: "600s" }),
42 });
43
44 /** Default push path for a topic's deliveries. */
45 export const topicPushPath = (topic: Topic, props: TopicEventSourceProps) =>
46 props.path ?? `/__alchemy/pubsub/${pathSegment(topic.LogicalId)}`;
47
48 interface PushEnvelope {
49 message?: TopicMessage["message"];
50 subscription?: string;
51 deliveryAttempt?: number;
52 }
53
54 /**
55 * Push implementation of `GCP.PubSub.TopicEventSource` for HTTP hosts
56 * (`GCP.Run.Service` / `GCP.Function`, `GCP.CloudFunctions.Function`).
57 *
58 * Deploy-time: grants the host's runtime service account
59 * `roles/run.invoker` on the host and creates a push subscription to the
60 * host's URL, signed with an OIDC token for that account. Runtime: claims
61 * `POST` deliveries on the push path, verifies the token, and runs the
62 * handler. 204 acks the message; a failed handler answers 500 and Pub/Sub
63 * redelivers per the subscription's retry policy.
64 *
65 * @layer
66 * @provides GCP.PubSub.TopicEventSource
67 * @category Run
68 */
69 export const TopicEventSource = Layer.effect(
70 PubSubTopicEventSource,
71 Effect.gen(function* () {
72 const subscription = yield* Subscription;
73
74 return Effect.fn(function* <Req = never>(
75 topic: Topic,
76 props: TopicEventSourceProps,
77 handler: (messages: Stream.Stream<TopicMessage>) => Effect.Effect<void, never, Req>,
78 ) {
79 const host = yield* pushHost("GCP.PubSub.TopicEventSource");
80 const path = topicPushPath(topic, props);
81
82 if (!globalThis.__ALCHEMY_RUNTIME__) {
83 const endpoint = hostEndpoint(host);
84 yield* Namespace.push(
85 host.LogicalId,
86 Effect.gen(function* () {
87 yield* grantSelfInvoker(host);
88 yield* subscription(`${topic.LogicalId}-Push`, {
89 topic: topic.name,
90 ackDeadlineSeconds: props.ackDeadlineSeconds ?? 60,
91 filter: props.filter,
92 ...deliveryPolicyOf(props),
93 pushConfig: {
94 pushEndpoint: Output.interpolate`${endpoint.url}${path}`,
95 oidcToken: {
96 serviceAccountEmail: endpoint.serviceAccount,
97 audience: deliveryAudience(endpoint.url, path),
98 },
99 },
100 });
101 }),
102 );
103 }
104
105 yield* listenForDeliveries(host, path, (request) =>
106 Effect.gen(function* () {
107 const envelope = (yield* request.json.pipe(Effect.orElseSucceed(() => undefined))) as
108 | PushEnvelope
109 | undefined;
110 if (envelope?.message === undefined) {
111 // Malformed deliveries can never succeed; ack so they don't loop.
112 return HttpServerResponse.empty({ status: 204 });
113 }
114 yield* handler(
115 Stream.make({
116 message: envelope.message,
117 subscription: envelope.subscription ?? "",
118 deliveryAttempt: envelope.deliveryAttempt,
119 }),
120 ).pipe(Effect.orDie);
121 return HttpServerResponse.empty({ status: 204 });
122 }),
123 );
124 }) as TopicEventSourceService;
125 }),
126 );