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
| 1 | import { CurrentActivity } from "alchemy/WorkflowEncoding"; |
| 2 | import * as Cause from "effect/Cause"; |
| 3 | import * as Context from "effect/Context"; |
| 4 | import * as Data from "effect/Data"; |
| 5 | import type * as DateTime from "effect/DateTime"; |
| 6 | import type * as Duration from "effect/Duration"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Option from "effect/Option"; |
| 9 | import * as Schema from "effect/Schema"; |
| 10 | import type * as Command from "./Command.ts"; |
| 11 | import { DefinitionError, UnhandledCommand } from "./DefinitionError.ts"; |
| 12 | import type * as Event from "./Event.ts"; |
| 13 | import { judge, settle, targetId as internalTargetId } from "./internal.ts"; |
| 14 | import type * as Middleware from "./Middleware.ts"; |
| 15 | import type * as Read from "./Read.ts"; |
| 16 | import type * as Rejection from "./Rejection.ts"; |
| 17 | import * as RequestContext from "./RequestContext.ts"; |
| 18 | import type * as Telemetry from "./Telemetry.ts"; |
| 19 | |
| 20 | /** |
| 21 | * The instance type of a class: `InstanceOf<typeof NotOwner>` is `NotOwner`. |
| 22 | * Distributes over a union of classes. |
| 23 | */ |
| 24 | export type InstanceOf<C> = C extends abstract new (...args: any[]) => infer I ? I : never; |
| 25 | |
| 26 | /** |
| 27 | * Context passed to every `decide` handler. |
| 28 | */ |
| 29 | export interface DecideContext<Id> { |
| 30 | /** The id of the aggregate instance handling the command. */ |
| 31 | readonly id: Id; |
| 32 | /** The id the command was sent with; its events' envelopes carry it too. */ |
| 33 | readonly commandId: string; |
| 34 | /** The stream the command's events commit to, e.g. `Account/a-1`. */ |
| 35 | readonly stream: string; |
| 36 | /** The stream's version before this decision: `0` for a new instance. */ |
| 37 | readonly version: number; |
| 38 | /** The time the command is being handled. Controlled by stories via `clock`. */ |
| 39 | readonly now: DateTime.Utc; |
| 40 | } |
| 41 | |
| 42 | /** |
| 43 | * Metadata recorded with every committed event. Its schema is what Api clients |
| 44 | * decode, so the wire carries every field. |
| 45 | */ |
| 46 | export const Envelope = Schema.Struct({ |
| 47 | /** The id of the aggregate instance that committed the event. */ |
| 48 | id: Schema.String, |
| 49 | /** The stream the event belongs to, e.g. `Account/a-1`. */ |
| 50 | stream: Schema.String, |
| 51 | /** The event's sequence number within its stream, starting at 1. */ |
| 52 | seq: Schema.Number, |
| 53 | /** The commit time. */ |
| 54 | at: Schema.DateTimeUtc, |
| 55 | /** The id of the command that produced the event. */ |
| 56 | commandId: Schema.String, |
| 57 | /** |
| 58 | * The id of the first command in the chain that led here: the same for a |
| 59 | * command, the events it records, and every reaction and command they cause. |
| 60 | */ |
| 61 | correlationId: Schema.String, |
| 62 | }); |
| 63 | |
| 64 | /** An {@link Envelope} whose `id` is the aggregate's (branded) id. */ |
| 65 | export type Envelope<Id = string> = typeof Envelope.Type & { readonly id: Id }; |
| 66 | |
| 67 | /** |
| 68 | * The outcome of a successfully handled command. |
| 69 | */ |
| 70 | export interface Receipt<Ev = unknown, Reply = unknown> { |
| 71 | /** The stream the command was applied to, e.g. `Account/a-1`. */ |
| 72 | readonly stream: string; |
| 73 | /** The stream's version (last sequence number) after the command. */ |
| 74 | readonly version: number; |
| 75 | /** The events committed by the command (empty for an accepted no-op). */ |
| 76 | readonly events: ReadonlyArray<Ev>; |
| 77 | /** The command's reply, if it declares one. */ |
| 78 | readonly reply: Reply; |
| 79 | } |
| 80 | |
| 81 | /** |
| 82 | * What {@link Client.schedule} returns: the pending command's id, to |
| 83 | * `unschedule` it by, and when it is due. |
| 84 | */ |
| 85 | export interface ScheduleReceipt { |
| 86 | /** The command id: the one passed in `options`, or the one derived for it. */ |
| 87 | readonly commandId: string; |
| 88 | /** When the command is due, on the platform's clock. */ |
| 89 | readonly at: DateTime.Utc; |
| 90 | } |
| 91 | |
| 92 | type ByTag<U, T> = Extract<U, { readonly tag: T }>; |
| 93 | type ReplyTags<C extends Command.Any> = C extends { |
| 94 | readonly reply: Schema.Top; |
| 95 | readonly tag: infer T extends string; |
| 96 | } |
| 97 | ? T |
| 98 | : never; |
| 99 | |
| 100 | type IdSchema = Schema.Top & { readonly Type: string; readonly Encoded: string }; |
| 101 | |
| 102 | /** |
| 103 | * What `decide` returns for a command: events, a rejection, or an Effect of |
| 104 | * either. The Effect may read what the command's middleware provides. |
| 105 | */ |
| 106 | export type Decision<C extends Command.Any> = |
| 107 | | ReadonlyArray<InstanceOf<C["events"][number]>> |
| 108 | | InstanceOf<C["rejects"][number]> |
| 109 | | Effect.Effect< |
| 110 | ReadonlyArray<InstanceOf<C["events"][number]>>, |
| 111 | InstanceOf<C["rejects"][number]>, |
| 112 | Command.ContextOf<C> |
| 113 | >; |
| 114 | |
| 115 | /** The event classes a set of commands may record. */ |
| 116 | export type EventsOf<C extends ReadonlyArray<Command.Any>> = C[number]["events"][number]; |
| 117 | |
| 118 | /** |
| 119 | * The pure definition of an aggregate: identity, state, the commands it |
| 120 | * decides and the events it folds. Its events are those its commands declare. |
| 121 | */ |
| 122 | export interface Definition< |
| 123 | Id extends IdSchema, |
| 124 | S extends Schema.Top, |
| 125 | C extends ReadonlyArray<Command.Any>, |
| 126 | Ms extends Middleware.List = readonly [], |
| 127 | Rejects extends ReadonlyArray<Rejection.Any> = readonly [], |
| 128 | E extends Event.Any = EventsOf<C>, |
| 129 | > { |
| 130 | /** Schema of the aggregate id (a string or branded string). */ |
| 131 | readonly id: Id; |
| 132 | /** Schema of the aggregate's state. Used to persist snapshots. */ |
| 133 | readonly state: S; |
| 134 | /** The state of an instance that has never committed an event. */ |
| 135 | readonly initial: S["Type"]; |
| 136 | /** Every command this aggregate handles, each declaring the events it records. */ |
| 137 | readonly commands: C; |
| 138 | /** |
| 139 | * One handler per command: returns the events to commit (from the command's |
| 140 | * declared events), an empty array for an accepted no-op, or one of the |
| 141 | * command's declared rejections. A handler may be an Effect that reads the |
| 142 | * context its command's middleware provides (e.g. `yield* CurrentActor`) |
| 143 | * and fails with a rejection; it may require nothing else. |
| 144 | */ |
| 145 | readonly decide: { |
| 146 | readonly [T in C[number]["tag"]]: ( |
| 147 | state: S["Type"], |
| 148 | command: InstanceOf<ByTag<C[number], T>>, |
| 149 | ctx: DecideContext<Id["Type"]>, |
| 150 | ) => Decision<ByTag<C[number], T>>; |
| 151 | }; |
| 152 | /** |
| 153 | * One handler per event: folds a committed event into state. It covers |
| 154 | * every state and never fails: `decide` refuses a command with a rejection |
| 155 | * before it records an event, so a handler keeps a state its event can't |
| 156 | * follow. |
| 157 | */ |
| 158 | readonly evolve: { |
| 159 | readonly [T in E["tag"]]: ( |
| 160 | state: S["Type"], |
| 161 | event: InstanceOf<ByTag<E, T>>, |
| 162 | envelope: Envelope<Id["Type"]>, |
| 163 | ) => S["Type"]; |
| 164 | }; |
| 165 | /** |
| 166 | * One handler per command that declares a reply: computes it from the |
| 167 | * updated state and the committed events. Like `evolve`, it covers every |
| 168 | * state and never fails. |
| 169 | */ |
| 170 | readonly reply?: { |
| 171 | readonly [T in ReplyTags<C[number]>]: ( |
| 172 | state: S["Type"], |
| 173 | events: ReadonlyArray<InstanceOf<E>>, |
| 174 | ) => NonNullable<ByTag<C[number], T>["reply"]>["Type"]; |
| 175 | }; |
| 176 | /** |
| 177 | * Let an Api expose this aggregate's state and committed events to clients |
| 178 | * (`get`, `watch`, `events`): its middleware, rejections, and `validate`, |
| 179 | * which judges each read against the instance's current state. |
| 180 | */ |
| 181 | readonly read?: Read.Contract<{ readonly id: Id["Type"] }, S["Type"], Ms, Rejects>; |
| 182 | } |
| 183 | |
| 184 | /** |
| 185 | * Type-level identity of an aggregate in an Effect's requirements. |
| 186 | */ |
| 187 | export interface Key<Name extends string> { |
| 188 | readonly "~alchemy/Domain/Aggregate": Name; |
| 189 | } |
| 190 | |
| 191 | /** |
| 192 | * Options for {@link Client.send}. |
| 193 | */ |
| 194 | export interface SendOptions { |
| 195 | /** Idempotency key. A command with an already-seen id returns the original receipt. */ |
| 196 | readonly commandId?: string; |
| 197 | } |
| 198 | |
| 199 | /** |
| 200 | * The instance already handled a command with this id, so it can no longer |
| 201 | * be scheduled or cancelled: a deadline that fired before it was cancelled, |
| 202 | * or a command id that was already sent. |
| 203 | */ |
| 204 | export class AlreadyExecuted extends Data.TaggedError("AlreadyExecuted")<{ |
| 205 | readonly aggregate: string; |
| 206 | readonly id: string; |
| 207 | readonly commandId: string; |
| 208 | }> {} |
| 209 | |
| 210 | /** The scheduled command with this id was already cancelled. */ |
| 211 | export class AlreadyCancelled extends Data.TaggedError("AlreadyCancelled")<{ |
| 212 | readonly aggregate: string; |
| 213 | readonly id: string; |
| 214 | readonly commandId: string; |
| 215 | }> {} |
| 216 | |
| 217 | /** No command was ever scheduled with this id on the instance. */ |
| 218 | export class NotScheduled extends Data.TaggedError("NotScheduled")<{ |
| 219 | readonly aggregate: string; |
| 220 | readonly id: string; |
| 221 | readonly commandId: string; |
| 222 | }> {} |
| 223 | |
| 224 | /** |
| 225 | * Options for {@link Client.schedule}: when to send, absolutely or after a delay. |
| 226 | */ |
| 227 | export type ScheduleOptions = SendOptions & |
| 228 | ( |
| 229 | | { readonly at: DateTime.Utc; readonly after?: never } |
| 230 | | { readonly after: Duration.Input; readonly at?: never } |
| 231 | ); |
| 232 | |
| 233 | /** |
| 234 | * When a scheduled command is due: an epoch-millisecond time, or a delay the |
| 235 | * platform measures on its own clock (stories control it with `clock`). |
| 236 | */ |
| 237 | export type Due = { readonly at: number } | { readonly afterMillis: number }; |
| 238 | |
| 239 | /** |
| 240 | * Metadata a platform receives with every command. |
| 241 | */ |
| 242 | export interface SendMeta { |
| 243 | readonly commandId: string; |
| 244 | /** The command context services the sender provided, encoded. */ |
| 245 | readonly context: RequestContext.Json; |
| 246 | /** The flow the command belongs to (see {@link Envelope.correlationId}). */ |
| 247 | readonly correlationId?: string; |
| 248 | /** The span that sent the command, so the aggregate's span continues its trace. */ |
| 249 | readonly trace?: Telemetry.TraceJson; |
| 250 | /** Link to `trace` instead of continuing it: the command runs later (scheduled). */ |
| 251 | readonly link?: boolean; |
| 252 | } |
| 253 | |
| 254 | type AnyHandlers = { readonly [tag: string]: (...args: never[]) => unknown }; |
| 255 | |
| 256 | /** |
| 257 | * The widened shape of every {@link Definition}. |
| 258 | */ |
| 259 | export interface AnyDefinition { |
| 260 | readonly id: IdSchema; |
| 261 | readonly state: Schema.Top; |
| 262 | readonly initial: unknown; |
| 263 | readonly commands: ReadonlyArray<Command.Any>; |
| 264 | readonly events: ReadonlyArray<Event.Any>; |
| 265 | readonly decide: AnyHandlers; |
| 266 | readonly evolve: AnyHandlers; |
| 267 | readonly reply?: AnyHandlers; |
| 268 | readonly read?: Read.AnyContract; |
| 269 | } |
| 270 | |
| 271 | /** An aggregate instance to address: its id, or a ref carrying it. */ |
| 272 | export type Target<Def extends AnyDefinition> = |
| 273 | | Def["id"]["Type"] |
| 274 | | { readonly id: Def["id"]["Type"] }; |
| 275 | |
| 276 | type CommandClassOf<Def extends AnyDefinition, Cmd> = ByTag< |
| 277 | Def["commands"][number], |
| 278 | Cmd extends { readonly _tag: infer T } ? T : never |
| 279 | >; |
| 280 | |
| 281 | type ReplyOf<C> = C extends { readonly reply: infer R } |
| 282 | ? R extends Schema.Top |
| 283 | ? R["Type"] |
| 284 | : void |
| 285 | : void; |
| 286 | |
| 287 | /** |
| 288 | * The runtime API of an aggregate, obtained with `yield* MyAggregate`. Resolve |
| 289 | * it once while building a policy or an operation, then call it per event or |
| 290 | * request; its methods require nothing. |
| 291 | * |
| 292 | * **Example:** Sending a command |
| 293 | * ```typescript |
| 294 | * const accounts = yield* Account; |
| 295 | * const { reply } = yield* accounts.send(accountId, new WithdrawMoney({ amount: 30 })); |
| 296 | * ``` |
| 297 | */ |
| 298 | export interface Client<Def extends AnyDefinition> { |
| 299 | /** |
| 300 | * Send a command. Succeeds with a {@link Receipt} once the resulting events |
| 301 | * are committed, or fails with one of the command's declared rejections. |
| 302 | * Requires the context the command's middleware provides (e.g. the current |
| 303 | * actor): an Api's middleware provides it, other senders provide it. |
| 304 | */ |
| 305 | readonly send: <Cmd extends InstanceOf<Def["commands"][number]>>( |
| 306 | target: Target<Def>, |
| 307 | command: Cmd, |
| 308 | options?: SendOptions, |
| 309 | ) => Effect.Effect< |
| 310 | Receipt<InstanceOf<Def["events"][number]>, ReplyOf<CommandClassOf<Def, Cmd>>>, |
| 311 | InstanceOf<CommandClassOf<Def, Cmd>["rejects"][number]>, |
| 312 | Command.ContextOf<CommandClassOf<Def, Cmd>> |
| 313 | >; |
| 314 | /** |
| 315 | * Send a command later, durably: a deadline or a reminder. Only commands |
| 316 | * that never reject can be scheduled, since nobody is waiting to handle a |
| 317 | * rejection when it fires; such a command reports a fact ("the approval |
| 318 | * window closed") and records nothing when it no longer applies. |
| 319 | * Scheduling again with the same command id replaces the earlier one. |
| 320 | * Returns the command id to `unschedule` it by, and when it is due. Fails with `AlreadyExecuted` when the instance already handled a command |
| 321 | * with that id. |
| 322 | */ |
| 323 | readonly schedule: <Cmd extends InstanceOf<Schedulable<Def>>>( |
| 324 | target: Target<Def>, |
| 325 | command: Cmd, |
| 326 | options: ScheduleOptions, |
| 327 | ) => Effect.Effect<ScheduleReceipt, AlreadyExecuted, Command.ContextOf<CommandClassOf<Def, Cmd>>>; |
| 328 | /** |
| 329 | * Cancel a pending scheduled command by the command id it was scheduled |
| 330 | * with. Once it succeeds, the command never runs. Fails with |
| 331 | * `AlreadyExecuted` when the command ran first, `AlreadyCancelled` when it |
| 332 | * was cancelled before, and `NotScheduled` when nothing was scheduled with |
| 333 | * that id. |
| 334 | */ |
| 335 | readonly unschedule: ( |
| 336 | target: Target<Def>, |
| 337 | commandId: string, |
| 338 | ) => Effect.Effect<void, AlreadyExecuted | AlreadyCancelled | NotScheduled>; |
| 339 | /** Read the current state of an instance. */ |
| 340 | readonly state: (target: Target<Def>) => Effect.Effect<Def["state"]["Type"]>; |
| 341 | } |
| 342 | |
| 343 | /** The commands of a definition that never reject, so can be scheduled. */ |
| 344 | export type Schedulable<Def extends AnyDefinition> = Extract< |
| 345 | Def["commands"][number], |
| 346 | { readonly rejects: readonly [] } |
| 347 | >; |
| 348 | |
| 349 | /** |
| 350 | * The untyped form of {@link Client} the framework implements. |
| 351 | * |
| 352 | * @internal |
| 353 | */ |
| 354 | export interface ClientImpl { |
| 355 | readonly send: ( |
| 356 | target: unknown, |
| 357 | command: { readonly _tag: string }, |
| 358 | options?: SendOptions, |
| 359 | ) => Effect.Effect<Receipt, unknown>; |
| 360 | readonly schedule: ( |
| 361 | target: unknown, |
| 362 | command: { readonly _tag: string }, |
| 363 | options: ScheduleOptions, |
| 364 | ) => Effect.Effect<ScheduleReceipt, AlreadyExecuted>; |
| 365 | readonly unschedule: ( |
| 366 | target: unknown, |
| 367 | commandId: string, |
| 368 | ) => Effect.Effect<void, AlreadyExecuted | AlreadyCancelled | NotScheduled>; |
| 369 | readonly state: (target: unknown) => Effect.Effect<unknown>; |
| 370 | } |
| 371 | |
| 372 | /** |
| 373 | * Structural constraint satisfied by every aggregate class. |
| 374 | */ |
| 375 | export interface Any extends Context.Key<unknown, unknown> { |
| 376 | readonly kind: "Aggregate"; |
| 377 | readonly aggregateName: string; |
| 378 | readonly definition: AnyDefinition; |
| 379 | } |
| 380 | |
| 381 | /** The id type of an aggregate class. */ |
| 382 | export type IdOf<A extends Any> = A["definition"]["id"]["Type"]; |
| 383 | /** The state type of an aggregate class. */ |
| 384 | export type StateOf<A extends Any> = A["definition"]["state"]["Type"]; |
| 385 | /** The event instance types of an aggregate class. */ |
| 386 | export type EventOf<A extends Any> = InstanceOf<A["definition"]["events"][number]>; |
| 387 | /** The command instance types of an aggregate class. */ |
| 388 | export type CommandOf<A extends Any> = InstanceOf<A["definition"]["commands"][number]>; |
| 389 | /** The requirement identifier of an aggregate class. */ |
| 390 | export type Identifier<A extends Any> = A extends Context.Key<infer I, unknown> ? I : never; |
| 391 | |
| 392 | /** |
| 393 | * Options for {@link predict}: what the server would give `decide`. A command |
| 394 | * with middleware needs `context`: what its middleware provides, from a |
| 395 | * client-side Layer of the same services. |
| 396 | */ |
| 397 | export type PredictOptions<Id = string, R = never> = PredictBase<Id> & |
| 398 | ([R] extends [never] |
| 399 | ? { readonly context?: Context.Context<never> } |
| 400 | : { readonly context: Context.Context<R> }); |
| 401 | |
| 402 | interface PredictBase<Id> { |
| 403 | /** The id of the instance the command targets. */ |
| 404 | readonly id: Id; |
| 405 | /** The time the command is decided at (the server stamps commands with its clock). */ |
| 406 | readonly now: DateTime.Utc; |
| 407 | /** The state's version: `decide` sees it, and predicted envelopes continue from it. Defaults to `0`. */ |
| 408 | readonly version?: number; |
| 409 | /** The id the command will be sent with, for `decide` and the predicted envelopes. Defaults to `""`. */ |
| 410 | readonly commandId?: string; |
| 411 | /** Defaults to the command id. */ |
| 412 | readonly correlationId?: string; |
| 413 | } |
| 414 | |
| 415 | /** |
| 416 | * What the aggregate would do with a command, decided locally: the events it |
| 417 | * would record and the state after them, the rejection it would return, or |
| 418 | * `Unpredictable` when only the server can tell. `cause` says why: `decide` |
| 419 | * waited on something asynchronous (the server awaits it; `predict` is |
| 420 | * synchronous), died, or broke its command's declaration through a cast (a |
| 421 | * `DefinitionError`, which the server dies on). |
| 422 | */ |
| 423 | export type Prediction<State, Ev, Rej, Id = string> = |
| 424 | | { |
| 425 | readonly _tag: "Accepted"; |
| 426 | readonly events: ReadonlyArray<Ev>; |
| 427 | /** One envelope per event, as the server would stamp it (`seq` from `version`). */ |
| 428 | readonly envelopes: ReadonlyArray<Envelope<Id>>; |
| 429 | readonly state: State; |
| 430 | } |
| 431 | | { readonly _tag: "Rejected"; readonly rejection: Rej } |
| 432 | | { readonly _tag: "Unpredictable"; readonly cause: Cause.Cause<unknown> }; |
| 433 | |
| 434 | /** |
| 435 | * Run an aggregate's own `decide` and `evolve` for one command, without a |
| 436 | * platform: the same events and state, or the same rejection, as the server |
| 437 | * for the same state, id and time. Use it to show a command's outcome before |
| 438 | * the server answers. |
| 439 | * |
| 440 | * An effectful decision runs here synchronously, as the kernel runs it: a |
| 441 | * rejection fails with itself, and a `decide` that suspends or dies gives |
| 442 | * `Unpredictable`. `predict` never throws. |
| 443 | */ |
| 444 | export const predict = ( |
| 445 | aggregate: Any, |
| 446 | state: unknown, |
| 447 | command: { readonly _tag: string }, |
| 448 | options: PredictOptions, |
| 449 | ): Prediction<unknown, { readonly _tag: string }, { readonly _tag: string }> => { |
| 450 | const def = aggregate.definition; |
| 451 | const cls = def.commands.find((c) => c.tag === command._tag); |
| 452 | const decide = def.decide[command._tag] as |
| 453 | | ((state: unknown, command: unknown, ctx: DecideContext<unknown>) => unknown) |
| 454 | | undefined; |
| 455 | if (!cls || !decide) { |
| 456 | return { |
| 457 | _tag: "Unpredictable", |
| 458 | cause: Cause.die( |
| 459 | new DefinitionError({ |
| 460 | reason: new UnhandledCommand({ |
| 461 | aggregate: aggregate.aggregateName, |
| 462 | command: command._tag, |
| 463 | }), |
| 464 | }), |
| 465 | ), |
| 466 | }; |
| 467 | } |
| 468 | const version = options.version ?? 0; |
| 469 | const commandId = options.commandId ?? ""; |
| 470 | const stream = `${aggregate.aggregateName}/${String(options.id)}`; |
| 471 | let decision = decide(state, command, { |
| 472 | id: options.id, |
| 473 | now: options.now, |
| 474 | commandId, |
| 475 | stream, |
| 476 | version, |
| 477 | }); |
| 478 | if (Effect.isEffect(decision)) { |
| 479 | const settled = decision.pipe( |
| 480 | Effect.provideContext((options.context ?? Context.empty()) as Context.Context<unknown>), |
| 481 | Effect.runSyncExit, |
| 482 | settle, |
| 483 | ); |
| 484 | if (settled._tag === "Failed") return { _tag: "Unpredictable", cause: settled.cause }; |
| 485 | decision = settled.decision; |
| 486 | } |
| 487 | const judged = judge(aggregate.aggregateName, cls, decision); |
| 488 | if (judged._tag === "Undeclared") |
| 489 | return { _tag: "Unpredictable", cause: Cause.die(judged.error) }; |
| 490 | if (judged._tag === "Rejected") return judged; |
| 491 | const envelopes: Array<Envelope> = []; |
| 492 | let next = state; |
| 493 | judged.events.forEach((event, index) => { |
| 494 | const envelope: Envelope = { |
| 495 | id: options.id, |
| 496 | stream, |
| 497 | seq: version + index + 1, |
| 498 | at: options.now, |
| 499 | commandId, |
| 500 | correlationId: options.correlationId ?? commandId, |
| 501 | }; |
| 502 | envelopes.push(envelope); |
| 503 | next = (def.evolve[event._tag] as (s: unknown, e: unknown, env: unknown) => unknown)( |
| 504 | next, |
| 505 | event, |
| 506 | envelope, |
| 507 | ); |
| 508 | }); |
| 509 | return { _tag: "Accepted", events: judged.events, envelopes, state: next }; |
| 510 | }; |
| 511 | |
| 512 | const RefClass = Symbol.for("alchemy/Domain/Ref.class"); |
| 513 | |
| 514 | /** |
| 515 | * A typed address of one aggregate instance: aggregate type plus id. |
| 516 | */ |
| 517 | export interface Ref<A extends Any = Any> { |
| 518 | readonly aggregate: A["aggregateName"]; |
| 519 | readonly id: IdOf<A>; |
| 520 | readonly [RefClass]: A; |
| 521 | } |
| 522 | |
| 523 | /** @internal */ |
| 524 | export const refClass = <A extends Any>(ref: Ref<A>): A => ref[RefClass]; |
| 525 | |
| 526 | /** |
| 527 | * One entity that decides, such as a bank account: a consistency boundary. |
| 528 | * It takes a command, checks it against its current state, and records events |
| 529 | * or returns a rejection. Each instance handles one command at a time, and |
| 530 | * its events, new state and reply commit together. |
| 531 | * |
| 532 | * ### Deciding and evolving |
| 533 | * **Example:** An account that refuses overdrafts |
| 534 | * ```typescript |
| 535 | * import * as Domain from "@alchemy.run/domain"; |
| 536 | * import * as Schema from "effect/Schema"; |
| 537 | * |
| 538 | * export const AccountId = Schema.String.pipe(Schema.brand("AccountId")); |
| 539 | * |
| 540 | * export class MoneyWithdrawn extends Domain.Event("MoneyWithdrawn", { |
| 541 | * amount: Schema.Int, |
| 542 | * balanceAfter: Schema.Int, |
| 543 | * }) {} |
| 544 | * |
| 545 | * export class InsufficientFunds extends Domain.Rejection("InsufficientFunds", { |
| 546 | * balance: Schema.Int, |
| 547 | * requested: Schema.Int, |
| 548 | * }) {} |
| 549 | * |
| 550 | * export class WithdrawMoney extends Domain.Command("WithdrawMoney", { |
| 551 | * target: AccountId, |
| 552 | * input: { amount: Schema.Int }, |
| 553 | * events: [MoneyWithdrawn], |
| 554 | * rejects: [InsufficientFunds], |
| 555 | * reply: { balance: Schema.Int }, |
| 556 | * }) {} |
| 557 | * |
| 558 | * export class Account extends Domain.Aggregate("Account", { |
| 559 | * id: AccountId, |
| 560 | * state: Schema.Struct({ balance: Schema.Int }), |
| 561 | * initial: { balance: 0 }, |
| 562 | * commands: [WithdrawMoney], |
| 563 | * decide: { |
| 564 | * WithdrawMoney: (s, cmd) => |
| 565 | * cmd.amount > s.balance |
| 566 | * ? new InsufficientFunds({ balance: s.balance, requested: cmd.amount }) |
| 567 | * : [new MoneyWithdrawn({ amount: cmd.amount, balanceAfter: s.balance - cmd.amount })], |
| 568 | * }, |
| 569 | * evolve: { |
| 570 | * MoneyWithdrawn: (_, e) => ({ balance: e.balanceAfter }), |
| 571 | * }, |
| 572 | * reply: { |
| 573 | * WithdrawMoney: (s) => ({ balance: s.balance }), |
| 574 | * }, |
| 575 | * }) {} |
| 576 | * ``` |
| 577 | * |
| 578 | * ### Authorizing in decide |
| 579 | * A handler can be an `Effect.fn` that reads what the command's middleware |
| 580 | * provides. |
| 581 | * |
| 582 | * **Example:** Only the owner may withdraw |
| 583 | * ```typescript |
| 584 | * decide: { |
| 585 | * WithdrawMoney: Effect.fn(function* (s, cmd) { |
| 586 | * const actor = yield* CurrentActor; |
| 587 | * if (actor.customerId !== s.owner) return yield* new NotOwner(); |
| 588 | * return [new MoneyWithdrawn({ amount: cmd.amount, balanceAfter: s.balance - cmd.amount })]; |
| 589 | * }), |
| 590 | * }, |
| 591 | * ``` |
| 592 | * |
| 593 | * ### Exposing reads |
| 594 | * `read` lets an Api expose the aggregate itself, so a client can get it, |
| 595 | * watch it, and follow its events. `validate` judges every read. |
| 596 | * |
| 597 | * **Example:** A read contract |
| 598 | * ```typescript |
| 599 | * read: { |
| 600 | * middleware: [Session], |
| 601 | * rejects: [NotOwner], |
| 602 | * validate: Effect.fn(function* (_request, s) { |
| 603 | * const actor = yield* CurrentActor; |
| 604 | * if (actor.customerId !== s.owner) return yield* new NotOwner(); |
| 605 | * }), |
| 606 | * }, |
| 607 | * ``` |
| 608 | * |
| 609 | * ### Sending and scheduling |
| 610 | * **Example:** From a policy or your own code |
| 611 | * ```typescript |
| 612 | * const accounts = yield* Account; |
| 613 | * const { reply } = yield* accounts.send(accountId, new WithdrawMoney({ amount: 30 })); |
| 614 | * yield* accounts.schedule(accountId, new SendStatement(), { after: "30 days", commandId: "statement" }); |
| 615 | * yield* accounts.unschedule(accountId, "statement"); // cancel it while it is pending |
| 616 | * ``` |
| 617 | * |
| 618 | * @primitive |
| 619 | */ |
| 620 | export const makeRef = <A extends Any>(aggregate: A, id: IdOf<A>): Ref<A> => { |
| 621 | const ref = { aggregate: aggregate.aggregateName, id } as Ref<A>; |
| 622 | Object.defineProperty(ref, RefClass, { value: aggregate, enumerable: false }); |
| 623 | return ref; |
| 624 | }; |
| 625 | |
| 626 | /** The stream id of a ref, e.g. `Account/a-1`. */ |
| 627 | export const streamOf = (ref: { readonly aggregate: string; readonly id: string }) => |
| 628 | `${ref.aggregate}/${ref.id}`; |
| 629 | |
| 630 | /** The id addressed by a {@link Target}. @internal */ |
| 631 | export const targetId = internalTargetId; |
| 632 | |
| 633 | /** |
| 634 | * Deterministic command ids for sends made while a policy handles a trigger, |
| 635 | * so a re-run of the same trigger is deduplicated by the target aggregate. |
| 636 | * |
| 637 | * @internal |
| 638 | */ |
| 639 | export class PolicyRun extends Context.Service<PolicyRun, { readonly next: () => string }>()( |
| 640 | "alchemy/Domain/PolicyRun", |
| 641 | ) {} |
| 642 | |
| 643 | /** |
| 644 | * The command id for a send: the caller's; inside a saga step, the step's |
| 645 | * next id, so a step that runs again sends the same commands; the policy |
| 646 | * run's next deterministic id; or a fresh one. |
| 647 | * |
| 648 | * @internal |
| 649 | */ |
| 650 | export const commandIdFor = (options: SendOptions | undefined): Effect.Effect<string> => |
| 651 | options?.commandId !== undefined |
| 652 | ? Effect.succeed(options.commandId) |
| 653 | : Effect.gen(function* () { |
| 654 | // A step is the narrower scope: a saga started by a policy runs inside it. |
| 655 | const step = yield* Effect.serviceOption(CurrentActivity); |
| 656 | if (Option.isSome(step)) return step.value.next(); |
| 657 | const policy = yield* Effect.serviceOption(PolicyRun); |
| 658 | if (Option.isSome(policy)) return policy.value.next(); |
| 659 | return yield* Effect.sync(() => crypto.randomUUID()); |
| 660 | }); |
| 661 | |
| 662 | /** |
| 663 | * Declare an aggregate: a consistency boundary keyed by id that decides |
| 664 | * commands against its current state and records events. |
| 665 | * |
| 666 | * The class is also a service tag: `yield* Customer` gives its {@link Client} |
| 667 | * (`send`, `state`), provided by the Domain's Layer. |
| 668 | * |
| 669 | * **Example:** Declaring an aggregate |
| 670 | * ```typescript |
| 671 | * export class Customer extends Domain.Aggregate("Customer", { |
| 672 | * id: CustomerId, |
| 673 | * state: CustomerState, |
| 674 | * initial: { _tag: "New" }, |
| 675 | * commands: [Register], // declares events: [CustomerRegistered] |
| 676 | * decide: { |
| 677 | * Register: (s, cmd) => |
| 678 | * s._tag === "Registered" ? new AlreadyRegistered() : [new CustomerRegistered({ name: cmd.name })], |
| 679 | * }, |
| 680 | * evolve: { |
| 681 | * CustomerRegistered: (_, e) => ({ _tag: "Registered", name: e.name }), |
| 682 | * }, |
| 683 | * }) {} |
| 684 | * |
| 685 | * const customers = yield* Customer; |
| 686 | * yield* customers.send("c-1", new Register({ name: "sam" })); |
| 687 | * ``` |
| 688 | */ |
| 689 | export const make = < |
| 690 | const Name extends string, |
| 691 | Id extends IdSchema, |
| 692 | S extends Schema.Top, |
| 693 | const C extends ReadonlyArray<Command.Any>, |
| 694 | const Ms extends Middleware.List = readonly [], |
| 695 | const Rejects extends ReadonlyArray<Rejection.Any> = readonly [], |
| 696 | // The declared `read`, inferred apart from `Definition` so the type records it. |
| 697 | // Its constraint carries no members, so it never narrows how `read` is typed. |
| 698 | const R extends object | undefined = object | undefined, |
| 699 | >( |
| 700 | name: Name, |
| 701 | definition: Definition<Id, S, C, Ms, Rejects> & TargetsMatch<Id, C> & { readonly read?: R }, |
| 702 | ): AggregateClass<Name, Resolved<Id, S, C, Ms, Rejects, ReadOf<R>>> => { |
| 703 | const Tag = Context.Service<Key<Name>, Client<Resolved<Id, S, C, Ms, Rejects, ReadOf<R>>>>()( |
| 704 | `alchemy/Domain/Aggregate/${name}`, |
| 705 | ); |
| 706 | // oxlint-disable-next-line effecttsgo/schema-sync -- ids decode synchronously when building refs |
| 707 | const decodeId = Schema.decodeUnknownSync( |
| 708 | definition.id as unknown as Schema.Codec<unknown, unknown>, |
| 709 | ); |
| 710 | return class extends Tag { |
| 711 | static readonly kind = "Aggregate" as const; |
| 712 | static readonly aggregateName: Name = name; |
| 713 | static readonly definition: Resolved<Id, S, C, Ms, Rejects, ReadOf<R>> = { |
| 714 | ...definition, |
| 715 | events: [...new Set(definition.commands.flatMap((command) => command.events))], |
| 716 | } as unknown as Resolved<Id, S, C, Ms, Rejects, ReadOf<R>>; |
| 717 | /** Address one instance of this aggregate. */ |
| 718 | static ref<Self extends Any>(this: Self, id: Self["definition"]["id"]["Encoded"]): Ref<Self> { |
| 719 | return makeRef(this, decodeId(id) as IdOf<Self>); |
| 720 | } |
| 721 | /** Decide a command locally. See {@link predict}. */ |
| 722 | static predict( |
| 723 | this: Any, |
| 724 | state: unknown, |
| 725 | command: { readonly _tag: string }, |
| 726 | options: PredictOptions, |
| 727 | ) { |
| 728 | return predict(this, state, command, options); |
| 729 | } |
| 730 | } as unknown as AggregateClass<Name, Resolved<Id, S, C, Ms, Rejects, ReadOf<R>>>; |
| 731 | }; |
| 732 | |
| 733 | /** |
| 734 | * A command whose `target` is the aggregate's `id`, both ways; any other |
| 735 | * command becomes a message naming it. |
| 736 | */ |
| 737 | type CheckTarget<Id extends IdSchema, Cmd> = Cmd extends Command.Any |
| 738 | ? [Id["Type"]] extends [Cmd["target"]["Type"]] |
| 739 | ? [Cmd["target"]["Type"]] extends [Id["Type"]] |
| 740 | ? Cmd |
| 741 | : `${Cmd["tag"]}'s target must be this aggregate's id schema` |
| 742 | : `${Cmd["tag"]}'s target must be this aggregate's id schema` |
| 743 | : Cmd; |
| 744 | |
| 745 | /** |
| 746 | * Every command's `target` must be the aggregate's `id`: an Api decodes the |
| 747 | * target with the command's schema and the aggregate decodes it with its own. |
| 748 | * A mismatched command is a type error on its entry in `commands`. |
| 749 | */ |
| 750 | export type TargetsMatch<Id extends IdSchema, C extends ReadonlyArray<Command.Any>> = { |
| 751 | readonly commands: { readonly [K in keyof C]: CheckTarget<Id, C[K]> }; |
| 752 | }; |
| 753 | |
| 754 | /** |
| 755 | * The `read` an aggregate declared, or `undefined`. With none declared, `R` |
| 756 | * is left at its default, which includes `undefined`; a declared contract |
| 757 | * never does. |
| 758 | */ |
| 759 | type ReadOf<R> = undefined extends R ? undefined : R; |
| 760 | |
| 761 | /** |
| 762 | * A definition with its events collected from its commands. `R` is the |
| 763 | * `read` it declared, or `undefined`: an aggregate that declares one has a |
| 764 | * required `read` in its type, so an Api can tell which aggregates it may |
| 765 | * serve. |
| 766 | */ |
| 767 | export type Resolved< |
| 768 | Id extends IdSchema, |
| 769 | S extends Schema.Top, |
| 770 | C extends ReadonlyArray<Command.Any>, |
| 771 | Ms extends Middleware.List = readonly [], |
| 772 | Rejects extends ReadonlyArray<Rejection.Any> = readonly [], |
| 773 | R extends Read.AnyContract | undefined = Read.AnyContract | undefined, |
| 774 | > = Definition<Id, S, C, Ms, Rejects> & { |
| 775 | readonly events: ReadonlyArray<EventsOf<C>>; |
| 776 | readonly read: R; |
| 777 | }; |
| 778 | |
| 779 | /** |
| 780 | * The class type returned by {@link make}. |
| 781 | */ |
| 782 | export interface AggregateClass< |
| 783 | Name extends string, |
| 784 | Def extends AnyDefinition, |
| 785 | > extends Context.ServiceClass<Key<Name>, string, Client<Def>> { |
| 786 | readonly kind: "Aggregate"; |
| 787 | readonly aggregateName: Name; |
| 788 | readonly definition: Def; |
| 789 | /** Address one instance of this aggregate. */ |
| 790 | ref<Self extends Any>(this: Self, id: Self["definition"]["id"]["Encoded"]): Ref<Self>; |
| 791 | /** |
| 792 | * Decide a command locally, with this aggregate's own `decide` and |
| 793 | * `evolve`: the events and state, or the rejection, the server would give |
| 794 | * for the same state, id and time. A command with middleware needs |
| 795 | * `context`: what its middleware provides, from a client-side Layer. See |
| 796 | * {@link predict}. |
| 797 | * |
| 798 | * **Example:** Show a withdrawal before the bank answers |
| 799 | * ```typescript |
| 800 | * const context = yield* Layer.build(Layer.succeed(CurrentActor, actor)); |
| 801 | * const outcome = Account.predict(state, new WithdrawMoney({ amount: 30 }), { id, now, context }); |
| 802 | * if (outcome._tag === "Rejected") showError(outcome.rejection); // InsufficientFunds |
| 803 | * if (outcome._tag === "Accepted") showPending(outcome.state); |
| 804 | * ``` |
| 805 | */ |
| 806 | predict<Self extends Any, Cmd extends CommandOf<Self>>( |
| 807 | this: Self, |
| 808 | state: StateOf<Self>, |
| 809 | command: Cmd, |
| 810 | options: PredictOptions<IdOf<Self>, Command.ContextOf<CommandClassOf<Self["definition"], Cmd>>>, |
| 811 | ): Prediction< |
| 812 | StateOf<Self>, |
| 813 | InstanceOf<CommandClassOf<Self["definition"], Cmd>["events"][number]>, |
| 814 | InstanceOf<CommandClassOf<Self["definition"], Cmd>["rejects"][number]>, |
| 815 | IdOf<Self> |
| 816 | >; |
| 817 | } |