The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type { RuntimeContext } from "alchemy/RuntimeContext"; |
| 2 | import * as Context from "effect/Context"; |
| 3 | import * as Duration from "effect/Duration"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import * as Layer from "effect/Layer"; |
| 6 | import type * as Aggregate from "./Aggregate.ts"; |
| 7 | import type * as Event from "./Event.ts"; |
| 8 | import type * as Key from "./Key.ts"; |
| 9 | import type * as DomainStream from "./Stream.ts"; |
| 10 | import type * as View from "./View.ts"; |
| 11 | |
| 12 | /** |
| 13 | * One input a projection's handler receives: an event, the key it was routed |
| 14 | * to, and where it came from. |
| 15 | */ |
| 16 | export interface Input<Key extends Key.Any, S, E> { |
| 17 | /** The key this input was routed to. */ |
| 18 | readonly key: Key.RefOf<Key>; |
| 19 | /** The route named in `keyOf` that brought it here, if any. */ |
| 20 | readonly route: string | undefined; |
| 21 | /** The aggregate or view instance the event came from (a view key's value for a Schema-keyed view). */ |
| 22 | readonly source: Key.RefOf<View.SourceKey<S>>; |
| 23 | readonly event: E; |
| 24 | readonly envelope: Aggregate.Envelope; |
| 25 | /** For a view source: the view's state after the event. */ |
| 26 | readonly state: View.SourceState<S>; |
| 27 | /** The input's place in its key's input log, from 1. */ |
| 28 | readonly position: number; |
| 29 | } |
| 30 | |
| 31 | /** |
| 32 | * A projection's handler: one run of a key's inputs, in order. It runs at |
| 33 | * least once per input, so make its writes idempotent (an upsert keyed by |
| 34 | * `envelope.stream` and `envelope.seq` is). Resolve your store, and any stream |
| 35 | * it writes, while building it, in `toLayer`; the handler itself may only need |
| 36 | * the runtime it runs in (`RuntimeContext`), as a database binding does. |
| 37 | */ |
| 38 | export type Handler<I> = (batch: ReadonlyArray<I>) => Effect.Effect<void, never, RuntimeContext>; |
| 39 | |
| 40 | /** |
| 41 | * How a projection's Layer tunes it. These are variants: they change how it |
| 42 | * runs, never what it means. |
| 43 | */ |
| 44 | export interface Options { |
| 45 | /** |
| 46 | * Hand the handler up to `size` inputs of one key at once, waiting up to |
| 47 | * `wait` for a batch to fill. Without it, the handler gets one input at a |
| 48 | * time, as soon as it arrives. |
| 49 | */ |
| 50 | readonly batch?: { readonly size: number; readonly wait?: Duration.Input }; |
| 51 | /** |
| 52 | * Bump it to run the projection again over the whole history, for example |
| 53 | * after its store was lost or emptied, or once its handler writes a new |
| 54 | * shape. Clear or migrate your store first if a replayed write would not |
| 55 | * overwrite the old one. 0 when omitted. |
| 56 | */ |
| 57 | readonly version?: number; |
| 58 | } |
| 59 | |
| 60 | /** A projection's implementation, as its Layer provides it. @internal */ |
| 61 | export interface Implementation<I> { |
| 62 | readonly handle: Handler<I>; |
| 63 | readonly options: Options; |
| 64 | } |
| 65 | |
| 66 | type Sources<From extends ReadonlyArray<View.Source>> = From[number]; |
| 67 | |
| 68 | /** |
| 69 | * Structural constraint satisfied by every projection class. |
| 70 | */ |
| 71 | export interface Any extends Context.Key<unknown, unknown> { |
| 72 | readonly kind: "Projection"; |
| 73 | readonly projectionName: string; |
| 74 | readonly definition: { |
| 75 | readonly from: ReadonlyArray<View.Source>; |
| 76 | readonly key: Key.Any; |
| 77 | readonly keyOf?: { readonly [key: string]: unknown }; |
| 78 | readonly on: ReadonlyArray<Event.Any>; |
| 79 | readonly writes?: ReadonlyArray<DomainStream.Any>; |
| 80 | }; |
| 81 | /** The service that reports the projection's progress (`caughtUp`). */ |
| 82 | readonly Progress: Context.Key<unknown, Progress>; |
| 83 | } |
| 84 | |
| 85 | /** The input type of a projection class. */ |
| 86 | export type InputOf<P extends Any> = Input< |
| 87 | P["definition"]["key"], |
| 88 | Sources<P["definition"]["from"]>, |
| 89 | Aggregate.InstanceOf<P["definition"]["on"][number]> |
| 90 | >; |
| 91 | |
| 92 | /** The requirement identifier of a projection class. */ |
| 93 | export type Identifier<P extends Any> = P extends Context.Key<infer I, unknown> ? I : never; |
| 94 | |
| 95 | /** The requirement identifier of a projection's progress service. */ |
| 96 | export type ProgressIdentifier<P extends Any> = P extends Any |
| 97 | ? P["Progress"] extends Context.Key<infer I, unknown> |
| 98 | ? I |
| 99 | : never |
| 100 | : never; |
| 101 | |
| 102 | /** |
| 103 | * A projection's progress, provided by the hosted model. |
| 104 | */ |
| 105 | export interface Progress { |
| 106 | /** |
| 107 | * Whether the history recorded before this projection, or before its |
| 108 | * current version, has reached it (been accepted into its keys' logs). |
| 109 | */ |
| 110 | readonly history: Effect.Effect<View.History>; |
| 111 | /** |
| 112 | * Wait until the projection has handled every event of a command that it |
| 113 | * consumes, so a read of your store sees that write. |
| 114 | */ |
| 115 | readonly caughtUp: ( |
| 116 | receipt: { |
| 117 | readonly stream: string; |
| 118 | readonly version: number; |
| 119 | readonly events: ReadonlyArray<unknown>; |
| 120 | }, |
| 121 | options?: { readonly timeout?: Duration.Input }, |
| 122 | ) => Effect.Effect<void, View.ConsistencyTimeout>; |
| 123 | } |
| 124 | |
| 125 | /** |
| 126 | * Type-level identity of a projection in an Effect's requirements. |
| 127 | */ |
| 128 | export interface ProjectionKey<Name extends string> { |
| 129 | readonly "~alchemy/Domain/Projection": Name; |
| 130 | } |
| 131 | |
| 132 | /** Type-level identity of a projection's progress service. */ |
| 133 | export interface ProgressKey<Name extends string> { |
| 134 | readonly "~alchemy/Domain/Projection/Progress": Name; |
| 135 | } |
| 136 | |
| 137 | /** |
| 138 | * The pure definition of a projection: its invariants. |
| 139 | */ |
| 140 | export interface Definition< |
| 141 | From extends ReadonlyArray<View.Source>, |
| 142 | Key extends Key.Any, |
| 143 | On extends ReadonlyArray<Event.Any>, |
| 144 | Writes extends ReadonlyArray<DomainStream.Any>, |
| 145 | > { |
| 146 | /** The aggregates and views whose events it consumes. */ |
| 147 | readonly from: From; |
| 148 | /** |
| 149 | * What partitions it: an aggregate, whose refs are its keys, or a string |
| 150 | * Schema, whose values are. Inputs for one key are handled in order, one |
| 151 | * key at a time; keys run in parallel. |
| 152 | */ |
| 153 | readonly key: Key; |
| 154 | /** |
| 155 | * Which key each input goes to, by event tag or source name. May be omitted |
| 156 | * for a source keyed by the same aggregate or Schema. Return a ref (an |
| 157 | * aggregate key) or a value (a Schema key), or an object of named routes to |
| 158 | * send one event to several keys. |
| 159 | */ |
| 160 | readonly keyOf?: { |
| 161 | readonly [K in View.HandlerKey<From>]?: View.Routed<View.KeyFn<Key, View.InputFor<From, K>>>; |
| 162 | }; |
| 163 | /** The events it consumes. */ |
| 164 | readonly on: On; |
| 165 | /** The streams it appends to. Each stream has exactly one writer, keyed like it. */ |
| 166 | readonly writes?: Writes; |
| 167 | } |
| 168 | |
| 169 | /** |
| 170 | * Consumes events into a store you own: a database, a search index, a |
| 171 | * warehouse, or a `Domain.Stream`. Inputs are routed to keys and handled in |
| 172 | * order per key, at least once, and batched if its Layer says so. A projection |
| 173 | * never sends commands: replaying it must never act on the world again. |
| 174 | * |
| 175 | * The declaration holds what it means (sources, partitioning, events, the |
| 176 | * streams it writes). Its Layer holds how it runs: the handler, and options |
| 177 | * such as batching. |
| 178 | * |
| 179 | * ### Writing to a database |
| 180 | * **Example:** A ledger table, one row per movement |
| 181 | * ```typescript |
| 182 | * import * as Domain from "@alchemy.run/domain"; |
| 183 | * import * as Effect from "effect/Effect"; |
| 184 | * import { Account } from "./Account.ts"; |
| 185 | * import { MoneyDeposited } from "./DepositMoney.ts"; |
| 186 | * import { LedgerStore } from "./LedgerStore.ts"; |
| 187 | * |
| 188 | * export class Ledger extends Domain.Projection("Ledger", { |
| 189 | * from: [Account], |
| 190 | * key: Account, |
| 191 | * on: [MoneyDeposited], |
| 192 | * }) {} |
| 193 | * |
| 194 | * export const LedgerLive = Ledger.toLayer( |
| 195 | * Effect.gen(function* () { |
| 196 | * const store = yield* LedgerStore; |
| 197 | * return Effect.fn(function* (batch) { |
| 198 | * yield* store.upsert( |
| 199 | * batch.map(({ key, event, envelope }) => ({ |
| 200 | * id: `${envelope.stream}:${envelope.seq}`, |
| 201 | * account: key.id, |
| 202 | * amount: event.amount, |
| 203 | * })), |
| 204 | * ); |
| 205 | * }); |
| 206 | * }), |
| 207 | * { batch: { size: 500, wait: "2 seconds" } }, |
| 208 | * ); |
| 209 | * ``` |
| 210 | * |
| 211 | * ### Reading your own write |
| 212 | * **Example:** Wait for the projection before querying the store |
| 213 | * ```typescript |
| 214 | * const receipt = yield* accounts.send(accountId, new DepositMoney({ amount: 100 })); |
| 215 | * yield* Ledger.caughtUp(receipt); |
| 216 | * ``` |
| 217 | * |
| 218 | * @primitive |
| 219 | */ |
| 220 | export const make = < |
| 221 | const Name extends string, |
| 222 | const From extends ReadonlyArray<View.Source>, |
| 223 | Key extends Key.Any, |
| 224 | const On extends ReadonlyArray<Event.Any>, |
| 225 | const Writes extends ReadonlyArray<DomainStream.Any> = readonly [], |
| 226 | >( |
| 227 | name: Name, |
| 228 | definition: Definition<From, Key, On, Writes>, |
| 229 | ): ProjectionClass<Name, From, Key, On, Writes> => { |
| 230 | type I = Input<Key, Sources<From>, Aggregate.InstanceOf<On[number]>>; |
| 231 | const Tag = Context.Service<ProjectionKey<Name>, Implementation<I>>()( |
| 232 | `alchemy/Domain/Projection/${name}`, |
| 233 | ); |
| 234 | const Progress = Context.Service<ProgressKey<Name>, Progress>()( |
| 235 | `alchemy/Domain/Projection/${name}/Progress`, |
| 236 | ); |
| 237 | return class extends Tag { |
| 238 | static readonly kind = "Projection" as const; |
| 239 | static readonly projectionName: Name = name; |
| 240 | static readonly definition = definition; |
| 241 | static readonly Progress = Progress; |
| 242 | static caughtUp( |
| 243 | receipt: Parameters<Progress["caughtUp"]>[0], |
| 244 | options?: Parameters<Progress["caughtUp"]>[1], |
| 245 | ) { |
| 246 | return Effect.gen(function* () { |
| 247 | const progress = yield* Progress; |
| 248 | return yield* progress.caughtUp(receipt, options); |
| 249 | }); |
| 250 | } |
| 251 | static toLayer<E, R>(build: Effect.Effect<Handler<I>, E, R>, options: Options = {}) { |
| 252 | return Layer.effect( |
| 253 | Tag, |
| 254 | Effect.map(build, (handle): Implementation<I> => ({ handle, options })), |
| 255 | ); |
| 256 | } |
| 257 | } as unknown as ProjectionClass<Name, From, Key, On, Writes>; |
| 258 | }; |
| 259 | |
| 260 | /** |
| 261 | * The class type returned by {@link make}. |
| 262 | */ |
| 263 | export interface ProjectionClass< |
| 264 | Name extends string, |
| 265 | From extends ReadonlyArray<View.Source>, |
| 266 | Key extends Key.Any, |
| 267 | On extends ReadonlyArray<Event.Any>, |
| 268 | Writes extends ReadonlyArray<DomainStream.Any>, |
| 269 | > extends Context.ServiceClass< |
| 270 | ProjectionKey<Name>, |
| 271 | string, |
| 272 | Implementation<Input<Key, Sources<From>, Aggregate.InstanceOf<On[number]>>> |
| 273 | > { |
| 274 | readonly kind: "Projection"; |
| 275 | readonly projectionName: Name; |
| 276 | readonly definition: Definition<From, Key, On, Writes>; |
| 277 | readonly Progress: Context.Service<ProgressKey<Name>, Progress>; |
| 278 | /** |
| 279 | * Wait until this projection has handled every event of a command that it |
| 280 | * consumes. Provided by the hosted model. |
| 281 | */ |
| 282 | caughtUp( |
| 283 | receipt: Parameters<Progress["caughtUp"]>[0], |
| 284 | options?: Parameters<Progress["caughtUp"]>[1], |
| 285 | ): Effect.Effect<void, View.ConsistencyTimeout, ProgressKey<Name>>; |
| 286 | /** |
| 287 | * Implement the projection. The construction Effect runs once, resolving |
| 288 | * your store and the streams it writes; the handler requires nothing. |
| 289 | * `options` tune how it runs, such as batching. |
| 290 | */ |
| 291 | toLayer<E, R>( |
| 292 | build: Effect.Effect< |
| 293 | Handler<Input<Key, Sources<From>, Aggregate.InstanceOf<On[number]>>>, |
| 294 | E, |
| 295 | R |
| 296 | >, |
| 297 | options?: Options, |
| 298 | ): Layer.Layer<ProjectionKey<Name>, E, R>; |
| 299 | } |
| 300 | |
| 301 | /** @internal */ |
| 302 | export const batchMillis = (options: Options) => |
| 303 | options.batch |
| 304 | ? { |
| 305 | size: Math.max(1, options.batch.size), |
| 306 | waitMillis: options.batch.wait |
| 307 | ? Duration.toMillis(Duration.fromInputUnsafe(options.batch.wait)) |
| 308 | : 0, |
| 309 | } |
| 310 | : undefined; |