@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 225 lines 7.08 KB
Raw
1 import * as Context from "effect/Context";
2 import type * as Duration from "effect/Duration";
3 import type * as Effect from "effect/Effect";
4 import type * as Option from "effect/Option";
5 import type * as EffectStream from "effect/Stream";
6 import type * as Aggregate from "./Aggregate.ts";
7 import type * as Event from "./Event.ts";
8 import type { Filter } from "./Filter.ts";
9 import type * as Key from "./Key.ts";
10 import type * as Middleware from "./Middleware.ts";
11 import type * as Read from "./Read.ts";
12 import type * as Rejection from "./Rejection.ts";
13 import type { ConsistencyTimeout, Page } from "./View.ts";
14
15 /**
16 * One entry of a stream key: the event appended, and where it sits.
17 */
18 export interface Entry<E, Id = string> {
19 readonly event: E;
20 /** `id` is the stream key, `stream` is `Stream/key`, `seq` counts the key's entries. */
21 readonly envelope: Aggregate.Envelope<Id>;
22 }
23
24 /**
25 * Structural constraint satisfied by every stream class.
26 */
27 export interface Any extends Context.Key<unknown, unknown> {
28 readonly kind: "Stream";
29 readonly streamName: string;
30 readonly definition: {
31 readonly key: Key.Any;
32 readonly entries: ReadonlyArray<Event.Any>;
33 } & Read.AnyContract;
34 /** Type-level only: the entry events. */
35 readonly "~event": unknown;
36 }
37
38 /** The entry event type of a stream class. */
39 export type EventOf<S extends Any> = S["~event"];
40 /** The key of a stream class: an aggregate, or a string Schema. */
41 export type KeyOf<S extends Any> = S["definition"]["key"];
42
43 /**
44 * The pure definition of a stream.
45 */
46 export interface Definition<
47 Key extends Key.Any,
48 Entries extends ReadonlyArray<Event.Any>,
49 Ms extends Middleware.List = readonly [],
50 Rejects extends ReadonlyArray<Rejection.Any> = readonly [],
51 > extends Read.Contract<
52 Key.RefOf<Key>,
53 Entry<Aggregate.InstanceOf<Entries[number]>, Key.IdOf<Key>> | null,
54 Ms,
55 Rejects
56 > {
57 /**
58 * What keys this stream, one ordered log per key: an aggregate, whose refs
59 * are its keys, or a string Schema, whose values are.
60 */
61 readonly key: Key;
62 /** The events the stream's entries may be. */
63 readonly entries: Entries;
64 }
65
66 /**
67 * What a projection's handler passes to {@link Host.append}: the input it is
68 * handling. Every input a projection handler receives qualifies.
69 */
70 export interface Origin<Key extends Key.Any> {
71 readonly key: Key.RefOf<Key>;
72 }
73
74 /**
75 * The API of a stream, obtained with `yield* MyStream`.
76 */
77 export interface Host<Key extends Key.Any, E> {
78 /** The latest entry of a key, or `none` if nothing was appended. */
79 readonly peek: (
80 key: Key.RefOf<Key>,
81 options?: {
82 /** Wait until the stream's writer has handled this write (a command's `stream` and `version`). */
83 readonly atLeast?: { readonly stream: string; readonly version: number };
84 readonly timeout?: Duration.Input;
85 },
86 ) => Effect.Effect<Option.Option<Entry<E, Key.IdOf<Key>>>, ConsistencyTimeout>;
87 /** The latest entry, then each new one. */
88 readonly watch: (
89 key: Key.RefOf<Key>,
90 ) => EffectStream.Stream<Option.Option<Entry<E, Key.IdOf<Key>>>>;
91 /** Every entry from `after` (an entry `seq`), then live ones. */
92 readonly events: (
93 key: Key.RefOf<Key>,
94 options?: { readonly after?: number; readonly where?: Filter<E> },
95 ) => EffectStream.Stream<Entry<E, Key.IdOf<Key>>>;
96 /** A page of a key's entries, oldest first unless `order` is `"desc"`. */
97 readonly list: (
98 key: Key.RefOf<Key>,
99 options?: {
100 readonly where?: Filter<E>;
101 readonly order?: "asc" | "desc";
102 readonly take?: number;
103 readonly after?: number;
104 },
105 ) => Effect.Effect<Page<Entry<E, Key.IdOf<Key>>>>;
106 /**
107 * Append entries for the input a projection is handling, to that input's
108 * key. Only a projection that lists this stream in `writes` may append, and
109 * a replayed or redelivered input appends nothing twice.
110 */
111 readonly append: (origin: Origin<Key>, ...events: ReadonlyArray<E>) => Effect.Effect<void>;
112 }
113
114 /**
115 * Type-level identity of a stream in an Effect's requirements.
116 */
117 export interface StreamKey<Name extends string> {
118 readonly "~alchemy/Domain/Stream": Name;
119 }
120
121 /**
122 * A keyed, append-only log: one ordered list of entries per key, kept and
123 * replayable. A projection writes it; clients read it through an Api with the
124 * same middleware and `validate` as a view. Its latest entry is its current
125 * value, so a stream of snapshots serves both "what is it now?" (`peek`) and
126 * "tell me every change" (`watch`, `events`).
127 *
128 * ### Declaring a stream
129 * **Example:** An account card, one entry per change
130 * ```typescript
131 * import * as Domain from "@alchemy.run/domain";
132 * import * as Schema from "effect/Schema";
133 * import { Account } from "./Account.ts";
134 *
135 * export class CardChanged extends Domain.Event("CardChanged", {
136 * owner: Schema.String,
137 * balance: Schema.Int,
138 * }) {}
139 *
140 * export class AccountCard extends Domain.Stream("AccountCard", {
141 * key: Account,
142 * entries: [CardChanged],
143 * }) {}
144 * ```
145 *
146 * ### Writing it from a projection
147 * A projection lists the streams it writes, then appends for the input it is
148 * handling.
149 *
150 * **Example:** Append a card for every summary change
151 * ```typescript
152 * export class AccountCards extends Domain.Projection("AccountCards", {
153 * from: [AccountSummary],
154 * key: Account,
155 * on: [MoneyDeposited],
156 * writes: [AccountCard],
157 * }) {}
158 *
159 * export const AccountCardsLive = AccountCards.toLayer(
160 * Effect.gen(function* () {
161 * const cards = yield* AccountCard;
162 * return Effect.fn(function* (batch) {
163 * for (const input of batch) {
164 * yield* cards.append(input, new CardChanged({ owner: input.state.owner, balance: input.state.balance }));
165 * }
166 * });
167 * }),
168 * );
169 * ```
170 *
171 * ### Reading it
172 * **Example:** Through an Api
173 * ```typescript
174 * const latest = yield* bank.AccountCard.peek(accountId);
175 * yield* bank.AccountCard.watch(accountId).pipe(
176 * Stream.runForEach(({ state: card }) => Effect.log(card)),
177 * );
178 * ```
179 *
180 * @primitive
181 */
182 export const make = <
183 const Name extends string,
184 Key extends Key.Any,
185 const Entries extends ReadonlyArray<Event.Any>,
186 const Ms extends Middleware.List = readonly [],
187 const Rejects extends ReadonlyArray<Rejection.Any> = readonly [],
188 >(
189 name: Name,
190 definition: Definition<Key, Entries, Ms, Rejects>,
191 ): StreamClass<
192 Name,
193 Definition<Key, Entries, Ms, Rejects>,
194 Key,
195 Aggregate.InstanceOf<Entries[number]>
196 > => {
197 const Tag = Context.Service<StreamKey<Name>, Host<Key, Aggregate.InstanceOf<Entries[number]>>>()(
198 `alchemy/Domain/Stream/${name}`,
199 );
200 return class extends Tag {
201 static readonly kind = "Stream" as const;
202 static readonly streamName: Name = name;
203 static readonly definition = definition;
204 } as unknown as StreamClass<
205 Name,
206 Definition<Key, Entries, Ms, Rejects>,
207 Key,
208 Aggregate.InstanceOf<Entries[number]>
209 >;
210 };
211
212 /**
213 * The class type returned by {@link make}.
214 */
215 export interface StreamClass<
216 Name extends string,
217 Def,
218 Key extends Key.Any,
219 E,
220 > extends Context.ServiceClass<StreamKey<Name>, string, Host<Key, E>> {
221 readonly kind: "Stream";
222 readonly streamName: Name;
223 readonly definition: Def;
224 readonly "~event": E;
225 }