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

main
ts 264 lines 9.76 KB
Raw
1 import * as Effect from "effect/Effect";
2 import * as Exit from "effect/Exit";
3 import * as Option from "effect/Option";
4 import * as Rpc from "effect/rpc/Rpc";
5 import * as RpcSchema from "effect/rpc/RpcSchema";
6 import * as Schema from "effect/Schema";
7 import type * as Aggregate from "./Aggregate.ts";
8 import { type Filter, matches } from "./Filter.ts";
9 import { decodeEnvelope, type Kernel } from "./Kernel.ts";
10 import * as Key from "./Key.ts";
11 import type {
12 Json,
13 Push,
14 StoredEvent,
15 StreamEntry,
16 StreamMeta,
17 Subscription,
18 ViewEntry,
19 ViewSnapshot,
20 } from "./Platform.ts";
21 import type * as Read from "./Read.ts";
22 import { contractOf, nameOf, readRpcs } from "./ReadRpcs.ts";
23 import * as RequestContext from "./RequestContext.ts";
24 import type * as DomainStream from "./Stream.ts";
25 import type * as View from "./View.ts";
26
27 /**
28 * Pushing to live reads. A platform that holds subscriptions on its objects
29 * (a WebSocket per `watch` or `events` read, on the Durable Object that owns
30 * the key) asks these functions what to send after each commit. They judge
31 * the change with the read's `validate`, apply its filter, and encode Effect
32 * RPC messages, so a client reads a pushed stream exactly like a streamed
33 * response.
34 *
35 * @internal
36 */
37
38 interface Codecs {
39 readonly chunk: (values: ReadonlyArray<unknown>) => Effect.Effect<Json, Schema.SchemaError>;
40 readonly exit: (exit: Exit.Exit<void, unknown>) => Effect.Effect<Json, Schema.SchemaError>;
41 }
42
43 const codecCache = new WeakMap<object, Codecs>();
44
45 /** The JSON codecs Effect RPC uses for a stream RPC's chunks and exit. */
46 const codecsOf = (rpc: Rpc.Any): Codecs => {
47 const cached = codecCache.get(rpc);
48 if (cached) return cached;
49 const props = rpc as Rpc.AnyWithProps;
50 const success = RpcSchema.isStreamSchema(props.successSchema)
51 ? props.successSchema.success
52 : Schema.Any;
53 const codecs: Codecs = {
54 chunk: Schema.encodeUnknownEffect(
55 Schema.toCodecJson(Schema.NonEmptyArray(success)),
56 ) as Codecs["chunk"],
57 exit: Schema.encodeUnknownEffect(
58 Schema.toCodecJson(Rpc.exitSchema(rpc as Rpc.AnyWithProps)),
59 ) as Codecs["exit"],
60 };
61 codecCache.set(rpc, codecs);
62 return codecs;
63 };
64
65 /** Encode a read's refusal (a middleware error) as the `Exit` that ends it. */
66 export const refuse = (rpc: Rpc.Any, error: unknown): Effect.Effect<Json, Schema.SchemaError> =>
67 codecsOf(rpc).exit(Exit.fail(error));
68
69 type Validate = (request: Read.Request<unknown>, state: unknown) => Effect.Effect<void, unknown>;
70
71 /** One item to push: the value to send (if the filter keeps it) and the state to judge. */
72 interface Item {
73 readonly state: unknown;
74 readonly value: Option.Option<unknown>;
75 /** A marker (`CaughtUp`), sent as is: `validate` does not judge it. */
76 readonly marker?: true;
77 }
78
79 /**
80 * Judge each item in order and encode what passes: one `Chunk` of the kept
81 * values, then, if `validate` rejected an item, the `Exit` that ends the read.
82 */
83 const encode = (
84 entry: View.Any | Aggregate.Any | DomainStream.Any,
85 subscription: Subscription,
86 ref: unknown,
87 items: ReadonlyArray<Item>,
88 cursor: number,
89 ): Effect.Effect<Push> =>
90 Effect.gen(function* () {
91 const rpcs = readRpcs(entry);
92 const rpc = subscription.mode === "watch" ? rpcs.watch : rpcs.events;
93 const codecs = codecsOf(rpc);
94 const validate = contractOf(entry).validate as Validate | undefined;
95 const context = yield* RequestContext.restore(subscription.context);
96 const values: Array<unknown> = [];
97 let rejection: Option.Option<unknown> = Option.none();
98 for (const item of items) {
99 if (validate && !item.marker) {
100 const judged = yield* validate({ mode: subscription.mode, key: ref }, item.state).pipe(
101 Effect.provideContext(context),
102 Effect.result,
103 );
104 if (judged._tag === "Failure") {
105 rejection = Option.some(judged.failure);
106 break;
107 }
108 }
109 if (Option.isSome(item.value)) values.push(item.value.value);
110 }
111 const messages: Array<Json> = [];
112 if (values.length > 0) {
113 messages.push({
114 _tag: "Chunk",
115 requestId: subscription.requestId,
116 values: yield* codecs.chunk(values),
117 });
118 }
119 if (Option.isSome(rejection)) {
120 messages.push({
121 _tag: "Exit",
122 requestId: subscription.requestId,
123 exit: yield* codecs.exit(Exit.fail(rejection.value)),
124 });
125 }
126 return {
127 messages,
128 subscription: { ...subscription, cursor },
129 done: Option.isSome(rejection),
130 };
131 }).pipe(Effect.orDie);
132
133 /**
134 * The first push of an `events` read is its history: mark its end once, with
135 * a `CaughtUp` item after the history's items.
136 */
137 const markCaughtUp = (subscription: Subscription, items: ReadonlyArray<Item>, cursor: number) =>
138 subscription.caughtUpSent
139 ? { subscription, items }
140 : {
141 subscription: { ...subscription, caughtUpSent: true },
142 items: [
143 ...items,
144 {
145 state: null,
146 value: Option.some({ _tag: "CaughtUp", cursor }),
147 marker: true,
148 } satisfies Item,
149 ],
150 };
151
152 const where = (subscription: Subscription) => subscription.where as Filter<unknown> | undefined;
153
154 /** What a view key's subscriber receives after a commit (or when it connects). */
155 export const viewPush =
156 (kernel: Kernel, view: View.Any) =>
157 (
158 key: string,
159 subscription: Subscription,
160 snapshot: ViewSnapshot,
161 entries: ReadonlyArray<ViewEntry>,
162 ): Effect.Effect<Push> =>
163 Effect.gen(function* () {
164 const ref = Key.refOf(view.definition.key, key);
165 if (subscription.mode === "watch") {
166 if (snapshot.version <= subscription.cursor) {
167 return { messages: [], subscription, done: false };
168 }
169 const state = snapshot.state === null ? null : kernel.decodeViewState(view, snapshot.state);
170 const visible = state !== null && matches(where(subscription), state) ? state : null;
171 return yield* encode(
172 view,
173 subscription,
174 ref,
175 [{ state, value: Option.some({ state: visible, cursor: snapshot.seq }) }],
176 snapshot.version,
177 );
178 }
179 const fresh = entries.filter((entry) => entry.seq > subscription.cursor);
180 const items = yield* Effect.forEach(fresh, (stored) =>
181 Effect.map(kernel.decodeViewEntry(view, stored), (decoded): Item => ({
182 state: decoded.state,
183 value: matches(where(subscription), decoded.event) ? Option.some(decoded) : Option.none(),
184 })),
185 );
186 const cursor = fresh.length > 0 ? fresh[fresh.length - 1]!.seq : subscription.cursor;
187 const marked = markCaughtUp(subscription, items, cursor);
188 return yield* encode(view, marked.subscription, ref, marked.items, cursor);
189 });
190
191 /** What an aggregate instance's subscriber receives after a commit (or when it connects). */
192 export const aggregatePush =
193 (kernel: Kernel, aggregate: Aggregate.Any) =>
194 (
195 id: string,
196 subscription: Subscription,
197 current: { readonly state: Json; readonly version: number },
198 events: ReadonlyArray<StoredEvent>,
199 ): Effect.Effect<Push> =>
200 Effect.gen(function* () {
201 const ref = { aggregate: nameOf(aggregate), id } as Aggregate.Ref;
202 const state = kernel.decodeState(aggregate, current.state);
203 if (subscription.mode === "watch") {
204 if (current.version <= subscription.cursor) {
205 return { messages: [], subscription, done: false };
206 }
207 return yield* encode(
208 aggregate,
209 subscription,
210 ref,
211 [{ state, value: Option.some({ state, cursor: current.version }) }],
212 current.version,
213 );
214 }
215 const fresh = events.filter((stored) => stored.envelope.seq > subscription.cursor);
216 // Judged against the instance's state now, since events carry no state.
217 const items = yield* Effect.forEach(fresh, (stored) =>
218 Effect.map(kernel.decodeEvent(stored.event), (event): Item => ({
219 state,
220 value: Option.some({ event, envelope: decodeEnvelope(stored.envelope) }),
221 })),
222 );
223 const cursor = fresh.length > 0 ? fresh[fresh.length - 1]!.envelope.seq : subscription.cursor;
224 const marked = markCaughtUp(subscription, items, cursor);
225 return yield* encode(aggregate, marked.subscription, ref, marked.items, cursor);
226 });
227
228 /** What a stream key's subscriber receives after an append (or when it connects). */
229 export const streamPush =
230 (kernel: Kernel, stream: DomainStream.Any) =>
231 (
232 key: string,
233 subscription: Subscription,
234 meta: StreamMeta,
235 entries: ReadonlyArray<StreamEntry>,
236 latest: StreamEntry | undefined,
237 ): Effect.Effect<Push> =>
238 Effect.gen(function* () {
239 const ref = Key.refOf(stream.definition.key, key);
240 if (subscription.mode === "watch") {
241 if (meta.seq <= subscription.cursor) {
242 return { messages: [], subscription, done: false };
243 }
244 const decoded = latest ? yield* kernel.decodeStreamEntry(latest) : null;
245 return yield* encode(
246 stream,
247 subscription,
248 ref,
249 [{ state: decoded, value: Option.some({ state: decoded, cursor: meta.seq }) }],
250 meta.seq,
251 );
252 }
253 const fresh = entries.filter((entry) => entry.seq > subscription.cursor);
254 // Each entry is judged as the key's latest entry at that point.
255 const items = yield* Effect.forEach(fresh, (stored) =>
256 Effect.map(kernel.decodeStreamEntry(stored), (decoded): Item => ({
257 state: decoded,
258 value: matches(where(subscription), decoded.event) ? Option.some(decoded) : Option.none(),
259 })),
260 );
261 const cursor = fresh.length > 0 ? fresh[fresh.length - 1]!.seq : subscription.cursor;
262 const marked = markCaughtUp(subscription, items, cursor);
263 return yield* encode(stream, marked.subscription, ref, marked.items, cursor);
264 });