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

main
ts 1,454 lines 56.5 KB
Raw
1 import type { HttpEffect } from "alchemy/Http";
2 import * as Cause from "effect/Cause";
3 import * as Context from "effect/Context";
4 import * as Deferred from "effect/Deferred";
5 import * as Duration from "effect/Duration";
6 import * as Effect from "effect/Effect";
7 import * as Effectable from "effect/Effectable";
8 import * as Exit from "effect/Exit";
9 import type * as Headers from "effect/http/Headers";
10 import * as HttpClient from "effect/http/HttpClient";
11 import * as HttpClientRequest from "effect/http/HttpClientRequest";
12 import { HttpServerRequest } from "effect/http/HttpServerRequest";
13 import * as HttpServerResponse from "effect/http/HttpServerResponse";
14 import * as Layer from "effect/Layer";
15 import * as Option from "effect/Option";
16 import * as Queue from "effect/Queue";
17 import * as Rpc from "effect/rpc/Rpc";
18 import * as RpcClient from "effect/rpc/RpcClient";
19 import * as RpcClientError from "effect/rpc/RpcClientError";
20 import * as RpcGroup from "effect/rpc/RpcGroup";
21 import * as RpcMessage from "effect/rpc/RpcMessage";
22 import type * as RpcMiddleware from "effect/rpc/RpcMiddleware";
23 import * as RpcSerialization from "effect/rpc/RpcSerialization";
24 import * as RpcServer from "effect/rpc/RpcServer";
25 import * as Schema from "effect/Schema";
26 import type * as Scope from "effect/Scope";
27 import * as Socket from "effect/socket/Socket";
28 import * as Stream from "effect/Stream";
29 import * as Tracer from "effect/Tracer";
30 import type * as Aggregate from "./Aggregate.ts";
31 import * as Command from "./Command.ts";
32 import { DefinitionError, NotInModel, Unreadable, UnroutedCommand } from "./DefinitionError.ts";
33 import { type Filter, matches } from "./Filter.ts";
34 import { decodeEnvelope } from "./Kernel.ts";
35 import * as Key from "./Key.ts";
36 import * as Middleware from "./Middleware.ts";
37 import * as Model from "./Model.ts";
38 import {
39 type AggregateStore,
40 captureContext,
41 type StreamStore,
42 type Subscription,
43 type ViewStore,
44 } from "./Platform.ts";
45 import type * as Read from "./Read.ts";
46 import { contractOf, nameOf, readRpcs } from "./ReadRpcs.ts";
47 import * as RequestContext from "./RequestContext.ts";
48 import type * as DomainStream from "./Stream.ts";
49 import type * as View from "./View.ts";
50 import * as Watch from "./Watch.ts";
51
52 /**
53 * What an Api exposes: commands (writes); views, streams, and aggregates that
54 * declare a `read` contract (reads).
55 */
56 export type Servable = Command.Any | View.Any | Aggregate.Any | DomainStream.Any;
57
58 /** The names of the commands a model holds: their tags. */
59 export type CommandName<M extends Model.Any> = M["commands"][number]["tag"];
60 /** The names of the views a model holds. */
61 export type ViewName<M extends Model.Any> = M["views"][number]["viewName"];
62 /** The names of the streams a model holds. */
63 export type StreamName<M extends Model.Any> = M["streams"][number]["streamName"];
64 /** The names of the aggregates a model holds that declare `read`, so an Api may serve them. */
65 export type AggregateName<M extends Model.Any> = ReadableName<M["aggregates"][number]>;
66
67 /** An aggregate's name, unless its type says it declared no `read`. */
68 type ReadableName<A> = A extends Aggregate.Any
69 ? [A["definition"]["read"]] extends [undefined]
70 ? never
71 : A["aggregateName"]
72 : never;
73
74 /**
75 * What {@link make} takes: the model, and the names of what of it the Api
76 * serves. A kind it does not list is served whole: every command, view and
77 * stream of the model, and every aggregate that declares `read`. `[]` serves
78 * none of a kind.
79 */
80 export interface Options<
81 M extends Model.Any,
82 C extends ReadonlyArray<CommandName<M>>,
83 V extends ReadonlyArray<ViewName<M>>,
84 S extends ReadonlyArray<StreamName<M>>,
85 A extends ReadonlyArray<AggregateName<M>>,
86 > {
87 /** The model the Api is over. */
88 readonly model: M;
89 /** The commands a client may send. Every command of the model by default. */
90 readonly commands?: C;
91 /** The views a client may read. Every view of the model by default. */
92 readonly views?: V;
93 /** The streams a client may read. Every stream of the model by default. */
94 readonly streams?: S;
95 /** The aggregates a client may read directly, through their `read` contract. Every one that declares `read` by default. */
96 readonly aggregates?: A;
97 }
98
99 /** What an Api over `M` serves, from the names it lists. */
100 export type ServedBy<
101 M extends Model.Any,
102 C extends ReadonlyArray<string>,
103 V extends ReadonlyArray<string>,
104 S extends ReadonlyArray<string>,
105 A extends ReadonlyArray<string>,
106 > =
107 | Extract<M["commands"][number], { readonly tag: C[number] }>
108 | Extract<M["views"][number], { readonly viewName: V[number] }>
109 | Extract<M["streams"][number], { readonly streamName: S[number] }>
110 | Extract<M["aggregates"][number], { readonly aggregateName: A[number] }>;
111
112 type Commands<E extends Servable> = Extract<E, Command.Any>;
113 type Views<E extends Servable> = Extract<E, View.Any>;
114 type Streams<E extends Servable> = Extract<E, DomainStream.Any>;
115 type Aggregates<E extends Servable> = Exclude<E, Command.Any | View.Any | DomainStream.Any>;
116
117 // ---------------------------------------------------------------- client types
118
119 type ContractOf<D> = D extends Read.AnyContract ? D : never;
120 type RejectionOf<D> = Aggregate.InstanceOf<NonNullable<ContractOf<D>["rejects"]>[number]>;
121 type MiddlewareOf<D> = NonNullable<ContractOf<D>["middleware"]>;
122
123 /** Everything a read can fail with: the declared rejections, the middleware's errors, transport. */
124 export type ReadError<D> =
125 | RejectionOf<D>
126 | Middleware.Errors<MiddlewareOf<D>>
127 | RpcClientError.RpcClientError;
128
129 interface CallOptions {
130 readonly headers?: Headers.Input;
131 }
132
133 /** The typed client of a view exposed in an Api. */
134 export interface ViewClient<V extends View.Any> {
135 /** The key's current state (`null` if it does not exist or the filter excludes it). */
136 readonly get: (
137 key: Key.IdOf<View.KeyOf<V>>,
138 options?: CallOptions & {
139 /** Wait until the view has applied this write (a command's `stream` and `version`). */
140 readonly atLeast?: { readonly stream: string; readonly version: number };
141 readonly where?: Filter<View.StateOf<V>>;
142 },
143 ) => Effect.Effect<View.StateOf<V> | null, ReadError<V["definition"]> | View.ConsistencyTimeout>;
144 /**
145 * The key's state with its cursor, then every change. Ends with a rejection
146 * when `validate` stops allowing it.
147 */
148 readonly watch: (
149 key: Key.IdOf<View.KeyOf<V>>,
150 options?: CallOptions & { readonly where?: Filter<View.StateOf<V>> },
151 ) => Stream.Stream<Read.Snapshot<View.StateOf<V> | null>, ReadError<V["definition"]>>;
152 /**
153 * The events the key emitted, each with the state after it: history from
154 * `after` (a cursor), a {@link Read.CaughtUp} frame, then live events.
155 */
156 readonly events: (
157 key: Key.IdOf<View.KeyOf<V>>,
158 options?: CallOptions & {
159 readonly after?: number;
160 readonly where?: Filter<View.EventOf<V>>;
161 },
162 ) => Stream.Stream<
163 View.Entry<View.StateOf<V>, View.EventOf<V>, Key.IdOf<View.KeyOf<V>>> | Read.CaughtUp,
164 ReadError<V["definition"]>
165 >;
166 /** A page of the key's emitted events. */
167 readonly list: (
168 key: Key.IdOf<View.KeyOf<V>>,
169 options?: CallOptions & {
170 /** Wait until the view has applied this write (a command's `stream` and `version`). */
171 readonly atLeast?: { readonly stream: string; readonly version: number };
172 readonly where?: Filter<View.EventOf<V>>;
173 readonly order?: "asc" | "desc";
174 readonly take?: number;
175 readonly after?: number;
176 },
177 ) => Effect.Effect<
178 View.Page<View.Entry<View.StateOf<V>, View.EventOf<V>, Key.IdOf<View.KeyOf<V>>>>,
179 ReadError<V["definition"]> | View.ConsistencyTimeout
180 >;
181 /**
182 * The key's state and the cursor it is valid at, read together. Render the
183 * state, then follow `events(key, { after: cursor })`: every later change
184 * arrives once, and none is missed.
185 */
186 readonly snapshot: (
187 key: Key.IdOf<View.KeyOf<V>>,
188 options?: CallOptions & {
189 /** Wait until the view has applied this write (a command's `stream` and `version`). */
190 readonly atLeast?: { readonly stream: string; readonly version: number };
191 readonly where?: Filter<View.StateOf<V>>;
192 },
193 ) => Effect.Effect<
194 Read.Snapshot<View.StateOf<V> | null>,
195 ReadError<V["definition"]> | View.ConsistencyTimeout
196 >;
197 }
198
199 /** The typed client of a stream exposed in an Api. */
200 export interface StreamClient<S extends DomainStream.Any> {
201 /** The key's latest entry, or `null` if nothing was appended. */
202 readonly peek: (
203 key: Key.IdOf<DomainStream.KeyOf<S>>,
204 options?: CallOptions & {
205 /** Wait until the stream's writer has handled this write (a command's `stream` and `version`). */
206 readonly atLeast?: { readonly stream: string; readonly version: number };
207 },
208 ) => Effect.Effect<
209 DomainStream.Entry<DomainStream.EventOf<S>, Key.IdOf<DomainStream.KeyOf<S>>> | null,
210 ReadError<S["definition"]> | View.ConsistencyTimeout
211 >;
212 /**
213 * The key's latest entry (`null` before any) with its cursor, then each new
214 * one. Ends with a rejection when `validate` stops allowing it.
215 */
216 readonly watch: (
217 key: Key.IdOf<DomainStream.KeyOf<S>>,
218 options?: CallOptions,
219 ) => Stream.Stream<
220 Read.Snapshot<DomainStream.Entry<
221 DomainStream.EventOf<S>,
222 Key.IdOf<DomainStream.KeyOf<S>>
223 > | null>,
224 ReadError<S["definition"]>
225 >;
226 /** The key's entries from `after` (a cursor), a {@link Read.CaughtUp} frame, then live ones. */
227 readonly events: (
228 key: Key.IdOf<DomainStream.KeyOf<S>>,
229 options?: CallOptions & {
230 readonly after?: number;
231 readonly where?: Filter<DomainStream.EventOf<S>>;
232 },
233 ) => Stream.Stream<
234 DomainStream.Entry<DomainStream.EventOf<S>, Key.IdOf<DomainStream.KeyOf<S>>> | Read.CaughtUp,
235 ReadError<S["definition"]>
236 >;
237 /** A page of the key's entries. */
238 readonly list: (
239 key: Key.IdOf<DomainStream.KeyOf<S>>,
240 options?: CallOptions & {
241 readonly where?: Filter<DomainStream.EventOf<S>>;
242 readonly order?: "asc" | "desc";
243 readonly take?: number;
244 readonly after?: number;
245 },
246 ) => Effect.Effect<
247 View.Page<DomainStream.Entry<DomainStream.EventOf<S>, Key.IdOf<DomainStream.KeyOf<S>>>>,
248 ReadError<S["definition"]>
249 >;
250 }
251
252 /** A committed event of an aggregate, as a client receives it. */
253 export interface Recorded<E, Id> {
254 readonly event: E;
255 readonly envelope: Aggregate.Envelope<Id>;
256 }
257
258 /** The typed client of an aggregate exposed in an Api (through its `read` contract). */
259 export interface AggregateClient<A extends Aggregate.Any> {
260 /** The instance's current state. */
261 readonly get: (
262 key: Aggregate.IdOf<A>,
263 options?: CallOptions,
264 ) => Effect.Effect<Aggregate.StateOf<A>, ReadError<A["definition"]["read"]>>;
265 /** The instance's state with its cursor, then its state after every commit. */
266 readonly watch: (
267 key: Aggregate.IdOf<A>,
268 options?: CallOptions,
269 ) => Stream.Stream<Read.Snapshot<Aggregate.StateOf<A>>, ReadError<A["definition"]["read"]>>;
270 /**
271 * The instance's committed events: history from `after` (a cursor), a
272 * {@link Read.CaughtUp} frame, then live.
273 */
274 readonly events: (
275 key: Aggregate.IdOf<A>,
276 options?: CallOptions & { readonly after?: number },
277 ) => Stream.Stream<
278 Recorded<Aggregate.EventOf<A>, Aggregate.IdOf<A>> | Read.CaughtUp,
279 ReadError<A["definition"]["read"]>
280 >;
281 }
282
283 /** How a command is sent: its idempotency key and the call's headers. */
284 export interface CommandOptions extends CallOptions {
285 /** A resend with the same id returns the first receipt instead of deciding again. */
286 readonly commandId?: string;
287 }
288
289 /** The input and options after a command's target. The input may be left out when it has no required field. */
290 type CommandArgs<Input> = {} extends Input
291 ? [input?: Input, options?: CommandOptions]
292 : [input: Input, options?: CommandOptions];
293
294 /** The typed client of a command exposed in an Api: `bank.WithdrawMoney(target, input, options)`. */
295 export type CommandClient<C extends Command.Any> =
296 C["rpc"] extends Rpc.Rpc<
297 infer _Tag,
298 infer Payload,
299 infer Success,
300 infer Error,
301 infer Middleware,
302 infer _Requires
303 >
304 ? Payload["Type"] extends { readonly target: infer Target; readonly input: infer Input }
305 ? (
306 target: Target,
307 ...args: CommandArgs<Input>
308 ) => Effect.Effect<
309 Success["Type"],
310 | Error["Type"]
311 | Middleware["error"]["Type"]
312 | Middleware["~ClientError"]
313 | RpcClientError.RpcClientError,
314 | Payload["EncodingServices"]
315 | Success["DecodingServices"]
316 | Error["DecodingServices"]
317 | Middleware["error"]["DecodingServices"]
318 >
319 : never
320 : never;
321
322 /**
323 * The typed client of an Api: commands as methods (`bank.WithdrawMoney(...)`),
324 * views and aggregates as namespaces (`bank.AccountSummary.watch(...)`).
325 */
326 export type ApiClient<E extends Servable> = {
327 readonly [C in Commands<E> as C["tag"]]: CommandClient<C>;
328 } & {
329 readonly [V in Views<E> as V["viewName"]]: ViewClient<V>;
330 } & {
331 readonly [S in Streams<E> as S["streamName"]]: StreamClient<S>;
332 } & {
333 readonly [A in Aggregates<E> as A["aggregateName"]]: AggregateClient<A>;
334 };
335
336 /** Type-level identity of an Api's client service. */
337 export interface ClientKey<Name extends string> {
338 readonly "~alchemy/Domain/Api/Client": Name;
339 }
340
341 /** What `yield* MyApi` gives a Worker: the Api served over HTTP. */
342 export interface ApiServer {
343 /** Use as the Worker's `fetch`. Commands and reads over HTTP; live reads over WebSockets. */
344 readonly fetch: HttpEffect;
345 }
346
347 /**
348 * The class type returned by {@link make}. The class is itself an Effect:
349 * `yield* MyApi` serves it, requiring the hosted Domain and the Layers of every
350 * middleware what it serves declares.
351 */
352 export interface ApiClass<
353 Name extends string,
354 Serves extends ReadonlyArray<Servable>,
355 > extends Effect.Effect<ApiServer, never, Model.Internals | MiddlewareServices<Serves>> {
356 new (_: never): {};
357 readonly kind: "Api";
358 readonly apiName: Name;
359 /** The model this Api is over. */
360 readonly model: Model.Any;
361 /** The commands, views, streams and aggregates this Api serves. */
362 readonly serves: Serves;
363 /** The command classes this Api exposes, in the order it lists them. */
364 readonly commands: ReadonlyArray<Commands<Serves[number]>>;
365 /**
366 * One Schema for every rejection this Api's commands declare: a union of the
367 * rejection classes, each once, decoding to class instances as the client
368 * fails with them. `Schema.Never` when no command rejects.
369 */
370 readonly rejections: RejectionUnion<Commands<Serves[number]>["rejects"][number]>;
371 /** The underlying Effect RPC group. */
372 readonly group: RpcGroup.RpcGroup<Rpc.Any>;
373 /**
374 * A typed client. Provide a protocol: {@link protocolHttp},
375 * {@link protocolWebSocket} or {@link protocolInProcess}.
376 */
377 readonly client: Effect.Effect<
378 ApiClient<Serves[number]>,
379 never,
380 Scope.Scope | RpcClient.Protocol | MiddlewareClients<Serves>
381 >;
382 /** The client as a service, for code that uses it without owning the connection. */
383 readonly Client: Context.Service<ClientKey<Name>, ApiClient<Serves[number]>>;
384 /** Build {@link Client} for the life of the Layer, over the protocol provided to it. */
385 readonly layerClient: Layer.Layer<
386 ClientKey<Name>,
387 never,
388 RpcClient.Protocol | MiddlewareClients<Serves>
389 >;
390 /** {@link client} over {@link protocolHttp}. */
391 readonly clientHttp: (
392 url: string,
393 ) => Effect.Effect<
394 ApiClient<Serves[number]>,
395 never,
396 Scope.Scope | HttpClient.HttpClient | MiddlewareClients<Serves>
397 >;
398 /** {@link layerClient} over {@link protocolHttp}. */
399 readonly layerClientHttp: (
400 url: string,
401 ) => Layer.Layer<ClientKey<Name>, never, HttpClient.HttpClient | MiddlewareClients<Serves>>;
402 /** {@link client} over {@link protocolWebSocket}. */
403 readonly clientWebSocket: (
404 url: string,
405 ) => Effect.Effect<
406 ApiClient<Serves[number]>,
407 never,
408 Scope.Scope | HttpClient.HttpClient | Socket.WebSocketConstructor | MiddlewareClients<Serves>
409 >;
410 /** {@link layerClient} over {@link protocolWebSocket}. */
411 readonly layerClientWebSocket: (
412 url: string,
413 ) => Layer.Layer<
414 ClientKey<Name>,
415 never,
416 HttpClient.HttpClient | Socket.WebSocketConstructor | MiddlewareClients<Serves>
417 >;
418 /** {@link client} over {@link protocolInProcess}. In a Worker, build it per request. */
419 readonly clientInProcess: Effect.Effect<
420 ApiClient<Serves[number]>,
421 never,
422 Scope.Scope | Model.Internals | MiddlewareServices<Serves> | MiddlewareClients<Serves>
423 >;
424 /** {@link layerClient} over {@link protocolInProcess}. */
425 readonly layerClientInProcess: Layer.Layer<
426 ClientKey<Name>,
427 never,
428 Model.Internals | MiddlewareServices<Serves> | MiddlewareClients<Serves>
429 >;
430 }
431
432 type EntryMiddleware<E> = E extends Command.Any
433 ? E["middleware"][number]
434 : E extends View.Any | DomainStream.Any
435 ? NonNullable<E["definition"]["middleware"]>[number]
436 : E extends Aggregate.Any
437 ? NonNullable<NonNullable<E["definition"]["read"]>["middleware"]>[number]
438 : never;
439
440 /** The middleware services the server needs for every entry. */
441 type MiddlewareServices<Serves extends ReadonlyArray<Servable>> =
442 EntryMiddleware<Serves[number]> extends infer M
443 ? M extends RpcMiddleware.AnyService
444 ? M["Identifier"]
445 : never
446 : never;
447
448 /** The client-side middleware every entry needs (e.g. attaching a session token). */
449 type MiddlewareClients<Serves extends ReadonlyArray<Servable>> =
450 EntryMiddleware<Serves[number]> extends infer M
451 ? M extends RpcMiddleware.AnyService
452 ? M extends { readonly requiredForClient: true }
453 ? RpcMiddleware.ForClient<M["Identifier"]>
454 : never
455 : never
456 : never;
457
458 const rpcsOf = (entry: Servable): ReadonlyArray<Rpc.Any> =>
459 entry.kind === "Command" ? [entry.rpc] : Object.values(readRpcs(entry));
460
461 // ---------------------------------------------------------------- handlers
462
463 /**
464 * Only an entry's declared errors are public. Anything else (an
465 * infrastructure error, an undeclared rejection) becomes a defect, so it
466 * never leaks as a typed error the client cannot decode.
467 */
468 const declaredOnly = (rpc: Rpc.Any) => {
469 const props = rpc as Rpc.AnyWithProps;
470 const isDeclared = Schema.is(props.errorSchema);
471 const success = props.successSchema as Schema.Top & { readonly error?: Schema.Top };
472 const isDeclaredInStream = success.error ? Schema.is(success.error) : isDeclared;
473 return {
474 effect: <A, E, R>(effect: Effect.Effect<A, E, R>) =>
475 Effect.catchIf(
476 effect,
477 (e) => !isDeclared(e),
478 (e) => Effect.die(e),
479 ),
480 stream: <A, E, R>(stream: Stream.Stream<A, E, R>) =>
481 Stream.catchIf(
482 stream,
483 (e) => !isDeclaredInStream(e),
484 (e) => Stream.die(e),
485 ),
486 };
487 };
488
489 /** The wire payload of a command: its target, an optional command id, and its input. */
490 interface CommandPayload {
491 readonly target: string;
492 readonly commandId?: string;
493 readonly input: object;
494 }
495
496 interface ReadPayload {
497 readonly key: string;
498 readonly where?: unknown;
499 readonly atLeast?: { readonly stream: string; readonly version: number };
500 readonly after?: number;
501 readonly order?: "asc" | "desc";
502 readonly take?: number;
503 }
504
505 const caughtUpAt = (seq: number): Read.CaughtUp => ({ _tag: "CaughtUp", cursor: seq });
506
507 /**
508 * A key's events from `start`, with a `CaughtUp` frame after its history: the
509 * events up to `end`, the key's `seq` when the read began. `keep` judges and
510 * filters each event after the end is found, so a filtered-out last event
511 * still ends the history.
512 */
513 const withCaughtUp = <A>(
514 start: number,
515 end: number,
516 events: Stream.Stream<A, unknown>,
517 seqOf: (event: A) => number,
518 keep: (event: A) => Effect.Effect<ReadonlyArray<unknown>, unknown>,
519 ): Stream.Stream<unknown, unknown> => {
520 let sent = start >= end;
521 const rest = events.pipe(
522 Stream.mapEffect((event) =>
523 keep(event).pipe(
524 Effect.map((out) => {
525 if (sent || seqOf(event) < end) return out;
526 sent = true;
527 return [...out, caughtUpAt(seqOf(event))];
528 }),
529 ),
530 ),
531 Stream.flatMap((out) => Stream.fromIterable(out)),
532 );
533 return start >= end ? Stream.concat(Stream.succeed(caughtUpAt(start)), rest) : rest;
534 };
535
536 type Handler = (input: never) => unknown;
537
538 /**
539 * The first thing an Api lists that it cannot serve: a name its model does
540 * not hold, or an aggregate without a `read` contract. The type of the
541 * options rules both out; this catches a model typed as `Model.Any`.
542 */
543 /** Why an Api cannot serve something it lists. */
544 type Unservable = NotInModel | Unreadable;
545
546 const notInModel = (
547 _apiModel: Model.Any,
548 unresolved: ReadonlyArray<Unservable>,
549 ): DefinitionError | undefined =>
550 unresolved.length === 0 ? undefined : new DefinitionError({ reason: unresolved[0]! });
551
552 const handlersOf = (
553 apiModel: Model.Any,
554 entries: ReadonlyArray<Servable>,
555 unresolved: ReadonlyArray<Unservable>,
556 ): Effect.Effect<Record<string, Handler>, never, Model.Internals> =>
557 Effect.gen(function* () {
558 const problem = notInModel(apiModel, unresolved);
559 if (problem) return yield* Effect.die(problem);
560 const internals = yield* Model.Internals;
561 const handlers: Record<string, Handler> = {};
562 for (const entry of entries) {
563 if (entry.kind === "Command") {
564 const aggregate = internals.commands.get(entry.tag);
565 if (!aggregate) {
566 return yield* Effect.die(
567 new DefinitionError({ reason: new UnroutedCommand({ command: entry.tag }) }),
568 );
569 }
570 const declared = declaredOnly(entry.rpc);
571 // Runs inside the command's middleware, so the context it provides
572 // (the session's actor) travels with the command to its aggregate.
573 handlers[entry.tag] = ({ target, commandId, input }: CommandPayload) =>
574 declared.effect(
575 // oxlint-disable-next-line effecttsgo/new-schema-class -- `make` on a generic command class loses its instance type
576 aggregate.send(target, new entry(input), { commandId }).pipe(
577 Effect.map((receipt) => ({
578 reply: receipt.reply,
579 stream: receipt.stream,
580 version: receipt.version,
581 })),
582 ),
583 );
584 continue;
585 }
586 // Serving an aggregate's state without its read contract would skip its middleware.
587 if (entry.kind === "Aggregate" && !entry.definition.read) {
588 return yield* Effect.die(
589 new DefinitionError({ reason: new Unreadable({ aggregate: entry.aggregateName }) }),
590 );
591 }
592 const name = nameOf(entry);
593 const rpcs = readRpcs(entry);
594 const validate = contractOf(entry).validate as
595 | ((request: Read.Request<unknown>, state: unknown) => Effect.Effect<void, unknown>)
596 | undefined;
597 const check = (mode: Read.Mode, key: unknown) => (state: unknown) =>
598 validate ? validate({ mode, key }, state) : Effect.void;
599 const effect =
600 (rpc: Rpc.Any, handle: (payload: ReadPayload) => Effect.Effect<unknown, unknown>) =>
601 (payload: ReadPayload) =>
602 declaredOnly(rpc).effect(handle(payload));
603 const stream =
604 (rpc: Rpc.Any, handle: (payload: ReadPayload) => Stream.Stream<unknown, unknown>) =>
605 (payload: ReadPayload) =>
606 declaredOnly(rpc).stream(handle(payload));
607
608 if (entry.kind === "Stream") {
609 const host = internals.streamHosts.get(name)!;
610 const key = entry.definition.key;
611 const refOf = (id: string) => Key.refOf(key, id);
612 const latest = (id: string) =>
613 host.peek(refOf(id)).pipe(Effect.orDie, Effect.map(Option.getOrNull));
614 handlers[`${name}.peek`] = effect(rpcs.get, ({ key: id, atLeast }) =>
615 host.peek(refOf(id), { atLeast }).pipe(
616 Effect.flatMap((found) => {
617 const entry = Option.getOrNull(found);
618 return check("get", refOf(id))(entry).pipe(Effect.as(entry));
619 }),
620 ),
621 );
622 handlers[`${name}.watch`] = stream(rpcs.watch, ({ key: id }) =>
623 host.watch(refOf(id)).pipe(
624 Stream.mapEffect((found) => {
625 const entry = Option.getOrNull(found);
626 return check(
627 "watch",
628 refOf(id),
629 )(entry).pipe(Effect.as({ state: entry, cursor: entry?.envelope.seq ?? 0 }));
630 }),
631 ),
632 );
633 handlers[`${name}.events`] = stream(rpcs.events, ({ key: id, after, where }) => {
634 const start = after ?? 0;
635 return Stream.unwrap(
636 latest(id).pipe(
637 Effect.map((last) =>
638 withCaughtUp(
639 start,
640 last?.envelope.seq ?? 0,
641 host.events(refOf(id), { after: start }),
642 (entry) => entry.envelope.seq,
643 // Each entry is judged as the key's latest entry at that point.
644 (entry) =>
645 matches(where as Filter<unknown> | undefined, entry.event)
646 ? check("events", refOf(id))(entry).pipe(Effect.as([entry]))
647 : Effect.succeed([]),
648 ),
649 ),
650 ),
651 );
652 });
653 handlers[`${name}.list`] = effect(rpcs.list!, ({ key: id, where, order, take, after }) =>
654 latest(id).pipe(
655 Effect.flatMap((entry) => check("list", refOf(id))(entry)),
656 Effect.andThen(
657 host.list(refOf(id), {
658 where: where as Filter<unknown> | undefined,
659 order,
660 take,
661 after,
662 }),
663 ),
664 ),
665 );
666 continue;
667 }
668
669 if (entry.kind === "View") {
670 const host = internals.viewHosts.get(name)!;
671 const key = entry.definition.key;
672 const refOf = (id: string) => Key.refOf(key, id);
673 const visible = (state: unknown, where: unknown) =>
674 state !== null && matches(where as Filter<unknown> | undefined, state) ? state : null;
675 handlers[`${name}.get`] = effect(rpcs.get, ({ key: id, atLeast, where }) =>
676 host.query(refOf(id), { atLeast }).pipe(
677 Effect.flatMap((found) => {
678 const state = Option.getOrNull(found);
679 return check("get", refOf(id))(state).pipe(Effect.as(visible(state, where)));
680 }),
681 ),
682 );
683 const viewStore = internals.views.get(name)!;
684 // From the stored snapshots, so each state comes with the seq it is valid at.
685 handlers[`${name}.watch`] = stream(rpcs.watch, ({ key: id, where }) =>
686 viewStore.changes(id).pipe(
687 Stream.mapEffect((snapshot) => {
688 const state =
689 snapshot.state === null
690 ? null
691 : internals.kernel.decodeViewState(entry, snapshot.state);
692 return check(
693 "watch",
694 refOf(id),
695 )(state).pipe(Effect.as({ state: visible(state, where), cursor: snapshot.seq }));
696 }),
697 ),
698 );
699 handlers[`${name}.events`] = stream(rpcs.events, ({ key: id, after, where }) => {
700 const start = after ?? 0;
701 return Stream.unwrap(
702 viewStore.read(id).pipe(
703 Effect.map((snapshot) =>
704 withCaughtUp(
705 start,
706 snapshot.seq,
707 host.events(refOf(id), { after: start }),
708 (entry) => entry.envelope.seq,
709 (entry) =>
710 matches(where as Filter<unknown> | undefined, entry.event)
711 ? check("events", refOf(id))(entry.state).pipe(Effect.as([entry]))
712 : Effect.succeed([]),
713 ),
714 ),
715 ),
716 );
717 });
718 handlers[`${name}.snapshot`] = effect(rpcs.snapshot!, ({ key: id, atLeast, where }) =>
719 host
720 .snapshot(refOf(id), { atLeast })
721 .pipe(
722 Effect.flatMap(({ state, cursor }) =>
723 check(
724 "get",
725 refOf(id),
726 )(state).pipe(Effect.as({ state: visible(state, where), cursor })),
727 ),
728 ),
729 );
730 handlers[`${name}.list`] = effect(
731 rpcs.list!,
732 ({ key: id, atLeast, where, order, take, after }) =>
733 host.query(refOf(id), { atLeast }).pipe(
734 Effect.flatMap((found) => found.pipe(Option.getOrNull, check("list", refOf(id)))),
735 Effect.andThen(
736 host.list(refOf(id), {
737 where: where as Filter<unknown> | undefined,
738 order,
739 take,
740 after,
741 }),
742 ),
743 ),
744 );
745 continue;
746 }
747
748 const store = internals.aggregates.get(name)!;
749 const refOf = (id: string) => ({ aggregate: name, id });
750 const stateOf = (json: unknown) => internals.kernel.decodeState(entry, json);
751 handlers[`${name}.get`] = effect(rpcs.get, ({ key: id }) =>
752 store.state(id).pipe(
753 Effect.flatMap(({ state }) => {
754 const decoded = stateOf(state);
755 return check("get", refOf(id))(decoded).pipe(Effect.as(decoded));
756 }),
757 ),
758 );
759 handlers[`${name}.watch`] = stream(rpcs.watch, ({ key: id }) =>
760 store.changes(id).pipe(
761 Stream.mapEffect(({ state, version }) => {
762 const decoded = stateOf(state);
763 return check(
764 "watch",
765 refOf(id),
766 )(decoded).pipe(Effect.as({ state: decoded, cursor: version }));
767 }),
768 ),
769 );
770 handlers[`${name}.events`] = stream(rpcs.events, ({ key: id, after }) => {
771 const start = after ?? 0;
772 return Stream.unwrap(
773 store.state(id).pipe(
774 Effect.map(({ version }) =>
775 withCaughtUp(
776 start,
777 version,
778 store.tail(id, start),
779 (stored) => stored.envelope.seq,
780 // Judged against the instance's state now, since events carry no state.
781 (stored) =>
782 store.state(id).pipe(
783 Effect.flatMap(({ state }) => check("events", refOf(id))(stateOf(state))),
784 Effect.andThen(internals.kernel.decodeEvent(stored.event)),
785 Effect.map((event) => [{ event, envelope: decodeEnvelope(stored.envelope) }]),
786 ),
787 ),
788 ),
789 ),
790 );
791 });
792 }
793 return handlers;
794 });
795
796 // ---------------------------------------------------------------- live reads
797
798 /** The query parameter carrying a live read's request (a WebSocket upgrade cannot carry a body). */
799 const LIVE_PARAM = "read";
800
801 /**
802 * A live read as the client sends it: the Effect RPC request's id, tag and
803 * payload, plus the cursor to resume from after a reconnect. Never headers:
804 * a URL ends up in logs, so a live read authenticates with what its upgrade
805 * request carries (in a browser, its cookies).
806 */
807 const LiveRequest = Schema.Struct({
808 id: Schema.Union([Schema.String, Schema.Number]),
809 tag: Schema.String,
810 payload: Schema.Unknown,
811 cursor: Schema.optional(Schema.Number),
812 /** The client's span, as the RPC protocol carries it, so the read joins the caller's trace. */
813 traceId: Schema.optional(Schema.String),
814 spanId: Schema.optional(Schema.String),
815 sampled: Schema.optional(Schema.Boolean),
816 });
817 type LiveRequest = typeof LiveRequest.Type;
818
819 const decodeLiveRequest = Schema.decodeUnknownOption(Schema.fromJsonString(LiveRequest));
820
821 /** The live read the current request asks for, if its query parameter decodes. */
822 const liveRequestOf = (request: { readonly url: string }): LiveRequest | undefined => {
823 const raw = new URL(request.url, "http://localhost").searchParams.get(LIVE_PARAM);
824 return raw === null ? undefined : Option.getOrUndefined(decodeLiveRequest(raw));
825 };
826
827 /**
828 * Serve live reads (`watch` and `events`) as WebSockets. The read's
829 * middleware runs here, in the Worker, against the upgrade request's own
830 * headers (cookies, in a browser); the context it provides travels with
831 * the subscription to the object that owns the key, which pushes to the
832 * socket on every commit. A refused read still connects, to deliver its
833 * typed rejection.
834 */
835 const liveReads = (
836 entries: ReadonlyArray<Servable>,
837 internals: Model.Internals["Service"],
838 middleware: Context.Context<never>,
839 ) => {
840 const reads = new Map<
841 string,
842 {
843 readonly rpc: Rpc.AnyWithProps;
844 readonly mode: "watch" | "events";
845 readonly store?: AggregateStore | ViewStore | StreamStore;
846 }
847 >();
848 for (const entry of entries) {
849 if (entry.kind === "Command") continue;
850 const name = nameOf(entry);
851 const store =
852 entry.kind === "View"
853 ? internals.views.get(name)
854 : entry.kind === "Stream"
855 ? internals.streams.get(name)
856 : internals.aggregates.get(name);
857 const rpcs = readRpcs(entry);
858 reads.set(`${name}.watch`, { rpc: rpcs.watch as Rpc.AnyWithProps, mode: "watch", store });
859 reads.set(`${name}.events`, { rpc: rpcs.events as Rpc.AnyWithProps, mode: "events", store });
860 }
861 return Effect.gen(function* () {
862 const request = yield* HttpServerRequest;
863 const live = liveRequestOf(request);
864 const read = live && reads.get(live.tag);
865 if (!live || !read) return HttpServerResponse.text("Unknown live read", { status: 400 });
866 if (!read.store?.connect) {
867 return HttpServerResponse.text("This platform streams live reads as responses", {
868 status: 501,
869 });
870 }
871 const payload = yield* Schema.decodeUnknownEffect(Schema.toCodecJson(read.rpc.payloadSchema))(
872 live.payload,
873 ).pipe(Effect.option);
874 if (Option.isNone(payload))
875 return HttpServerResponse.text("Invalid live read", { status: 400 });
876 const { key, where, after } = payload.value as ReadPayload;
877 yield* Effect.annotateCurrentSpan({ "domain.read": live.tag, "domain.key": String(key) });
878 // Run the read's middleware, as the RPC server would, around capturing what it provides.
879 let authorized: Effect.Effect<RequestContext.Json, unknown> = RequestContext.capture;
880 for (const service of read.rpc.middlewares) {
881 const run = Context.getUnsafe(middleware, service) as unknown as (
882 effect: Effect.Effect<RequestContext.Json, unknown>,
883 options: unknown,
884 ) => Effect.Effect<RequestContext.Json, unknown>;
885 authorized = run(authorized, {
886 rpc: read.rpc,
887 client: new Rpc.ServerClient(0),
888 requestId: RpcMessage.RequestId(live.id),
889 headers: request.headers,
890 payload: payload.value,
891 });
892 }
893 const subscription: Subscription = {
894 requestId: live.id,
895 mode: read.mode,
896 where: where as Subscription["where"],
897 context: {},
898 cursor: live.cursor ?? (read.mode === "watch" ? -1 : (after ?? 0)),
899 };
900 const judged = yield* authorized.pipe(
901 Effect.map((context): Subscription => ({ ...subscription, context })),
902 Effect.catch((error) =>
903 Watch.refuse(read.rpc, error).pipe(
904 Effect.orDie,
905 Effect.map((refused): Subscription => ({ ...subscription, refused })),
906 ),
907 ),
908 );
909 return yield* read.store.connect(String(key), judged);
910 }).pipe(
911 // A live read continues the trace of the client that opened it, like an RPC call.
912 (effect) =>
913 Effect.flatMap(HttpServerRequest, (request) => {
914 const live = liveRequestOf(request);
915 return effect.pipe(
916 Effect.withSpan(`Domain.read ${live?.tag ?? "unknown"}`, {
917 kind: "server",
918 ...(live?.traceId && live.spanId
919 ? {
920 parent: Tracer.externalSpan({
921 traceId: live.traceId,
922 spanId: live.spanId,
923 sampled: live.sampled ?? true,
924 }),
925 }
926 : {}),
927 }),
928 );
929 }),
930 );
931 };
932
933 // ---------------------------------------------------------------- client
934
935 type Flat = Record<string, (payload: unknown, options?: CallOptions) => unknown>;
936
937 /** Shape the flat Effect RPC client into commands plus view and aggregate namespaces. */
938 const nest = (entries: ReadonlyArray<Servable>, flat: Flat): unknown => {
939 const client: Record<string, unknown> = {};
940 for (const entry of entries) {
941 if (entry.kind === "Command") {
942 const send = flat[entry.tag]!;
943 client[entry.tag] = (
944 target: unknown,
945 input: object = {},
946 { commandId, ...options }: CommandOptions = {},
947 ) => send({ target, commandId, input }, options);
948 continue;
949 }
950 const name = nameOf(entry);
951 const call =
952 (method: string) =>
953 (key: unknown, options: CallOptions & Record<string, unknown> = {}) => {
954 const { headers, ...rest } = options;
955 return flat[`${name}.${method}`]!({ key, ...rest }, { headers });
956 };
957 client[name] =
958 entry.kind === "View"
959 ? {
960 get: call("get"),
961 watch: call("watch"),
962 events: call("events"),
963 list: call("list"),
964 snapshot: call("snapshot"),
965 }
966 : entry.kind === "Stream"
967 ? { peek: call("peek"), watch: call("watch"), events: call("events"), list: call("list") }
968 : { get: call("get"), watch: call("watch"), events: call("events") };
969 }
970 return client;
971 };
972
973 /**
974 * Serves an Api in the caller's process and connects a client to it. Messages
975 * are encoded as on the wire but never leave memory.
976 */
977 const makeProtocolInProcess = (
978 model: Model.Any,
979 entries: ReadonlyArray<Servable>,
980 unresolved: ReadonlyArray<Unservable>,
981 group: RpcGroup.RpcGroup<Rpc.Any>,
982 ): Layer.Layer<RpcClient.Protocol, never, Model.Internals> =>
983 Layer.effect(
984 RpcClient.Protocol,
985 Effect.gen(function* () {
986 const codecFor = Schema.toCodecJson as RpcSerialization.CodecFor;
987 const disconnects = yield* Queue.unbounded<number>();
988 const clientIds = new Set<number>();
989 let toServer = (_: number, __: RpcMessage.FromClientEncoded): Effect.Effect<void> =>
990 Effect.void;
991 let toClient = (_: number, __: RpcMessage.FromServerEncoded): Effect.Effect<void> =>
992 Effect.void;
993 const server = yield* RpcServer.Protocol.make((write) => {
994 toServer = write;
995 return Effect.succeed({
996 disconnects,
997 send: (clientId: number, response: RpcMessage.FromServerEncoded) =>
998 toClient(clientId, response),
999 end: () => Effect.void,
1000 clientIds: Effect.sync(() => new Set(clientIds) as ReadonlySet<number>),
1001 initialMessage: Effect.succeedNone,
1002 supportsAck: true,
1003 supportsTransferables: false,
1004 supportsSpanPropagation: true,
1005 supportsNotifications: false,
1006 codecFor,
1007 });
1008 });
1009 const protocol = yield* RpcClient.Protocol.make((write) => {
1010 toClient = write;
1011 return Effect.succeed({
1012 send: (clientId: number, request: RpcMessage.FromClientEncoded) =>
1013 toServer(clientId, request),
1014 supportsAck: true,
1015 supportsTransferables: false,
1016 codecFor,
1017 });
1018 });
1019 const handlers = yield* handlersOf(model, entries, unresolved);
1020 // The middleware services in the caller's scope run for every request.
1021 yield* RpcServer.make(group).pipe(
1022 Effect.provide(
1023 Layer.mergeAll(
1024 Layer.succeed(RpcServer.Protocol, server),
1025 group.toLayer(handlers as never) as Layer.Layer<never>,
1026 ),
1027 ),
1028 Effect.forkScoped,
1029 );
1030 return RpcClient.Protocol.of({
1031 ...protocol,
1032 run: (clientId, write) =>
1033 Effect.suspend(() => {
1034 clientIds.add(clientId);
1035 return protocol.run(clientId, write);
1036 }).pipe(
1037 Effect.onExit(() => {
1038 clientIds.delete(clientId);
1039 return Queue.offer(disconnects, clientId);
1040 }),
1041 ),
1042 });
1043 }),
1044 );
1045
1046 // The names an Api lists that its model does not hold.
1047 const Unresolved = Symbol.for("alchemy/Domain/Api/Unresolved");
1048
1049 // A class so `class BankApi extends Domain.Api(...) {}` works.
1050 const build = (
1051 name: string,
1052 model: Model.Any,
1053 entries: ReadonlyArray<Servable>,
1054 unresolved: ReadonlyArray<Unservable>,
1055 group: RpcGroup.RpcGroup<Rpc.Any>,
1056 ): unknown => {
1057 const client = RpcClient.make(group).pipe(
1058 Effect.map((flat) => nest(entries, flat as unknown as Flat)),
1059 );
1060 const Client = Context.Service<ClientKey<string>, unknown>()(`alchemy/Domain/Api/${name}/Client`);
1061 const commands = entries.filter((entry): entry is Command.Any => entry.kind === "Command");
1062 const rejectionClasses = [...new Set(commands.flatMap((command) => command.rejects))];
1063 const rejections = rejectionClasses.length === 0 ? Schema.Never : Schema.Union(rejectionClasses);
1064 // Serve the Api over HTTP (Effect RPC, NDJSON), with live reads over WebSockets.
1065 const serve = Effect.gen(function* () {
1066 const handlers = yield* handlersOf(model, entries, unresolved);
1067 // The middleware services (declared in the Api's requirements), for every request.
1068 const middleware = yield* captureContext();
1069 const layer = Layer.mergeAll(
1070 group.toLayer(handlers as never),
1071 RpcSerialization.layerNdjson,
1072 Layer.succeedContext(middleware),
1073 );
1074 // One server per request: Workers forbid sharing I/O objects across requests.
1075 const rpc = RpcServer.toHttpEffect(group).pipe(Effect.flatten, Effect.provide(layer));
1076 const live = liveReads(entries, yield* Model.Internals, middleware);
1077 const fetch = Effect.gen(function* () {
1078 const request = yield* HttpServerRequest;
1079 return request.headers.upgrade?.toLowerCase() === "websocket" ? yield* live : yield* rpc;
1080 }) as unknown as HttpEffect;
1081 return { fetch };
1082 });
1083 // The client for the life of the caller's scope, over the given protocol.
1084 const clientOver = <R>(protocol: Layer.Layer<RpcClient.Protocol, never, R>) =>
1085 Effect.flatMap(Layer.build(protocol), (context) => Effect.provide(client, context));
1086 const layerClient = Layer.effect(Client, client);
1087 const inProcess = makeProtocolInProcess(model, entries, unresolved, group);
1088 return Object.assign(
1089 class {},
1090 // The class is an Effect: `yield* MyApi` serves it.
1091 Effectable.Prototype({ label: `alchemy/Domain/Api<${name}>`, evaluate: () => serve }),
1092 {
1093 kind: "Api" as const,
1094 apiName: name,
1095 model,
1096 serves: entries,
1097 [Unresolved]: unresolved,
1098 commands,
1099 rejections,
1100 group,
1101 client,
1102 Client,
1103 layerClient,
1104 clientHttp: (url: string) => clientOver(protocolHttp(url)),
1105 layerClientHttp: (url: string) => layerClient.pipe(Layer.provide(protocolHttp(url))),
1106 clientWebSocket: (url: string) => clientOver(protocolWebSocket(url)),
1107 layerClientWebSocket: (url: string) =>
1108 layerClient.pipe(Layer.provide(protocolWebSocket(url))),
1109 clientInProcess: clientOver(inProcess),
1110 layerClientInProcess: layerClient.pipe(Layer.provide(inProcess)),
1111 },
1112 );
1113 };
1114
1115 /**
1116 * The public surface of a domain for one kind of client: the commands it may
1117 * send, and the views and aggregates (with a `read` contract) it may read.
1118 * Nothing in an Api needs a handler. The class is an Effect: `yield* MyApi`
1119 * gives a Worker its `fetch`. Call it with a typed client over
1120 * `Domain.protocolHttp`, `Domain.protocolWebSocket` or
1121 * `Domain.protocolInProcess`, or with `clientHttp`, `clientWebSocket` or
1122 * `clientInProcess`, which provide them.
1123 *
1124 * ### Declaring an Api
1125 * **Example:** What customers may reach
1126 * ```typescript
1127 * import * as Domain from "@alchemy.run/domain";
1128 * import { Account, DepositMoney, WithdrawMoney } from "./Account.ts";
1129 * import { AccountSummary } from "./AccountSummary.ts";
1130 * import { Bank } from "./Bank.ts";
1131 *
1132 * // Serving something Bank does not hold is a type error; nothing unlisted is served.
1133 * export class CustomerApi extends Domain.Api("CustomerApi", {
1134 * model: Bank,
1135 * commands: ["DepositMoney", "WithdrawMoney"],
1136 * views: ["AccountSummary"],
1137 * aggregates: ["Account"],
1138 * }) {}
1139 * ```
1140 *
1141 * ### Serving it from a Worker
1142 * **Example:** The Api as a Worker's fetch
1143 * ```typescript
1144 * import * as Cloudflare from "@alchemy.run/cloudflare";
1145 * import * as DomainCloudflare from "@alchemy.run/cloudflare/Domain";
1146 * import * as Effect from "effect/Effect";
1147 * import * as Layer from "effect/Layer";
1148 * import { Bank, BankPolicies } from "./Bank.ts";
1149 * import { CustomerApi } from "./CustomerApi.ts";
1150 * import { SessionLive } from "./Session.ts";
1151 *
1152 * const BankLive = SessionLive.pipe(
1153 * Layer.provideMerge(Bank.layer(BankPolicies)),
1154 * Layer.provide(DomainCloudflare.layerDurableObjects()),
1155 * );
1156 *
1157 * export default class BankWorker extends Cloudflare.Worker<BankWorker>()(
1158 * "BankWorker",
1159 * { main: import.meta.url },
1160 * Effect.gen(function* () {
1161 * const api = yield* CustomerApi;
1162 * return { fetch: api.fetch };
1163 * }).pipe(Effect.provide(BankLive)),
1164 * ) {}
1165 * ```
1166 *
1167 * ### Calling it
1168 * `Domain.protocolWebSocket` sends commands, `get` and `list` over HTTP, and
1169 * opens a WebSocket for each `watch` and `events`, pushed by the object that
1170 * owns the key. `Domain.protocolHttp` sends everything over HTTP.
1171 *
1172 * **Example:** A typed client
1173 * ```typescript
1174 * const bank = yield* CustomerApi.client;
1175 * const { reply } = yield* bank.DepositMoney(accountId, { amount: 1_000 });
1176 * const summary = yield* bank.AccountSummary.get(accountId);
1177 * yield* bank.AccountSummary.watch(accountId).pipe(
1178 * Stream.runForEach(({ state }) => Effect.log(state?.balance)),
1179 * );
1180 * ```
1181 *
1182 * ### Calling it in process
1183 * `clientInProcess` serves the Api in the caller's process, through the
1184 * middleware of everything it serves, with nothing sent over a network. Code that has
1185 * already authenticated its caller provides a middleware Layer that trusts it.
1186 *
1187 * **Example:** A webhook that deposits as the system
1188 * ```typescript
1189 * const asSystem = Layer.succeed(Session, (effect) =>
1190 * Effect.provideService(effect, CurrentActor, system("payments-webhook")),
1191 * );
1192 * const bank = yield* CustomerApi.clientInProcess.pipe(Effect.provide(asSystem));
1193 * yield* bank.DepositMoney(accountId, { amount: 1_000 });
1194 * ```
1195 *
1196 * @primitive
1197 */
1198 export const make = <
1199 const Name extends string,
1200 M extends Model.Any,
1201 const C extends ReadonlyArray<CommandName<M>> = ReadonlyArray<CommandName<M>>,
1202 const V extends ReadonlyArray<ViewName<M>> = ReadonlyArray<ViewName<M>>,
1203 const S extends ReadonlyArray<StreamName<M>> = ReadonlyArray<StreamName<M>>,
1204 const A extends ReadonlyArray<AggregateName<M>> = ReadonlyArray<AggregateName<M>>,
1205 >(
1206 name: Name,
1207 options: Options<M, C, V, S, A>,
1208 ): ApiClass<Name, ReadonlyArray<ServedBy<M, C, V, S, A>>> => {
1209 const { model } = options;
1210 // What the Api lists but cannot serve, as the message it dies with when served.
1211 const unresolved: Array<Unservable> = [];
1212 const pick = <T>(
1213 all: ReadonlyArray<T>,
1214 names: ReadonlyArray<string> | undefined,
1215 nameOfT: (t: T) => string,
1216 ): ReadonlyArray<T> =>
1217 names === undefined
1218 ? all
1219 : names.flatMap((n) => {
1220 const found = all.find((t) => nameOfT(t) === n);
1221 if (found === undefined)
1222 unresolved.push(new NotInModel({ entity: n, model: model.modelName }));
1223 return found === undefined ? [] : [found];
1224 });
1225 const serves: ReadonlyArray<Servable> = [
1226 ...pick(model.commands, options.commands, (c) => c.tag),
1227 ...pick(model.views, options.views, (v) => v.viewName),
1228 ...pick(model.streams, options.streams, (s) => s.streamName),
1229 ...pick(model.aggregates, options.aggregates, (a) => a.aggregateName).filter((aggregate) => {
1230 if (aggregate.definition.read !== undefined) return true;
1231 // Unlisted, an aggregate without `read` is simply not served; listed, it is a mistake.
1232 if (options.aggregates !== undefined) {
1233 unresolved.push(new Unreadable({ aggregate: aggregate.aggregateName }));
1234 }
1235 return false;
1236 }),
1237 ];
1238 return build(
1239 name,
1240 model,
1241 serves,
1242 unresolved,
1243 RpcGroup.make(...serves.flatMap(rpcsOf)) as unknown as RpcGroup.RpcGroup<Rpc.Any>,
1244 ) as ApiClass<Name, ReadonlyArray<ServedBy<M, C, V, S, A>>>;
1245 };
1246
1247 /**
1248 * The HTTP protocol for an Api client (NDJSON, so streams work). Live reads
1249 * are streamed responses, which the platform feeds by polling the key; use
1250 * {@link protocolWebSocket} to have them pushed instead. Requires an
1251 * `HttpClient`, e.g. `FetchHttpClient.layer`.
1252 */
1253 export const protocolHttp = (
1254 url: string,
1255 ): Layer.Layer<RpcClient.Protocol, never, HttpClient.HttpClient> =>
1256 RpcClient.layerProtocolHttp({ url }).pipe(Layer.provide(RpcSerialization.layerNdjson));
1257
1258 /**
1259 * The protocol for a client in the same process as the model. It serves the
1260 * Api right there: the middleware of everything it serves runs, from the Layers
1261 * in scope, and nothing leaves memory. Requires the hosted Domain, like
1262 * serving the Api.
1263 * In a Worker, build it per request.
1264 */
1265 export const protocolInProcess = <Name extends string, Serves extends ReadonlyArray<Servable>>(
1266 api: ApiClass<Name, Serves>,
1267 ): Layer.Layer<RpcClient.Protocol, never, Model.Internals | MiddlewareServices<Serves>> =>
1268 makeProtocolInProcess(
1269 api.model,
1270 api.serves,
1271 (api as unknown as { readonly [Unresolved]: ReadonlyArray<Unservable> })[Unresolved],
1272 api.group,
1273 );
1274
1275 /** A frame of a live read: an Effect RPC message, plus the cursor to resume from. */
1276 const LiveFrame = Schema.StructWithRest(
1277 Schema.Struct({ _tag: Schema.String, cursor: Schema.optional(Schema.Number) }),
1278 [Schema.Record(Schema.String, Schema.Unknown)],
1279 );
1280 const decodeLiveFrame = Schema.decodeUnknownEffect(Schema.fromJsonString(LiveFrame));
1281
1282 /** The RPCs served as live reads. */
1283 const isLiveRead = (tag: string) => tag.endsWith(".watch") || tag.endsWith(".events");
1284
1285 /** Attempts in a row a live read may fail to (re)connect before it fails. */
1286 const RECONNECTS = 8;
1287
1288 /**
1289 * The WebSocket protocol for an Api client. Calls (commands, `get`, `list`)
1290 * go over HTTP like {@link protocolHttp}; every live read (`watch`,
1291 * `events`) opens its own WebSocket, which the Api hands to the object that
1292 * owns the key (on Cloudflare, its Durable Object). Each commit is pushed
1293 * down the socket, so nothing polls and the object hibernates in between. A
1294 * dropped socket reconnects and resumes after the last value it delivered.
1295 *
1296 * A browser cannot set headers on a WebSocket, and a URL ends up in logs,
1297 * so headers client middleware attaches apply to calls only. A live read
1298 * authenticates with what its upgrade request carries: in a browser, the
1299 * cookies of the Api's origin, so serve the app and the Api from one origin
1300 * and keep sessions in an `HttpOnly`, `SameSite` cookie. Requires an
1301 * `HttpClient` and a `Socket.WebSocketConstructor`
1302 * (`Socket.layerWebSocketConstructorGlobal` in browsers and Workers).
1303 *
1304 * **Example:** Watching a view over a WebSocket
1305 * ```typescript
1306 * const BankConnection = CustomerApi.layerClient.pipe(
1307 * Layer.provide(Domain.protocolWebSocket("https://bank.example.com/api")),
1308 * Layer.provide(Layer.mergeAll(FetchHttpClient.layer, Socket.layerWebSocketConstructorGlobal)),
1309 * );
1310 * ```
1311 */
1312 export const protocolWebSocket = (
1313 url: string,
1314 ): Layer.Layer<RpcClient.Protocol, never, HttpClient.HttpClient | Socket.WebSocketConstructor> =>
1315 Layer.effect(
1316 RpcClient.Protocol,
1317 Effect.gen(function* () {
1318 const client = HttpClient.mapRequest(
1319 yield* HttpClient.HttpClient,
1320 HttpClientRequest.prependUrl(url),
1321 );
1322 const http = yield* RpcClient.makeProtocolHttp(client).pipe(
1323 Effect.provide(RpcSerialization.layerNdjson),
1324 );
1325 const constructor = yield* Socket.WebSocketConstructor;
1326 const socketUrl = url.replace(/^http/, "ws");
1327 const writers = new Map<
1328 number,
1329 (message: RpcMessage.FromServerEncoded) => Effect.Effect<void>
1330 >();
1331 const stops = new Map<string, Deferred.Deferred<void>>();
1332
1333 const liveRead = (clientId: number, request: RpcMessage.RequestEncoded) =>
1334 Effect.gen(function* () {
1335 let cursor: number | undefined;
1336 let ended = false;
1337 let failures = 0;
1338 const connect = Effect.gen(function* () {
1339 const live: LiveRequest = {
1340 id: request.id,
1341 tag: request.tag,
1342 payload: request.payload,
1343 cursor,
1344 ...(request.traceId && request.spanId
1345 ? { traceId: request.traceId, spanId: request.spanId, sampled: request.sampled }
1346 : {}),
1347 };
1348 const socket = yield* Socket.makeWebSocket(
1349 `${socketUrl}?${LIVE_PARAM}=${encodeURIComponent(JSON.stringify(live))}`,
1350 );
1351 const pull = yield* Socket.readerString(socket);
1352 while (!ended) {
1353 for (const text of yield* pull) {
1354 const { cursor: next, ...message } = yield* decodeLiveFrame(text);
1355 failures = 0;
1356 if (next !== undefined) cursor = next;
1357 if (message._tag === "Exit") ended = true;
1358 yield* Effect.suspend(
1359 () =>
1360 writers.get(clientId)?.(message as RpcMessage.FromServerEncoded) ?? Effect.void,
1361 );
1362 }
1363 }
1364 }).pipe(Effect.scoped, Effect.provideService(Socket.WebSocketConstructor, constructor));
1365
1366 while (!ended) {
1367 const exit = yield* Effect.exit(connect);
1368 if (ended) return;
1369 // A close without an `Exit` (a deploy, an evicted object) reconnects and resumes.
1370 if (++failures > RECONNECTS) {
1371 return yield* RpcClientError.RpcClientError.make({
1372 reason: RpcClientError.RpcClientDefect.make({
1373 message: `Live read ${request.tag} lost its connection`,
1374 cause: Exit.isFailure(exit) ? Cause.squash(exit.cause) : undefined,
1375 }),
1376 });
1377 }
1378 yield* Effect.sleep(Duration.millis(Math.min(5_000, 100 * 2 ** failures)));
1379 }
1380 });
1381
1382 return RpcClient.Protocol.of({
1383 run: (clientId, write) =>
1384 Effect.suspend(() => {
1385 writers.set(clientId, write);
1386 return http.run(clientId, write);
1387 }).pipe(Effect.ensuring(Effect.sync(() => writers.delete(clientId)))),
1388 send: (clientId, request, transferables) => {
1389 if (request._tag === "Request" && isLiveRead(request.tag)) {
1390 return Effect.gen(function* () {
1391 const stop = yield* Deferred.make<void>();
1392 stops.set(String(request.id), stop);
1393 yield* Effect.raceFirst(liveRead(clientId, request), Deferred.await(stop)).pipe(
1394 Effect.ensuring(Effect.sync(() => stops.delete(String(request.id)))),
1395 );
1396 });
1397 }
1398 if (request._tag === "Interrupt") {
1399 const stop = stops.get(String(request.requestId));
1400 if (stop) return Deferred.succeed(stop, undefined).pipe(Effect.asVoid);
1401 }
1402 return http.send(clientId, request, transferables);
1403 },
1404 supportsAck: false,
1405 supportsTransferables: false,
1406 codecFor: http.codecFor,
1407 });
1408 }),
1409 );
1410
1411 // ---------------------------------------------------------------- generic helpers
1412
1413 /** The Schema of a union of rejection classes; `Schema.Never` when there are none. */
1414 type RejectionUnion<R> = [R] extends [never]
1415 ? typeof Schema.Never
1416 : Schema.Codec<Aggregate.InstanceOf<R>, Schema.Codec.Encoded<R>>;
1417
1418 /**
1419 * Any Api class. Use it to write code that works with every Api, such as a
1420 * helper that turns each command of an Api into a UI action. `ApiClass` does
1421 * not fit there: its client type is exact, so a concrete Api is not an
1422 * `ApiClass<string, ReadonlyArray<Servable>>`.
1423 *
1424 * **Example:** A helper for any Api
1425 * ```typescript
1426 * const tagsOf = <A extends Domain.Api.Any>(api: A): ReadonlyArray<Domain.Api.CommandsOf<A>["tag"]> =>
1427 * api.commands.map((command) => command.tag);
1428 *
1429 * tagsOf(CustomerApi); // ["DepositMoney", "WithdrawMoney"]
1430 * ```
1431 */
1432 export interface Any {
1433 readonly kind: "Api";
1434 readonly apiName: string;
1435 /** The model the Api is over. */
1436 readonly model: Model.Any;
1437 /** The commands, views, streams and aggregates the Api serves. */
1438 readonly serves: ReadonlyArray<Servable>;
1439 /** The command classes the Api exposes, in order. */
1440 readonly commands: ReadonlyArray<Command.Any>;
1441 /** One Schema for every rejection the Api's commands declare. */
1442 readonly rejections: Schema.Top;
1443 /** The Api's client service. */
1444 readonly Client: Context.Key<ClientKey<string>, unknown>;
1445 }
1446
1447 /** The command classes an Api exposes. */
1448 export type CommandsOf<A extends Any> = A["commands"][number];
1449
1450 /** The rejection classes the commands of an Api declare. */
1451 export type RejectionsOf<A extends Any> = CommandsOf<A>["rejects"][number];
1452
1453 /** The client an Api's `Client` service gives (`yield* MyApi.Client`). */
1454 export type ClientOf<A extends Any> = A["Client"]["Service"];