# Ontologic — full documentation > A zero-dependency TypeScript toolkit for Domain-Driven Design: domain entities and value objects that enforce their own invariants, versioned domain events with an outbox-backed event bus, a Result type for explicit domain failures, and typed resumable workflows. This file concatenates every page of the Ontologic documentation. Canonical HTML version: https://ontologic.site/docs - Ontologic is published on npm as `ontologic` and has no runtime dependencies. - All examples import from the package root: `import { DomainEntity, ok, err } from "ontologic"`. - Worked, tested examples live at https://github.com/SachaCR/ontologic/tree/main/src/examples --- # Introduction --- Source: https://ontologic.site/docs/intro # Model Your Business in TypeScript with Ontologic Software has a tendency to drift away from the business it was built to serve. It starts small: a rule that should belong to the domain ends up in a controller. A concept that has a precise name in the business is called something vague in the code. A constraint that everyone agrees on lives in three different places or none. Over time, the code and the business speak different languages, and every change becomes a translation exercise. **Domain-Driven Design** (DDD) is a set of principles and patterns that fights this drift. The core idea is simple: let the business domain its vocabulary, its rules, its logic drive the structure of your code. When your code reflects the real world it models, it becomes easier to understand, easier to change, and harder to get wrong. `ontologic` is a TypeScript library that gives you the building blocks to do this in practice. It provides a small set of well-defined primitives that encode DDD concepts directly into your type system so you spend less time enforcing patterns manually and more time thinking about your domain. --- ## Core concepts `ontologic` is organized around a few key ideas. Each one has its own page read them in order if you're new to DDD, or jump to what you need. ### [Domain Entity](https://ontologic.site/docs/domain-model/domain-entity) An entity is a domain object with a unique identity and a lifecycle. It owns its state, enforces its invariants, and exposes behavior rather than raw data. If you're new to `ontologic`, start here. ### [Value Object](https://ontologic.site/docs/domain-model/value-object) Some concepts in your domain have no identity — an amount of money, a date range, an address. Two of them with the same fields are simply the same thing. Value objects bundle those fields with the rules that make them valid, so an invalid one cannot exist. ### [Domain Events](https://ontologic.site/docs/domain-model/domain-events) A domain event is a record that something meaningful happened past tense, immutable, and named after a business fact. Events are the mechanism by which different parts of your system stay in sync without becoming tightly coupled. ### [The Result Pattern](https://ontologic.site/docs/domain-model/result-pattern) Some failures are not bugs — they are valid branches of the business logic. The Result pattern makes those failures explicit in the type system, so callers are forced to handle them and errors carry structured context rather than just a message string. ### [Invariants](https://ontologic.site/docs/domain-model/invariants) An invariant is a rule that must always be true about an entity not just after certain operations, but at all times. `ontologic` checks invariants on every state read, catching corrupted data the moment it enters the system. ### [Repository](https://ontologic.site/docs/domain-model/repository) The repository is the interface between your domain and your persistence layer. It hides all database details behind a clean, domain-friendly API and ensures that entity state and domain events are always saved together in a single transaction. ### [Event Bus](https://ontologic.site/docs/event-bus/event-bus) The event bus delivers domain events to the rest of your system. A pluggable connector interface lets you use any broker SQS, Kafka, RabbitMQ, Redis, or others. While the publisher and listener logic stays the same across all environments. In-memory connectors are included for tests and local prototyping. ### [Message Relay](https://ontologic.site/docs/event-bus/message-relay) The message relay is the bridge between the outbox table and the event bus. It reads events that were persisted by the repository and forwards them to the broker, tracking exactly what has been published so the system can recover from failures without skipping or restarting from scratch. ### [Command Bus](https://ontologic.site/docs/event-bus/command-bus) The command bus is request/response over a broker: a caller sends a command to the service that handles it and gets its answer back as a `Result`, with a timeout. It uses the same pluggable connectors as the event bus, with Redis and SQS connectors available as companion packages. ### [Workflows](https://ontologic.site/docs/workflows) A workflow is a typed, resumable orchestration for multi-step business processes. `ontologic` provides two flavors: a step-by-step chain for linear pipelines and a graph for processes where steps fan out and combine results in parallel. Both give you observability, persistence, and the ability to resume after a failure exactly where the previous run stopped. --- ## Who is this for? `ontologic` is for TypeScript developers who want to apply DDD patterns without writing a lot of boilerplate, and without committing to a heavy framework. You don't need prior DDD experience the documentation explains concepts from first principles. But if you're already familiar with DDD, you'll find the primitives familiar and the TypeScript integration straightforward. --- ## Installation ```bash npm install ontologic ``` That's it. `ontologic` has no runtime dependencies. --- # Domain Model --- Source: https://ontologic.site/docs/domain-model/domain-entity # Domain Entity Domain-Driven Design (DDD) is an approach to software development that puts the **business domain** at the center of your code. Rather than thinking in terms of database tables or HTTP endpoints, you model the real world: its concepts, its rules, its vocabulary. A **Domain Entity** is one of the core building blocks of DDD. It represents a meaningful concept in your domain that has: - A **unique identity** that persists over time - A **lifecycle** — it is created, it changes, and eventually it may be deleted - **Behavior** — it doesn't just hold data, it knows how to act on it Think of a bank account. It has an ID, it can be credited and debited, and it has rules (e.g. you can't spend more than you have). It's a perfect candidate for a Domain Entity. --- ## The problem with plain objects Before diving into how `ontologic` helps, let's look at what happens without it. ```typescript // A plain object — no rules, no protection const account = { id: "abc-123", balance: 100, }; // Anyone can do this — there's nothing stopping it account.balance = -9999; ``` Nothing prevents invalid state. The balance constraint lives... nowhere? In some validator function somewhere? In the controller? In the database? It's scattered and easy to forget. DDD says: the object itself should be responsible for staying valid. --- ## State Encapsulation The first thing a Domain Entity does is **own its state**. External code can read it, but cannot mutate it directly. With `ontologic`, you extend `DomainEntity` and keep your state internal: ```typescript import { DomainEntity } from "ontologic"; interface BankAccountState { ownerId: string; balance: number; } class BankAccount extends DomainEntity { static create(params: { ownerId: string }): BankAccount { const id = randomUUID(); return new BankAccount(id, { ownerId: params.ownerId, balance: 0, }); } deposit(amount: number): void { this.state.balance += amount; } getBalance(): number { return this.state.balance; } } ``` The `state` property is `protected` — only the entity and its subclasses can touch it. When you call `readState()`, you get back a **safe copy** — a deep clone by default — so there's no way for outside code to accidentally mutate the internal state. (When your state holds live sub-entities, you control how that copy is produced — see [Custom serialization](#custom-serialization-for-states-with-sub-entities).) This is encapsulation in the DDD sense: **the entity controls all changes to itself**. --- ## Invariants An **invariant** is a rule that must always be true about your entity. No matter what operation you perform, the entity should never end up in a state that violates it. A classic invariant for a bank account: _the balance must never be negative_. With `ontologic`, you express this as a `BaseDomainInvariant`: ```typescript import { BaseDomainInvariant } from "ontologic"; const balanceIsPositive = new BaseDomainInvariant( "Balance must be positive", (state) => state.balance >= 0, ); ``` Then you attach it to your entity: ```typescript class BankAccount extends DomainEntity { constructor(id: string, state: BankAccountState) { super(id, state); this.addInvariant(balanceIsPositive); } // ... } ``` You can also pass them through the constructor's options, which enforces them from the very first moment: ```typescript super(id, state, { invariants: [balanceIsPositive] }); ``` :::warning Changed in 1.7.0 The constructor's third parameter used to be the invariant array itself: ```typescript super(id, state, [balanceIsPositive]); // 1.6.x and earlier — no longer valid ``` It is now an options object, so that `serialize` could be added alongside `invariants`. Upgrading from 1.6.x, the old form fails to compile with `TS2559: Type 'BaseDomainInvariant[]' has no properties in common with type 'DomainEntityOptions'`. The fix is to wrap it: `{ invariants: [...] }`, or call `addInvariant(...)` in the constructor body. The error is loud rather than silent, so a type-check after upgrading will find every occurrence. ::: From this point on, **every time the state is read**, the invariant is checked. If the state is ever found in violation, a `CorruptedStateError` is thrown immediately — before any corrupted data can propagate through the system. ```typescript import { CorruptedStateError } from "ontologic"; const account = BankAccount.fromState("abc-123", { ownerId: "u1", balance: -50, }); try { account.readState(); } catch (err) { if (err instanceof CorruptedStateError) { err.name; // "CORRUPTED_STATE" err.entityId; // "abc-123" err.state; // the offending state, for logging err.violations; // [{ description: "Balance must be positive" }] } } ``` ### `CorruptedStateError` is not a domain failure The library treats corrupted state as a **programmer error**, not as a recoverable domain failure. The entity was constructed with valid state and something — a method, a hydration step, a hand-written migration — drove it into an invalid state. That is a bug. There is no safe way to "handle" it and continue manipulating the entity. For that reason, `CorruptedStateError` extends `Error` directly and is **thrown**, not returned. Do not try to wrap it in a `Result`. The right reaction at the application boundary is: 1. Log every field on the error (`entityId`, `state`, `violations`). 2. Fail the current operation. 3. Page whoever owns the entity, because something in your code path is producing illegal state. If you find yourself wanting to catch and recover from one, the underlying failure is probably a **domain failure** (something the business explicitly allows to fail) and deserves its own `DomainError` subtype returned inside a `Result`, not an invariant. When several invariants fail at once, every failing description is collected into `err.violations`, so a single log line tells you all the rules the state broke — not just the first one the checker happened to hit. Invariants also compose. You can combine them with logical operators: ```typescript const balanceIsPositive = new BaseDomainInvariant( "Balance is positive", (state) => state.balance >= 0, ); const balanceIsReasonable = new BaseDomainInvariant( "Balance is under limit", (state) => state.balance <= 1_000_000, ); // Both must hold const validBalance = balanceIsPositive.and(balanceIsReasonable); // Logical operators available: .and() .or() .not() .xor() .andNot() ``` This lets you build complex business rules from simple, readable, named pieces. --- ## Reading state without paying for safety `readState()` is safe by default: it runs the invariants and returns a **safe copy** — a deep clone unless you supply a custom [`serialize`](#custom-serialization-for-states-with-sub-entities). For most code paths, that's exactly what you want. On hot paths, tight loops, large state objects, high-throughput services, the copy shows up in profiles. The entity exposes two opt-in accessors for those cases: ```typescript account.readState(); // safe copy + invariant check (default, safe) account.unsafeReadState(); // no clone, but invariant check still runs account.unsafeRawState(); // no clone, no check (cheapest, fully on you) ``` - **`unsafeReadState(): Readonly`**: returns the live internal state without cloning. The return type is `Readonly`, which signals at the type level that you must not mutate it. Invariants still run, so a corrupted entity still throws `CorruptedStateError`. Use this when you only need to **read** the state and the clone cost is measurable. - **`unsafeRawState(): State`**: returns the live internal state with no clone and no invariant check. The cheapest possible accessor and the most dangerous one. Reserve it for code that is provably read-only or that already holds an invariant proof by construction. A practical rule: - Default to `readState()`. It is the right choice 99% of the time. - Reach for `unsafeReadState()` only after a profiler tells you the clone matters. - Reach for `unsafeRawState()` only when you also need to skip the invariant check (for example, inside a serialization adapter where you've already validated the state upstream). Both methods are deliberately named `unsafe*` so they are grep-able in code review. --- ## Custom serialization for states with sub-entities By default, `readState()` produces its safe copy with `structuredClone`. That is exactly right when your state is plain, JSON-like data — the common case, and it needs no configuration. But `structuredClone` **drops class prototypes**. If your state holds live instances — the sub-entities of an aggregate, value objects with behavior — cloning turns them back into plain objects and strips their methods: ```typescript class OrderLine { constructor( private state: { sku: string; quantity: number; unitPrice: number }, ) {} subtotal(): number { return this.state.quantity * this.state.unitPrice; } serialize() { return { ...this.state }; } } const line = new OrderLine({ sku: "A", quantity: 2, unitPrice: 10 }); structuredClone(line).subtotal(); // 💥 TypeError: subtotal is not a function — the prototype is gone ``` To keep sub-entities alive inside an aggregate, give the entity a **`serialize`** function through the constructor's options. `readState()` calls it instead of `structuredClone`, and you decide how the rich internal state collapses into a plain, decoupled snapshot. `DomainEntity` takes a second type parameter for this: `DomainEntity`. `State` is the rich internal form (holding live sub-entities); `Serialized` is the plain form `readState()` hands out. ```typescript interface OrderState { lines: OrderLine[]; // live sub-entities, with domain logic } interface OrderSnapshot { lines: { sku: string; quantity: number; unitPrice: number }[]; // plain data } class Order extends DomainEntity { constructor(id: string, state: OrderState) { super(id, state, { serialize: (state) => ({ lines: state.lines.map((line) => line.serialize()), }), }); } total(): number { // sub-entity logic stays usable internally return this.state.lines.reduce((sum, line) => sum + line.subtotal(), 0); } } ``` The sub-entities keep their behavior inside the entity, while `readState()` still returns a plain, side-effect-free snapshot that outside code cannot use to reach back into the aggregate. **When to provide `serialize`:** - Your state contains **class instances** — sub-entities, value objects, anything with methods you still need after a read. - **Not** for plain data. If your state is only objects, arrays, strings, numbers, dates, `Map`/`Set`, leave `serialize` out — the `structuredClone` default is correct and there's nothing to do. Two things to keep in mind: - **`serialize` is not persistence.** Its only job is to decouple the returned value from the entity's internals. How that snapshot is stored in a database or put on the wire is the [Repository](https://ontologic.site/docs/domain-model/repository)'s concern — and that's also where you rehydrate the sub-entities on the way back in. - **The entity takes ownership of the state you pass it.** Because it cannot defensively clone on construction without stripping sub-entity prototypes, it keeps the exact object you hand to the constructor. Do not keep mutating that reference afterward. --- ## Domain Logic Domain logic is **behavior that belongs to the entity itself**, not to a service or a controller. If the bank account knows how to validate a withdrawal, you never need to duplicate that check anywhere else in the codebase. In `ontologic`, you express domain logic as methods on your entity. When a business rule can fail, you return a `Result` instead of throwing. But `Result` is not meant to wrap every possible failure — only **domain failures**. The distinction matters: - An **insufficient funds** error is a domain error. It is a valid, expected branch of the business logic. The caller must handle it explicitly, because it is part of the domain's vocabulary. - A **JSON parse failure** or a database connection timeout is a technical error. It is unexpected, it is not part of the domain, and it should be thrown and caught at the application boundary like any other exception. Using `Result` for technical errors would pollute every call site with error handling for things that are not the domain's concern. Reserve it for failures that have **business meaning**. ```typescript import { Result, ok, err, DomainError } from "ontologic"; class InsufficientFunds extends DomainError< "INSUFFICIENT_FUNDS", { available: number; requested: number } > { constructor(context: { available: number; requested: number }) { super({ name: "INSUFFICIENT_FUNDS", message: "Not enough funds to complete the withdrawal", context, }); } } class BankAccount extends DomainEntity { withdraw(amount: number): Result { if (this.state.balance < amount) { return err( new InsufficientFunds({ available: this.state.balance, requested: amount, }), ); } this.state.balance -= amount; return ok(); } } ``` The caller is forced to handle both outcomes: ```typescript const result = account.withdraw(500); if (result.isErr()) { console.log("Failed:", result.error.message); console.log("Available:", result.error.context.available); } else { console.log("Withdrawal successful"); } ``` Notice what this achieves: - The withdrawal logic lives **in the entity**, not scattered in services - The error is **typed** — you know exactly what can go wrong and what context it carries - The caller **cannot ignore** the failure case (no silent exceptions) - The entity remains in **valid state** — you never mutate the balance if the rule fails - The failure is **meaningful to the domain** — `InsufficientFunds` is something a business person would recognize, not a technical artifact This is domain logic done right: the entity is the single source of truth for what is allowed. --- ## Domain Events A **Domain Event** is a record that something meaningful happened in your domain. Not a log line — a first-class object that says _"this happened, at this time, to this entity"_. Domain events are useful for: - **Reacting** to changes in other parts of the system (e.g. send an email when an account is opened) - **Auditing** what happened over time - **Building Read Model**: Use [Event Sourcing](https://ontologic.site/docs/event-sourcing) to project event into rich data model In `ontologic`, you define events by extending `DomainEvent`: ```typescript import { DomainEvent } from "ontologic"; interface MoneyWithdrawnPayload { amount: number; } class MoneyWithdrawn extends DomainEvent< "MONEY_WITHDRAWN", 1, MoneyWithdrawnPayload > { constructor(entityId: string, payload: MoneyWithdrawnPayload) { super({ name: "MONEY_WITHDRAWN", version: 1, entityId, payload }); } } ``` Returning an event from a method is **optional** — not every state change needs to produce one. But it is highly recommended for any operation that has meaning outside the entity itself. If something happened that another part of the system might care about, make it explicit with an event rather than leaving observers to poll or infer. When you do return events, your entity methods become the natural place to emit them: ```typescript class BankAccount extends DomainEntity { withdraw(amount: number): Result { if (this.state.balance < amount) { return err( new InsufficientFunds({ available: this.state.balance, requested: amount, }), ); } this.state.balance -= amount; return ok(new MoneyWithdrawn(this.id(), { amount })); } } ``` The caller receives the event and can do whatever the application needs — store it, dispatch it, log it: ```typescript const result = account.withdraw(200); if (result.isOk()) { const event = result.value; await eventStore.save(event); await messageBus.publish(event); } ``` ### Several events from one operation An operation often produces more than one event. Creating an account and crediting it immediately is two facts, not one: the entity knows how to create itself, and it knows how to apply a credit, and each hands back its own event. The use case collects them and saves them together — `saveWithEvents` takes one event or an array, and writes them with the state atomically: ```typescript class OpenAccountWithDepositUseCase implements UseCase< OpenAccountWithDepositCommand, AccountState, never > { constructor(private readonly accounts: BankAccountRepository) {} async execute(command: OpenAccountWithDepositCommand) { const { ownerId, initialDeposit } = command.payload; const events: DomainEventInterface[] = []; const { account, creationEvent } = BankAccount.create({ ownerId }); events.push(creationEvent); const depositEvent = account.deposit({ amount: initialDeposit }); events.push(depositEvent); const saved = await this.accounts.saveWithEvents(account, events); if (saved.isErr()) { throw saved.error; } return ok(account.readState()); } } ``` See [Use Case](https://ontologic.site/docs/application/use-case) for the full shape, including why the error side is `never` here. Both events here come from the entity, which is the normal case. When an event exists only in a context the aggregate has no business holding — a referral programme, say — the use case can build that one itself and save it alongside. See [Events you can't assign to a single entity](https://ontologic.site/docs/domain-model/domain-events#events-you-cant-assign-to-a-single-entity). A few things worth noting about how `ontologic` models events: - The **name** is a string literal type (`"MONEY_WITHDRAWN"`) — it's both a runtime value and a compile-time type - The **version** is typed too, so you can handle different versions of the same event gracefully as your domain evolves - The **payload** is deep-cloned on construction — nobody can mutate the event after it's created --- ## Putting It All Together Here is a more complete example using the `CreditBalance` entity from the library's own examples. A credit balance tracks purchased credits and sub-credits for an organization: ```typescript // 1. Define the state shape interface CreditBalanceState { id: string; organizationId: string; subCreditBalance: number; lockedBalance: number; purchasedCreditBalance: number; } // 2. Define an invariant — balance must never go negative const balanceIsPositive = new BaseDomainInvariant( "Balance Is Positive", (state) => state.subCreditBalance >= 0, ); // 3. Define events class CreditBalanceDebited extends DomainEvent< "CREDIT_BALANCE_DEBITED", 1, { amount: number } > { constructor(entityId: string, payload: { amount: number }) { super({ name: "CREDIT_BALANCE_DEBITED", version: 1, entityId, payload }); } } // 4. Define errors class NotEnoughFunds extends DomainError< "NOT_ENOUGH_FUNDS", { available: number; amount: number } > { constructor(message: string, context: { available: number; amount: number }) { super({ name: "NOT_ENOUGH_FUNDS", message, context }); } } // 5. Build the entity class CreditBalance extends DomainEntity { constructor(id: string, state: CreditBalanceState) { super(id, state); this.addInvariant(balanceIsPositive); // attached here — always enforced } static create(params: { organizationId: string }) { const id = randomUUID(); return new CreditBalance(id, { id, organizationId: params.organizationId, subCreditBalance: 0, lockedBalance: 0, purchasedCreditBalance: 0, }); } debit(params: { amount: number; }): Result { const { amount } = params; if (this.state.subCreditBalance < amount) { return err( new NotEnoughFunds("Not enough credits", { available: this.state.subCreditBalance, amount, }), ); } this.state.subCreditBalance -= amount; return ok(new CreditBalanceDebited(this.id(), { amount })); } available(): number { return this.state.subCreditBalance - this.state.lockedBalance; } } // 6. Use it const balance = CreditBalance.create({ organizationId: "org-1" }); const result = balance.debit({ amount: 50 }); if (result.isErr()) { // Fully typed: result.error is NotEnoughFunds console.error( `Cannot debit: only ${result.error.context.available} available`, ); } else { // Fully typed: result.value is CreditBalanceDebited await eventStore.save(result.value); } ``` --- ## Summary | Concept | What it means | How `ontologic` helps | | ------------------------ | ------------------------------------------- | ----------------------------------------------------- | | **State Encapsulation** | The entity controls its own data | `protected state`, safe-copy `readState()` | | **Custom serialization** | Keep sub-entities alive inside an aggregate | `serialize` option, `DomainEntity` | | **Invariants** | Rules that must always hold | `BaseDomainInvariant`, checked on read | | **Domain Logic** | Behavior lives in the entity | Methods return `Result` | | **Domain Events** | Records of meaningful things that happened | Typed `DomainEvent` with name, version, payload | DDD is ultimately about making your code reflect reality. When your `BankAccount` class knows what it means to be a bank account — what it can do, what it can't, what happens when it changes — you stop fighting the code and start thinking in your domain. `ontologic` gives you the structure to do that without ceremony. --- Source: https://ontologic.site/docs/domain-model/value-object # Value Object A [Domain Entity](https://ontologic.site/docs/domain-model/domain-entity) is defined by **who it is**. A **Value Object** is defined by **what it is**. Two bank accounts with the same balance are still two different accounts — they have identities, and one can change without the other changing. But two amounts of `€50` are simply the same amount. There is no "which €50" — the question doesn't mean anything. Money has no identity, only a value. That difference has a practical consequence: an entity's state changes over its lifetime, while a value object is replaced wholesale. You don't "change" `€50` into `€70`; you throw it away and use `€70` instead. --- ## Why not just use a plain object? You could represent money as `{ amount: 50, currency: "EUR" }`. Nothing stops you. But nothing stops anyone else, either: ```typescript const price = { amount: -50, currency: "EUR" }; // negative money const total = { amount: 50, currency: "PIZZA" }; // not a currency price.amount = 999; // mutated from the outside ``` Every rule about what makes a valid amount of money now lives wherever somebody remembered to write it. A value object gathers those rules in one place and enforces them on construction, so an invalid instance cannot exist. --- ## Defining a value object `ValueObject` is the same machinery as `DomainEntity`, minus the identity and the version: ```typescript import { ValueObject, BaseDomainInvariant } from "ontologic"; interface MoneyState { amount: number; currency: string; } const amountIsPositive = new BaseDomainInvariant( "Amount must be >= 0", (state) => state.amount >= 0, ); export class Money extends ValueObject { private constructor(state: MoneyState) { super(state, { invariants: [amountIsPositive] }); } static make(amount: number, currency = "EUR"): Money { return new Money({ amount, currency }); } add(other: Money): Money { const otherState = other.readState(); if (otherState.currency !== this.state.currency) { throw new Error("Cannot add amounts in different currencies"); } // Return a NEW instance — never mutate a value object. return Money.make(this.state.amount + otherState.amount, this.state.currency); } } ``` Two things to notice: - **Invariants run in the constructor.** `Money.make(-10)` throws `CorruptedStateError` immediately. There is no window in which an invalid `Money` exists. - **Behavior returns new instances.** `add` does not mutate `this.state`; it produces a new `Money`. This is what "no identity" means in practice. You can pass invariants through the constructor options as above, or attach them with `addInvariant()` after construction — both work, but the options form is preferable because the rule is then enforced from the very first moment. --- ## Reading the state The accessors mirror `DomainEntity` exactly: ```typescript money.readState(); // invariant check + safe copy (default, use this) money.unsafeReadState(); // invariant check, no copy (Readonly) money.unsafeRawState(); // no check, no copy (cheapest, fully on you) ``` `readState()` deep-clones by default, so callers cannot reach back into the value object and mutate it. Reach for the unsafe variants only when a profiler tells you the clone matters, and never mutate what they hand back. When an invariant fails, `CorruptedStateError` is thrown with `entityId` set to the class name — a value object has no id to report. --- ## Custom serialization Like `DomainEntity`, `ValueObject` takes a second type parameter and a `serialize` option for states holding live class instances that `structuredClone` would strip of their prototypes: ```typescript class Line extends ValueObject { constructor(state: LineState) { super(state, { serialize: (s) => ({ sku: s.sku, total: s.price * s.quantity }), }); } } ``` When `Serialized` differs from `State`, you **must** provide `serialize` — the `structuredClone` default cannot produce it. And as with entities, `serialize` is not persistence: its only job is to decouple the returned value from the internals. See [Domain Entity](https://ontologic.site/docs/domain-model/domain-entity) for the full discussion. --- ## Value object or entity? | Question | Answer | |---|---| | Do two instances with identical fields mean the same thing? | Value Object | | Does it need to be tracked over time, across changes? | Entity | | Would you ever store it in its own table with its own id? | Entity | | Is it replaced wholesale rather than modified? | Value Object | | Does it emit domain events? | Entity | Money, dates, addresses, coordinates, email addresses, quantities, and ranges are almost always value objects. Orders, users, accounts, and shipments are almost always entities. A value object can live inside an entity's state — that is the common case, and it is exactly why the `serialize` option exists. --- ## Summary | Concept | `DomainEntity` | `ValueObject` | |---|---|---| | Identity | `id()` | none | | Version / optimistic locking | `version()`, `setVersion()` | none | | Invariants | yes | yes | | Domain events | yes | no | | Changes over time | mutates its state | replaced by a new instance | A value object is the smallest useful unit of domain modelling: a name, a shape, and the rules that make it valid. Reach for one whenever you catch yourself passing a bare `number` or `string` that has rules attached to it. --- Source: https://ontologic.site/docs/domain-model/domain-events # Domain Events In Domain-Driven Design, a **Domain Event** is a record that something meaningful happened in your domain. Not a log line. Not a notification. A first-class object that says: _"this thing happened, it's a fact, and it matters to the business."_ A few examples of domain events: - `OrderPlaced` - `PaymentFailed` - `UserRegistered` - `InventoryReserved` Notice the naming pattern: **past tense**. That's intentional, and important. A domain event is not a command (_"PlaceOrder"_) and it is not a query (_"GetOrder"_). It is a **fact about the past**. It has already happened. It cannot be undone. --- ## Events are facts, not intentions This distinction shapes how you think about them. When you issue a command, it might fail. An order might be rejected. A payment might be declined. But once an event exists — once `OrderPlaced` has been emitted — it is a permanent record. The order _was_ placed. That's the truth, and nothing can change it. This is why domain events use past tense: they record what already occurred, not what you hope will occur. ```typescript // Not this — it's an instruction, not a fact class PlaceOrder { ... } // This — it records something that already happened class OrderPlaced extends DomainEvent<"ORDER_PLACED", 1, { orderId: string; total: number }> { constructor(entityId: string, payload: { orderId: string; total: number }) { super({ name: "ORDER_PLACED", version: 1, entityId, payload }); } } ``` --- ## Events are immutable Because events describe the past, **you cannot change them**. You can't go back in time. In `ontologic`, this is enforced at the library level: the payload is **deep-cloned** on construction. Once an event is created, no part of it can be mutated — not by the entity that produced it, not by the code that receives it. ```typescript const event = new OrderPlaced("order-123", { orderId: "order-123", total: 99 }); // The payload is a clone — mutating it has no effect on the event const payload = event.payload; payload.total = 0; // This does nothing to the original event ``` This immutability is not just a technical detail. It reflects the nature of history: you can observe what happened, but you cannot rewrite it. --- ## Events are a shared contract This is perhaps the most important thing to understand about domain events in practice: **they are public API**. When you publish a domain event, other parts of the system will start listening to it. A `PaymentReceived` event might trigger an invoice generation, a shipping request, and a customer notification — in three different services. Once those consumers exist, **you cannot change the event's shape without coordinating with all of them**. Think of it like a REST API endpoint: once it's in use, you own it. You can add fields in a backwards-compatible way, but you can't remove or rename them without breaking consumers. This is why `ontologic` includes a **version number** on every event: ```typescript class PaymentReceived extends DomainEvent< "PAYMENT_RECEIVED", 1, { amount: number; currency: string } > { constructor(entityId: string, payload: { amount: number; currency: string }) { super({ name: "PAYMENT_RECEIVED", version: 1, entityId, payload }); } } ``` When your domain evolves and you need to change the shape of an event, you create a new version instead of modifying the old one: ```typescript // New version with additional context class PaymentReceived extends DomainEvent< "PAYMENT_RECEIVED", 2, { amount: number; currency: string; paymentMethod: string } > { constructor( entityId: string, payload: { amount: number; currency: string; paymentMethod: string }, ) { super({ name: "PAYMENT_RECEIVED", version: 2, entityId, payload }); } } ``` Consumers that still handle version 1 keep working. Consumers that need the new data can migrate to version 2. The version makes the contract explicit and evolution safe. --- ## Defining and emitting events with `ontologic` You define a domain event by extending `DomainEvent` with three type parameters: the event name, the version, and the payload shape. ```typescript import { DomainEvent } from "ontologic"; interface MoneyDepositedPayload { amount: number; } class MoneyDeposited extends DomainEvent< "MONEY_DEPOSITED", 1, MoneyDepositedPayload > { constructor(entityId: string, payload: MoneyDepositedPayload) { super({ name: "MONEY_DEPOSITED", version: 1, entityId, payload }); } } ``` Events are typically emitted from entity methods. When an operation succeeds, the method returns the event as its success value: ```typescript class BankAccount extends DomainEntity { deposit(amount: number): MoneyDeposited { this.state.balance += amount; return new MoneyDeposited(this.id(), { amount }); } } ``` Or, when the operation can fail, using `Result`: ```typescript class BankAccount extends DomainEntity { withdraw(amount: number): Result { if (this.state.balance < amount) { return err( new InsufficientFunds({ available: this.state.balance, requested: amount, }), ); } this.state.balance -= amount; return ok(new MoneyWithdrawn(this.id(), { amount })); } } ``` The caller receives the event and passes it to the repository, which persists the entity and the event **atomically** in a single transaction: ```typescript const result = account.withdraw(200); if (result.isOk()) { const event = result.value; // MoneyWithdrawn await repository.saveWithEvents(account, [event]); } ``` Saving the entity and its events in the same transaction is important. If you saved them separately — entity first, then the event — a failure between the two would leave your system in an inconsistent state: the balance changed, but nobody was told. `ontologic`'s repository prevents this by guaranteeing you get both or neither. ### Publishing with the Outbox pattern At this point the event is persisted, but nothing has been notified yet. You might be tempted to publish to a message bus immediately after the save — but that's a second operation that can fail independently of the first. Your database committed, but the broker was down for a second: the event is saved and will never be published. The solution is the **Outbox pattern**. Instead of publishing directly, a background process reads unpublished events from the database and forwards them to the message bus. Because it reads from the same database that was written to in the transaction, it is guaranteed to eventually publish every event that was saved. This separates two concerns that should never be coupled: - **Writing** — the use case saves state and records what happened, transactionally - **Publishing** — a reliable background process, the [Message Relay](/docs/event-bus/message-relay), delivers events to the rest of the system The use case stays simple. The delivery guarantee is handled by infrastructure, not by application code. `ontologic` provides an [Event Bus](https://ontologic.site/docs/event-bus/event-bus) with a pluggable connector interface to handle the delivery side of this pattern. --- ## Not every state change needs an event Returning an event from a method is **optional**. Not every mutation needs to produce one. The question to ask is: _"Does something outside this entity care that this happened?"_ - If a withdrawal might trigger a low-balance notification, produce an event. - If you're just updating a display name that nobody else cares about, maybe you don't need one. The more important something is to the business — the more other systems or processes depend on it — the more it deserves to be captured as an explicit event. --- ## Events you can't assign to a single entity Sometimes an event can only be produced at the **use case level**, because the entity alone doesn't have enough context. Consider a referral program: when someone signs up using a friend's referral link, their account is opened and they immediately receive $50. The `BankAccount` entity knows how to create itself and how to apply a deposit — but it has no idea _why_ the money is there. That context only exists in the use case. Yet _"an account was opened via referral"_ is exactly the kind of business fact worth capturing. The marketing team wants to know how many referrals are converting. The finance team wants to audit bonus payouts. Without an explicit event, that information is lost — buried in a generic deposit with no origin. This is where the use case produces the event itself: ```typescript interface ReferralAccountOpenedPayload { newAccountId: string; referrerId: string; bonusAmount: number; } class ReferralAccountOpened extends DomainEvent< "REFERRAL_ACCOUNT_OPENED", 1, ReferralAccountOpenedPayload > { constructor(entityId: string, payload: ReferralAccountOpenedPayload) { super({ name: "REFERRAL_ACCOUNT_OPENED", version: 1, entityId, payload }); } } const REFERRAL_BONUS = 50; class OpenAccountViaReferralUseCase implements UseCase { constructor(private readonly accounts: BankAccountRepository) {} async execute(command: OpenAccountViaReferralCommand) { const { newUserId, referrerId } = command.payload; // The entity produces what it can know from its own state. const { account, creationEvent } = BankAccount.create({ ownerId: newUserId }); const depositEvent = account.deposit({ amount: REFERRAL_BONUS }); // Only the use case knows the deposit was a referral bonus. const referralEvent = new ReferralAccountOpened(account.id(), { newAccountId: account.id(), referrerId, bonusAmount: REFERRAL_BONUS, }); const saved = await this.accounts.saveWithEvents(account, [ creationEvent, depositEvent, referralEvent, ]); if (saved.isErr()) { throw saved.error; } return ok(account.readState()); } } ``` The entity handles the mechanics. The use case holds the meaning. Note that all three events are saved together — the entity's own events are not replaced by the use case's, they are joined by it. The rule of thumb: if the event can be produced with only the entity's internal state, let the entity produce it. If the event requires knowledge that only the use case has, produce it in the use case. You could of course put `account.applyReferralBonus(referrerId)` on the entity instead, and sometimes that is the better model. The question to ask is whether the aggregate should know the concept at all: if teaching it the rule means teaching it a context it has no business holding, the event belongs to the use case. Ontologic does not decide that for you — nobody knows your domain and its constraints better than you do. --- ## Summary | Property | What it means | | ------------------- | -------------------------------------------------------------------------------- | | **Past tense name** | Events record facts, not intentions — something that already happened | | **Immutable** | The payload is frozen at creation — you cannot rewrite history | | **Versioned** | Events are a shared contract; versioning lets the contract evolve safely | | **Optional** | Not every state change needs an event — only ones that matter outside the entity | Domain events make your system's history explicit. Instead of inferring what happened from the current state of a database, you have a precise, typed record of every meaningful thing that occurred — who did it, when, and with what data. That record is what makes systems observable, evolvable, and trustworthy. --- Source: https://ontologic.site/docs/domain-model/invariants # Invariants An **invariant** is a rule that must always be true about your entity — no matter what. Not "usually true". Not "true after most operations". Always. If an invariant is violated, the entity is in a corrupted state and nothing should be trusted about it. A bank account balance must never be negative. An order cannot have zero line items. A user must always have at least one role. These are invariants: non-negotiable truths about your domain objects. --- ## The problem without invariants Without explicit invariants, rules get scattered. The balance check might live in the `withdraw` method, but what stops someone from directly setting the balance through some other path? What happens when you load an entity from the database and the data is already invalid due to a past bug? ```typescript // A bug six months ago wrote a negative balance to the database. // You load it, it looks fine, you operate on it, you make things worse. const account = BankAccount.fromState("abc-123", { ownerId: "u1", balance: -200 }); account.deposit(100); // Now it's -100. Still wrong. Nobody noticed. ``` The entity had no way to reject the corrupted state on entry. The invariant was only checked at one specific point in the code — not at the boundary of the entity itself. --- ## Expressing invariants with `ontologic` In `ontologic`, you define an invariant as a `BaseDomainInvariant` — a named predicate over your entity's state: ```typescript import { BaseDomainInvariant } from "ontologic"; interface BankAccountState { balance: number; } const balanceIsPositive = new BaseDomainInvariant( "Balance must be positive", (state) => state.balance >= 0 ); ``` You attach it to your entity in the constructor: ```typescript class BankAccount extends DomainEntity { constructor(id: string, state: BankAccountState) { super(id, state); this.addInvariant(balanceIsPositive); } } ``` From this point on, **every time the state is read**, the invariant is checked. If it is violated, an error is thrown immediately — before any corrupted data can propagate further through the system. ```typescript // This is caught at the boundary, before anything else runs const account = BankAccount.fromState("abc-123", { ownerId: "u1", balance: -200 }); account.readState(); // throws: "Corrupted state detected — Balance must be positive" ``` The entity becomes its own gatekeeper. You no longer need to remember to check preconditions everywhere — the entity checks itself. --- ## Invariants are not the same as validation It's worth drawing a clear line between invariants and input validation. **Input validation** happens at the boundary of your system — when data arrives from outside (a form submission, an API request). It rejects malformed input before it enters the domain. Validation is about format and shape: "is this a valid email address?", "is this number in the expected range?". **Invariants** operate inside the domain. They express rules about the *internal consistency* of your model. They are not about user input — they are about what it means for an entity to be in a valid state at all. A user might submit a withdrawal amount that is perfectly valid input (a positive number, correctly formatted) but that would violate a domain invariant (the resulting balance would be negative). Input validation passes. The domain invariant prevents the operation. --- ## Composing invariants Simple invariants can be combined into more expressive rules using logical operators: ```typescript const balanceIsPositive = new BaseDomainInvariant( "Balance is positive", (state) => state.balance >= 0 ); const balanceIsUnderLimit = new BaseDomainInvariant( "Balance is under limit", (state) => state.balance <= 1_000_000 ); // Both must hold const balanceIsValid = balanceIsPositive.and(balanceIsUnderLimit); ``` Available operators: | Operator | Meaning | |---|---| | `.and(other)` | Both invariants must hold | | `.or(other)` | At least one must hold | | `.not()` | The invariant must not hold | | `.xor(other)` | Exactly one must hold | | `.andNot(other)` | This must hold and the other must not | This lets you build complex business rules out of small, named, testable pieces — and give each piece a name that communicates its intent. --- ## Where to define invariants Invariants should be defined close to the state they describe, and attached to the entity in the constructor. This ensures they are enforced for every instance of the entity, whether it was just created or just loaded from the database. ```typescript // Defined at module level — reusable, named, testable const balanceIsPositive = new BaseDomainInvariant( "Balance is positive", (state) => state.balance >= 0 ); class BankAccount extends DomainEntity { constructor(id: string, state: BankAccountState) { super(id, state); this.addInvariant(balanceIsPositive); // enforced for every instance } } ``` Defining them at module level also makes them easy to unit test independently of the entity: ```typescript expect(balanceIsPositive.complyWith({ balance: 100 }).isCompliant).toBe(true); expect(balanceIsPositive.complyWith({ balance: -1 }).isCompliant).toBe(false); ``` `complyWith(state)` returns an `InvariantCheckResult` — `{ isCompliant: boolean; description: string; operator?: string }` — rather than a bare boolean. The `description` is the name you gave the invariant, and it is what `CorruptedStateError` reports when the rule is violated. --- ## Summary Invariants are the domain's immune system. They don't just prevent bad operations — they reject bad state on entry, catching corrupted data the moment it is loaded, before it can do any damage. When you encode your business rules as invariants rather than scattering checks across methods and services, you get an entity that is self-defending: one that cannot be put into an invalid state, regardless of how it is used. --- Source: https://ontologic.site/docs/domain-model/result-pattern # The Result Pattern When an operation can fail, there are two common ways to communicate that failure to the caller: throw an exception, or return a value that represents the outcome. Exceptions work well for unexpected, unrecoverable situations. But not all failures are unexpected. In a business domain, some failures are entirely normal — a withdrawal when the balance is too low, a reservation when the slot is already taken, a coupon code that has expired. These are not exceptional situations. They are valid branches of the business logic, and the caller should be expected to handle them. The **Result pattern** makes this explicit. Instead of throwing, a method returns a `Result` — a value that is either a success (carrying the happy-path output) or an error (carrying the failure details). The caller is forced to decide what to do in both cases. --- ## The problem with exceptions for domain failures Consider a withdrawal method that throws when funds are insufficient: ```typescript class BankAccount { withdraw(amount: number): void { if (this.state.balance < amount) { throw new Error("Insufficient funds"); } this.state.balance -= amount; } } ``` The signature tells you nothing about what can go wrong. Nothing in TypeScript will remind you to handle the failure case. You might write: ```typescript account.withdraw(500); // Moved on — forgot this could throw await repository.save(account); ``` And it works fine in tests, because the balance is always high enough. It fails in production, unhandled, at 2am. The failure was predictable. The business knew about it. The code just didn't say so. --- ## Modelling the failure branch explicitly With `ontologic`, you express this as a typed `Result`: ```typescript import { Result, ok, err, DomainError } from "ontologic"; class InsufficientFunds extends DomainError<"INSUFFICIENT_FUNDS", { available: number; requested: number }> { constructor(context: { available: number; requested: number }) { super({ name: "INSUFFICIENT_FUNDS", message: "Not enough funds to complete the withdrawal", context, }); } } class BankAccount extends DomainEntity { withdraw(amount: number): Result { if (this.state.balance < amount) { return err(new InsufficientFunds({ available: this.state.balance, requested: amount, })); } this.state.balance -= amount; return ok(); } } ``` Now the method signature is honest: it tells you that a withdrawal can fail with `InsufficientFunds`, and it forces you to deal with it: ```typescript const result = account.withdraw(500); if (result.isErr()) { console.log("Withdrawal failed:", result.error.message); console.log("Available:", result.error.context.available); return; } // Here, TypeScript knows the withdrawal succeeded await repository.save(account); ``` You cannot ignore the error case. There is no way to accidentally skip it. The type system has your back. --- ## What makes a failure a domain failure? Not every error belongs in a `Result`. The distinction is important. A **domain failure** is a failure that has meaning in the business. It is a valid, expected outcome that a business person would recognize and could describe: - "You can't withdraw more than your balance" - "You can't book a slot that's already taken" - "This coupon code has already been used" These are not bugs. They are rules. They deserve to be modelled explicitly, with a name, a type, and context that tells the caller exactly what went wrong. A **technical error** is something else entirely — a database connection timeout, a JSON parse failure, a network error. These are not part of your domain. They are infrastructure problems that the domain layer has no business knowing about. They should be thrown and caught at the application boundary, like any other unexpected exception. Using `Result` for technical errors would pollute every call with error handling for things that aren't the domain's concern: ```typescript // Don't do this — a database error is not a domain failure withdraw(amount: number): Result { ... } ``` The rule: if a business person would recognize it as a valid scenario, it's a domain failure — use `Result`. If it's infrastructure misbehaving, throw. --- ## Typed errors carry context One of the key benefits of `DomainError` over a plain `Error` is that it carries **typed context**. When `InsufficientFunds` is thrown as a plain exception, the caller gets a message string. They have to parse it to know the available balance. When it's a typed `DomainError`, the caller gets structured data: ```typescript class InsufficientFunds extends DomainError< "INSUFFICIENT_FUNDS", { available: number; requested: number } > { ... } // The caller knows exactly what's there result.error.context.available // number result.error.context.requested // number result.error.name // "INSUFFICIENT_FUNDS" result.error.message // human-readable string ``` This makes error handling at the application layer clean and reliable, without any string parsing or casting. --- ## Summary | | Exceptions | Result | |---|---|---| | **Use for** | Unexpected, unrecoverable failures | Expected, named domain failures | | **Visibility** | Hidden from the signature | Explicit in the return type | | **Handling** | Optional — easy to forget | Required — enforced by the type system | | **Context** | A message string | Typed, structured data | The Result pattern is not about avoiding exceptions. It is about being honest in your code about what can go wrong in your domain — and giving the caller the tools to respond to it meaningfully. --- ## A note on the implementation The `Result` type in `ontologic` — `ok`, `err`, and the `Result` type — is directly inspired by and largely copied from [neverthrow](https://github.com/supermacro/neverthrow), an excellent library by Gil Mizrahi. It was vendored rather than listed as a dependency so that installing `ontologic` does not force a transitive dependency on your project. You get the same clean API without the version management overhead. If you're already using `neverthrow` in your project, the two `Result` types are different implementations with the same shape — they won't conflict, but you shouldn't mix them in the same function signature. --- Source: https://ontologic.site/docs/domain-model/repository # Repository In Domain-Driven Design, a **Repository** is the interface between your domain and your persistence layer. Its job is simple: store entities and retrieve them. Everything else — SQL queries, ORM mappings, connection pooling — is an implementation detail that your domain should never need to know about. The domain speaks in entities. The repository translates. --- ## Why the domain shouldn't touch the database If your entity methods contain database calls, two things happen: 1. Your domain logic becomes impossible to test without a real database 2. Your persistence concerns leak into your business rules, and the two become tangled over time DDD keeps these concerns separate by design. The entity knows how to behave. The repository knows how to persist. Neither knows how the other works. ```typescript // The entity has no idea where it's stored class BankAccount extends DomainEntity { withdraw(amount: number): Result { // Pure domain logic — no database, no I/O } } // The repository has no idea about domain rules class BankAccountRepository { async getById(id: string): Promise { ... } async save(account: BankAccount): Promise { ... } } ``` This separation keeps your domain logic fast, portable, and easy to reason about. --- ## Saving entities and events together The most important responsibility of the repository in `ontologic` is saving entities and their domain events **atomically** — in a single transaction. This matters because an entity state change and the event that records it are inseparable. If the entity is saved but the event is not, the rest of the system never learns what happened. If the event is saved but the entity is not, you have a record of something that technically didn't stick. Either way, your system is inconsistent. `ontologic`'s repository solves this with `saveWithEvents`: ```typescript const result = account.withdraw(200); if (result.isOk()) { await repository.saveWithEvents(account, [result.value]); } ``` Both the updated entity state and the event are written in a single database transaction. You get both, or neither. There is no in-between. --- ## The repository as a collection A useful mental model: think of the repository as a collection that happens to be backed by a database. You don't call `INSERT INTO accounts ...` — you call `repository.save(account)`. You don't call `SELECT * FROM accounts WHERE id = $1` — you call `repository.getById(id)`. The persistence mechanism is completely hidden behind a clean, domain-friendly interface. `ontologic` gives you that interface as `Repository`. Every method returns a `Result` rather than throwing, so infrastructure failures are values you can inspect: ```typescript interface Repository { save(entity: Entity): Promise>; saveWithEvents( entity: Entity, domainEvents: DomainEventInterface | DomainEventInterface[], ): Promise>; getById(id: string): Promise>; list(params: { limit: number; offset: number }): Promise< Result<{ limit: number; offset: number; data: Entity[] }, Error> >; getEvents( entityId: string, options?: { limit: number; offset: number }, ): Promise[], Error>>; getEventsAfter( entityId: string, eventId: string | undefined, limit?: number, ): Promise[], Error>>; onChanges(handler: (entityId: string) => void): void; } ``` Note that a missing entity is `ok(undefined)`, not an error — "this order does not exist" is a domain decision for the caller to make, not an infrastructure failure. This interface is what the domain and use cases depend on. The actual implementation — Postgres, SQLite, an in-memory store for tests — can be swapped without touching a single line of domain code. --- ## Testing with the built-in in-memory repository `ontologic` ships with a generic `InMemoryRepository` that you can use directly — no need to write your own. It takes **two** type parameters: your entity, and the union of that entity's domain events. Pass your `fromState` factory to the constructor — that is how the repository rehydrates entities: ```typescript import { InMemoryRepository } from 'ontologic'; class BankAccountRepository extends InMemoryRepository< BankAccount, BankAccountEvent > { constructor() { super(BankAccount.fromState); } } ``` That's it. The repository is ready to use in your tests and for rapid prototyping — remember that every method returns a `Result`: ```typescript const repository = new BankAccountRepository(); // Save an entity and its events atomically const result = account.withdraw(200); if (result.isOk()) { await repository.saveWithEvents(account, result.value); } // Retrieve the entity — unwrap the Result, then check for undefined const found = await repository.getById(account.id()); if (found.isOk() && found.value !== undefined) { console.log(found.value.readState()); } // Inspect stored events const events = await repository.getEvents(account.id()); ``` Your tests become fast, deterministic, and free of infrastructure setup — without sacrificing any coverage of the domain logic. When you are ready to move to a real database, replace `InMemoryRepository` with your production implementation without touching a single line of domain code. --- ## Optimistic locking Two requests can load the same entity at the same time, both make a valid decision, and both save — the second silently overwrites the first. Optimistic locking catches that. Every `DomainEntity` carries a version: ```typescript entity.version(); // the version the entity was loaded at; 0 when never persisted entity.setVersion(n); // called by the repository after a successful save ``` The contract is a division of labour: - **The repository** reads `version()` to guard the write, and calls `setVersion()` afterwards so a second save of the same instance uses the up-to-date version. - **Domain code never calls `setVersion()`.** Mutating the version outside a persistence boundary defeats the entire mechanism. When the persisted version no longer matches, the repository returns a `ConcurrentWriteError` **inside a `Result`** — deliberately returned rather than thrown, so that retry sits in ordinary control flow: ```typescript const saveResult = await repository.save(account); if (saveResult.isErr() && saveResult.error.name === "CONCURRENT_WRITE") { // Somebody else committed first. Reload, re-apply, retry. } ``` This is the opposite of [`CorruptedStateError`](https://ontologic.site/docs/domain-model/domain-entity), which signals a bug and is thrown. A concurrent write is not a bug — it is an expected outcome under load, and recoverable. :::warning `InMemoryRepository` does **not** implement optimistic locking. Versions stay at `0` and every `save()` succeeds. It is built for tests and prototyping, where there is no concurrency to guard against. Any production repository you write should implement the version check itself. ::: A production implementation guards the write in SQL and only calls `setVersion` when a row actually came back: ```typescript // UPDATE ... SET version = version + 1 WHERE id = $1 AND version = $2 // Zero rows returned means somebody else got there first. if (rows.length === 0) { return err( new ConcurrentWriteError({ entityId: entity.id(), expectedVersion: entity.version(), }), ); } entity.setVersion(rows[0].version); return ok(undefined); ``` --- ## Summary | Responsibility | Belongs to | |---|---| | Domain rules and behavior | Entity | | Storing and retrieving entities | Repository | | Atomic save of entity + events | `saveWithEvents` | | Guarding against concurrent writes | Repository, via `version()` / `setVersion()` | | Deciding what to do about a lost race | Caller, via `ConcurrentWriteError` | The repository is the seam between your domain and the outside world. Keep it narrow, keep it clean, and your domain stays honest. --- # Application --- Source: https://ontologic.site/docs/application/use-case # Use Case An entity knows its own rules. A use case knows everything else: which aggregates to load, which rule spans more than one of them, and what to persist when the domain says yes. `ontologic` gives you one interface for it. ```typescript export interface UseCase< Action extends ActionInterface, Output, Errors extends DomainError, > { execute(action: Action): Promise>; } ``` Three type arguments, and each one is a contract: what the use case is **asked** to do, what it **produces**, and which domain failures a caller **must** handle. ## The action is a Command or a Query A use case does not take a loose input object. It takes an **action**, and the action carries the intent. A `Command` is a request to change something, which the domain may refuse. A `Query` is a request to read, which it cannot. Both are declared the same way a `DomainEvent` is — a literal name bound once in the subclass, and a payload: ```typescript import { Command, Query } from "ontologic"; export class PayOrderCommand extends Command< "PAY_ORDER", { id: string; invoiceId: string } > { constructor(payload: { id: string; invoiceId: string }) { super({ name: "PAY_ORDER", payload }); } } export class ReadOrderQuery extends Query<"READ_ORDER", { id: string }> { constructor(payload: { id: string }) { super({ name: "READ_ORDER", payload }); } } ``` Choose by what the use case does with its aggregates. If it calls `save` or `saveWithEvents`, it is a command. If it only reads, it is a query. That choice is not a comment. Each class holds private fields, so the two are **nominally distinct**: a `Query` is never assignable where a `Command` is expected, even when the payloads are identical. ```typescript declare function pay(command: PayOrderCommand): void; pay(new ReadOrderQuery({ id: "order-1" })); // Argument of type 'ReadOrderQuery' is not assignable to parameter of type // 'PayOrderCommand'. Type 'ReadOrderQuery' is missing the following properties // from type 'PayOrderCommand': #name, #payload ``` Both expose `name`, `payload` and `kind` (`"command"` or `"query"`), and both clone the payload on the way in and on the way out — so nothing that hands you an action can mutate it afterwards, and nothing you do with `action.payload` reaches back into it. Because every read of `payload` produces a fresh clone, destructure it once at the top of `execute` rather than reaching for it repeatedly. ## Writing a use case Dependencies are constructor parameters — one per aggregate the use case touches: ```typescript import { Result, UseCase, err, ok, switchGuard } from "ontologic"; export class PayOrderUseCase implements UseCase< PayOrderCommand, OrderState, InvalidStatusTransition | EntityNotFound > { constructor(private readonly orders: OrderRepository) {} async execute( command: PayOrderCommand, ): Promise> { const { id, invoiceId } = command.payload; const resultGetById = await this.orders.getById(id); if (resultGetById.isErr()) { throw resultGetById.error; // technical failure → throw } const order = resultGetById.value; if (order === undefined) { return err(new EntityNotFound("This order does not exist", { entityId: id })); } const result = order.pay({ invoiceId }); if (result.isErr()) { switch (result.error.name) { case "INVALID_STATUS_TRANSITION": return err(result.error); default: switchGuard(result.error.name); } } const saveResult = await this.orders.saveWithEvents(order, result.value); if (saveResult.isErr()) { throw saveResult.error; } return ok(order.readState()); // return the state, never the entity } } ``` The rule that decides every branch: **technical failures are thrown, domain failures are returned**. A dead database is not a business outcome. A missing order might be — that is a decision the domain gets to make, so it comes back in the `Result`. ## The error side cannot be widened This does not compile: ```typescript export class PayOrderUseCase implements UseCase {} // ^^^^^ // Type 'Error' does not satisfy the constraint 'DomainError'. // Property 'context' is missing in type 'Error'. ``` `Errors` is constrained to `DomainError`, and `DomainError` declares a `context` property that plain `Error` does not have. So `Result` is rejected at the type level. That is deliberate. A widened error union throws away the exhaustiveness checking that makes [`switchGuard`](https://ontologic.site/docs/domain-model/result-pattern) useful, and leaves callers unable to see what they have to handle. Name the failures: ```typescript export type RegisterLoanError = | BookNotFoundError | BookLostCannotBeLoanedError | BookAlreadyOnLoanError | MemberActiveLoanLimitExceededError; ``` A use case with no domain failure mode says so with `never`: ```typescript export class AddBookUseCase implements UseCase {} ``` ## Read many aggregates, write one `saveWithEvents(entity, events)` is the only atomic unit — there is no cross-aggregate transaction. So a use case should **read from as many aggregates as it needs and write to exactly one**. Each aggregate it touches is one more constructor parameter, which makes the shape visible at the top of the class: ```typescript export class RegisterLoanUseCase implements UseCase { constructor( private readonly libraryCollection: LibraryCollection, // read private readonly loanRegister: LoanRegister, // written ) {} } ``` Needing two writes is a signal that the aggregate boundary is wrong, or that the second change should be driven by an event instead. ## Keep the framework out A use case is a plain class. Don't put `@Injectable()` or any other framework decorator on it — wiring it into a container is the composition root's job: ```typescript // NestJS, in the module — the use case stays framework-free { provide: RegisterLoanUseCase, useFactory: (books: LibraryCollection, loans: LoanRegister) => new RegisterLoanUseCase(books, loans), inject: [LibraryCollection, LoanRegister], } ``` ## Why declare all this Beyond the compiler checks, a declared use case is one a **tool can read**. `implements UseCase` is a written type reference, so its action, its output and its failure modes can be recovered from the source without running anything — which is what lets documentation and diagrams be generated from the code rather than maintained beside it. Where use cases were only a naming convention, none of that was knowable: an exported async function returning a `Result` might be a use case, or might be a helper. ## Where to go next - [Repository](https://ontologic.site/docs/domain-model/repository) — the port a use case loads and saves through - [Result pattern](https://ontologic.site/docs/domain-model/result-pattern) — `ok`, `err` and `switchGuard` - [Domain Entity](https://ontologic.site/docs/domain-model/domain-entity) — which rules belong on the entity instead --- # Messaging --- Source: https://ontologic.site/docs/event-bus/event-bus # Event Bus Once domain events are persisted via the [Outbox pattern](https://ontologic.site/docs/domain-model/domain-events#publishing-with-the-outbox-pattern), a message relay needs to read them from the database and then use an event bus to deliver events to the rest of your system. `ontologic` ships a typed event bus with a **publisher** and a **listener**, each backed by a pluggable **connector**. The connector is the only piece you swap out between environments: the publisher/listener logic stays the same whether you're running tests locally or processing millions of messages in production. --- ## Core concepts ### Publisher The publisher publish events to a message broker. It accepts any event that matches your domain's event union type, validates the metadata, and hands off the serialized message to its connector. ### Listener The listener subscribes to incoming messages from the broker and dispatches them to your handlers. You register a handler per event name — or a wildcard handler for everything — before starting the listener. Every delivery ends in exactly one of four ways, decided by the listener rather than by the connector: | Outcome | Message | Reported through | | --- | --- | --- | | Your handler resolves | `ack()` | — | | No handler registered for the event | `ack()` | `onUnhandled(name)` | | Envelope has no `event.name` | `ack()` | `onError(error)` | | Content is not JSON, or fails the validator | `nack()` | `onError(error)` | | Your handler throws | `nack()` | `onError(error)` | ### Connector The connector is the adapter between the event bus and the underlying broker. It is the only thing that knows about Kafka, SQS, RabbitMQ, or whatever you're running. The publisher and listener each depend on a connector interface — swap the connector, keep everything else. ### Ordered or not Whether events are delivered in order is your choice, per consumer. Sometimes order matters (a projection that applies an entity's events one after the other), sometimes it doesn't (sending an email per event). - The **publisher** takes a plain publisher connector (`kind: "publisher"`) or an ordered one (`kind: "ordered-publisher"`). An ordered connector requires an `orderingKey` on every `publish`, usually the entity id, which is what the [message relay](https://ontologic.site/docs/event-bus/message-relay) passes. - The **listener** takes a plain listener connector (`kind: "listener"`) or an ordered one (`kind: "ordered-listener"`), which hands a key's events over one after the other. --- ## Defining your event union Start by defining the union of all domain events your service produces or consumes. The event bus is generic over this union, which gives you type-safe handlers. ```typescript import { DomainEvent } from "ontologic"; class OrderPlaced extends DomainEvent< "ORDER_PLACED", 1, { orderId: string; total: number } > { constructor(entityId: string, payload: { orderId: string; total: number }) { super({ name: "ORDER_PLACED", version: 1, entityId, payload }); } } class PaymentReceived extends DomainEvent< "PAYMENT_RECEIVED", 1, { amount: number; currency: string } > { constructor(entityId: string, payload: { amount: number; currency: string }) { super({ name: "PAYMENT_RECEIVED", version: 1, entityId, payload }); } } type OrderEvents = OrderPlaced | PaymentReceived; ``` --- ## Publishing events ```typescript import { DomainEventBusPublisher } from "ontologic"; const publisher = new DomainEventBusPublisher({ publisherConnector: myConnector, }); await publisher.start(); await publisher.publish( new OrderPlaced("order-123", { orderId: "order-123", total: 99 }), { id: "evt-abc", createdAt: new Date().toISOString(), }, ); await publisher.stop(); ``` The `publish` method validates the metadata before forwarding. An invalid `id` or `createdAt` throws immediately — the event is never sent. With an ordered publisher connector, pass the key whose events must stay in order, usually the entity id. Publishing to an ordered connector without one throws: ```typescript await publisher.publish(event, metadata, { orderingKey: event.entityId }); ``` ### Event metadata Every published event carries metadata alongside the event payload: | Field | Type | Required | Description | | ----------- | -------- | -------- | ----------------------------------------------------------------- | | `id` | `string` | Yes | Unique identifier for this event occurrence | | `createdAt` | `string` | Yes | ISO 8601 datetime with timezone (e.g. `2024-01-15T10:30:00.000Z`) | | `offset` | `number` | No | Position in the event stream, if tracked | --- ## Listening to events ```typescript import { DomainEventBusListener } from "ontologic"; const listener = new DomainEventBusListener({ listenerConnector: myConnector, options: { validator: parseOrderEvents }, }); listener.listenTo("ORDER_PLACED", async (event, metadata) => { // event is typed as OrderPlaced console.log(event.payload.orderId, metadata.id); }); listener.listenTo("PAYMENT_RECEIVED", async (event, metadata) => { // event is typed as PaymentReceived console.log(event.payload.amount, event.payload.currency); }); await listener.start(); ``` You must register at least one handler before calling `start()` — starting without handlers throws an error. ### Wildcard handler To handle all incoming events with a single callback, use `"*"` as the event name: ```typescript listener.listenTo("*", async (event, metadata) => { console.log("received", event.name, metadata.id); }); ``` The wildcard handler is used as a fallback: if an incoming event has no specific handler registered, it falls through to `"*"`. If there is no specific handler and no wildcard, the message is **acknowledged** and the name is reported through `onUnhandled`. Acknowledged, not nack'd: `listenTo` is per event name precisely so a consumer can take only what concerns it, and a nack asks the broker to deliver the message again. Nothing about the second attempt would differ — the handler is still not registered — so a nack here buys a redelivery loop, or a dead-letter queue filling with events that were never this consumer's business. If you want to notice a handler you forgot to wire, register `onUnhandled`: ```ts listener.onUnhandled((eventName) => { logger.debug(`no handler for ${eventName}`); }); ``` It is deliberately not `onError`. An unsubscribed event is a routine outcome, and a consumer with selective subscriptions would otherwise see a constant stream of non-errors on its error channel. --- ## Connectors The connector is the only environment-specific piece of the event bus. Everything above — generic types, metadata validation, handler dispatch, ack/nack semantics — is implemented once in the publisher and listener, independent of the broker. ### Implementing a connector To integrate a broker, implement two interfaces. They live in `ontologic`'s shared bus connector contract, which the [command bus](https://ontologic.site/docs/event-bus/command-bus) uses too: **Publisher connector:** ```typescript interface IPublisherConnector { readonly kind: "publisher"; status: "STARTED" | "STOPPED"; start(): Promise; stop(): Promise; publish(message: string, options?: { orderingKey?: string }): Promise; onError(handler: (error: Error) => void): void; checkConnection(): Promise; } ``` **Listener connector:** ```typescript interface IListenerConnector { readonly kind: "listener"; status: "STARTED" | "STOPPED"; start(): Promise; stop(): Promise; onMessage(handler: (message: ReceivedMessage) => Promise): void; topicName(): string; onError(handler: (error: Error) => void): void; checkConnection(): Promise; } ``` **Received message:** ```typescript interface ReceivedMessage { content: string; // JSON-serialized { event, metadata } envelope ack(): Promise; nack(): Promise; } ``` That's the full contract. The connector never sees the event name: the listener reads it from `event.name` inside the envelope to route to the right handler. An envelope without an event name is acked and reported through `onError`, because redelivering it cannot make it routable. The `kind` field is a discriminator. Several connector interfaces are otherwise structurally identical, and without it TypeScript would accept a listener where an ordered listener was expected. The listener calls `ack()` after your handler resolves successfully, and `nack()` if it throws. How ack/nack are implemented is entirely up to the connector — requeue, dead-letter, or discard are all valid choices depending on your broker and your requirements. :::warning[A failing event blocks its group] An event whose handler throws is nacked. On `SqsOrderedListener`, nothing behind it with the same ordering key then runs until it succeeds. That is deliberate: skipping it would corrupt everything downstream. Set `nackVisibilitySeconds` as the retry delay, never set `maxDeliveries` on an event listener, and use no redrive policy (or a very high `maxReceiveCount`) on event queues. ::: :::note[Upgrading a connector written for 1.9] 1.10 changed the connector contract: - `publish(name, message, options)` is now `publish(message, options)`. - `ReceivedMessage.name` is gone; routing reads `event.name` from the envelope. - Every connector declares a `kind` and implements `checkConnection()`. Listeners also implement `topicName()`. - `onError` handlers receive an `Error`. - The interfaces and in-memory connectors moved from `event-bus/connectors` to the shared bus connectors. They are still exported from `ontologic`. ::: ### Supported brokers The connector interfaces are intentionally thin. Any broker that can route named messages and support acknowledgments fits the model: | Broker | Notes | | ------------------ | ------------------------------------------------------------------------------- | | **AWS SQS** | `@ontologics/sqs-connectors`: `SqsPublisher`/`SqsListener` on a standard queue, or `SqsOrderedPublisher`/`SqsOrderedListener` on a FIFO queue for per-entity order | | **Apache Kafka** | Topic per event name, or a single topic with the event name in the key | | **Google Pub/Sub** | One topic per event, subscription per listener | | **RabbitMQ** | Topic exchanges with the event name as the routing key | | **Redis Streams** | `@ontologics/redis-connectors`: `RedisOrderedPublisher`/`RedisOrderedListener` (a stream and a consumer group). Per-key order holds only with a single consumer | --- ## In-memory connectors `ontologic` ships in-memory connectors out of the box: ```typescript import { InMemoryConnectors } from "ontologic"; const connectors = new InMemoryConnectors(); const publisher = new DomainEventBusPublisher({ publisherConnector: connectors.publisher, }); const listener = new DomainEventBusListener({ listenerConnector: connectors.listener, options: { validator: parseOrderEvents }, }); ``` The connectors share an internal `EventEmitter`. Publishing an event immediately delivers it to every registered listener in the same process: in-memory listeners broadcast, there are no competing consumers. `connectors.orderedPublisher` and `connectors.orderedListener` are there too, to test against the ordered connector kinds. **These connectors are intended for tests and local prototyping only.** They have no persistence, no retry logic, no dead-letter queue, and no cross-process delivery. If the process restarts, unprocessed messages are gone. Ack and nack are no-ops. Do not use them in production. ### Using in-memory connectors in tests ```typescript import { InMemoryConnectors, DomainEventBusPublisher, DomainEventBusListener, } from "ontologic"; test("listener receives published events", async () => { const connectors = new InMemoryConnectors(); const publisher = new DomainEventBusPublisher({ publisherConnector: connectors.publisher, }); const listener = new DomainEventBusListener({ listenerConnector: connectors.listener, options: { validator: parseOrderEvents }, }); const received: OrderPlaced[] = []; listener.listenTo("ORDER_PLACED", async (event) => { received.push(event as OrderPlaced); }); await listener.start(); await publisher.start(); await publisher.publish( new OrderPlaced("order-1", { orderId: "order-1", total: 50 }), { id: "evt-1", createdAt: new Date().toISOString() }, ); expect(received).toHaveLength(1); expect(received[0].payload.total).toBe(50); await publisher.stop(); await listener.stop(); }); ``` Each test builds its own `new InMemoryConnectors()`, so there is no shared state between tests. --- ## Validating event shape A validator is **required** on the listener. Events travel over the wire as JSON. When the listener receives a message and deserializes it, the result is a plain JavaScript object — not an instance of your `DomainEvent` class. Without a validator, your handler receives a structurally correct object but one that is missing the class identity: `instanceof` checks fail, prototype methods are absent, and any class-level invariants you rely on are silently bypassed. The validator is the step that reconstructs a real event instance from the raw wire payload: ```typescript import { DomainEvent } from "ontologic"; // with a schema library like Zod const OrderPlacedSchema = z.object({ entityId: z.string().min(1), name: z.literal("ORDER_PLACED"), version: z.literal(1), payload: z.object({ orderId: z.string(), total: z.number() }), }); function parseOrderPlaced(raw: unknown): OrderPlaced { const data = OrderPlacedSchema.parse(raw); return new OrderPlaced(data.entityId, data.payload); } ``` Pass the validator when constructing the listener: ```typescript const listener = new DomainEventBusListener({ listenerConnector: myConnector, options: { validator: parseOrderPlaced, }, }); ``` The validator runs after deserialization and before your handler is called. If it throws, the message is nack'd, the error is reported through `onError`, and your handler is never invoked. --- ## Error handling Both the publisher and listener surface connector-level errors through an `onError` callback. Wire it up before calling `start()`: ```typescript publisher.onError((error) => { logger.error("event bus publisher error", { error }); }); listener.onError((error) => { logger.error("event bus listener error", { error }); }); ``` The handler always receives an `Error`: anything else that gets thrown is wrapped in one first. Handler-level errors (thrown inside a `listenTo` callback) result in an automatic `nack()` and are reported through `onError`. Events with no matching handler do not reach `onError` — they are acknowledged and reported through `onUnhandled` instead, because an event you did not subscribe to is not a failure. --- ## Lifecycle Both publisher and listener follow the same lifecycle: 1. **Configure** — pass connectors and options to the constructor 2. **Register handlers** (listener only) — call `listenTo` before `start` 3. **Start** — call `start()` to initialize the connector and begin processing 4. **Stop** — call `stop()` to stop the connector. Whether messages already received finish first is the connector's behaviour: `@ontologics/sqs-connectors` listeners wait for them, the in-memory ones don't ```typescript await publisher.start(); // ... publish events await publisher.stop(); await listener.start(); // ... process events await listener.stop(); ``` Starting a publisher or listener whose connector is already started, or stopping one that is already stopped, has no effect. Both also expose `status()` and `checkConnection()`, which delegates to the connector and throws if its check fails. These are the same lifecycle methods the [command bus](https://ontologic.site/docs/event-bus/command-bus) emitter and receiver expose. --- Source: https://ontologic.site/docs/event-bus/message-relay # Message Relay The **Message Relay** is the bridge between your outbox table and your event bus. Its job is to read domain events that were persisted by the [repository](https://ontologic.site/docs/domain-model/repository#saving-entities-and-events-together) and forward them to the rest of your system via the [event bus](https://ontologic.site/docs/event-bus/event-bus). It is designed to be **fault-tolerant**: it tracks exactly which events have been published so that, after a crash or restart, it picks up precisely where it left off — no events skipped, however events maybe be published twice. --- ## The Outbox pattern The **Outbox pattern** solves a fundamental problem in distributed systems: how do you guarantee that a domain event is both persisted to your database _and_ delivered to the message broker, even if one of them fails? The naive approach consist to save the entity, then publish the event. But it has a gap: if the process crashes after the save but before the publish, the event is lost forever. Doing it in the other order has the same problem in reverse. The outbox pattern closes this gap by writing the event to the **same database transaction** as the entity state change. The event is stored in an "outbox" table first. Then a separate process (the Message Relay) reads from that table and forwards events to the broker. The two steps are decoupled, and each can be retried independently. The key guarantee: if the relay crashes mid-batch, it restarts from the last checkpoint and re-publishes only the remaining events. The entity state in the database is never at risk. --- ## How it works When triggered for a given entity, the relay runs the following sequence: 1. **Lock** the entity to prevent concurrent relay runs for the same entity 2. **Read** the last event ID that was successfully published for this entity 3. **Fetch** all events from the outbox that come after that checkpoint 4. For each event, **publish** it via the event bus, then **update** the checkpoint 5. **Unlock** the entity in all cases, even on failure Because the checkpoint is updated after each individual event, a failure mid-batch means the relay will re-attempt from the last successfully published event on the next run — not from the beginning. --- ## Setup The `MessageRelay` class takes four dependencies: ```typescript import { MessageRelay } from "ontologic"; const relay = new MessageRelay( repository, // Repository — source of outbox events stateRepository, // MessageRelayStateRepository — tracks publishing progress "Order", // entityName — scopes the checkpoint to this entity type publisher, // DomainEventBusPublisher — delivers events to the bus ); ``` --- ## Triggering the relay The relay exposes a `handler` method that you call with an `entityId`. In the simplest setup where the relay runs in the same process as your application. You can wire it directly to the repository's `onChanges` callback: ```typescript repository.onChanges(relay.handler.bind(relay)); ``` This works well for prototyping and single-process deployments. In production however, **you may want to run the relay in a separate process** to isolate it from your application and scale it independently. In that case `onChanges` is no longer available, and you need another way to trigger the handler. Common approaches include: - **Periodic polling** — run the relay on a cron schedule (e.g. every second), scanning for unpublished events across all entities - **HTTP / gRPC** — your application calls an endpoint on the relay process after saving an entity - etc... The right choice depends on your latency requirements and infrastructure. --- ## Tracking publishing state The relay depends on a `MessageRelayStateRepository` to persist its checkpoint. This repository must implement four operations: ```typescript interface MessageRelayStateRepository { lock(params: { entityId: string; entityName: string }): Promise; unlock(params: { entityId: string; entityName: string }): Promise; getLastEventIdPublished(params: { entityId: string; entityName: string; }): Promise; updateLastEventIdPublished(params: { eventId: string; entityId: string; entityName: string; }): Promise; } ``` The checkpoint is keyed by `(entityId, entityName)`, so a single state repository can safely track multiple entity types. ### In-memory implementation For tests and local development, `ontologic` ships a ready-to-use in-memory implementation: ```typescript import { InMemoryMessageRelayStateRepository } from "ontologic"; const stateRepository = new InMemoryMessageRelayStateRepository(); ``` It stores state in a `Map` in memory. **Do not use it in production** state is lost on process restart. ### Production implementation For production you must implement `MessageRelayStateRepository` backed by durable storage. The right choice depends on your stack: | Storage | Notes | | -------------- | -------------------------------------------------------------------------------------- | | **PostgreSQL** | Store state in a `message_relay_state` table; use `SELECT ... FOR UPDATE` for the lock | | **Redis** | Use a hash for state and `SET NX PX` for the distributed lock | | **DynamoDB** | Use a conditional write for the lock and a single item per `(entityName, entityId)` | If the relay runs in a separate process from your application, the state repository **must** be backed by shared external storage an in-process `Map` cannot be seen across process boundaries. --- ## Error handling A failure while relaying (reading the outbox, publishing an event, moving the checkpoint, or a lock already held by another run) is reported through `onError`, always as an `Error`. The run stops at the failed event, and the next run for that entity starts again from the last checkpoint. `handler()` itself never rejects, so a relay wired to `onChanges` cannot take the process down. Register `onError` so failures are not silent: ```typescript relay.onError((error) => { logger.error("message relay error", { error }); }); ``` A run that took the lock always releases it, even when an error occurs, so a failed relay run never leaves an entity permanently locked. A run that could not take it, because another run for the same entity holds it, leaves that lock alone. --- ## Full example ```typescript import { MessageRelay, InMemoryMessageRelayStateRepository, DomainEventBusPublisher, InMemoryConnectors, } from "ontologic"; // Set up the event bus const connectors = new InMemoryConnectors(); const publisher = new DomainEventBusPublisher({ publisherConnector: connectors.publisher, }); await publisher.start(); // Set up the relay const stateRepository = new InMemoryMessageRelayStateRepository(); const relay = new MessageRelay(repository, stateRepository, "Order", publisher); relay.onError((error) => { console.error("relay error", error); }); // Trigger the relay whenever an entity changes repository.onChanges(relay.handler.bind(relay)); // Now, saving an entity with events will automatically trigger the relay const result = order.place({ items }); if (result.isOk()) { await repository.saveWithEvents(order, result.value); // onChanges fires → relay reads the new event → publishes it → updates checkpoint } ``` --- ## Summary | Concern | Handled by | | -------------------------------- | ----------------------------- | | Reading events from the outbox | `Repository.getEventsAfter` | | Delivering events to the bus | `DomainEventBusPublisher` | | Tracking publishing progress | `MessageRelayStateRepository` | | Preventing concurrent relay runs | `lock` / `unlock` | | Recovering from failure | Per-event checkpoint updates | The relay ensures that every event written to the outbox is eventually delivered — and that delivery survives failures without duplicating or losing events. --- Source: https://ontologic.site/docs/event-bus/command-bus # Command Bus The [event bus](https://ontologic.site/docs/event-bus/event-bus) is fire-and-forget: a publisher announces that something happened, and has no idea who listens. A **command bus** is the opposite. It is request/response over a broker: a caller sends a command to whichever service handles it and **waits for the answer**, with a timeout. `ontologic` ships a typed command bus with an **emitter** (the caller side) and a **receiver** (the handler side), backed by the same pluggable connectors as the event bus. --- ## Core concepts A command bus is two one-way channels, not one duplex channel: ``` commands emitter --ordered publish--> receiver (one topic, ordered by key) responses receiver --dynamic publish--> emitter (one topic per emitter) ``` ### Emitter `CommandBusEmitter` publishes a command, then waits for the matching response on its own response topic. `send()` resolves with a `Result`: `Ok(payload)` when the handler succeeded, or `Err(error)` when it refused, threw, or did not answer in time. ### Receiver `CommandBusReceiver` consumes commands, runs your handler, and publishes the response back to the topic the emitter named in the command. That is why the response side is a **dynamic** publisher: many emitters can share one receiver, each with its own response topic. ### Commands A command on the bus is the same [use-case `Command`](https://ontologic.site/docs/application/use-case) you hand to a use case in-process: a `name` and a JSON-serializable `payload`. Plain objects with that shape work too. ```typescript import { Command, type CommandMetadata } from "ontologic"; interface PlaceOrderPayload { orderId: string; items: { sku: string; quantity: number }[]; } class PlaceOrderCommand extends Command<"PLACE_ORDER", PlaceOrderPayload> { constructor(payload: PlaceOrderPayload) { super({ name: "PLACE_ORDER", payload }); } } ``` Like an event, a command travels with **metadata**, which identifies this occurrence: | Field | Type | Required | Description | | --- | --- | --- | --- | | `id` | `string` | Yes | Unique per command. The emitter matches the response on it; use it for idempotency | | `createdAt` | `string` | Yes | ISO 8601 date time with timezone | Extend `CommandMetadata` for anything else you want to carry, such as a correlation id: ```typescript interface PlaceOrderMetadata extends CommandMetadata { correlationId: string; } ``` On the wire the envelope is `{ command, metadata, responseTopicName }`, the same shape as the event bus's `{ event, metadata }`. The response topic is added by the emitter. --- ## Handling commands A command arrives as plain JSON, not as an instance of your class. As on the event bus listener, the receiver therefore takes a **required validator**. It checks the raw command and rebuilds your class: ```typescript function parsePlaceOrder(raw: unknown): PlaceOrderCommand { const data = PlaceOrderSchema.parse(raw); // Zod, or hand-written checks return new PlaceOrderCommand(data.payload); } const receiver = new CommandBusReceiver( { commandSubscriber: commandOrderedListener, responsePublisher: responseDynamicPublisher, }, { validator: parsePlaceOrder }, ); ``` If the validator throws, the handler never runs and the emitter gets an `INVALID_COMMAND` failure right away, instead of waiting for a timeout. A handler receives the command and its metadata, like an event handler, and returns a [`Result`](https://ontologic.site/docs/domain-model/result-pattern). A business refusal is a value, not an exception: ```typescript import { DomainError, err, ok, type CommandHandlerResponse } from "ontologic"; async function handlePlaceOrder( command: PlaceOrderCommand, metadata: PlaceOrderMetadata, ): Promise { const { orderId, items } = command.payload; if (items.length === 0) { return err( new DomainError({ name: "EMPTY_ORDER", message: `Order ${orderId} has no item`, context: { orderId, correlationId: metadata.correlationId }, }), ); } return ok({ orderId, status: "PLACED" }); } receiver.process(handlePlaceOrder); await receiver.start(); ``` You must call `process()` before `start()`. Starting without a handler throws. Throwing works too: the receiver catches it and answers with a failure. Keep throwing for the genuinely unexpected. --- ## Sending commands ```typescript const emitter = new CommandBusEmitter( { commandPublisher: commandOrderedPublisher, responseSubscriber: responseListener, }, { timeout: 5000 }, // default: 10000ms ); await emitter.start(); const result = await emitter.send( { command: new PlaceOrderCommand({ orderId: "order-1", items: [{ sku: "BOOK-1", quantity: 2 }], }), metadata: { id: crypto.randomUUID(), createdAt: new Date().toISOString(), correlationId: "corr-1", }, // Commands sharing a key are handled in order. orderingKey: "order-1", }, { timeout: 2000 }, // optional, per call ); if (result.isErr()) { console.log(result.error.name, result.error.message); } ``` `send()` **throws** rather than returning an `Err` when the command never left. That happens when: - the emitter is not started, or is stopping; - the command or its metadata fails validation; - another command with the same `metadata.id` is already in flight; - the publish itself fails. Once the command is on the broker, every outcome is a `Result`. ### Failure responses Every `Err` coming out of `send()` keeps the full wire error as its `cause`, including a `code` and a `context`: | Situation | `error.name` | `cause.code` | `cause.context` | | --- | --- | --- | --- | | Handler returned `err(error)` | the error's name | the error's `code`, or `COMMAND_REJECTED` | the error's `context` (e.g. a `DomainError`), or `null` | | Handler threw | the thrown error's name | its `code`, or `HANDLER_THREW` | its `context`, or `null` | | Receiver's validator threw | the thrown error's name | its `code`, or `INVALID_COMMAND` | its `context`, or `null` | | No answer within the timeout | `TIMEOUT_ERROR` | `COMMAND_TIMEOUT` | `{ commandId }` | | Still waiting when a forced `stop()` gives up | `EMITTER_STOPPED_ERROR` | `EMITTER_STOPPED` | `{ commandId }` | ```typescript if (result.isErr()) { const wire = result.error.cause as { code: string; context: unknown }; if (wire.code === "COMMAND_TIMEOUT") { // The command may still have been handled. See below. } } ``` A handler's error `context` crosses the wire as JSON. Keep it serializable. --- ## Delivery guarantees - **The receiver acks once the handler has returned**, whatever it returned. A command that failed is not retried by the bus. - **A receiver that crashes mid-handler** leaves the command unacked, so the broker can deliver it again. SQS does this once the visibility timeout expires. Redis does it only when a consumer with the same name restarts. Either way, a handler can run more than once for the same command. - **A timeout or a forced stop does not cancel anything.** The command was published, and a receiver may still handle it. So make handlers idempotent on `metadata.id`. On a timeout, check whether the command was handled before retrying it. --- ## Lifecycle ```typescript await receiver.start(); await emitter.start(); // ... await emitter.stop(); await receiver.stop(); ``` Starting something already started, or stopping something already stopped, has no effect. `stop()` is graceful on both sides, like an HTTP server draining its connections: it refuses new work, waits for in-flight work to finish, and only then stops the connectors. While it drains, `status()` reports `STOPPING`. - **Emitter:** new `send()` calls throw. Commands already sent keep waiting for their response, and the response listener stays up to deliver it. Each one is bounded by its timeout, so `stop()` resolves at the latest when the longest remaining timeout expires. - **Receiver:** the command listener stops first, so nothing new comes in, and a command that still arrives is nacked back to the broker for another receiver. Handlers already running finish, and their responses are still published. The response publisher stops last. The drain has a hard limit, **2 minutes by default**, so a handler that never returns cannot hold the shutdown forever. Pass your own as `stop({ timeout })`, in milliseconds: ```typescript await emitter.stop({ timeout: 20_000 }); await receiver.stop({ timeout: 20_000 }); ``` When the limit hits, `stop()` stops the connectors anyway, resolves, and reports what it abandoned through `onError`: - **Emitter:** commands still waiting resolve with an `EMITTER_STOPPED` failure. - **Receiver:** commands still being handled were never acked, so the broker can deliver them again. That's one more reason to make handlers idempotent. In a process that runs both, stop the emitter before the receiver. Set your platform's shutdown grace period above the stop limit, or lower the limit to fit it. Kubernetes defaults to 30 seconds, so with the 2-minute default you'd pass something like `stop({ timeout: 25_000 })`. Both sides expose `onError(handler)` for connector failures and malformed messages, `status()`, and `checkConnection()`. The emitter also exposes `metrics()`, which returns `{ inFlightCommands }`. --- ## Connectors The command bus needs four connectors, all from the shared bus connector contract: | Role | Interface | `kind` | | --- | --- | --- | | Emitter publishes commands | `IOrderedPublisherConnector` | `ordered-publisher` | | Receiver consumes commands | `IOrderedListenerConnector` | `ordered-listener` | | Receiver publishes responses | `IDynamicPublisherConnector` | `dynamic-publisher` | | Emitter consumes responses | `IListenerConnector` | `listener` | ```typescript interface IOrderedPublisherConnector { readonly kind: "ordered-publisher"; publish(message: string, options: { orderingKey: string }): Promise; // + status, start, stop, onError, checkConnection } interface IDynamicPublisherConnector { readonly kind: "dynamic-publisher"; publishTo(params: { topicName: string; message: string }): Promise; // + status, start, stop, onError, checkConnection } ``` The listener interfaces are the ones described on the [event bus page](https://ontologic.site/docs/event-bus/event-bus#implementing-a-connector). The emitter reads `topicName()` on its response listener to tell receivers where to reply. Commands and responses want different transports. A command is not volatile: someone is waiting for its answer, and it must survive a crashed handler, so it belongs on a durable, ordered queue. A response whose caller has already timed out is worth nothing, so cheap pub/sub fits. ### In-memory For tests and local prototyping: ```typescript import { InMemoryCommandBusConnectors } from "ontologic"; const connectors = new InMemoryCommandBusConnectors(); const receiver = new CommandBusReceiver( { commandSubscriber: connectors.commandOrderedListener, responsePublisher: connectors.responseDynamicPublisher, }, { validator: parsePlaceOrder }, ); const emitter = new CommandBusEmitter({ commandPublisher: connectors.commandOrderedPublisher, responseSubscriber: connectors.responseListener, }); ``` Same caveats as the event bus in-memory connectors: single process, no persistence. Do not use them in production. One set serves **one emitter and one receiver**: in-memory listeners broadcast every message to every subscriber, so a second receiver would handle every command again, and a second emitter would see the first one's responses. ### Redis and SQS Production connectors ship as separate packages, so `ontologic` itself stays dependency-free: | Package | Provides | Use it for | | --- | --- | --- | | `@ontologics/redis-connectors` | `RedisOrderedPublisher`, `RedisOrderedListener` (streams + consumer group), `RedisDynamicPublisher`, `RedisListener` (pub/sub) | Both channels | | `@ontologics/sqs-connectors` | `SqsOrderedPublisher`, `SqsOrderedListener` (FIFO queue, `orderingKey` → `MessageGroupId`, groups in parallel) | Commands. Pair with Redis for responses | ```bash npm install @ontologics/redis-connectors npm install @ontologics/sqs-connectors # optional, for commands ``` What to know before running them in production: - **Redis streams keep per-key order only with a single consumer.** A consumer group spreads entries across consumers. SQS FIFO keeps per-key order across several listeners. - **Redis: call `onError()` before `start()`**, or node-redis gives up reconnecting on the first failure. - **SQS: the queue needs `ContentBasedDeduplication`**, and a visibility timeout longer than your slowest handler. - **SQS: a receiver's `stop()` can take up to `waitTimeSeconds`** (20 by default). It lets the long poll in progress finish instead of aborting it, because an aborted poll can stay open on the broker side (observed on LocalStack) and swallow the next commands until their visibility timeout expires. Lower `waitTimeSeconds` for faster shutdowns. - **SQS: set `maxDeliveries` on the command listener.** A command delivered more times than that is dropped and reported to `onDiscard`, so a poison command no longer holds up the commands behind it with the same ordering key. `SqsOrderedListener` handles each ordering key in order and different keys in parallel, up to `maxInFlight` (default 50). Each package's README has the details. --- # Workflows --- Source: https://ontologic.site/docs/workflows # Workflows Some business operations cannot fit in a single method. A SEPA payment is not just a database write — it is a sequence: check the balance, validate the receiver, run an AML screen, reserve the funds, then create the transfer. Other processes look less like a chain and more like a graph: pull user data and order data and inventory data in parallel, then combine the three into a single decision. `ontologic` ships two flavors of workflow for these two shapes: - **[Step workflow](https://ontologic.site/docs/workflows/step-workflow)** — a typed, linear chain where each step's output feeds the next. Built with `WorkflowBuilder`. Optionally fans out to a fixed set of concurrent subtasks at any point in the chain. - **[Graph workflow](https://ontologic.site/docs/workflows/graph-workflow)** — a DAG of nodes where each node has named children, runs them concurrently, and receives a record of their outputs as its input. Built with `WorkflowNode` and `GraphWorkflow`. Both share the same core promises: - **Observability** — subscribe to step-by-step progress via `onChanges`. - **Persistence** — workflow state lives in a `WorkflowState` object saved through any `WorkflowStateRepository`. - **Resumability** — a re-run skips any step whose result is already cached in the state, so a crashed run picks up exactly where it stopped. - **Failure handling** — when a step throws, the error is wrapped with the step's name and the original error is preserved as `cause`. --- ## Why not just chain async functions? Plain `await` chains work for two or three steps. They start to creak when: - A step fails halfway through, and you need to know **which** one and **why** without parsing stack traces. - The process must be **resumable** after a crash, picking up at the step that didn't finish. - The intermediate values are useful for **observability**: auditing, debugging, business reporting. - Each step has a **different input shape**, and you want the type system to enforce the order. - Steps run **in parallel** and you want the type system to track which result came from where. Both workflow flavors give you all of that without forcing a heavy framework. Steps are plain functions, the chain or graph is type-checked end to end, and the state is a plain object you can persist anywhere. --- ## Shared state Both flavors thread the same state object through every step: | Field | What it holds | | ------------- | ---------------------------------------------------------- | | `id` | Stable identifier for this workflow run | | `name` | Human-readable name | | `input` | The original input | | `stepResults` | A `Map` of step name → step output | | `error` | The step that failed and the wrapped error message, if any | | `status` | `TODO` → `IN_PROGRESS` → `DONE`, or `FAILED` | `stepResults` is the source of truth for **what has finished so far**. It is also the mechanism behind resumability: if a step's name is already a key in `stepResults`, both flavors skip its handler and reuse the cached output. A `WorkflowStateRepository` is the pluggable persistence interface — `save` and `getById`. `ontologic` ships `InMemoryWorkflowStateRepository` for tests and local prototyping; swap it for Postgres, MongoDB, or anything else, and the rest of your workflow code is unchanged. --- ## Observability — `onChanges` Both flavors expose an `onChanges` callback that fires as steps transition: ```typescript workflow.onChanges((event) => { // event = // | { step: string; status: "IN_PROGRESS" } // | { step: string; status: "DONE" } // | { step: string; status: "FAILED"; error: Error } }); ``` Both flavors emit the same three statuses, and `step` is the name you gave the step or node. The parallel subtasks of `addStepWithSubtasks` report under their own subtask names. Use it for logging, progress UIs, metrics, or audit trails. Subscribe before calling `execute()`. The event shape is exported as `WorkflowChangeEvent`, so a handler defined outside the `onChanges` call can still be typed: ```typescript import { WorkflowChangeEvent } from "ontologic"; function logProgress(event: WorkflowChangeEvent) { console.log(`${event.step} → ${event.status}`); } workflow.onChanges(logProgress); ``` --- ## Failures are first-class When any step's handler throws, both flavors: 1. Wrap the error with the step's name and the original error as `cause`. 2. Set `state.error` to `{ step, error, name }` so the failure is visible in the persisted state. 3. Mark `state.status` as `FAILED`. 4. Emit a `FAILED` event through `onChanges`. ```typescript try { await workflow.execute(repository); } catch (err) { // err.message contains the step name // err.cause is the original error from the handler } ``` For domain-meaningful cancellations (a balance too low, a receiver flagged as fraudulent), throw a `DomainError` from inside the handler rather than a plain `Error`. The same wrapping applies, and the structured context survives in `error.cause`. From there, your code decides which failures deserve a retry and on what schedule. --- ## Choosing between step and graph | Question | Use this | | ------------------------------------------------------ | ---------------------------- | | Each step depends on exactly one prior step's output | Step | | A step occasionally fans out to a fixed set of N tasks | Step + `addStepWithSubtasks` | | Dependencies form a tree or DAG with branching | Graph | | You want to name and reference inputs by child node | Graph | | Linear pipeline, no fan-out | Step | If your process reads naturally as _"do A, then B, then C"_, the [step flavor](https://ontologic.site/docs/workflows/step-workflow) matches that shape. If it reads as _"D depends on B and C, which both depend on A"_, the [graph flavor](https://ontologic.site/docs/workflows/graph-workflow) lets the dependency structure live in the code rather than in your head. --- Source: https://ontologic.site/docs/workflows/step-workflow # Step workflow Use the step flavor when your process is essentially a chain: each step depends on the previous one's output, and the order is sequential. Steps are added one after the other with `addStep`, and the type system enforces that the output of step N matches the input of step N+1. The shared semantics — state, persistence, observability via `onChanges`, and structured failure handling — are described on the [Workflows introduction](https://ontologic.site/docs/workflows). This page focuses on the step-specific API. --- ## Building a chain A workflow starts from an input and threads it through a series of typed steps: ```typescript import { WorkflowBuilder, WorkflowStep } from "ontologic"; interface SepaPaymentRequest { accountId: string; receiverIban: string; amount: number; } const checkAccountBalance: WorkflowStep< SepaPaymentRequest, SepaPaymentRequest > = { name: "Check Account Balance", handler: async (request) => { if (request.amount > 3000) { throw new Error("Not enough funds"); } return request; }, }; const checkReceiverIsValid: WorkflowStep< SepaPaymentRequest, SepaPaymentRequest & { receiverName: string } > = { name: "Check Receiver Is Valid", handler: async (request) => ({ ...request, receiverName: "John Doe", }), }; const workflow = new WorkflowBuilder({ id: randomUUID(), name: "SEPA Payment", input: { accountId: "ACC-001", receiverIban: "...", amount: 250 }, }) .addStep(checkAccountBalance) .addStep(checkReceiverIsValid); const result = await workflow.execute(); ``` The chain is type-checked end-to-end: `checkReceiverIsValid` expects `SepaPaymentRequest`, so it can only be added after a step that produces it. Reordering is a compile error, not a runtime surprise. --- ## Parallel subtasks inside a step When a step needs to fan out into N independent subtasks and aggregate their results, use `addStepWithSubtasks`. Subtasks run concurrently; the step's output is a record keyed by subtask name: ```typescript const workflow = new WorkflowBuilder({ id: randomUUID(), name: "SEPA Payment", input: { accountId: "ACC-001", receiverIban: "...", amount: 250 }, }) .addStepWithSubtasks({ name: "Compliance Checks", subtasks: [ { name: "amlCheck", handler: async (req) => ({ amlScore: 0.12, cleared: true }), }, { name: "kycCheck", handler: async (req) => ({ kycCleared: true }), }, ], }) .addStep({ name: "Decision", handler: async (input) => input.amlCheck.cleared && input.kycCheck.kycCleared, }); ``` The next step receives `{ amlCheck: { amlScore: number; cleared: boolean }; kycCheck: { kycCleared: boolean } }` — the type system tracks each subtask's specific output by its name. If you need to capture a subtask's name as a precise string literal (for instance when storing them in a variable before passing to `subtasks`), use the `defineSubTask` helper: ```typescript import { defineSubTask } from "ontologic"; const amlCheck = defineSubTask({ name: "amlCheck", handler: async (req: SepaPaymentRequest) => ({ cleared: true }), }); ``` --- ## Persisting and resuming Pass a `WorkflowStateRepository` to `execute()` and the state is saved before the first step and after the last one (whether it succeeded or failed): ```typescript import { InMemoryWorkflowStateRepository } from "ontologic"; const repository = new InMemoryWorkflowStateRepository(); await workflow.execute(repository); // Later, after a crash, fetch the state and resume const state = await repository.getById(workflowId); const resumed = new WorkflowBuilder({ id: state.id, name: state.name, input: state.input, stepResult: state.stepResults, // pre-populated cache }) .addStep(checkAccountBalance) .addStep(checkReceiverIsValid); await resumed.execute(repository); ``` A workflow that crashed at step 4 of 5 will, on resume, fast-forward through steps 1–3 and only re-run from step 4. The same caching rule applies inside `addStepWithSubtasks`: a subtask-bearing step whose aggregated result is already in `stepResults` is skipped wholesale. --- ## Summary | Concept | Purpose | | ----------------------------- | ------------------------------------------------------------ | | `WorkflowBuilder` | Init a step-based workflow from an input | | `WorkflowStep` | A named, typed handler in the chain | | `addStep(...)` | Type-checked sequential composition | | `addStepWithSubtasks(...)` | Fan out to N concurrent subtasks; aggregate by name | | `defineSubTask(...)` | Helper that captures a subtask's name as a string literal | | `stepResult` constructor arg | Resume from a previous run by feeding cached results back in | | `execute(repository?)` | Run the chain; optionally persist initial and final state | --- Source: https://ontologic.site/docs/workflows/graph-workflow # Graph workflow Use the graph flavor when the dependencies between steps form a tree (or DAG) rather than a line: a node has _named_ children, runs them concurrently, and receives a record of their outputs as its input. The dependency structure lives in the code rather than in a procedural chain. The shared semantics — state, persistence, observability via `onChanges`, and structured failure handling — are described on the [Workflows introduction](https://ontologic.site/docs/workflows). This page focuses on the graph-specific API. --- ## Building a graph A graph workflow is a subclass of `GraphWorkflow` that constructs its root `WorkflowNode` in `build(...)`. Each node declares its children as a record: a string key plus the child node wired into that slot. ```typescript import { GraphWorkflow, WorkflowNode, InMemoryWorkflowStateRepository, WorkflowStateRepository, } from "ontologic"; interface MyInputs { url: string; data: number[]; name: string; } class MyWorkflow extends GraphWorkflow { constructor(params: { id: string; input: MyInputs; repository?: WorkflowStateRepository; }) { super({ ...params, name: "My Workflow", repository: params.repository ?? new InMemoryWorkflowStateRepository(), }); this.build((input) => this.#root(input)); } #root(input: MyInputs) { const dataSource = new WorkflowNode({ name: "Data Source", children: {}, handler: async () => ({ data: input.data }), }); const nameSource = new WorkflowNode({ name: "Name Source", children: {}, handler: async () => ({ name: input.name }), }); const summed = new WorkflowNode({ name: "Sum", children: { source: dataSource }, handler: async ({ source }) => ({ sum: source.data.reduce((s, c) => s + c), }), }); return new WorkflowNode({ name: "Combine", children: { total: summed, tag: nameSource }, handler: async ({ total, tag }) => `${tag.name} = ${total.sum}`, }); } } const workflow = new MyWorkflow({ id: randomUUID(), input: { url: "...", data: [1, 2, 3, 4, 5], name: "Sacha" }, }); const result = await workflow.execute(); ``` The handler of `Combine` receives `{ total, tag }` automatically typed as `{ total: { sum: number }; tag: { name: string } }` — the type system follows the graph. Children of the same node run concurrently via `Promise.all`. A node with `children: {}` is a leaf: it produces a value without depending on anything below it. --- ## Visualizing the graph `GraphWorkflow.getGraph()` returns a `Graph` — a plain tree of `{ name, status, childs }` — whose `toString()` renders it as ASCII, useful for debugging or shipping into logs: ```typescript console.log(workflow.getGraph().toString()); ``` ``` Combine ├── total: Sum │ └── source: Data Source └── tag: Name Source ``` Each line names a node; the prefix (`├──`, `└──`, `│`) reflects the position of that child among its siblings, and indentation shows depth. `toString()` accepts a `RenderTreeOptions` object: | Option | Default | Effect | | --------------- | -------- | --------------------------------------------------- | | `indent` | `4` | Characters between sibling columns (minimum 2) | | `verticalSpace` | `true` | Adds a skeleton row before each child | | `style` | `"thin"` | Glyph set — `"thin"` (`├─`) or `"heavy"` (`┣━`) | | `color` | `false` | Colorize node names by status using ANSI escapes | ```typescript console.log(workflow.getGraph().toString({ style: "heavy", color: true })); ``` With `color: true`, nodes are gray when `TODO`, orange when `IN_PROGRESS`, green when `DONE`, and red when `FAILED` — so calling it from inside an `onChanges` handler gives you a live progress tree in the terminal. --- ## Observability and persistence Subscribe to step transitions before calling `execute()`: ```typescript workflow.onChanges((event) => { // event = // | { step: string; status: "IN_PROGRESS" } // | { step: string; status: "DONE" } // | { step: string; status: "FAILED"; error: Error } }); ``` The repository passed to the `GraphWorkflow` constructor is saved after `execute()` completes. Resumability works the same way as the step flavor: a node whose name is already a key in `stepResults` skips its handler and reuses the cached output. For the full description of state, repository plumbing, and failure handling — all shared between both flavors — see the [Workflows introduction](https://ontologic.site/docs/workflows). --- ## Summary | Concept | Purpose | | -------------------------- | -------------------------------------------------------------- | | `GraphWorkflow` (subclass) | DAG-shaped workflow; constructs its root in `build(...)` | | `WorkflowNode` | Node with named children, runs them in parallel | | `children: {}` | Marks a leaf node — produces a value with no dependencies | | `children: { key: node }` | Wires `node` into the `key` slot of the handler input | | `getGraph()` | Returns the `Graph` tree; `.toString(opts)` renders it as ASCII | | `setContext(state)` | Shares the workflow state through the tree (called by `build`) | | `onChanges(...)` | Subscribe to `IN_PROGRESS` / `DONE` / `FAILED` events on any node | --- # Event Sourcing --- Source: https://ontologic.site/docs/event-sourcing # Event Sourcing Most applications store the **current state** of things. A row in a `carts` table says the cart holds two mugs. Ask it how it got there was one mug added twice, or two at once, and did the customer briefly add a tee and remove it? And the row has nothing to say. That history was overwritten the moment the state changed. **Event sourcing** inverts the storage. You persist the events (the facts) in order and you never persist the state at all. The state is what you get by replaying those facts from the beginning. That is the whole idea, and it has one consequence worth sitting with: the state is not data you keep. ```bash pnpm add @ontologics/event-sourcing ``` --- ## The state is a projection of events If the events are the truth, then any state is derived and deriving it is a projection. Start from nothing, apply the first event to get the first state, apply the second event to that, and so on until the stream runs out. Whatever falls out the end is the current state. `@ontologics/event-sourcing` gives that projection a name: an **`EventProjection`**. You declare one **applier** per event name, each a small pure function from `(state, event)` to the next state, and the projection runs them in order. An applier is not a handler. It must not send a mail, write a row, or read the clock. A projection replays the whole stream on every rebuild, so anything an applier touches gets touched again every time. --- ## Try it The cart below is event-sourced. It starts with a single event making it existing. Then every button pushed appends one event to the stream on the right. The cart you see is not stored anywhere: it is `apply()` projecting that stream, from scratch, on every render. Click an event to unfold its payload and rewind the cart to that version. Three things to notice. The count and the total are **not in the state**. They are computed from the lines when the cart renders. Storing them would mean two facts that can disagree. Rewinding **destroys nothing**. Viewing v3 of 7 replays the first three events; the other four are still in the stream, dimmed, and jumping back to the head brings them right back. And while you are looking at history, the cart buttons are **disabled**. A stream is append-only: you can add a fact to the end, but you cannot go back and change one. That restriction is not the demo being careful, it is the model being honest. --- ## Declaring a projection Here is the projection the demo above actually runs — the same code, not an illustration of it. ```typescript type CartLine = { sku: string; name: string; unitPrice: number; // in cents quantity: number; }; type CartState = { cartId: string; currency: string; lines: CartLine[]; }; const cartProjection = new EventProjection< CartState, CartEvent, "CART_CREATED" >({ name: "Cart", // Which event brings a cart into existence. Naming it lets a fold start from // nothing, and stops a stream replaying it onto a cart that already exists. creationEvent: "CART_CREATED", // One applier per event. The map is exhaustive over `CartEvent`: leave one // out and this does not compile. appliers: { // Declared like any other applier. The only difference is that it receives // no `state` — at the first event there is none, and asking for it would // not compile. CART_CREATED: ({ event }) => ({ cartId: event.payload.cartId, currency: event.payload.currency, lines: [], }), ITEM_ADDED: ({ event, state }) => { const existing = state.lines.find( (line) => line.sku === event.payload.sku, ); // Adding a sku already in the cart bumps its quantity rather than // opening a second line for the same product. if (existing) { return { ...state, lines: state.lines.map((line) => line.sku === event.payload.sku ? { ...line, quantity: line.quantity + event.payload.quantity } : line, ), }; } return { ...state, lines: [...state.lines, { ...event.payload }] }; }, ITEM_REMOVED: ({ event, state }) => ({ ...state, lines: state.lines.filter((line) => line.sku !== event.payload.sku), }), ITEM_QUANTITY_CHANGED: ({ event, state }) => ({ ...state, lines: state.lines.map((line) => line.sku === event.payload.sku ? { ...line, quantity: event.payload.quantity } : line, ), }), }, }); ``` Projecting a stream is then one call: ```typescript const { state, version } = cartProjection.apply({ events: [cartCreated, appleAdded, orangeAdded], }); // state → { cartId: "cart-7f3a", currency: "EUR", lines: [ … ] } // version → 3 ``` The projection holds no state of its own. A snapshot goes in, a new one comes out, and nothing is kept between calls. A single instance can rebuild any number of carts, and a test can replay the same stream from any starting point. --- ## Snapshots keep replay cheap Replaying from the first event is correct, and for a cart with seven events it is free. For an entity with fifty thousand it is not. A **snapshot** is a state plus the version it was projected to. Hand one to `apply()` and it starts there instead of from nothing, applying only the events recorded since: ```typescript // Fold everything once const first = cartProjection.apply({ events: allEvents }); // Later: start from what you already have, apply only what is new const next = cartProjection.apply({ snapshot: first, events: eventsRecordedSince, }); ``` The result of `apply()` is itself a valid snapshot, so there is no separate type to build. A snapshot is a cache, never a source of truth: delete every one of them and the stream still rebuilds the same state. Note that the creation event is not replayable on top of a snapshot. A cart that already exists cannot be created again, so passing a stream that still starts with `CART_CREATED` alongside a snapshot throws `CreationEventReplayedError` rather than silently re-creating the cart. That matters more than it sounds: a silent re-creation returns a brand new state carrying a version that counts on from the snapshot, which is a wrong answer that looks entirely plausible. --- ## State must be JSON-compatible A projection deep-clones the state as it folds, and checks it before and after, so an applier cannot leak a mutation back into the snapshot you passed in. That check constrains what a state may hold: it has to survive a round trip through `JSON.parse(JSON.stringify(state))` unchanged. Rejected: `undefined`, functions, symbols, `bigint`, `NaN` and the infinities, symbol keys, circular references, and class instances or built-ins such as `Map`, `Set`, `RegExp` and `Date`. In practice that means storing a `Date` as an ISO string and a `Map` as a plain object. Which is the right shape for persisted state anyway. A projected state is a record, not a live object graph, and giving it behaviour is how it stops being either. :::warning `@ontologics/event-sourcing` is early. The projection side described here is what exists today; the event store and the stream-append side of the package are not written yet, so persisting and reading back a stream is still yours to provide. ::: --- ## Summary | Concept | What it means | | ------------------------- | --------------------------------------------------------------------------- | | **Events are the truth** | The stream is persisted; the state is derived and disposable | | **`EventProjection`** | One applier per event name, folded in order by `apply()` | | **Exhaustive appliers** | One applier per event, checked at compile time rather than at fold time | | **Appliers are pure** | `(state, event) => state` replayed on every rebuild, so no side effects | | **Creation event** | Declared in the same map, but receives no prior state and cannot be replayed | | **Entity `version`** | Count of events folded in. It is the optimistic-locking token | | **Event `version`** | The payload's own contract version, for evolving the event shape | | **Snapshot** | A `{ state, version }` point in time to start from; never a source of truth | | **JSON-compatible state** | No `Date`, `Map`, class instances or `undefined` in a projected state | Storing facts instead of state costs you a fold and buys you the entire history.