@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, 06:00 UTC

main
ts 301 lines 10.3 KB
Raw
1 import * as Context from "effect/Context";
2 import * as Effect from "effect/Effect";
3 import * as Rpc from "effect/rpc/Rpc";
4 import type * as RpcGroup from "effect/rpc/RpcGroup";
5 import * as RpcSchema from "effect/rpc/RpcSchema";
6 import * as Schema from "effect/Schema";
7 import * as Aggregate from "./Aggregate.ts";
8 import type { Servable } from "./Api.ts";
9 import type * as Event from "./Event.ts";
10 import { FilterJson } from "./Filter.ts";
11 import * as Key from "./Key.ts";
12 import * as Middleware from "./Middleware.ts";
13 import * as Read from "./Read.ts";
14 import type * as DomainStream from "./Stream.ts";
15 import * as View from "./View.ts";
16
17 /**
18 * The RPCs of the views and aggregates an Api exposes. Shared by the Api
19 * (which serves them) and the platforms (which push their stream messages
20 * over WebSockets), so both encode exactly the same wire values.
21 *
22 * @internal
23 */
24
25 /** What `watch` sends: a state with its cursor. */
26 const snapshotSchema = (state: Schema.Top) => Schema.Struct({ state, cursor: Schema.Number });
27
28 /** Something an Api can expose for reading. */
29 export type Readable = View.Any | Aggregate.Any | DomainStream.Any;
30
31 export const nameOf = (entry: Readable) =>
32 entry.kind === "View"
33 ? entry.viewName
34 : entry.kind === "Stream"
35 ? entry.streamName
36 : entry.aggregateName;
37
38 export const union = (members: ReadonlyArray<Schema.Top>) =>
39 members.length === 0 ? Schema.Never : Schema.Union(members as ReadonlyArray<Schema.Top>);
40
41 /** The events a view emits: its declared events, or the events it applies. */
42 export const outputEvents = (view: View.Any): ReadonlyArray<Event.Any> => {
43 const def = view.definition;
44 if (def.events) return def.events;
45 const handles = (tag: string, source: string) =>
46 Boolean(def.evolve?.[tag] || def.evolve?.[source] || def.emit?.[tag] || def.emit?.[source]);
47 const out = new Set<Event.Any>();
48 for (const source of def.from) {
49 const name = nameOf(source);
50 const events =
51 source.kind === "View"
52 ? outputEvents(source as View.Any)
53 : (source as Aggregate.Any).definition.events;
54 for (const event of events) if (handles(event.tag, name)) out.add(event);
55 }
56 return [...out];
57 };
58
59 export interface ReadRpcs {
60 /** `get` for views and aggregates; `peek` for streams. */
61 readonly get: Rpc.Any;
62 readonly watch: Rpc.Any;
63 readonly events: Rpc.Any;
64 readonly list?: Rpc.Any;
65 /** Views only: the state and the cursor it is valid at. */
66 readonly snapshot?: Rpc.Any;
67 }
68
69 /**
70 * The read contract an entry's RPCs are built from. An aggregate without
71 * `read` gets an empty one so an Api still builds its schemas; serving that
72 * Api dies with a DefinitionError instead (see `handlersOf` in Api.ts).
73 */
74 export const contractOf = (entry: Readable): Read.AnyContract =>
75 entry.kind === "View" || entry.kind === "Stream"
76 ? entry.definition
77 : (entry.definition.read ?? {});
78
79 const rpcCache = new WeakMap<object, ReadRpcs>();
80
81 /** The RPCs of a view or aggregate exposed in an Api. */
82 export const readRpcs = (entry: Readable): ReadRpcs => {
83 const cached = rpcCache.get(entry);
84 if (cached) return cached;
85 const name = nameOf(entry);
86 const contract = contractOf(entry);
87 const guard = (rpc: Rpc.Any) => Middleware.apply(rpc, contract.middleware ?? []);
88 const error = union(contract.rejects ?? []);
89 // A read that takes `atLeast` can also time out waiting for the write.
90 const waitError = union([...(contract.rejects ?? []), View.ConsistencyTimeout]);
91 let rpcs: ReadRpcs;
92 if (entry.kind === "Stream") {
93 const def = entry.definition;
94 const key = Key.idSchemaOf(def.key);
95 const recorded = Schema.Struct({ event: union(def.entries), envelope: Aggregate.Envelope });
96 const latest = Schema.NullOr(recorded);
97 rpcs = {
98 get: guard(
99 Rpc.make(`${name}.peek`, {
100 payload: {
101 key,
102 atLeast: Schema.optional(
103 Schema.Struct({ stream: Schema.String, version: Schema.Number }),
104 ),
105 },
106 success: latest,
107 error: waitError,
108 }),
109 ),
110 watch: guard(
111 Rpc.make(`${name}.watch`, {
112 payload: { key },
113 success: snapshotSchema(latest),
114 error,
115 stream: true,
116 }),
117 ),
118 events: guard(
119 Rpc.make(`${name}.events`, {
120 payload: {
121 key,
122 after: Schema.optional(Schema.Number),
123 where: Schema.optional(FilterJson),
124 },
125 success: Schema.Union([Read.CaughtUp, recorded]),
126 error,
127 stream: true,
128 }),
129 ),
130 list: guard(
131 Rpc.make(`${name}.list`, {
132 payload: {
133 key,
134 where: Schema.optional(FilterJson),
135 order: Schema.optional(Schema.Literals(["asc", "desc"])),
136 take: Schema.optional(Schema.Number),
137 after: Schema.optional(Schema.Number),
138 },
139 success: Schema.Struct({
140 entries: Schema.Array(recorded),
141 cursor: Schema.NullOr(Schema.Number),
142 }),
143 error,
144 }),
145 ),
146 };
147 } else if (entry.kind === "View") {
148 const def = entry.definition;
149 const key = Key.idSchemaOf(def.key);
150 const state = Schema.NullOr(def.state ?? Schema.Null);
151 const recorded = Schema.Struct({
152 event: entry.pipe(outputEvents, union),
153 state,
154 envelope: Aggregate.Envelope,
155 });
156 rpcs = {
157 get: guard(
158 Rpc.make(`${name}.get`, {
159 payload: {
160 key,
161 atLeast: Schema.optional(
162 Schema.Struct({ stream: Schema.String, version: Schema.Number }),
163 ),
164 where: Schema.optional(FilterJson),
165 },
166 success: state,
167 error: waitError,
168 }),
169 ),
170 watch: guard(
171 Rpc.make(`${name}.watch`, {
172 payload: { key, where: Schema.optional(FilterJson) },
173 success: snapshotSchema(state),
174 error,
175 stream: true,
176 }),
177 ),
178 events: guard(
179 Rpc.make(`${name}.events`, {
180 payload: {
181 key,
182 after: Schema.optional(Schema.Number),
183 where: Schema.optional(FilterJson),
184 },
185 success: Schema.Union([Read.CaughtUp, recorded]),
186 error,
187 stream: true,
188 }),
189 ),
190 list: guard(
191 Rpc.make(`${name}.list`, {
192 payload: {
193 key,
194 atLeast: Schema.optional(
195 Schema.Struct({ stream: Schema.String, version: Schema.Number }),
196 ),
197 where: Schema.optional(FilterJson),
198 order: Schema.optional(Schema.Literals(["asc", "desc"])),
199 take: Schema.optional(Schema.Number),
200 after: Schema.optional(Schema.Number),
201 },
202 success: Schema.Struct({
203 entries: Schema.Array(recorded),
204 cursor: Schema.NullOr(Schema.Number),
205 }),
206 error: waitError,
207 }),
208 ),
209 snapshot: guard(
210 Rpc.make(`${name}.snapshot`, {
211 payload: {
212 key,
213 atLeast: Schema.optional(
214 Schema.Struct({ stream: Schema.String, version: Schema.Number }),
215 ),
216 where: Schema.optional(FilterJson),
217 },
218 success: snapshotSchema(state),
219 error: waitError,
220 }),
221 ),
222 };
223 } else {
224 const def = entry.definition;
225 const recorded = Schema.Struct({ event: union(def.events), envelope: Aggregate.Envelope });
226 rpcs = {
227 get: guard(Rpc.make(`${name}.get`, { payload: { key: def.id }, success: def.state, error })),
228 watch: guard(
229 Rpc.make(`${name}.watch`, {
230 payload: { key: def.id },
231 success: snapshotSchema(def.state),
232 error,
233 stream: true,
234 }),
235 ),
236 events: guard(
237 Rpc.make(`${name}.events`, {
238 payload: { key: def.id, after: Schema.optional(Schema.Number) },
239 success: Schema.Union([Read.CaughtUp, recorded]),
240 error,
241 stream: true,
242 }),
243 ),
244 };
245 }
246 rpcCache.set(entry, rpcs);
247 return rpcs;
248 };
249
250 /** One call an Api serves, as the HTTP and AI surfaces publish it. */
251 export interface Operation {
252 /** The command, view, stream or aggregate it belongs to. */
253 readonly served: Servable;
254 /** A command's tag, or a view's, stream's or aggregate's name. */
255 readonly name: string;
256 /** `send` for a command; the read's client method otherwise (`get`, `peek`, `watch`, ...). */
257 readonly operation: string;
258 readonly rpc: Rpc.AnyWithProps;
259 /** Whether the call answers with a stream of values (`watch`, `events`). */
260 readonly stream: boolean;
261 }
262
263 /** Every call an Api serves, in the order it serves them. */
264 export const operationsOf = (serves: ReadonlyArray<Servable>): ReadonlyArray<Operation> =>
265 serves.flatMap((served): ReadonlyArray<Operation> => {
266 if (served.kind === "Command") {
267 const rpc = served.rpc as Rpc.AnyWithProps;
268 return [{ served, name: served.tag, operation: "send", rpc, stream: false }];
269 }
270 const name = nameOf(served);
271 return Object.entries(readRpcs(served)).flatMap(([call, read]) => {
272 if (read === undefined) return [];
273 const rpc = read as Rpc.AnyWithProps;
274 // A stream's `get` RPC is its client's `peek`.
275 const operation =
276 (call as keyof ReadRpcs) === "get" && served.kind === "Stream" ? "peek" : call;
277 return [
278 { served, name, operation, rpc, stream: RpcSchema.isStreamSchema(rpc.successSchema) },
279 ];
280 });
281 });
282
283 /**
284 * An Api's in-process client for a caller from outside the app, such as an
285 * HTTP request or an MCP client. It runs no middleware's client half (what
286 * `RpcMiddleware.layerClient` provides): a credential the server holds for
287 * its own calls must never replace the caller's headers.
288 */
289 export const outsideClient = <A, R>(api: {
290 readonly group: RpcGroup.RpcGroup<Rpc.Any>;
291 readonly clientInProcess: Effect.Effect<A, never, R>;
292 }): Effect.Effect<A, never, R> => {
293 const middleware = new Set(
294 [...api.group.requests.values()].flatMap((rpc) => [...(rpc as Rpc.AnyWithProps).middlewares]),
295 );
296 // The keys `RpcMiddleware.layerClient` provides a middleware's client half under.
297 const halves = [...middleware].map(
298 (tag) => ({ key: `${tag.key}/Client` }) as unknown as Context.Key<never, unknown>,
299 );
300 return api.clientInProcess.pipe(Effect.updateContext(Context.omit(...halves)));
301 };