--- url: https://nimbus.overlap.at/guide/what-is-nimbus.md description: >- Nimbus is a lightweight TypeScript framework for event-driven apps with CloudEvents messaging, CQRS patterns, and built-in OpenTelemetry observability. --- # What is Nimbus? Nimbus is a lightweight TypeScript framework for building event-driven applications. It provides type-safe messaging patterns (Commands, Queries, Events) following the [CloudEvents](https://cloudevents.io/) specification, with built-in observability powered by [OpenTelemetry](https://opentelemetry.io/). ## Other Topics * [The Philosophy behind Nimbus](/guide/philosophy) * [Nimbus for AI](/guide/nimbus-for-ai) * [Architecture Recommendation](/guide/architecture) * [Glossary](/guide/glossary) — pinned terminology for humans and AI agents ## Who Is This For? Nimbus is a good fit if you are: * Building event-driven applications * Looking for explicit, traceable code without hidden magic * Wanting built-in observability without complex setup * Preferring a lightweight framework over heavyweight solutions ## Key Features * **CloudEvents-based messaging** - Commands, Queries, and Events following the industry-standard [CloudEvents](https://cloudevents.io/) specification * **Built-in observability** - Logging, tracing, and metrics via [OpenTelemetry](https://opentelemetry.io/) with zero boilerplate * **Type-safe validation** - Message validation with [Zod](https://zod.dev/) schemas * **MongoDB integration** - Repository pattern and CRUD operations with automatic tracing * **Hono middleware** - Ready-to-use middleware for HTTP APIs * **Runtime flexibility** - Published as plain ESM on npm; runs on Node.js, Bun and Deno --- --- url: https://nimbus.overlap.at/guide/philosophy.md description: >- Nimbus favors simplicity, explicit code, no framework magic, and a flat learning curve over heavy OOP or DI-heavy frameworks. --- # The Philosophy behind Nimbus Nimbus is built on a few core principles that set it apart from other TypeScript frameworks. ## Simplicity Nimbus aims to keep things simple and to avoid overly complex OOP or FP principles. No complex inheritance hierarchies, no dependency injection, no decorators. Just explicit code that is easy to understand and reason about. ## No Framework Magic Three lines of code to build a whole API is great, until something goes wrong and you have no clue why the magic stopped working. ## Flat and easy learning curve There are already great Frameworks like [NestJS](https://nestjs.com/) and [Effect](https://effect.website/) out there for building TypeScript applications. While those frameworks heavily emphasize either object-oriented or functional programming patterns this comes with the cost of a steep learning curve. Nimbus aims to have a learning curve that is as flat as possible. Be productive right from the start. ## Less Dependencies Every dependency you pull in is code you did not write, running with the same privileges as your own. The recent wave of supply chain attacks on the npm ecosystem has made this risk impossible to ignore: a single compromised package, anywhere in the tree, can put your entire application at risk. Nimbus takes this seriously. We keep our direct dependencies to a minimum and deliberately avoid packages that drag in long transitive chains. Less code from strangers means a smaller attack surface, faster installs, and a project you can actually audit. --- --- url: https://nimbus.overlap.at/guide/architecture.md description: >- Recommended foundation — Pure Core (side-effect-free domain logic) inside an Imperative Shell (HTTP, DB, I/O), aligned with CQRS and Event Sourcing. --- # Architecture Nimbus tries to not be too opinionated and does not enforce a specific architecture or design pattern. You should pick the parts you need for the problem you are trying to solve. * CQRS * Event Sourcing * Domain Driven Design * Hexagonal Architecture * Modular Monolith * Microservices * ... On this page we will recommend an architecture idea that lays a good foundation for your application. ## A Good Foundation We recommend to build your application around the idea of a **Pure Core** and an **Imperative Shell**. It aligns well with Hexagonal Architecture (Ports & Adapters) and is a good foundation for patterns like CQRS and Event Sourcing. ![Illustration of the pure core imperative shell architecture](/nimbus-pure-core-imperative-shell.svg) ## The Pure Core The business logic represents the most valuable part of any application. It should be focused, testable, and free from external dependencies. The pure core contains domain logic that: * Can be perfectly discovered and modelled with Domain Driven Design * Accepts type-safe inputs and returns type-safe outputs * Has no side effects (no I/O operations) * Can be tested by running functions with different inputs and comparing outputs - no mocking needed! * Represents the unique value proposition of the application ## The Imperative Shell The shell handles all interactions with the outside world - HTTP requests, database operations, file system access, and other I/O operations. It orchestrates the pure core by providing it with data and persisting the results. The shell's responsibilities include: * Receiving external input (HTTP requests, messages, etc.) * Fetching data from external sources * Calling pure core functions * Persisting results * Sending responses ## Flow of Information Information flows in one direction: **Shell → Core → Shell** The shell can call the core at any time, but the core never calls the shell. This unidirectional flow ensures that business logic remains pure and testable. ![Illustration of the flow of information](/nimbus-flow-of-information.svg) In an HTTP API scenario: 1. Shell receives HTTP request 2. Shell fetches necessary data from database 3. Shell calls core business logic 4. Shell persists results to database 5. Shell sends HTTP response For complex scenarios requiring multiple database queries with business logic in between, core functions can be composed and called sequentially by the shell. ## Testing Recommendation * Unit tests for the pure core. * E2E tests to ensure the whole system works. As the name "pure" core already implies, no side effects are allowed. This makes it easy to test the core by running functions with different inputs and comparing outputs - no mocking needed! Also the core is the most important part of your application as it holds your whole business logic and domain knowledge. So fast and easy to write unit tests give you the most bang for your buck. End to end tests will ensure all parts of your application work together as expected. --- --- url: https://nimbus.overlap.at/guide/nimbus-for-ai.md description: >- Event Sourcing gives AI systems rich, time-ordered domain history. Nimbus ships llms.txt and agent skills that help coding agents learn and apply the framework accurately. --- # Nimbus for AI The conversation around AI today is dominated by ever larger models and increasingly autonomous agents. It is easy to get caught up in the hype and lose sight of what actually makes these systems useful. AI is not a magic wand. No LLM, no matter how capable, can answer meaningful questions about your business or solve real problems if the data it relies on is incomplete, inconsistent, or missing the context of *how* things came to be. The model is only as good as what you feed it. This is where event-driven architecture, and in particular **Event Sourcing**, becomes a strategic asset. Instead of storing only the current state of your system, Event Sourcing captures every fact that ever happened as an immutable event. The result is a complete, time-ordered history of your business domain - exactly the kind of high-quality, contextual data that AI systems thrive on. ## Nimbus as AI Enabler Nimbus is meant to build applications based on messages: [Commands](/guide/core/commands), [Events](/guide/core/events), and [Queries](/guide/core/queries). This is the perfect fit to combine it with Domain Driven Design and Event Sourcing. This way you are building the data foundation that makes future AI use cases - from analytics and forecasting to agentic workflows - viable rather than aspirational. ## Documentation for Agents Coding agents can load the full Nimbus guide from a single URL: * [llms.txt](https://nimbus.overlap.at/llms.txt) — link-rich index of every guide page (Markdown) * [llms-full.txt](https://nimbus.overlap.at/llms-full.txt) — entire guide in one file Use the [Glossary](/guide/glossary) to pin terminology and reduce hallucinations. Per-page Markdown mirrors are available at the same path with a `.md` suffix (for example `/guide/core/commands.md`). ## Skills for Agents The documentation tells a coding agent what Nimbus is. Skills tell it how to work with Nimbus. A skill is a set of reusable instructions that an agent loads whenever a task matches the description of the skill. Nimbus ships two skills in the [skills](https://github.com/overlap-dev/Nimbus/tree/main/skills) folder of the repository. | Skill | What it does | | ------------------------ | ------------------------------------------------------------------------- | | `nimbus-domain-modeling` | Creates and sharpens the domain model of your project together with you. | | `nimbus` | Plans and implements backend code with Nimbus based on that domain model. | ### Installation The skills are installed with the [skills CLI](https://github.com/vercel-labs/skills). Run the following command from the root of your project. ```bash npx skills add overlap-dev/Nimbus ``` The CLI asks which skills you want to install and which coding agents should get them. The two skills are made to work together so we recommend to install both. To install only one of them use the `--skill` option. ```bash npx skills add overlap-dev/Nimbus --skill nimbus ``` Skills are installed into the current project by default. Add the `-g` option to make them available across all of your projects. To get the latest version of the skills later on run the update command. ```bash npx skills update ``` ### An Opinionated Workflow The Nimbus packages try to not be too opinionated. The skills are different. A coding agent delivers better and more consistent results when it follows clear rules. So the skills make the decisions up front and follow one fixed workflow. This workflow is built around [ESDM](https://www.esdm.io/), the Event-Sourced Domain Modeling language. The domain is modeled first and the code is implemented from that model afterwards. The [ESDM Demo](/guide/esdm-demo) page explains both steps and shows the result in a complete example application. The modeling skill needs the `esdm` binary on your `PATH`. Follow the [ESDM installation guide](https://www.esdm.io/getting-started/installing-esdm/) to set it up. ### Project Structure Both skills follow a given project structure. The domain model and the architecture decision records live in the `docs` folder and the code lives in `src`. ``` / ├── docs/ │ ├── adr/ # architecture decision records │ └── domain-model/ │ ├── schemas/ # created by `esdm add-schema` │ └── model/ # the ESDM model └── src/ ``` You do not need to create these folders yourself. The modeling skill creates them as soon as there is something to write down. The code mirrors the model. Every Bounded Context is a top-level folder. Every consistency unit of the model is a folder inside its Bounded Context and a prefix names its ESDM kind. | Prefix | ESDM kind | | ------ | ---------------------------- | | `agg-` | Aggregate | | `rm-` | Read Model | | `pm-` | Process Manager | | `dcb-` | Dynamic Consistency Boundary | | `ext-` | External System | Inside of each folder the code is split into a **Pure Core** and an **Imperative Shell** as described on the [Architecture](/guide/architecture) page. A shortened example for a ticketing application looks like this. ``` src/ ├── ticketing/ # Bounded Context │ ├── agg-ticket/ # Aggregate │ │ ├── core/ │ │ │ ├── domain/ │ │ │ ├── commands/ │ │ │ └── events/ │ │ └── shell/ │ │ ├── commands/ │ │ ├── policies/ │ │ └── event-handlers/ │ ├── rm-tickets/ # Read Model │ └── pm-settled-archive/ # Process Manager ├── shared/ # code used by more than one Bounded Context └── main.ts ``` Projects that also contain a frontend keep the backend in `src/api` or `src/server` and follow the same layout inside of that folder. Nimbus does not ship classes like `Aggregate` or `ProcessManager`. So the `nimbus` skill maps every ESDM construct onto a composition of Nimbus building blocks. | ESDM | Nimbus | | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Aggregate | One **subject** stream. The state and its reducer live in the core next to one pure function per command. The shell handler replays the events, calls the core and writes the new events with **preconditions**. | | Read Model | A **projection** in the shell that writes to a MongoDB **repository**. Queries read from that repository only. | | Process Manager | The process state and its reducer live in the core. Shell event handlers observe events, persist the process state and send commands through the command **router**. | | Policy | A stateless handler in the shell of the unit that owns the target command. It observes an event and issues that command through the command **router**. | The complete rules are part of the `nimbus` skill. Have a look at [PROJECT-STRUCTURE.md](https://github.com/overlap-dev/Nimbus/blob/main/skills/nimbus/PROJECT-STRUCTURE.md) and [ESDM-MAPPING.md](https://github.com/overlap-dev/Nimbus/blob/main/skills/nimbus/ESDM-MAPPING.md) for all the details. This structure is stricter than the layout of the demo in the [In Depth Example](/guide/in-depth-example). When the two disagree the structure of the skill wins. ::: tip See it in action The [ESDM Demo](/guide/esdm-demo) shows this structure in a complete application. It contains the ESDM model, the architecture decision records and the code that implements them. ::: --- --- url: https://nimbus.overlap.at/guide/quickstart.md description: >- Install @nimbus-cqrs packages from npm for Node.js, Bun, or Deno; core is required, other packages are optional by need. --- # Quickstart To get started with Nimbus you need to install the core package and other relevant Nimbus packages based on your needs. All packages live under the `@nimbus-cqrs` scope on npm: [@nimbus-cqrs/core](https://www.npmjs.com/package/@nimbus-cqrs/core) (and the rest of the [@nimbus-cqrs](https://www.npmjs.com/org/nimbus-cqrs) scope). The packages are published as plain ESM with bundled type declarations and run on Node.js 24+, Bun and Deno. ## Dependencies Nimbus tries to keep dependencies as low as possible.\ Theses are the dependencies Nimbus relies on. * [Zod](https://zod.dev/) * [OpenTelemetry API](https://opentelemetry.io/docs/languages/js/) * [ulid](https://github.com/ulid/javascript) for message IDs * [picocolors](https://github.com/alexeyraspopov/picocolors) for colored console output ## Installation Depending on your package manager or runtime you can install Nimbus with the following commands. ### npm ```bash npm install @nimbus-cqrs/core ``` ### pnpm ```bash pnpm add @nimbus-cqrs/core ``` ### Bun ```bash bun add @nimbus-cqrs/core ``` ### Deno ```bash deno add npm:@nimbus-cqrs/core ``` --- --- url: https://nimbus.overlap.at/guide/in-depth-example.md description: >- Walkthrough of eventsourcing-demo — CQRS, Event Sourcing, pure core vs shell, projections, and queries with links to source files. --- # An in Depth Example This page is dedicated to explain the example application ["eventsourcing-demo"](https://github.com/overlap-dev/Nimbus/tree/main/examples/eventsourcing-demo) in depth with all the underlying concepts and patterns. If you are new to Nimbus, Event Driven Architecture, Event Sourcing or CQRS, this is the right place to get some better insights on how everything works. ## How to Read This Page Take your time. There is nothing to memorize, and you will not be tested at the end. Every concept on this page is introduced in plain English first and only then shown in code, so feel free to skim, jump back, and re-read sections that feel new. The demo itself is small. About 25 short, well-commented files. The most rewarding way to follow along is to clone the repo and open it in your editor next to this page. Whenever you see a file path mentioned, `CMD+Click` (or `F12`) on a function name in the demo to jump straight to its definition. ::: tip Open the code while you read [examples/eventsourcing-demo](https://github.com/overlap-dev/Nimbus/tree/main/examples/eventsourcing-demo) is the repo. Keep it open in a second window. ::: ## Source code map All paths below are under [`examples/eventsourcing-demo`](https://github.com/overlap-dev/Nimbus/tree/main/examples/eventsourcing-demo) on `main`. Line ranges point at the symbols discussed on this page. | Area | File | Lines | | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | | Bootstrap | [`src/main.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/main.ts#L1-L76) | App startup order | | HTTP | [`src/http.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/http.ts#L22-L117) | Hono app and server | | Event store | [`src/eventsourcingdb.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/eventsourcingdb.ts#L11-L60) | Client + observers | | MongoDB | [`src/mongodb.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/mongodb.ts#L5-L22) | Connection setup | | Write router | [`src/write/commandRouter.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/write/commandRouter.ts#L4-L30) | Command router | | Read router | [`src/read/queryRouter.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/read/queryRouter.ts#L4-L30) | Query router | | Invite HTTP | [`src/write/iam/users/shell/http.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/write/iam/users/shell/http.ts#L28-L49) | `/invite-user` route | | Invite shell handler | [`inviteUser.command.ts` (shell)](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/write/iam/users/shell/commands/inviteUser.command.ts#L23-L73) | `inviteUserCommandHandler` | | Invite core | [`inviteUser.command.ts` (core)](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/write/iam/users/core/commands/inviteUser.command.ts#L60-L94) | `inviteUser` | | Accept shell handler | [`acceptUserInvitation.command.ts` (shell)](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/write/iam/users/shell/commands/acceptUserInvitation.command.ts#L17-L103) | Replay + persist | | State reducer | [`user.state.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/write/iam/users/core/domain/user.state.ts#L20-L39) | `applyEventToUserState` | | Users projection | [`users.projection.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/read/iam/users/projections/users.projection.ts#L28-L70) | `projectUsers` | | Users consumer | [`users.projection.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/read/iam/users/projections/users.projection.ts#L83-L91) | `usersProjection` | | Users collection | [`users.collection.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/read/iam/users/projections/users.collection.ts#L7-L76) | Schema and indexes | | Users repository | [`users.repository.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/read/iam/users/projections/users.repository.ts#L1-L67) | `UserRepository` | | Get user query | [`getUser.query.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/read/iam/users/queries/getUser.query.ts#L23-L31) | `getUserQueryHandler` | | Register commands | [`registerUserCommands.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/write/iam/users/shell/commands/registerUserCommands.ts#L19-L33) | Router registration | | Register queries | [`registerUserQueries.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/read/iam/users/queries/registerUserQueries.ts#L18-L38) | Router registration | ## The Mental Model in Five Minutes Before we open a single file, let us agree on a tiny vocabulary. These four ideas are everything you need to make sense of the demo. ### Events Are Facts An **event** is something that already happened, written down in a way that cannot be changed afterwards. "Jane was invited at 09:14" is an event. We never edit the past - we only ever append new events to the end of a log. This sounds modest, but it has a big consequence: the event log becomes the single source of truth. Every other shape of data in your system is derived from it. ### State Is a Fold Over Events If events are the source of truth, then "current state" is just what you get when you walk through the events in order and apply them one by one. Reduce them, fold them, accumulate them - whichever word you like. For example, if a user has these two events in the log: ``` 1. UserInvited { id: "abc", email: "jane@x.com", invitedAt: "..." } 2. UserInvitationAccepted { acceptedAt: "..." } ``` Then their current state - "Jane, invited and accepted" - is what you get by replaying both events into an empty `UserState` object. That is the whole trick. ### CQRS: Two Sides of the Same Story **CQRS** stands for Command Query Responsibility Segregation. The fancy name hides a simple idea: separate the code that **changes** the system from the code that **reads** from it. * The **write side** accepts commands ("invite this user"), enforces business rules, and emits events. * The **read side** projects those events into shapes that are easy to query ("give me all pending invitations"). Both sides talk through the event log. They do not have to share data models. The read side can have many different views, each optimized for a specific question. ### Pure Core, Imperative Shell Inside the write side we make one more separation: the **pure core** (the business logic) is wrapped by an **imperative shell** (the I/O). The core is plain functions with no side effects - easy to test, easy to reason about. The shell handles HTTP, databases, and external systems, and calls the core when it is time to think. The [Architecture](/guide/architecture) page goes into the why and how of this split. For now, just remember: the core is where the business lives, the shell is where the world lives. ### Mapping the Real World (DDD) We organize the application using **Domain Driven Design** principles. The big idea is simple: the folder structure should look like the real-world business it serves, not like a layered framework. Code that belongs to the same part of the business lives together, and code that belongs to different parts stays apart. In the demo this shows up as two levels: * **Domains** group everything related to one area of the business. Our example has the `iam` (Identity and Access Management) domain. A real application might also have `billing`, `inventory`, or `notifications` next to it. * **Modules** live inside a domain and represent a concept the domain cares about. Inside `iam` we have a `users` module. Later we might add `roles` or `permissions` modules right beside it. So `iam/users` reads like a sentence: "the users module of the IAM domain." This shape pays off as the application grows - new features land in obvious places, and you can reason about one domain without holding the whole codebase in your head. Put together, the loop the whole demo follows looks like this: ```mermaid flowchart LR Cmd[Command] --> Core[Pure core] Core --> Evt[Events] Evt --> Store[(EventSourcingDB)] Store --> Proj[Projection] Proj --> View[(MongoDB view)] View --> Query[Query] ``` Every concept above maps to a concrete piece of the demo. We will revisit each one in context. ## Meet the Use Case The demo lives in the IAM (Identity and Access Management) domain. The story is intentionally small so we can focus on patterns, not features. There are two actors: * An **admin** who invites someone to the system. * An **invitee** who accepts the invitation when they receive it. There are two commands - the things that can happen: * `inviteUser` - the admin sends an invitation to an email address. * `acceptUserInvitation` - the invitee accepts a pending invitation. And there are three queries - the things we can ask about the system: * `getUser` - fetch a single user by id. * `listUsers` - list every user. * `listPendingUsersEmails` - list the email addresses of users who have been invited but not yet accepted. That is the entire scope. Two write operations, three read operations, and a small projection in the middle that keeps the read side up to date. The rest of this page walks through how Nimbus turns that into a runnable application. ## A Tour of the Folder ``` src/ ├── main.ts # Application entrypoint ├── http.ts # Hono app + middleware + sub-routers ├── eventsourcingdb.ts # ESDB client + event observers ├── mongodb.ts # MongoDB connection manager ├── otel.ts # Optional OpenTelemetry bootstrap ├── telemetry.ts # Telemetry shutdown hook ├── write/ # CQRS write side │ ├── commandRouter.ts │ ├── http.ts │ └── iam/users/ │ ├── core/ # Pure business logic, no I/O │ │ ├── commands/ │ │ ├── domain/ │ │ └── events/ │ └── shell/ # I/O: HTTP + command handlers │ ├── commands/ │ └── http.ts └── read/ # CQRS read side (no core/shell split) ├── queryRouter.ts ├── http.ts └── iam/users/ ├── projections/ ├── queries/ └── http.ts ``` Notice two things. First, on the **write side** the slice splits into `core` and `shell`. The core is where we put pure functions and types: command schemas, the `UserState` reducer, event definitions. The shell is where we put everything that touches the outside world: the HTTP routes, the command handlers that load state and persist events. This split lets us write fast unit tests for the core while keeping the messy I/O cleanly separated. Second, on the **read side** there is no `core/shell` split. Why? Because the read side does not really have business logic. It just listens to events and projects them into a shape that is easy to query. Reducer in, document out, no rules to enforce. Adding a `core/shell` split here would be ceremony without payoff. ## Setting the Stage: Bootstrap, Dependency by Dependency [`src/main.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/main.ts#L1-L76) is short on purpose. It is a linear list of "start this, then start that", because everything later in the file depends on everything earlier in the file. Open it now and read along - we will go through it from top to bottom. ### Logging First Logging is set up before anything else. Everything that follows might want to log something, and we want every log line to be formatted the same way and routed to the same place from the very first instant. ```typescript setupLogger({ logLevel: parseLogLevel(process.env.LOG_LEVEL), formatter: process.env.LOG_FORMAT === "pretty" ? prettyLogFormatter : jsonLogFormatter, useConsoleColors: process.env.LOG_FORMAT === "pretty", truncator: createLogTruncator(), }); ``` Once `setupLogger` has run, anywhere else in the app we can call `getLogger()` and get the same configured instance. The `truncator` shortens large payloads before they are written so a single log line can not flood your log pipeline. The full logging story lives in [Logging](/guide/core/logging). ### MongoDB Connection We use MongoDB to store the read-side projections. The `MongoConnectionManager` is a small singleton that owns the connection so every repository in the app can grab the same client. ```typescript export const initMongoDB = () => { const env = getEnv({ variables: ["MONGO_URL"], }); setupMongoConnectionManager({ name: "default", uri: env.MONGO_URL, options: { /* ... */ }, }); }; ``` The pattern is documented in [Connection Manager](/guide/mongodb/connection-manager). The little [`getEnv`](/guide/core/get-env) helper next to it is what reads `MONGO_URL` from the environment with a friendly error if it is missing. ### EventSourcingDB Client Now things get interesting. We initialize EventSourcingDB and, in the same call, register an **event observer** for the `/users` subject: ```typescript const checkpointStore = new MongoCheckpointStore(() => { return getMongoConnectionManager().getCollection( env.MONGO_DB, MONGO_CHECKPOINTS_COLLECTION.name ); }); await setupEventSourcingDBClient({ url: new URL(env.ESDB_URL), apiToken: env.ESDB_API_TOKEN, eventObservers: [ { name: "iam", subject: "/users", recursive: true, checkpointStore, consumers: [usersProjection, contactsProjection], }, ], }); ``` Three ideas to absorb here: 1. **EventSourcingDB doubles as our event bus.** When we write a new event, every observer that watches its subject receives it. There is no separate message broker to deploy or maintain. 2. **An observer feeds consumers.** The observer watches one subject and hands every event to the **consumers** in its list. Here these are our two projections. They run one after the other in the order they are declared. 3. **Checkpoints matter.** On every startup, the observer first **replays** the past events for `/users` that its consumers have not seen yet, then keeps listening to new ones. Every consumer remembers the id of the last event it finished in a **checkpoint**, and the `checkpointStore` persists those checkpoints in MongoDB. Without them we would re-apply the entire history every time we boot. We will get to `usersProjection` and the checkpoints later, when we look at the read side. For now you only need to know that the wiring happens here. Full client setup lives in [Client Setup](/guide/eventsourcingdb/client-setup). ### Command and Query Routers Nimbus has a small abstraction called a **router** that takes a typed message (a command or a query), looks up its handler by `type`, validates the data with the registered schema, and invokes the handler. There is one router per side of CQRS: ```typescript initCommandRouter(); initQueryRouter(); ``` Each call creates a named router (`'commandRouter'` and `'queryRouter'`) and registers the slice's messages with it. Anywhere in the app we can later call `getRouter('commandRouter')` and get the same instance. The router itself is documented at [Router](/guide/core/router). ### HTTP Server Finally, we start the HTTP server: ```typescript const server = startHttpServer(); ``` The order matters. By the time the first request arrives, the logger, the database connections, and both routers are guaranteed to be ready. If they were not, the very first request could find a half-built application. ### Graceful Shutdown The two signal listeners at the bottom of `main.ts` give the HTTP server a chance to finish in-flight requests before the process exits. ```typescript process.on("SIGTERM", () => { shutdown("SIGTERM").catch(() => process.exit(1)); }); process.on("SIGINT", () => { shutdown("SIGINT").catch(() => process.exit(1)); }); ``` Nothing exotic, but it is the kind of detail that pays off the moment your app gets deployed somewhere real. ## The HTTP Front Door [`src/http.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/http.ts#L22-L117) builds the [Hono](https://hono.dev/) app and lines up middlewares before mounting the two sub-routers. Let us walk through them in order. ```typescript app.use(correlationId()); app.use(logger({ enableTracing: true, tracerName: "api" })); app.use(cors()); app.use( secureHeaders({ /* ... */ }) ); app.use(compress()); app.get("/health" /* ... */); app.route("/command", httpCommandRouter); app.route("/query", httpQueryRouter); app.onError(handleError); ``` * `correlationId()` reads (or generates) a correlation ID per request and attaches it to the request context. Think of it as a thread you can pull on later: every log line and every Nimbus message that flows out of this request will carry the same id, so when something goes wrong you can grep the logs and see the whole story. Details: [CorrelationID Middleware](/guide/hono/correlationid). * `logger(...)` produces a structured log line per request and, with `enableTracing: true`, opens an OpenTelemetry trace span. Details: [Logger Middleware](/guide/hono/logger). * `cors()`, `secureHeaders(...)`, `compress()` - the usual web hygiene. Nothing Nimbus-specific. * `app.onError(handleError)` is the most important line on the page. It catches every Nimbus exception that bubbles up and turns it into a properly formatted HTTP error response - the right status code, a stable error code, and a JSON body. We will rely on this when we look at business-rule violations later. Details: [onError Handler](/guide/hono/on-error). The two `app.route(...)` calls hook the command sub-tree under `/command` and the query sub-tree under `/query`. Notice how the URL itself reflects the CQRS split: writes go through `/command/...`, reads go through `/query/...`. That makes the boundary visible in production logs and in your API gateway, not just in the codebase. ## The Journey of a Command: "Invite a User" Time to follow a single request from end to end. We will pretend we are an admin sending `POST /command/iam/users/invite-user` with a JSON body. Each step gets its own heading so you can pause whenever you want. ### Step 1 - The HTTP Request Arrives The route lives in [`src/write/iam/users/shell/http.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/write/iam/users/shell/http.ts#L28-L49). From this point on, we are inside Nimbus territory. ```typescript httpUserCommandRouter.post("/invite-user", async (c) => { const body = await c.req.json(); const correlationId = getCorrelationId(c); const command = createCommand({ type: INVITE_USER_COMMAND_TYPE, source: "https://nimbus.overlap.at", correlationid: correlationId, data: body, // This is just an example on how authentication // context could be passed as an extension attribute. authcontext: { sub: "123", email: "test@example.com", }, }); const result = await getRouter("commandRouter").route(command); return c.json(result); }); ``` The Hono handler does only three things: parse the body, build a typed Nimbus command from it, and hand the command to the router. That is intentional. If you ever add a gRPC or WebSocket entrypoint, the only thing you would change is how the command is built. Everything past `getRouter("commandRouter").route(command)` would stay exactly the same. The `authcontext` is hard-coded here to keep the demo small. In a real application an authentication middleware would provide it. ### Step 2 - Building a Typed Command `createCommand` produces a fully-typed object that follows the [CloudEvents](https://cloudevents.io/) specification. It has fields like `id`, `time`, `source`, `correlationid`, `type`, and `data`. The fields are not Nimbus inventions - they are an open standard for describing events on the wire. The interesting one is `type`: ```typescript export const INVITE_USER_COMMAND_TYPE = "at.overlap.nimbus.invite-user"; ``` We use a reverse-DNS naming convention (also straight from CloudEvents) so that command and event types stay globally unique even if you later integrate with other systems. The router uses this string to find the right handler. The full command anatomy is documented at [Commands](/guide/core/commands). ### Step 3 - Routing When `route(command)` is called, the router looks up the registration whose `type` matches `command.type`, validates `command.data` against the registered Zod schema, and then calls the handler. Registrations live in one tidy file per module/domain: ```typescript export const registerUserCommands = () => { const router = getRouter("commandRouter"); router.register( INVITE_USER_COMMAND_TYPE, inviteUserCommandHandler, inviteUserCommandSchema ); router.register( ACCEPT_USER_INVITATION_COMMAND_TYPE, acceptUserInvitationCommandHandler, acceptUserInvitationCommandSchema ); }; ``` If validation fails, the router throws - and remember, our `onError` handler turns that into a clean `400 Bad Request` automatically. We never have to write `if (!body.email) return 400` anywhere. ### Step 4 - The Handler Lives in the Shell The handler for `inviteUser` is in [`src/write/iam/users/shell/commands/inviteUser.command.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/write/iam/users/shell/commands/inviteUser.command.ts#L23-L73). Its job is *coordination*, not business logic: ```typescript export const inviteUserCommandHandler = async (command: InviteUserCommand) => { const state: UserState = { id: ulid(), }; let isEmailPristine: boolean = false; const eventSourcingDBClient = getEventSourcingDBClient(); for await (const row of eventSourcingDBClient.runEventQlQuery(` FROM e IN events WHERE e.type == "${USER_INVITED_EVENT_TYPE}" AND e.data.payload.email == "${command.data.email.toLowerCase()}" PROJECT INTO { total: COUNT() } `)) { const total = (row as { total: number }).total; isEmailPristine = total === 0; } const events = inviteUser(state, command, isEmailPristine); const writtenEvents = await writeEvents(events, [ isSubjectPristine(events[0].subject), ]); return { userId: state.id, revision: writtenEvents[writtenEvents.length - 1].id, }; }; ``` Four steps of meaningful work: 1. **Build initial state.** Inviting a user starts a brand-new lifecycle, so we mint a fresh `ulid()` (a sortable, URL-safe id) and start with an empty `UserState`. There is nothing to load from the event log yet. 2. **Gather the facts the core needs.** An email address should only be invited once. The core has to know if the address is still free, but it is not allowed to do I/O. So the shell asks EventSourcingDB with a small EventQL query that counts the `UserInvited` events with the same email address. 3. **Call the core.** `inviteUser(state, command, isEmailPristine)` returns the events that should be appended. The handler does not know what those events look like or why they were chosen. That is the core's job. 4. **Persist the events.** `writeEvents` appends the events to EventSourcingDB and returns them with the ids the server assigned. The second argument is an array of preconditions and we will look at it in a second. The id of the last written event is the user's **revision**, which we hand back to the caller. It will matter when we accept the invitation. ::: tip Keep in mind Counting the `UserInvited` events is enough for this demo. If your application can delete users and wants to free their email address again, those events have to be part of the check as well. ::: ### Step 5 - The Pure Core Does the Thinking The core function lives in [`src/write/iam/users/core/commands/inviteUser.command.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/write/iam/users/core/commands/inviteUser.command.ts#L60-L94). It is the entire business definition of "what does it mean to invite a user". ```typescript // GIVEN: state = A // AND: command = B // WHEN: inviteUser(state, command) // THEN: [EventA, EventB] export const inviteUser = ( state: UserState, command: InviteUserCommand, isEmailPristine: boolean ): [UserInvitedEvent] => { const email = command.data.email.toLowerCase(); if (!isEmailPristine) { throw new Exception( "CONFLICT", "The email address is already used", { errorCode: "EMAIL_ALREADY_USED", email: command.data.email, }, 409 ); } const userInvitedEvent = createEvent({ type: USER_INVITED_EVENT_TYPE, source: command.source, correlationid: command.correlationid, subject: `/users/${state.id}`, data: { id: state.id, email: email, firstName: command.data.firstName, lastName: command.data.lastName, invitedAt: new Date().toISOString(), }, }); return [userInvitedEvent]; }; ``` Take a moment to appreciate what is *not* in this function. There is no database. No HTTP. No `await`. No mocks or test doubles to set up. It takes data in and returns data out. That is what "pure" means, and it is why every single business scenario can be unit-tested with a one-line `expect(inviteUser(state, command, true)).toEqual([...])` - no Nimbus, no Mongo, no Hono required. The arguments of the function define all the information the business rules need. Most of the time the state and the command are enough. Here the core also wants to know if the email address is still free, so the shell passes that fact in as `isEmailPristine`. If it is not, the core throws a `CONFLICT` exception and no event is produced. The `subject` field on the event is also worth pausing on. It is the address inside the event log where this event will live: `/users/abc`. Every event we ever write for this user will share this subject. That is what makes "give me everything that happened to user `abc`" a fast operation. ### Step 6 - Writing Events with a Precondition Back in the handler: ```typescript const writtenEvents = await writeEvents(events, [ isSubjectPristine(events[0].subject), ]); ``` `isSubjectPristine` says: "only succeed if the log under this subject is currently empty." Because we just generated a fresh `ulid()`, that should always be true. If it somehow is not - say, two requests arrived at the same millisecond and we hit the astronomically unlikely id collision - the write fails loudly instead of silently corrupting the log. Belt and suspenders. The full set of write helpers and preconditions is documented at [Write Events](/guide/eventsourcingdb/write-events). ### Step 7 - What Is Now in the Event Log? After this command succeeds, the event log contains one new entry under subject `/users/abc`: ``` subject: /users/abc type: at.overlap.nimbus.user-invited data: id: abc email: jane@example.com firstName: Jane lastName: Doe invitedAt: 2026-04-24T09:14:00.000Z ``` That is the only artifact this command produced. There is no row in any "users" table yet. The read side has not heard anything yet. That is fine - the projection will catch up in a moment. For now, the truth lives in the event log, where it belongs. ::: tip Try it locally With the demo running, you can fire this command from your terminal: ```bash curl -X POST http://localhost:3100/command/iam/users/invite-user \ -H "Content-Type: application/json" \ -d '{"email":"jane@example.com","firstName":"Jane","lastName":"Doe"}' ``` You will get back something like `{ "userId": "01H...", "revision": "1" }`. Hold on to both values. We need them for the next command. ::: ::: warning Prerequisites! You need to have the EventSourcingDB and MongoDB running locally in order to get the eventsourcing-demo application to work. You can find the instructions to run [**EventSourcingDB here**](https://docs.eventsourcingdb.io/getting-started/running-eventsourcingdb/). And you can find the instructions to install [**MongoDB here**](https://www.mongodb.com/try/download/community). ::: ## The Journey of a Command: "Accept the Invitation" Now we are the invitee. We received the email, clicked the link, and our client is sending `POST /command/iam/users/accept-user-invitation`. The shape of the journey is the same, but each step is meaningfully different. That is where the interesting parts of event sourcing come out. ### Loading State From History The handler is in [`src/write/iam/users/shell/commands/acceptUserInvitation.command.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/write/iam/users/shell/commands/acceptUserInvitation.command.ts#L17-L103). Unlike the invite handler, it cannot start from an empty state - "accepting" only makes sense if there is something to accept. So the first thing it does is replay the user's history into a fresh `UserState`: ```typescript let state: UserState = { id: command.data.id }; for await (const eventSourcingDBEvent of readEvents( `/users/${command.data.id}`, { recursive: false } )) { const event = eventSourcingDBEventToNimbusEvent(eventSourcingDBEvent); state = applyEventToUserState(state, event); } ``` This is the "state is a fold over events" idea, made concrete. We ask EventSourcingDB for every event under `/users/{id}` ([Read Events](/guide/eventsourcingdb/read-events)), convert each one back into a typed Nimbus event ([Event Mapping](/guide/eventsourcingdb/event-mapping)), and feed it into the reducer one by one. The reducer itself lives in [`src/write/iam/users/core/domain/user.state.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/write/iam/users/core/domain/user.state.ts#L14-L46): ```typescript export type UserState = { id: string; invitedAt?: string; acceptedAt?: string; }; export const applyEventToUserState = ( state: UserState, event: Event ): UserState => { if (isUserInvitedEvent(event)) { return { ...state, invitedAt: event.data.invitedAt, }; } if (isUserInvitationAcceptedEvent(event)) { return { ...state, acceptedAt: event.data.acceptedAt, }; } return state; }; export const hasPendingInvitation = (state: UserState): boolean => { return state.invitedAt !== undefined && state.acceptedAt === undefined; }; ``` `UserState` is just a TypeScript type - whatever fields the core needs to make decisions. `applyEventToUserState` is a small switch that updates state for each event type it cares about. The little `hasPendingInvitation` helper keeps a business predicate close to the core functions that need it. ### Business Rules in the Core With state in hand, the handler calls the core. The core's job is to enforce the rules and produce the resulting events: ```typescript if (!hasPendingInvitation(state)) { throw new InvalidInputException( "The user does not have a pending invitation", { errorCode: "USER_HAS_NO_PENDING_INVITATION", details: { userId: state.id }, } ); } const inviteExpiredAfterHours = 24; if ( state.invitedAt && new Date(state.invitedAt).getTime() + inviteExpiredAfterHours * 60 * 60 * 1000 < Date.now() ) { throw new InvalidInputException("The invitation has expired", { /* ... */ }); } ``` Two rules: there has to be a pending invitation, and it must not have expired. When a rule fails, the core throws a typed `InvalidInputException`. It does not return an HTTP response, it does not log anything - it just throws a domain-shaped exception. That is exactly what makes the core easy to test. Up in the HTTP layer, our `app.onError(handleError)` middleware catches these exceptions and turns them into proper HTTP responses, with the right status code and a stable `errorCode` field that clients can switch on. The full list of Nimbus exceptions and how they map to HTTP statuses is documented at [Exceptions](/guide/core/exceptions). ### Writing With Optimistic Concurrency Once the rules pass, the core returns a `UserInvitationAccepted` event and the handler appends it - this time with a different precondition: ```typescript let revision: string; try { const writtenEvents = await writeEvents(events, [ isSubjectOnEventId(events[0].subject, command.data.expectedRevision), ]); revision = writtenEvents[writtenEvents.length - 1].id; } catch (error) { const isStateConflict = error instanceof DbApiError && error.code === ErrorCode.preconditionViolated; getLogger().error({ category: "AcceptUserInvitationCommandHandler", message: "Error accepting user invitation", error: error as Error, }); if (isStateConflict) { throw new Exception( "CONFLICT", "The expected revision does not match the current revision anymore", { errorCode: "REVISION_CONFLICT", userId: state.id, expectedRevision: command.data.expectedRevision, }, 409 ); } else { throw error; } } return { userId: state.id, revision, }; ``` `expectedRevision` is the id of the last event the *client* saw for this user when it built its accept request. EventSourcingDB will only allow the write if the subject is still on that exact event. If somebody else managed to append a different event in the meantime, the write fails with a `DbApiError` whose `code` is `ErrorCode.preconditionViolated` (both imported from `eventsourcingdb`). The handler translates that into a Nimbus `Exception` with status `409`, which `handleError` turns into a proper HTTP conflict response. When the write succeeds, the id of the newly written event is the user's new revision. The handler returns it so the client can use it for its next command. ::: warning Why this precondition matters Imagine two browser tabs both trying to accept the same invitation at the same instant. Without `isSubjectOnEventId`, both writes would succeed, and the user would have two `UserInvitationAccepted` events in their history. With the precondition, the second write fails and the client can decide what to do (probably: refresh and tell the user it is already accepted). This pattern is called **optimistic concurrency control**. "Optimistic" because we let writers proceed without locks, and only check at commit time. ::: ### What Is Now in the Event Log? After both commands run, the log under `/users/abc` looks like this (simplified): ``` subject: /users/abc events: 1. type: at.overlap.nimbus.user-invited id: "1" data: { id: "abc", email: "jane@example.com", firstName: "Jane", lastName: "Doe", invitedAt: "..." } 2. type: at.overlap.nimbus.user-invitation-accepted id: "2" data: { acceptedAt: "..." } ``` Two events, in order. That is the entire history of Jane in our system - and from that history we can derive every read shape we will ever need. Which is exactly what the read side does next. ## From Events to a Read Model We are leaving the write side now. Take a breath. The hard architectural ideas are all behind us; the read side is mostly mechanical reduction. ### Observers in Plain English Remember the `eventObservers` array we passed to `setupEventSourcingDBClient` back in [`src/eventsourcingdb.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/eventsourcingdb.ts#L11-L60)? An **observer** is a background loop that watches one subject in EventSourcingDB and hands *every event matching that subject* to its **consumers**. It runs during the startup replay (catching up on history), and then it keeps running for every new event written from that point on. Our observer is called `iam`. It watches the subject `/users` with `recursive: true` so it picks up everything under `/users/abc`, `/users/xyz`, and so on. It feeds two consumers, `usersProjection` and `contactsProjection`. We will follow the first one. The second one builds another read model from the same events and works the same way. The full mechanics are at [Event Observer](/guide/eventsourcingdb/event-observer). ### The Consumer A **consumer** is one named reader of the observed events. `usersProjection` is defined in [`src/read/iam/users/projections/users.projection.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/read/iam/users/projections/users.projection.ts#L83-L91): ```typescript export const usersProjection: EventConsumer = { name: "iam.users", handles: (event) => { return ( isUserInvitedEvent(event) || isUserInvitationAcceptedEvent(event) ); }, handle: projectUsers, }; ``` It has three properties: * `name` identifies the consumer. The observer stores the progress of the consumer under this name, so it has to be unique in the application and it has to stay stable. * `handles` tells the observer which events the consumer wants to get. * `handle` is the function the observer calls for each of those events. ### The Projection Function `projectUsers` is in the [same file](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/read/iam/users/projections/users.projection.ts#L28-L70). It is a reducer, just like `applyEventToUserState` - except the state lives in MongoDB instead of in memory: ```typescript export const projectUsers = async (event: Event): Promise => { if (isUserInvitedEvent(event)) { const user: User = { _id: new ObjectId().toString(), id: event.data.id, revision: event.id, email: event.data.email, firstName: event.data.firstName, lastName: event.data.lastName, invitedAt: event.data.invitedAt, acceptedAt: null, }; await userRepository.insertOnce(user); return; } if (isUserInvitationAcceptedEvent(event)) { await userRepository.updateOne({ filter: { id: event.subject.split("/")[2] }, update: { $set: { revision: event.id, acceptedAt: new Date(event.data.acceptedAt), }, }, }); } }; ``` The pattern is simple. The observer already converted the raw ESDB event back into a typed Nimbus event, so all that is left to do is to dispatch on its type. On `UserInvited` we insert a brand-new document. On `UserInvitationAccepted` we patch the matching document. Notice the `revision: event.id` field on every write. Each document remembers the id of the last event that touched it. This is the revision a client reads together with the user and sends back as `expectedRevision` when it accepts the invitation. Also notice that there is no `try/catch`. If the projection can not apply an event it simply throws. We will see what the observer does with that in a moment. ### Worked Example Let us play out the two events from Jane's story and watch the document evolve. After `"1"` (the `UserInvited` event): ```json { "_id": "65...", "id": "abc", "revision": "1", "email": "jane@example.com", "firstName": "Jane", "lastName": "Doe", "invitedAt": "2026-04-24T09:14:00.000Z", "acceptedAt": null } ``` After `"2"` (the `UserInvitationAccepted` event): ```json { "_id": "65...", "id": "abc", "revision": "2", "email": "jane@example.com", "firstName": "Jane", "lastName": "Doe", "invitedAt": "2026-04-24T09:14:00.000Z", "acceptedAt": "2026-04-24T09:18:00.000Z" } ``` That is the whole job of the projection: turn the timeline of events into a row that is convenient to query. If you ever needed a *different* shape - say, a `pendingInvitationsByDay` view - you would write a second projection over the same events. Same source of truth, multiple views. ### Resuming After a Restart Every time the application starts, the observer has to know where each consumer stopped. That is the job of the **checkpoint**. After the consumers finished an event, the observer writes the id of that event to the checkpoint store. In the demo this is the `MongoCheckpointStore` we created in `eventsourcingdb.ts`, so the checkpoints live in a `nimbus_checkpoints` collection right next to the read model: ```json { "consumer": "iam.users", "observer": "iam", "position": "2", "updatedAt": { "$date": "2026-04-24T09:18:00.100Z" } } ``` On the next start the observer loads the checkpoints of its consumers and asks EventSourcingDB for everything after the lowest position. A consumer that is already further ahead skips the events it has seen. A consumer without a checkpoint starts at the beginning of the log. Without this, every restart would re-apply the entire event history. For an app that has been running for a year, that could be tens of millions of events, every time. With checkpoints, a restart catches up only on what is genuinely new. Checkpoints also make it easy to rebuild a read model. Stop the application, empty the collection of the read model, reset the checkpoint of its consumer and start again. The projection then replays the log from the beginning. The details are at [Checkpoint Store](/guide/mongodb/checkpoint-store). ::: warning Idempotency still matters A checkpoint is written *after* the consumer handled the event. If the application crashes right in between, the same event is delivered again on the next start. This is called **at-least-once** delivery and it means a projection has to be **idempotent**. Processing this event twice has to produce the same result as processing this event once. That is why the projection calls `insertOnce` and not a plain insert. It only inserts the user if there is no document with that id yet. The update for `UserInvitationAccepted` sets fixed values, so applying it twice is harmless as well. ::: ### When a Projection Fails `projectUsers` does not catch errors, and that is on purpose. A consumer that throws keeps its checkpoint on the last event it finished, and the observer retries the event a few times. If it still fails, the consumer is **halted**. A critical log entry is written, the failure is stored together with the checkpoint, and the consumer does not get any more events until the application is restarted. The other consumers of the observer keep going. This way a projection never silently skips an event. The `/health` route of the demo makes the problem visible as well. It asks every observer for its health and reports `eventObservers: "ERROR"` as soon as an observer stopped or one of its consumers is halted. ## Storing the Read Model The MongoDB pieces are split across two files: a **collection definition** and a **repository**. ### The Collection Definition [`src/read/iam/users/projections/users.collection.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/read/iam/users/projections/users.collection.ts#L7-L76) describes the shape of the documents and the indexes we want: ```typescript export const USERS_COLLECTION: MongoCollectionDefinition = { name: "users", options: { validator: { $jsonSchema: { /* ... */ }, }, }, indexes: [{ key: { id: 1 }, unique: true }, { key: { acceptedAt: 1 } }], }; ``` Each index serves a specific question: * `{ id: 1, unique }` powers `getUser` and `insertOnce`, and prevents duplicate user ids. * `{ acceptedAt: 1 }` powers `listPendingUsersEmails` (filter by `acceptedAt: null`). You provision these collections in your environments with [Deploy Collection](/guide/mongodb/deploy-collection). The `@nimbus-cqrs/mongodb` package exports a ready-made `MONGO_CHECKPOINTS_COLLECTION` definition for the checkpoints, which you deploy the same way. ### The Repository [`src/read/iam/users/projections/users.repository.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/read/iam/users/projections/users.repository.ts#L1-L67) extends Nimbus's [`MongoDBRepository`](/guide/mongodb/repository) with two concrete responsibilities: mapping between BSON documents and the `User` Zod type, and exposing the small helper that the projection needs to insert a user only once. ```typescript class UserRepository extends MongoDBRepository { override _mapDocumentToEntity(doc: Document): User { /* ... */ } override _mapEntityToDocument(user: User): Document { /* ... */ } public async insertOnce(user: User): Promise { const collection = await this._getCollection(); await updateOne({ collection, filter: { id: user.id }, update: { $setOnInsert: this._mapEntityToDocument(user) }, options: { upsert: true }, }); } } export const userRepository = new UserRepository(); ``` The mapping methods exist because BSON and TypeScript do not see the world the same way. A `Date` in BSON is not a `string`, an `ObjectId` is not a `string`, and we want our domain code to deal in the friendly TypeScript types. Doing the conversion explicitly keeps surprises out of the rest of the app. `insertOnce` is an upsert that only writes when it has to insert. If a user with that id already exists, MongoDB leaves the document untouched. The base `MongoDBRepository` gives every repository a clean set of [CRUD+](/guide/mongodb/crud) methods - `findOne`, `find`, `insertOne`, `updateOne`, etc. ## Answering Questions: Queries With the projection in place, queries become almost embarrassingly small. That is the payoff of CQRS: because the read side already shaped the data the way we wanted, query handlers are basically a Mongo lookup and a `return`. ### `getUser` [`src/read/iam/users/queries/getUser.query.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/read/iam/users/queries/getUser.query.ts#L23-L31): ```typescript export const GET_USER_QUERY_TYPE = "at.overlap.nimbus.get-user"; export const getUserQuerySchema = querySchema.extend({ type: z.literal(GET_USER_QUERY_TYPE), data: z.object({ id: z.string() }), }); export type GetUserQuery = z.infer; export const getUserQueryHandler = async (query: GetUserQuery) => { const user = await userRepository.findOne({ filter: { id: query.data.id }, }); const { _id, ...userWithoutId } = user; return userWithoutId; }; ``` Same trio as a command - a type, a Zod schema, a handler - but the handler does not enforce any business rules. It just reads. Detailed query semantics are at [Queries](/guide/core/queries). ### `listUsers` A `find` with no filter: ```typescript export const listUsersQueryHandler = async (_query: ListUsersQuery) => { const users = await userRepository.find({ filter: {}, limit: 0, skip: 0 }); return users.map((user) => { const { _id, ...userWithoutId } = user; return userWithoutId; }); }; ``` ### `listPendingUsersEmails` A filter on `acceptedAt: null`, then a projection down to just the email field: ```typescript export const listPendingUsersEmailsQueryHandler = async ( _query: ListPendingUsersEmailsQuery ) => { const users = await userRepository.find({ filter: { acceptedAt: null }, limit: 0, skip: 0, }); return users.map((user) => user.email); }; ``` Three queries, three short handlers, one projection feeding all of them. If we wanted a fourth query - say, "users invited in the last week" - we would just write a new handler that hits the same collection. No new projection, no new event, nothing else to wire. ### HTTP → Query The HTTP side mirrors the write side exactly. Here is `getUser`: ```typescript httpUsersQueryRouter.get("/get-user-by-id/:id", async (c) => { const id = c.req.param("id"); const correlationId = getCorrelationId(c); const query = createQuery({ type: GET_USER_QUERY_TYPE, source: "nimbus.overlap.at", correlationid: correlationId, data: { id }, }); const result = await getRouter("queryRouter").route(query); return c.json(result); }); ``` The other two routes follow the same shape. Build the typed query, route it, return the JSON. ## The Whole Picture, One More Time Here is the full lifecycle - inviting Jane, the projection catching up, and then a client reading her back. Pay attention to the yellow block in the middle, it marks the **async gap** between writing the event and the projection becoming queryable. ```mermaid sequenceDiagram participant Client participant Hono participant Cmd as commandRouter participant Core as Pure core participant ESDB as EventSourcingDB participant Obs as usersProjection participant Mongo as MongoDB participant Qry as queryRouter Client->>Hono: POST /command/.../invite-user Hono->>Cmd: route(InviteUserCommand) Cmd->>ESDB: is the email still free? ESDB-->>Cmd: yes Cmd->>Core: inviteUser(state, command, isEmailPristine) Core-->>Cmd: [UserInvitedEvent] Cmd->>ESDB: writeEvents([UserInvitedEvent]) ESDB-->>Cmd: ok Cmd-->>Hono: { userId, revision } Hono-->>Client: 200 OK Note over ESDB,Obs: async observer wakes up ESDB-->>Obs: deliver UserInvitedEvent Obs->>Mongo: insertOnce(user) Client->>Hono: GET /query/.../get-user-by-id/:id Hono->>Qry: route(GetUserQuery) Qry->>Mongo: userRepository.findOne Mongo-->>Qry: user Qry-->>Hono: user Hono-->>Client: 200 OK ``` That async gap is sometimes called **eventual consistency**. In practice it is usually milliseconds - the projection catches up almost immediately. But the property is real, and worth being explicit about: a client that writes and then immediately reads might briefly see the world before the write. Most user-facing flows handle this gracefully (return the new id from the write, then navigate); for the rare cases where you need read-your-writes guarantees, you can read events directly instead of going through the projection. Why is this shape worth the upfront thinking? A few reasons that compound over time. * **Replayability.** The event log is the truth. If you ever need a new view of the data, you write a new projection and replay the log into it. No backfills, no migrations. * **Audit and explainability.** Every change in the system is a discrete, time-stamped event with a `correlationid`. "Why does the user look like this?" has a literal, machine-readable answer. * **Multi-view reads.** One projection feeds many queries; many projections can feed many UIs. None of them step on each other because they are derivations, not the source. * **A foundation for AI and analytics.** Models and pipelines thrive on high-quality, time-ordered data. The event log is exactly that. The [Nimbus for AI](/guide/nimbus-for-ai) page expands on this idea. ## A Note on Aggregates If you have read about Domain Driven Design before, you might be wondering where the **Aggregate** is. In classical DDD, an Aggregate is a class that owns a consistency boundary - it loads its state, runs business methods on itself, and emits events. Nimbus does not ship an `Aggregate` abstraction. In this demo, the same idea is expressed by composing four small things: * `UserState` and `applyEventToUserState` - the data and the reducer that builds it. * The pure-core command functions (`inviteUser`, `acceptUserInvitation`) - the invariants and event production. * The shell command handlers - state replay and persistence orchestration. * EventSourcingDB preconditions (`isSubjectPristine`, `isSubjectOnEventId`) - the actual consistency boundary, enforced atomically by the event store. This composition is a deliberate choice. It keeps each piece small and testable on its own, and it lets the event store - which is the only thing that *can* enforce consistency atomically - own the consistency boundary, instead of pretending an in-memory class can. If you would rather have a single `Aggregate` class wrapping all four pieces, you are welcome to write one on top of these primitives. Nimbus will stay out of your way either direction. ## Extending the Demo: A Checklist for Your First Change The fastest way to lock in everything above is to add something. Here is the recipe for each shape of change. ### Add a new event 1. Create `*.event.ts` in `core/events/`: define the `_EVENT_TYPE` constant, the data Zod schema (`eventSchema.extend({...})`), the inferred TypeScript type, and a small `is*Event` type guard. 2. Handle it in `applyEventToUserState` if the write side needs to react to it. 3. Handle it in `projectUsers` and add it to `handles` of `usersProjection` to keep the read model up to date. ### Add a new command 1. Create `*.command.ts` in `core/commands/`: define the `_COMMAND_TYPE` constant, the input Zod schema (`commandSchema.extend({...})`), the inferred TypeScript type, and the pure function that takes `(state, command)` and returns events. 2. Create the matching handler in `shell/commands/`: load state, call the core, write events with the appropriate precondition. 3. Register the type, handler, and schema in [`registerUserCommands.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/write/iam/users/shell/commands/registerUserCommands.ts#L19-L33). 4. Expose an HTTP route in [`shell/http.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/write/iam/users/shell/http.ts#L28-L49) that builds the typed command and calls `getRouter('commandRouter').route(...)`. ### Add a new query 1. Create `*.query.ts` in `read/.../queries/`: define the `_QUERY_TYPE` constant, the schema (`querySchema.extend({...})`), the inferred type, and the handler that reads from the projection. 2. Register it in [`registerUserQueries.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/read/iam/users/queries/registerUserQueries.ts#L18-L38). 3. Expose an HTTP route in [`read/iam/users/http.ts`](https://github.com/overlap-dev/Nimbus/blob/main/examples/eventsourcing-demo/src/read/iam/users/http.ts#L1-L67) that builds the typed query and calls `getRouter('queryRouter').route(...)`. ### Where do tests fit? Two layers, and they pay off very differently. * **Unit tests for the pure core.** Cheap to write, instant to run, no mocks required. They cover every business rule in isolation. This is where you should spend the bulk of your testing energy. * **End-to-end tests against a running stack.** Slower, but they prove that the wiring (HTTP, router, ESDB, projection, Mongo) actually holds together. Run them against ephemeral containers in CI. ## Glossary / Cheat Sheet | Term | One-line definition | | -------------------- | --------------------------------------------------------------------------------------------------------------- | | **Command** | A typed, validated request to change state. Routed to one handler. | | **Event** | A typed fact that has already happened. Append-only, never edited. | | **Query** | A typed request to read state. Routed to one handler. | | **Subject** | The address inside the event log where related events live (e.g. `/users/abc`). | | **Revision** | The id of the last event written under a subject. Used for optimistic concurrency. | | **Projection** | A function that consumes events from the log and writes a queryable view (often into a different database). | | **Reducer** | A function `(state, event) => newState` that folds events into state. | | **Pure core** | The business logic, written as pure functions with no I/O. | | **Imperative shell** | The wrapper around the core that handles HTTP, databases, and external systems. | | **Router** | The Nimbus piece that maps a message `type` to its schema + handler and dispatches to it. | | **Handler** | The function that runs for a given command or query type. | | **Observer** | A background loop that watches one subject and hands every event to its consumers, both during replay and live. | | **Consumer** | A named reader of the events of an observer, for example a projection. Resumes from its own checkpoint. | | **Checkpoint** | The id of the last event a consumer finished. Stored so a restart continues where the consumer stopped. | --- --- url: https://nimbus.overlap.at/guide/esdm-demo.md description: >- The esdm-demo example application is a ticketing backend that follows the workflow and the project structure of the Nimbus skills, from the ESDM domain model to the code. --- # ESDM Demo Next to the "eventsourcing-demo" from the [In Depth Example](/guide/in-depth-example) there is a second example application called ["esdm-demo"](https://github.com/overlap-dev/Nimbus/tree/main/examples/esdm-demo). It is the backend of a small ticketing system. A frontend is not included. The In Depth Example explains the concepts behind Nimbus step by step. The ESDM Demo has a different goal. It shows what a project looks like when it follows the workflow and the structure of the [Nimbus skills](/guide/nimbus-for-ai#skills-for-agents). So this page is not a walkthrough. It tells you what is in the demo and where to look. ## What Is in the Demo The demo is split into two Bounded Contexts. * **ticketing** is the heart of the application. Tickets are created, assigned, moved through their status and archived. A policy starts the work on a ticket as soon as it is assigned. An event handler tells the new assignee by email. A process manager archives a ticket once it has been done for thirty days. A read model serves the ticket list and the ticket detail. * **iam** handles login and logout. It works with a fixed list of demo users to keep the focus on the ticketing context. ## Model First, Implement Second The workflow of the skills is built around [ESDM](https://www.esdm.io/), the Event-Sourced Domain Modeling language. ESDM describes an event-sourced domain as a set of YAML files. It covers the building blocks of Domain Driven Design, CQRS and Event Sourcing like Bounded Contexts, Aggregates, Commands, Events, Process Managers and Read Models. The format is plain enough that humans and coding agents can both read and write it. The skills treat the ESDM model as the source of truth for your project and work in two steps. 1. **Model first.** The `nimbus-domain-modeling` skill builds the model together with you. It challenges vague terms, checks them against the ubiquitous language and tests the model with concrete scenarios. Every resolved term is written to the ESDM files right away. The model stays free of implementation details so that all stakeholders can understand it. 2. **Implement second.** The `nimbus` skill loads the Nimbus [documentation for agents](/guide/nimbus-for-ai#documentation-for-agents), reads the model and implements every construct the task needs. If a construct is missing or contradicts the task the agent goes back and fixes the model before it writes any code. The demo keeps the results of both steps side by side. | Folder | What you find there | | ------------------- | ----------------------------------------------------------------------------------- | | `docs/domain-model` | The ESDM model of the two Bounded Contexts and the ESDM schemas. | | `docs/adr` | The architecture decision records, for example the decision to use EventSourcingDB. | | `src/api` | The code that implements the model with Nimbus. | ## The Opinionated Structure The code follows the [project structure](/guide/nimbus-for-ai#project-structure) of the skills. It mirrors the model, so every construct of the model has one obvious place in the code. | ESDM model | Code | | ----------------------------------- | -------------------------------------- | | Aggregate `ticket` | `src/api/ticketing/agg-ticket` | | Read Model `tickets` | `src/api/ticketing/rm-tickets` | | Process Manager `settled-archive` | `src/api/ticketing/pm-settled-archive` | | Dynamic Consistency Boundary `auth` | `src/api/iam/dcb-auth` | | External System `mailing` | `src/api/shared/ext-mailing` | A good way to explore the demo is to pick one construct, read its ESDM file and then open the matching folder in the code. The policy `start-work-on-assignment` of the `ticket` Aggregate is a small one to start with. The rules behind this structure and the mapping of every ESDM construct to the Nimbus building blocks are described on the [Nimbus for AI](/guide/nimbus-for-ai#project-structure) page. ::: tip Use the skills in your own project The [Nimbus for AI](/guide/nimbus-for-ai#installation) page shows how to install the skills with the `npx skills` commands. ::: --- --- url: https://nimbus.overlap.at/guide/glossary.md description: >- Pinned vocabulary for Nimbus, CQRS, and Event Sourcing — use these definitions literally when reasoning about the framework. --- # Glossary ## Terms * **Aggregate**: The consistency boundary for a stream of events on one **subject**; rebuilt by replaying events in order. Nimbus does not ship an `Aggregate` class — the idea is expressed by **state**, **reducers**, pure-core command functions, shell **handlers**, and EventSourcingDB **preconditions** (see [A Note on Aggregates](/guide/in-depth-example.html#a-note-on-aggregates)). * **Checkpoint**: Record of the position an **event consumer** resumes from after a restart, plus an optional failure marker. Persisted through a `CheckpointStore` (see [Checkpoint Store](/guide/core/checkpoint-store)). * **Bounded Context**: A DDD boundary within which a particular domain model, vocabulary, and rules apply consistently; in Nimbus, typically represented by a top-level **domain** folder (e.g. `iam`) and its **modules** (see [In Depth Example](/guide/in-depth-example)). * **CloudEvents**: Industry-standard envelope for **Commands**, **Events**, and **Queries** in Nimbus (`specversion`, `id`, `type`, `source`, `data`, etc.). See [cloudevents.io](https://cloudevents.io/). * **Command**: A write-side message expressing intent to change state; routed and validated, then handled to produce **events** (see [Commands](/guide/core/commands)). * **Correlation ID**: Identifier carried across messages and HTTP requests to trace a single operation through the system (see [CorrelationID Middleware](/guide/hono/correlationid)). * **Core**: See **Pure Core** — command functions, **reducers**, and event definitions live here. * **CQRS**: Command Query Responsibility Segregation — separate models and paths for writes (**commands**) and reads (**queries**). * **Domain**: A top-level business area in Nimbus folder layout (e.g. `iam`, `billing`) that groups related **modules** and represents the domain's **bounded context** (see [In Depth Example](/guide/in-depth-example)). * **Domain Driven Design (DDD)**: Organizing code around business **domains** and **modules** (e.g. `iam/users`) rather than technical layers. * **Event**: An immutable fact that already happened; appended to the **event log** and used to derive **state** (see [Events](/guide/core/events)). * **Event Bus**: In-process publish/subscribe for **events** inside one application via `NimbusEventBus` (see [Event Bus](/guide/core/event-bus)). In event-sourced deployments, EventSourcingDB **observers** often play this role across process restarts. * **Event Consumer**: Named unit an **event observer** feeds events to — a **projection**, policy, or process manager — that owns its own **checkpoint** and can depend on sibling consumers (see [Event Observer](/guide/eventsourcingdb/event-observer#event-consumers)). * **Event-Driven Architecture (EDA)**: Style where **commands**, **events**, and **queries** drive behavior and integration; Nimbus is built around this (see [What is Nimbus?](/guide/what-is-nimbus)). * **Event Log**: Append-only sequence of **events**; the source of truth in **Event Sourcing**. Every other data shape is derived from it (see [In Depth Example](/guide/in-depth-example)). * **Event Mapping**: Conversion between Nimbus **CloudEvents** and EventSourcingDB records, preserving **correlation ID** and schemas (see [Event Mapping](/guide/eventsourcingdb/event-mapping)). * **Event Observer**: Named background loop that watches one EventSourcingDB **subject** and hands every event to its **event consumers**, resuming from their **checkpoints** and reporting `catching-up`, `live`, or `stopped` (see [Event Observer](/guide/eventsourcingdb/event-observer)). * **Event Sourcing**: Persisting state changes as a sequence of **events**; current **state** is derived by **replay**ing them. * **EventSourcingDB**: External event store integrated via `@nimbus-cqrs/eventsourcingdb`; persists the **event log**, supports **preconditions**, and delivers events to **observers** (see [EventSourcingDB Package](/guide/eventsourcingdb/)). * **Handler**: Function registered on a **router**, **event bus**, or **event observer** that processes a **command**, **query**, or **event** matched by **message type**. * **Hexagonal Architecture**: Ports-and-adapters style; Nimbus **Pure Core** / **Imperative Shell** aligns with it (see [Architecture](/guide/architecture)). * **Imperative Shell**: The I/O layer (HTTP, databases, messaging) that orchestrates the **pure core** (see [Architecture](/guide/architecture)). * **Lower Bound**: Position in the **event log** from which an **event observer** resumes after reconnect or restart; derived from the lowest **checkpoint** of its **event consumers** so no full **replay** is needed (see [Event Observer](/guide/eventsourcingdb/event-observer)). * **Message Type**: CloudEvents `type` field (reverse-DNS, e.g. `at.overlap.nimbus.invite-user`); the **router** uses it to select a **handler** (see [Commands](/guide/core/commands)). * **Module**: A DDD slice inside a **domain** for one business concept (e.g. `iam/users`) (see [In Depth Example](/guide/in-depth-example)). * **Nimbus Exception**: Structured error type in `@nimbus-cqrs/core` with optional HTTP status and details (see [Exceptions](/guide/core/exceptions)). * **OpenTelemetry**: Industry-standard observability API used by Nimbus for logging, tracing, and metrics (see [Observability](/guide/core/observability)). * **Preconditions**: EventSourcingDB checks that must pass before events are appended (e.g. `isSubjectPristine`, `isSubjectOnEventId`); enforce the **aggregate** consistency boundary atomically (see [Write Events](/guide/eventsourcingdb/write-events)). * **Projection**: Read-side function that turns **events** into **read model** documents or views. Run as an **event consumer** on an **event observer** (see [In Depth Example](/guide/in-depth-example)). * **Pure Core**: Side-effect-free domain logic (commands, **reducers**, event definitions) with no I/O (see [Architecture](/guide/architecture)). * **Query**: A read-side message requesting data without changing state (see [Queries](/guide/core/queries)). * **Read Model**: Query-optimized document or view derived from **events** via **projections** (see [Queries](/guide/core/queries)). * **Read Side**: CQRS path that serves **queries** and runs **projections**; does not append to the **event log** (see [In Depth Example](/guide/in-depth-example)). * **Reducer**: Pure function that folds an **event** into current **state** (e.g. `applyEventToUserState`) (see [In Depth Example](/guide/in-depth-example)). * **Replay**: Reading **events** in order to rebuild **state** or refresh a **projection** (see [Read Events](/guide/eventsourcingdb/read-events)). * **Repository**: Type-safe MongoDB access layer extending `MongoDBRepository` for **read model** persistence (see [Repository](/guide/mongodb/repository)). * **Router**: Type-safe message dispatcher (`MessageRouter`) that validates and traces **commands**, **queries**, or **events** (see [Router](/guide/core/router)). * **Shell**: See **Imperative Shell** — command **handlers**, HTTP routes, and persistence live here. * **State**: Current shape of an **aggregate** after applying all relevant **events** via a **reducer**. * **Subject**: CloudEvents `subject` — typically identifies the aggregate or entity stream an **event** belongs to (see [Events](/guide/core/events)). * **Write Side**: CQRS path that accepts **commands**, enforces business rules, and appends **events** to the **event log** (see [In Depth Example](/guide/in-depth-example)). * **Zod**: Schema library used to validate **commands**, **queries**, and **events** in Nimbus (see [Commands](/guide/core/commands)). --- --- url: https://nimbus.overlap.at/guide/core.md description: >- Hub for @nimbus-cqrs/core — commands, queries, events, router, event bus, exceptions, logging, and observability. --- # Nimbus Core Package The core package is the foundation of the entire framework. It provides the essential building blocks for building event-driven applications following the CloudEvents specification. * npm: [@nimbus-cqrs/core](https://www.npmjs.com/package/@nimbus-cqrs/core) ## What's Included The core package provides: * **[Commands](/guide/core/commands)** - Write operations following the CloudEvents specification * **[Queries](/guide/core/queries)** - Read operations for fetching data * **[Events](/guide/core/events)** - Domain events for reactive architectures * **[Router](/guide/core/router)** - Message routing with validation and tracing * **[Event Bus](/guide/core/event-bus)** - Publish/subscribe for in-process events * **[Checkpoint Store](/guide/core/checkpoint-store)** - Contract and in-memory store for where event consumers resume * **[withRetry](/guide/core/with-retry)** - Shared retry helper with exponential backoff * **[Exceptions](/guide/core/exceptions)** - Structured error handling with HTTP status codes * **[Logging](/guide/core/logging)** - Structured logging with configurable formatters * **[Observability](/guide/core/observability)** - Built-in logging, tracing, and metrics using OpenTelemetry ## Installation ### npm ```bash npm install @nimbus-cqrs/core ``` ### pnpm ```bash pnpm add @nimbus-cqrs/core ``` ### Bun ```bash bun add @nimbus-cqrs/core ``` ### Deno ```bash deno add npm:@nimbus-cqrs/core ``` ## Example Application ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: --- --- url: https://nimbus.overlap.at/guide/core/commands.md description: >- Commands are CloudEvents-shaped write messages expressing intent to change state; validated and routed to handlers. --- # Commands Commands represent write operations - intentions to change system state in the application. Commands also fit perfectly into the CQRS pattern (Command Query Responsibility Segregation), where writes and reads are separated for better scalability and maintainability. But keep it simple for your use case and needs. CQRS in an option, but not required. ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: ## Key Characteristics * **Write Operations**: Commands modify application state * **Intent-Based**: Commands express what should happen (e.g., "InviteUser", "AcceptInvitation") * **Type-Safe**: Commands are fully typed and validated using Zod ## Command Structure A command in Nimbus follows the CloudEvents specification and consists of: ```typescript type Command = { specversion: "1.0"; id: string; correlationid: string; time: string; source: string; type: string; subject?: string; data: TData; datacontenttype?: string; dataschema?: string; }; ``` | Property | Description | | ----------------- | ------------------------------------------------------------------------------------- | | `specversion` | The CloudEvents specification version (always `'1.0'`) | | `id` | A globally unique identifier for the command | | `correlationid` | A unique identifier to correlate this command with related messages | | `time` | ISO 8601 timestamp when the command was created | | `source` | A URI reference identifying the system creating the command | | `type` | The command type following CloudEvents naming (e.g., `at.overlap.nimbus.invite-user`) | | `subject` | Optional identifier for the entity the command targets | | `data` | The command payload containing the business data | | `datacontenttype` | Optional MIME type of the data (defaults to `application/json`) | | `dataschema` | Optional URL to the schema the data adheres to | ## Command Schema Nimbus provides a base Zod schema for validating commands: ```typescript import { commandSchema } from "@nimbus-cqrs/core"; import { z } from "zod"; // Extend the base schema with your specific command type and data const inviteUserCommandSchema = commandSchema.extend({ type: z.literal("at.overlap.nimbus.invite-user"), data: z.object({ email: z.email(), firstName: z.string(), lastName: z.string(), }), }); type InviteUserCommand = z.infer; ``` ## Create Commands You can create commands using the `createCommand()` helper: ```typescript import { createCommand } from "@nimbus-cqrs/core"; import { InviteUserCommand } from "./inviteUser.command.ts"; const commandForJane = createCommand({ type: "at.overlap.nimbus.invite-user", source: "nimbus.overlap.at", data: { email: "jane@example.com", firstName: "Jane", lastName: "Doe", }, }); const commandForJohn = createCommand({ type: "at.overlap.nimbus.invite-user", source: "nimbus.overlap.at", data: { email: "john@example.com", firstName: "John", lastName: "Doe", }, }); ``` The `createCommand()` helper automatically generates default values for: * `id` - A unique ULID * `correlationid` - A unique ULID (if not provided) * `time` - Current ISO timestamp * `specversion` - Always `'1.0'` * `datacontenttype` - Defaults to `'application/json'` ## Routing Commands Commands are routed to handlers using the [MessageRouter](/guide/core/router). See the Router documentation for details on registering handlers and routing messages. --- --- url: https://nimbus.overlap.at/guide/core/queries.md description: >- Queries are CloudEvents-shaped read messages that fetch data without mutating application state. --- # Queries Queries represent read operations - requests for information without changing application state. Queries also fit perfectly into the CQRS pattern (Command Query Responsibility Segregation), where reads and writes are separated for better scalability and maintainability. But keep it simple for your use case and needs. CQRS in an option, but not required. ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: ## Key Characteristics * **Read Operations**: Queries fetch data without modifying state * **Idempotent**: Multiple executions return the same result (if data hasn't changed) * **Type-Safe**: Queries are fully typed and validated using Zod * **Optimized for Reading**: Can use specialized read models or databases ## Query Structure A query in Nimbus follows the CloudEvents specification and consists of: ```typescript type Query = { specversion: "1.0"; id: string; correlationid: string; time: string; source: string; type: string; data: TData; datacontenttype?: string; dataschema?: string; }; ``` | Property | Description | | ----------------- | -------------------------------------------------------------------------------- | | `specversion` | The CloudEvents specification version (always `'1.0'`) | | `id` | A globally unique identifier for the query | | `correlationid` | A unique identifier to correlate this query with related messages | | `time` | ISO 8601 timestamp when the query was created | | `source` | A URI reference identifying the system creating the query | | `type` | The query type following CloudEvents naming (e.g., `at.overlap.nimbus.get-user`) | | `data` | The query parameters (e.g., filters, pagination) | | `datacontenttype` | Optional MIME type of the data (defaults to `application/json`) | | `dataschema` | Optional URL to the schema the data adheres to | ## Query Schema Nimbus provides a base Zod schema for validating queries: ```typescript import { querySchema } from "@nimbus-cqrs/core"; import { z } from "zod"; // Extend the base schema with your specific query type and data const getUserQuerySchema = querySchema.extend({ type: z.literal("at.overlap.nimbus.get-user"), data: z.object({ id: z.string().length(24), }), }); type GetUserQuery = z.infer; ``` ## Create Queries You can create queries using the `createQuery()` helper: ```typescript import { createQuery } from "@nimbus-cqrs/core"; import { GetUserQuery } from "./getUser.query.ts"; const query = createQuery({ type: "at.overlap.nimbus.get-user", source: "nimbus.overlap.at", data: { id: "123", }, }); ``` The `createQuery()` helper automatically generates default values for: * `id` - A unique ULID * `correlationid` - A unique ULID (if not provided) * `time` - Current ISO timestamp * `specversion` - Always `'1.0'` * `datacontenttype` - Defaults to `'application/json'` ## Routing Queries Queries are routed to handlers using the [MessageRouter](/guide/core/router). See the Router documentation for details on registering handlers and routing messages. --- --- url: https://nimbus.overlap.at/guide/core/events.md description: >- Events are immutable CloudEvents facts about what already happened; they power event-driven and event-sourced designs. --- # Events Events represent facts - things that have already happened in the system. Events are immutable records of state changes that occurred in the application. They enable event-driven architectures, event sourcing, and asynchronous processing. ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: ## Key Characteristics * **Immutable Facts**: Events represent things that already happened and cannot be changed * **Past Tense**: Event names use past tense (e.g., "UserInvited", not "InviteUser") * **Observable**: Other parts of the system can subscribe and react to events * **Type-Safe**: Events are fully typed and validated using Zod ## Event Structure An event in Nimbus follows the CloudEvents specification and consists of: ```typescript type Event = { specversion: "1.0"; id: string; correlationid: string; time: string; source: string; type: string; subject: string; data: TData; datacontenttype?: string; dataschema?: string; }; ``` | Property | Description | | ----------------- | ------------------------------------------------------------------------------------ | | `specversion` | The CloudEvents specification version (always `'1.0'`) | | `id` | A globally unique identifier for the event | | `correlationid` | A unique identifier to correlate this event with related messages | | `time` | ISO 8601 timestamp when the event was created | | `source` | A URI reference identifying the system creating the event | | `type` | The event type following CloudEvents naming (e.g., `at.overlap.nimbus.user-invited`) | | `subject` | An identifier for the entity the event is about (e.g., `/users/123`) | | `data` | The event payload containing the business data | | `datacontenttype` | Optional MIME type of the data (defaults to `application/json`) | | `dataschema` | Optional URL to the schema the data adheres to | ## Event Subjects Unlike commands and queries, events **require** a `subject` field.\ Events use subjects to organize and identify the entities they relate to: ```typescript // Subject examples "/users/123"; // Specific user "/orders/456"; // Specific order "/users/123/orders/456"; // Order belonging to a user ``` ## Event Schema Nimbus provides a base Zod schema for validating events: ```typescript import { eventSchema } from "@nimbus-cqrs/core"; import { z } from "zod"; // Extend the base schema with your specific event type and data const userInvitedEventSchema = eventSchema.extend({ type: z.literal("at.overlap.nimbus.user-invited"), data: z.object({ _id: z.string(), email: z.string(), firstName: z.string(), lastName: z.string(), }), }); type UserInvitedEvent = z.infer; ``` ## Create Events You can create events using the `createEvent()` helper: ```typescript import { createEvent } from "@nimbus-cqrs/core"; import { UserInvitedEvent } from "./userInvited.event.ts"; const event = createEvent({ type: "at.overlap.nimbus.user-invited", source: "nimbus.overlap.at", correlationid: command.correlationid, subject: `/users/${userState._id}`, data: userState, }); ``` The `createEvent()` helper automatically generates default values for: * `id` - A unique ULID * `correlationid` - A unique ULID (if not provided) * `time` - Current ISO timestamp * `specversion` - Always `'1.0'` * `datacontenttype` - Defaults to `'application/json'` ## Best Practices ### Use Past Tense Names Event names should describe what happened, not what should happen: ```typescript // ✅ Good - Past tense UserInvitedEvent; OrderShippedEvent; PaymentProcessedEvent; // ❌ Bad - Imperative InviteUserEvent; ShipOrderEvent; ProcessPaymentEvent; ``` ### Propagate Correlation IDs Always pass correlation IDs from commands to events for tracing: ```typescript const event = createEvent({ type: USER_INVITED_EVENT_TYPE, source: "nimbus.overlap.at", correlationid: command.correlationid, // Always propagate data: state, }); ``` ### Use Meaningful Subjects Subjects should be hierarchical and meaningful: ```typescript // ✅ Good - Hierarchical and clear `/users/${userId}``/users/${userId}/orders/${orderId}``/organizations/${orgId}/members/${memberId}` // ❌ Bad - Flat and unclear `user-${userId}``order_${orderId}`; ``` ## Publish & Subscribe Events Events are published and subscribed to using the [EventBus](/guide/core/event-bus). See the EventBus documentation for details on publishing and subscribing to events. --- --- url: https://nimbus.overlap.at/guide/core/router.md description: >- MessageRouter routes commands, queries, and events to handlers with Zod validation and OpenTelemetry tracing. --- # Router The MessageRouter is responsible for routing incoming messages (commands, queries, and events) to their registered handlers. It provides automatic validation, type safety, and observability for all routed messages. ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: ## Setup and Configuration Configure the router at application startup using `setupRouter()`, then retrieve it anywhere using `getRouter()`. ```typescript import { getLogger, setupRouter } from "@nimbus-cqrs/core"; setupRouter("MyRouter", { logInput: (input) => { getLogger().debug({ category: "MyRouter", message: "Received input", data: { input }, ...(input?.correlationid ? { correlationId: input.correlationid } : {}), }); }, logOutput: (output) => { getLogger().debug({ category: "MyRouter", message: "Output", data: { output }, ...(output?.correlationid ? { correlationId: output.correlationid } : {}), }); }, }); ``` ### Configuration Options | Option | Type | Description | | ----------- | ----------------------- | ---------------------------------------------------- | | `logInput` | `(input: any) => void` | Optional callback invoked when a message is received | | `logOutput` | `(output: any) => void` | Optional callback invoked after successful handling | ## Registering Handlers Register handlers for message types using the `register()` method: ```typescript import { getRouter } from "@nimbus-cqrs/core"; export const registerUserMessages = () => { const router = getRouter("MyRouter"); // Register a command router.register( "at.overlap.nimbus.invite-user", async (command: InviteUserCommand) => { // Process command and return result }, inviteUserCommandSchema ); // Register an event router.register( "at.overlap.nimbus.user-invited", async (event: UserInvitedEvent) => { // Process event and return result }, inviteUserCommandSchema ); // Register a query router.register( "at.overlap.nimbus.get-user", async (query: GetUserQuery) => { // Process query and return result }, getUserQuerySchema ); }; ``` The `register()` method takes three arguments: | Argument | Description | | ------------- | --------------------------------------------------------------------- | | `messageType` | The CloudEvents type string (e.g., `'at.overlap.nimbus.invite-user'`) | | `handler` | An async function that processes the message and returns a result | | `schema` | A Zod schema used to validate the incoming message | ## Routing Messages Route messages to their handlers using the `route()` method: ```typescript import { createCommand, getRouter } from "@nimbus-cqrs/core"; const command = createCommand({ type: "at.overlap.nimbus.invite-user", source: "nimbus.overlap.at", correlationid: httpRequestCorrelationId, data: httpRequestBody, }); const router = getRouter("MyRouter"); const result = await router.route(command); ``` ## Validation The router automatically validates incoming messages against their registered schemas: 1. **Message Type Check**: Verifies the message has a `type` attribute 2. **Handler Lookup**: Finds the registered handler for the message type 3. **Schema Validation**: Validates the message against the Zod schema 4. **Handler Execution**: Passes the validated message to the handler If validation fails, an `InvalidInputException` is thrown with details about the validation errors: ```typescript { name: 'INVALID_INPUT', message: 'The provided input is invalid', statusCode: 400, details: { issues: [ { path: ['data', 'email'], message: 'Invalid email' } ] } } ``` ## Error Handling The router throws appropriate exceptions for different error conditions: | Error | Exception | Description | | ------------------ | ----------------------- | --------------------------------------------- | | Missing type | `InvalidInputException` | The message has no `type` attribute | | Unknown type | `NotFoundException` | No handler registered for the message type | | Validation failure | `InvalidInputException` | The message failed schema validation | | Handler error | *(propagated)* | Errors from handlers are propagated unchanged | ## Observability The router is fully instrumented with OpenTelemetry tracing and metrics. See the [Observability](/guide/core/observability) documentation for details. **Tracing**: * Automatic spans for every routed message **Metrics**: * `router_messages_routed_total` counter * `router_routing_duration_seconds` histogram --- --- url: https://nimbus.overlap.at/guide/core/event-bus.md description: >- NimbusEventBus provides in-process publish/subscribe for events with async delivery and retry on handler failure. --- # Event Bus The NimbusEventBus enables publish/subscribe messaging for [events](/guide/core/events) within your application. Events are delivered asynchronously to all registered handlers with automatic retry on failure. ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: ## Setup and Configuration Configure the event bus at application startup using `setupEventBus()`, then retrieve it anywhere using `getEventBus()`. ```typescript import { getLogger, setupEventBus } from "@nimbus-cqrs/core"; setupEventBus("MyEventBus", { maxRetries: 2, baseDelay: 1000, maxDelay: 30000, useJitter: true, logPublish: (event) => { getLogger().debug({ category: "MyEventBus", message: "Published event", data: { event }, ...(event?.correlationid ? { correlationId: event.correlationid } : {}), }); }, }); ``` ### Configuration Options | Option | Type | Default | Description | | ------------ | ----------------- | ------- | -------------------------------------------------- | | `maxRetries` | `number` | `2` | Maximum retry attempts for failed handlers | | `baseDelay` | `number` | `1000` | Base delay in milliseconds for exponential backoff | | `maxDelay` | `number` | `30000` | Maximum delay cap in milliseconds | | `useJitter` | `boolean` | `true` | Add randomness to delay to prevent thundering herd | | `logPublish` | `(event) => void` | - | Optional callback when an event is published | ## Subscribing to Events Subscribe to event types using `subscribeEvent()`: ```typescript import { getEventBus } from "@nimbus-cqrs/core"; const eventBus = getEventBus("MyEventBus"); eventBus.subscribeEvent({ type: "at.overlap.nimbus.user-invited", handler: async (event: UserInvitedEvent) => { // Process event and return result }, }); eventBus.subscribeEvent({ type: "at.overlap.nimbus.onboarding-started", handler: async (event: OnboardingStartedEvent) => { // Process event and return result }, onError: (error, event) => { // Handle the error }, options: { maxRetries: 0, // Override the default of 2 retries for this subscription }, }); ``` ### Subscription Options The `subscribeEvent()` method accepts the following options: | Option | Type | Description | | --------- | -------------------------- | ---------------------------------------------------- | | `type` | `string` | The CloudEvents type to subscribe to | | `handler` | `(event) => Promise` | Async handler function for the event | | `onError` | `(error, event) => void` | Optional callback when all retries are exhausted | | `options` | `object` | Optional retry options to override EventBus defaults | ## Publishing Events Publish events using `putEvent()`: ```typescript import { createEvent, getEventBus } from "@nimbus-cqrs/core"; const eventBus = getEventBus("default"); const event = createEvent({ type: "at.overlap.nimbus.user-invited", source: "nimbus.overlap.at", correlationid: command.correlationid, subject: `/users/${user.id}`, data: { email: user.email, firstName: user.firstName, lastName: user.lastName, }, }); eventBus.putEvent(event); ``` ## Retry Mechanism When a handler throws an error, the event bus automatically retries using exponential backoff via the shared [`withRetry`](/guide/core/with-retry) helper: 1. **First retry**: Waits `baseDelay` ms (default: 1000ms) 2. **Second retry**: Waits `baseDelay * 2` ms (2000ms) 3. **Third retry**: Waits `baseDelay * 4` ms (4000ms) 4. ... continues until `maxDelay` is reached With `useJitter: true`, a small random amount (up to 10% of the delay) is added to prevent multiple handlers from retrying simultaneously. After all retries are exhausted, the `onError` callback is invoked (if provided), or the error is logged. ## Event Size Limit The event bus enforces the CloudEvents specification size limit of 64KB. If you attempt to publish an event larger than this, a `GenericException` is thrown. ## Observability The event bus is fully instrumented with OpenTelemetry tracing and metrics. See the [Observability](/guide/core/observability) documentation for details. **Tracing:** * `eventbus.publish` span for event publishing * `eventbus.handle` span for event handling **Metrics:** * `eventbus_events_published_total` - Counter for published events * `eventbus_events_delivered_total` - Counter for delivered events (with success/error status) * `eventbus_event_handling_duration_seconds` - Histogram of handler execution time * `eventbus_retry_attempts_total` - Counter for retry attempts * `eventbus_event_size_bytes` - Histogram of event sizes --- --- url: https://nimbus.overlap.at/guide/core/checkpoint-store.md description: >- CheckpointStore is the contract for persisting where event consumers resume; the core ships the types and an in-memory implementation. --- # Checkpoint Store A **checkpoint** records where one event consumer resumes after a restart. The `CheckpointStore` type is the contract an [event observer](/guide/eventsourcingdb/event-observer) uses to load and persist those checkpoints. The core package defines the types and ships an in-memory implementation. Persistent implementations live in the storage packages, for example the [MongoCheckpointStore](/guide/mongodb/checkpoint-store). The contract knows nothing about a specific event store. A `position` is an opaque string owned by whoever runs the consumers. For EventSourcingDB it is the id of the last event the consumer finished. ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: ## Checkpoint ```typescript type Checkpoint = { consumer: string; observer: string; position?: string; updatedAt: string; failure?: { position: string; error: string; at: string; }; }; ``` | Property | Description | | ----------- | ------------------------------------------------------------------------------------------------------------ | | `consumer` | The stable name of the consumer, unique across the whole application. Renaming it replays the stream | | `observer` | The name of the observer the consumer belongs to | | `position` | The last position the consumer finished. Absent until the first one, in which case it starts at the beginning | | `updatedAt` | When the checkpoint was last written, as ISO 8601 | | `failure` | Set while the last attempt at `failure.position` failed. Cleared by the next successful save | A matching Zod schema is exported as `checkpointSchema` for store implementations that want to validate what they read back. ## CheckpointStore ```typescript type CheckpointStore = { load(consumers: readonly string[]): Promise>; save(updates: readonly CheckpointUpdate[]): Promise; reset(consumer: string, position?: string): Promise; }; ``` ### load Returns the checkpoints of the given consumers keyed by name. Consumers without a checkpoint are absent from the result and start from the beginning of the stream. ### save Persists every given `CheckpointUpdate`. Implementations write them in one round trip where the storage allows it, since an observer saves after every event. ```typescript type CheckpointUpdate = { consumer: string; observer: string; position?: string; failure?: { position: string; error: string; }; }; ``` * `position` left out keeps the stored position, so a failure can be recorded for a consumer that has not finished any event yet. * `failure` left out **clears** an existing failure marker. The marker therefore always reflects the most recent attempt. ### reset Moves a consumer to `position`, or back to the beginning of the stream when `position` is omitted, and clears any failure marker. Use it to rebuild a projection or to skip an event a consumer cannot handle. A consumer without a checkpoint is left alone. To give a new consumer a starting position use `save`. This is an **offline operation**. The observer running the consumer must not be active. It keeps its positions in memory and would overwrite the reset with its next save. Resetting a consumer declared with `startFrom: "head"` has no effect, since it ignores its stored position on every start (see [Live-only Consumers](/guide/eventsourcingdb/event-observer#live-only-consumers)). ## InMemoryCheckpointStore ```typescript import { InMemoryCheckpointStore } from "@nimbus-cqrs/core"; const checkpointStore = new InMemoryCheckpointStore(); ``` Keeps checkpoints in process memory. Every restart starts from an empty store, so consumers replay the whole stream. Use it in tests, or for consumers whose read models live in memory as well and have to be rebuilt on every start anyway. ## Implementing a Store A store for another database only has to implement the three methods above. Keep these properties: * Key records by `consumer` alone. Consumer names are unique across the application, and `reset` only receives the consumer name. * `load` must not fail for unknown consumers. Leave them out of the result. * `save` is called with several consumers at once. Write them together. * A save **without** `failure` removes a stored failure marker. * Treat `position` as an opaque string. Do not parse or compare it. See the [MongoCheckpointStore](/guide/mongodb/checkpoint-store) for a reference implementation. --- --- url: https://nimbus.overlap.at/guide/core/exceptions.md description: >- Structured Nimbus exceptions carry optional HTTP status codes and details for consistent API error responses. --- # Exceptions Nimbus provides a set of structured exceptions for handling errors in your application. These exceptions have and optional status code and can include additional details for debugging. ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: ## Status Codes The basic Exception class has an optional status code that can be set when creating the exceptions and you can assign any number as a value. However, Nimbus comes with some built-in exceptions that use the related HTTP status codes. As HTTP status codes are standardized and well-known we thought it would be a good idea to use them even though the Exceptions itself are transport agnostic. ## Built-in Exception Types | Exception | Status Code | Use Case | | ----------------------- | ----------- | ------------------------------------------- | | `GenericException` | 500 | Internal server errors, unexpected failures | | `InvalidInputException` | 400 | Validation errors, malformed requests | | `NotFoundException` | 404 | Resource not found | | `UnauthorizedException` | 401 | Authentication required or failed | | `ForbiddenException` | 403 | Authorization failed, access denied | ## Basic Usage All exceptions accept an optional message and details object: ```typescript import { ForbiddenException, GenericException, InvalidInputException, NotFoundException, UnauthorizedException, } from "@nimbus-cqrs/core"; // Generic server error (500) throw new GenericException("Something went wrong"); // Invalid input with details (400) throw new InvalidInputException("The input is invalid", { field: "email", reason: "Invalid email format", }); // Unauthorized (401) throw new UnauthorizedException(); // Forbidden (403) throw new ForbiddenException(); // Not found with details (404) throw new NotFoundException("User not found", { errorCode: "USER_NOT_FOUND", userId: "12345", }); ``` ## Converting from Standard Errors Use `fromError()` to convert a standard JavaScript error while preserving the stack trace: ```typescript import { GenericException } from "@nimbus-cqrs/core"; try { await someExternalService.call(); } catch (error) { const exception = new GenericException(); exception.fromError(error); throw exception; } ``` ## Converting from Zod Errors If you need to manually handle Zod validation: ```typescript import { InvalidInputException } from "@nimbus-cqrs/core"; import { z } from "zod"; const UserSchema = z.object({ email: z.email(), name: z.string().min(1), }); try { UserSchema.parse({ email: "invalid", name: "" }); } catch (error) { const exception = new InvalidInputException(); exception.fromZodError(error); throw exception; } ``` ## Creating Custom Exceptions Create custom exceptions by extending the base `Exception` class: ```typescript import { Exception } from "@nimbus-cqrs/core"; export class RateLimitException extends Exception { constructor(message?: string, details?: Record) { super( "RATE_LIMIT_EXCEEDED", message ?? "Rate limit exceeded", details, 429 // Too Many Requests ); } } // Usage throw new RateLimitException("Too many requests", { retryAfter: 60, limit: 100, }); ``` ## HTTP Integration When using the `@nimbus-cqrs/hono` package, exceptions are automatically converted to HTTP responses: ```typescript import { onError } from "@nimbus-cqrs/hono"; import { Hono } from "hono"; const app = new Hono(); // Configure error handler app.onError(onError); // Exceptions thrown in routes are converted to JSON responses app.get("/users/:id", async (c) => { throw new NotFoundException("User not found", { userId: c.req.param("id"), }); // Returns: { "error": "NOT_FOUND", "message": "User not found", "details": { "userId": "123" } } // Status: 404 }); ``` ## Best Practices ### Use Specific Exceptions Choose the most specific exception type for the situation: ```typescript // ✅ Good - Specific exception throw new NotFoundException("Order not found"); // ❌ Bad - Generic exception for known error throw new GenericException("Order not found"); ``` ### Include Helpful Details Add details that help with debugging: ```typescript throw new InvalidInputException("Invalid order data", { errorCode: "INVALID_ORDER", field: "quantity", value: -5, constraint: "must be positive", }); ``` ### Use Error Codes Include machine- and human-readable error codes for client handling: ```typescript throw new NotFoundException("User not found", { errorCode: "USER_NOT_FOUND", // Clients can check this AND translate it to a human-readable error message in multiple languages userId: id, }); ``` --- --- url: https://nimbus.overlap.at/guide/core/observability.md description: >- Built-in logging, tracing, and metrics via OpenTelemetry with zero boilerplate on routers, handlers, and messages. --- # Observability Observability is a first-class citizen in Nimbus. The framework is designed so that developers can focus on business logic without implementing logging, tracing, and metrics from the ground up. Every core component - from message routing to event handling - comes with automatic instrumentation. This means: * **Zero boilerplate** - Tracing spans and metrics are created automatically * **Consistent structure** - All logs follow the same format across your application * **Correlation built-in** - Every message carries a correlation ID for distributed tracing The three pillars of observability in Nimbus: 1. **Logging** - Structured console output with configurable formatters 2. **Tracing** - Distributed traces via OpenTelemetry spans 3. **Metrics** - Counters and histograms for monitoring ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: ## OpenTelemetry Standards Nimbus uses the [OpenTelemetry API](https://opentelemetry.io/) (`@opentelemetry/api`) for all observability instrumentation. This provides: * **Vendor-agnostic** - Export to any OTLP-compatible backend (Jaeger, Zipkin, Grafana, Honeycomb, Datadog, etc.) * **Industry standard** - Wide ecosystem support and community adoption * **Future-proof** - Backed by CNCF with active development ## Enabling OpenTelemetry Nimbus only depends on the OpenTelemetry *API*. Nothing is exported until your application registers an OpenTelemetry SDK, which is runtime specific. ### Node.js Install the Node SDK and start it before any application code runs. The simplest way is a small bootstrap module that is loaded with `node --import`: ```bash npm install @opentelemetry/sdk-node ``` ```typescript // src/otel.ts import { NodeSDK } from "@opentelemetry/sdk-node"; const sdk = new NodeSDK(); sdk.start(); export const shutdownTelemetry = () => sdk.shutdown(); ``` Await `shutdownTelemetry()` as the last step of your graceful shutdown, after the HTTP server and database connections have been drained and before calling `process.exit()`. Shutting the SDK down earlier (for example directly from a signal handler) drops the spans of requests that finish during draining, and exiting without awaiting it can cut off the final export. ```typescript // src/main.ts import { shutdownTelemetry } from "./otel.ts"; const shutdown = async () => { await server.shutdown(); await getMongoConnectionManager("default").close(); await shutdownTelemetry(); process.exit(0); }; ``` The SDK is configured through the standard `OTEL_*` environment variables: ```bash export OTEL_EXPORTER_OTLP_PROTOCOL="http/protobuf" export OTEL_EXPORTER_OTLP_ENDPOINT="https://your-otlp-endpoint.com/otlp" export OTEL_SERVICE_NAME=your-service-name export OTEL_RESOURCE_ATTRIBUTES=deployment.environment=production node --import ./src/otel.ts src/main.ts ``` All traces and metrics from Nimbus will be exported to your configured backend. See `examples/eventsourcing-demo/src/otel.ts` in the repository for a complete example. It registers the shutdown through a small `telemetry.ts` module so the application can also be started without the bootstrap. ### Deno Deno ships a built-in OpenTelemetry SDK, so no additional dependency is needed. Set `OTEL_DENO=true` together with the same `OTEL_*` variables as above and run your application with `deno run -A src/main.ts`. See [Deno's OpenTelemetry documentation](https://docs.deno.com/runtime/fundamentals/open_telemetry/) for details. ## Built-in Instrumentation ### MessageRouter The [MessageRouter](/guide/core/router) automatically creates spans for every routed message: **Tracing:** * Span name: `router.route` * Attributes: `messaging.system`, `messaging.router_name`, `messaging.destination`, `correlation_id` **Metrics:** * `router_messages_routed_total` - Counter for total messages routed (with `status: success|error`) * `router_routing_duration_seconds` - Histogram of routing duration ### EventBus The [NimbusEventBus](/guide/core/event-bus) instruments both publishing and handling: **Tracing:** * `eventbus.publish` span for event publishing * `eventbus.handle` span for event handling with retry tracking **Metrics:** * `eventbus_events_published_total` - Counter for published events * `eventbus_events_delivered_total` - Counter for delivered events (with `status: success|error`) * `eventbus_event_handling_duration_seconds` - Histogram of handler execution time * `eventbus_retry_attempts_total` - Counter for retry attempts * `eventbus_event_size_bytes` - Histogram of event sizes ### EventSourcingDB The [EventSourcingDB package](/guide/eventsourcingdb/) instruments writes, reads, and observers: **Tracing:** * `eventsourcingdb.writeEvents` / `eventsourcingdb.readEvents` client spans * `eventsourcingdb.observeEvent` consumer span per observed event (with id/type/subject attributes and handler `retry` events) **Metrics:** * `eventsourcingdb_operation_total` - Counter for read/write operations (with `status: success|error`) * `eventsourcingdb_operation_duration_seconds` - Histogram of operation duration * `eventsourcingdb_event_size_bytes` - Histogram of written event sizes (no labels) * `eventsourcingdb_observer_events_handled_total` - Counter for handled events (`status: success|skipped`) * `eventsourcingdb_observer_handling_duration_seconds` - Histogram of observer handler duration * `eventsourcingdb_observer_handler_retry_attempts_total` - Counter for handler retries * `eventsourcingdb_observer_connection_retry_attempts_total` - Counter for scheduled reconnects * `eventsourcingdb_observer_connection_reconnects_total` - Counter for successful reconnects (when events flow again) See [Event Observer](/guide/eventsourcingdb/event-observer) and [Write Events](/guide/eventsourcingdb/write-events) for details. ### Logger The [Logger](/guide/core/logging) outputs structured logs to the console. Runtimes that capture `console` output for OpenTelemetry (such as Deno's built-in SDK) export these logs alongside traces and metrics; on Node.js, forward stdout to your log collector or add a `console` instrumentation to the Node SDK. ## Custom Tracing with withSpan() For business logic that needs custom tracing, use the `withSpan()` higher-order function: ```typescript import { withSpan } from "@nimbus-cqrs/core"; const fetchUser = withSpan( { name: "fetchUser", attributes: { "user.source": "database", }, }, async (userId: string) => { return await db.users.findById(userId); }, ); // Usage - automatically traced const user = await fetchUser("123"); ``` ### Adding Dynamic Attributes Access the span within your function to add attributes based on runtime data: ```typescript import { withSpan } from "@nimbus-cqrs/core"; import { Span } from "@opentelemetry/api"; const processOrder = withSpan( { name: "processOrder" }, async (orderId: string, span: Span) => { const order = await db.orders.findById(orderId); // Add attributes based on the order span.setAttribute("order.total", order.total); span.setAttribute("order.items", order.items.length); return await processPayment(order); }, ); ``` ### Options | Option | Type | Description | | ------------ | ------------ | ------------------------------------------ | | `name` | `string` | The span name displayed in your tracing UI | | `tracerName` | `string` | Tracer name (defaults to `"nimbus"`) | | `kind` | `SpanKind` | Span kind (defaults to `INTERNAL`) | | `attributes` | `Attributes` | Initial attributes to set on the span | ## Correlation IDs All messages in Nimbus (Commands, Queries, Events) carry a `correlationid` field. This enables: * **Request tracing** - Follow a request through commands, events, and queries * **Log correlation** - Group related logs together * **Distributed tracing** - Track requests across services The correlation ID is automatically: * Generated when creating messages with `createCommand()`, `createQuery()`, or `createEvent()` * Propagated from commands to events they produce * Included in log output when provided * Added as a span attribute for tracing ```typescript // Correlation ID is passed from command to event const command = createCommand({ type: INVITE_USER_COMMAND_TYPE, source: "nimbus.overlap.at", correlationid: getCorrelationId(c), // From HTTP request data: body, }); // In the handler, create event with same correlation ID const event = createEvent({ type: USER_INVITED_EVENT_TYPE, source: "nimbus.overlap.at", correlationid: command.correlationid, // Propagate data: state, }); ``` ## Best Practices ### Use Structured Logging Always use the structured logger instead of `console.log`: ```typescript import { getLogger } from "@nimbus-cqrs/core"; // Good - structured and traceable getLogger().info({ message: "User created", category: "Users", data: { userId: user.id }, correlationId: command.correlationid, }); // Avoid - unstructured console.log("User created:", user.id); ``` ### Propagate Correlation IDs Always pass correlation IDs when creating events from commands: ```typescript const event = createEvent({ type: USER_INVITED_EVENT_TYPE, source: "nimbus.overlap.at", correlationid: command.correlationid, // Always propagate data: state, }); ``` ### Use withSpan for Important Operations Wrap critical business logic with `withSpan()` for visibility: ```typescript const validatePayment = withSpan( { name: "validatePayment" }, async (paymentDetails: PaymentDetails) => { // Critical logic is now traced }, ); ``` --- --- url: https://nimbus.overlap.at/guide/core/logging.md description: >- Structured console logging with JSON or pretty formatters, truncation, and OpenTelemetry integration. --- # Logging Nimbus provides a structured logger that outputs consistent, formatted log messages to the console. Because it writes plain structured output, it works with any log collector and with runtimes that export `console` output through OpenTelemetry. ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: ## Setup and Configuration Configure the logger at application startup using `setupLogger()`: ```typescript import { createLogTruncator, jsonLogFormatter, parseLogLevel, prettyLogFormatter, setupLogger, } from "@nimbus-cqrs/core"; import process from "node:process"; setupLogger({ logLevel: parseLogLevel(process.env.LOG_LEVEL), formatter: process.env.LOG_FORMAT === "pretty" ? prettyLogFormatter : jsonLogFormatter, useConsoleColors: process.env.LOG_FORMAT === "pretty", truncator: createLogTruncator(), }); ``` ### Configuration Options | Option | Type | Default | Description | | ------------------ | -------------- | ------------------ | -------------------------------------------- | | `logLevel` | `LogLevel` | `'silent'` | Minimum level to output | | `formatter` | `LogFormatter` | `jsonLogFormatter` | Function to format log records | | `useConsoleColors` | `boolean` | `false` | Enable colored output (for pretty formatter) | | `truncator` | `LogTruncator` | `undefined` | Optional truncator for log inputs | ## Log Levels Nimbus supports the following log levels in order of severity: | Level | Method | Description | | ---------- | ----------------- | -------------------------------------------- | | `debug` | `console.debug()` | Detailed debugging information | | `info` | `console.info()` | General information about application flow | | `warn` | `console.warn()` | Warning conditions that should be reviewed | | `error` | `console.error()` | Error conditions that need attention | | `critical` | `console.error()` | Critical failures requiring immediate action | | `silent` | *(none)* | Disables all log output | Messages below the configured log level are silently ignored. ### Parsing Log Levels Use `parseLogLevel()` to safely parse environment variables: ```typescript import { parseLogLevel } from "@nimbus-cqrs/core"; // Returns 'info' if LOG_LEVEL is 'info', otherwise returns default 'silent' const level = parseLogLevel(process.env.LOG_LEVEL); ``` ## Basic Usage Access the logger using `getLogger()`: ```typescript import { getLogger } from "@nimbus-cqrs/core"; const logger = getLogger(); logger.debug({ message: "Processing request", category: "API", data: { method: "POST", path: "/users" }, correlationId: "550e8400-e29b-41d4-a716-446655440000", }); logger.info({ message: "User created successfully", category: "Users", data: { userId: "12345" }, }); logger.warn({ message: "Rate limit approaching", category: "API", data: { currentRate: 95, maxRate: 100 }, }); logger.error({ message: "Failed to process payment", category: "Payments", error: new Error("Payment gateway timeout"), correlationId: "550e8400-e29b-41d4-a716-446655440000", }); logger.critical({ message: "Database connection lost", category: "Database", error: new Error("Connection refused"), }); ``` ## Log Input The log input object can contain the following properties: | Property | Type | Description | | ---------------- | ------------------------- | --------------------------------------------------------------------------------- | | `message` | `string` | **Required.** The log message | | `category` | `string` | Optional category for grouping logs (defaults to `'Default'`) | | `data` | `Record` | Optional structured data to include | | `error` | `Error` | Optional error with stack trace | | `correlationId` | `string` | Optional ID for tracing related operations | | `skipTruncation` | `boolean` | When `true`, skips the configured truncator for this call (not emitted in output) | ## Formatters Nimbus provides two built-in formatters: ### JSON Formatter (Production) Outputs structured JSON for easy parsing by log aggregation tools: ```typescript import { jsonLogFormatter, setupLogger } from "@nimbus-cqrs/core"; setupLogger({ logLevel: "info", formatter: jsonLogFormatter, }); // Output: // {"timestamp":"2025-01-22T10:00:00.000Z","level":"info","category":"Users","message":"User created","data":{"userId":"123"}} ``` ### Pretty Formatter (Development) Outputs human-readable colored logs for development: ```typescript import { prettyLogFormatter, setupLogger, getLogger } from "@nimbus-cqrs/core"; setupLogger({ logLevel: "debug", formatter: prettyLogFormatter, useConsoleColors: true, }); getLogger().debug({ message: "My message", category: "Category", data: { userId: "12345" }, }); // Outputs: // [Category] DEBUG :: My message // { // userId: '12345' // } ``` ## Truncation By default, log inputs are passed through unchanged. To avoid flooding log pipelines with large payloads, configure a truncator via `setupLogger`. Use the built-in factory, or supply a custom `LogTruncator`: ```typescript import { createLogTruncator, setupLogger } from "@nimbus-cqrs/core"; // Built-in defaults setupLogger({ truncator: createLogTruncator(), }); // Override limits setupLogger({ truncator: createLogTruncator({ maxBytes: 8_192, maxArrayItems: 50, maxObjectKeys: 50, maxDepth: 8, maxCategoryLength: 50, maxMessageLength: 100, maxStackLength: 200, maxDataStringLength: 200, }), }); ``` The built-in truncator processes each `LogInput` field separately and leaves `correlationId` untouched: | Field | Behavior | | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `message` / `category` | String length caps | | `data` | Structural limits (strings, arrays, object keys, depth, circular refs, common JS types), then a byte-size cliff for oversized or unserializable `data` | | `error` | Stays `Error`-shaped; truncates `message` / `stack`; copies enumerable custom fields; walks `cause` and aggregate errors (including non-`Error` values) up to `maxDepth` | | `correlationId` | Never truncated | | `skipTruncation` | Logger control flag; when `true`, truncation is skipped for that call | Inside `data`, common values are normalized before limits apply: `bigint` → string, `Date` → ISO string, `RegExp` → pattern string, `Map` / `Set` → arrays (with `maxArrayItems`), `Error` → plain object, and `ArrayBuffer` / typed arrays → size summaries. ### Truncator options | Option | Default | Applies to | | --------------------- | ------- | -------------------------------------------------------- | | `maxBytes` | `16384` | `data` size cliff only | | `maxArrayItems` | `50` | Arrays inside `data` (including converted `Map` / `Set`) | | `maxObjectKeys` | `50` | Own enumerable keys on plain objects inside `data` | | `maxDepth` | `8` | Object depth in `data`; also bounds `error.cause` chains | | `maxCategoryLength` | `50` | `category` | | `maxMessageLength` | `200` | `message` and `error.message` | | `maxStackLength` | `200` | `error.stack` | | `maxDataStringLength` | `200` | Strings inside `data` | If a configured truncator throws, the logger fails open: it warns to the console and logs the original input. Pass `skipTruncation: true` on a single log call to bypass truncation when you intentionally need the full payload: ```typescript getLogger().info({ message: "Full debug dump", data: hugePayload, skipTruncation: true, }); ``` ## OpenTelemetry Integration The logger writes structured JSON (or pretty) output to the console. How that output reaches your observability backend depends on the runtime: * **Node.js** - Ship stdout to your log collector (the usual approach in containers), or register an OpenTelemetry Node SDK with a `console` instrumentation to export logs over OTLP. * **Deno** - The built-in OpenTelemetry SDK captures `console` output automatically when `OTEL_DENO=true` is set, so logs are exported alongside traces and metrics. See the [Observability](/guide/core/observability) documentation for details on enabling OTEL export. ## Default Settings If `setupLogger()` is not called, the logger uses these defaults: ```typescript const defaultSettings = { logLevel: "silent", formatter: jsonLogFormatter, useConsoleColors: false, // truncator: undefined (no truncation) }; ``` This means logs are silent by default - you must explicitly configure the logger to see output. ## Nimbus Internal Logs All Nimbus components (Router, EventBus, etc.) use the same logger configured via `setupLogger()`. This ensures consistent log formatting and level filtering across your application. ## Best Practices ### Use Categories Group related logs with consistent category names: ```typescript logger.info({ message: "Query executed", category: "Database" }); logger.info({ message: "Request received", category: "API" }); logger.info({ message: "Email sent", category: "Notifications" }); ``` ### Include Correlation IDs Always include correlation IDs when available for distributed tracing: ```typescript logger.info({ message: "Processing order", category: "Orders", data: { orderId: order.id }, correlationId: command.correlationid, }); ``` ### Log Errors Properly Use the dedicated `error` property for errors to preserve stack traces: ```typescript // ✅ Good - Error is properly captured logger.error({ message: "Failed to save user", error: error, correlationId: command.correlationid, }); // ❌ Bad - Stack trace is lost logger.error({ message: "Failed to save user", data: { error: error.message }, }); ``` ### Use Appropriate Log Levels * `debug`: Detailed info for debugging (disabled in production) * `info`: Normal application flow * `warn`: Unexpected but recoverable situations * `error`: Errors that need investigation * `critical`: Failures requiring immediate action --- --- url: https://nimbus.overlap.at/guide/core/with-retry.md description: >- withRetry retries async work with exponential backoff, jitter, AbortSignal support, and hooks for custom retry decisions. --- # withRetry The `withRetry` helper retries a promise-returning (or sync) function with exponential backoff until it succeeds, retries are exhausted, or retries are aborted. It is used internally by the [Event Bus](/guide/core/event-bus) and [Event Observer](/guide/eventsourcingdb/event-observer) handler paths, and is available for your own application code. ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: ## Basic Usage ```typescript import { withRetry } from "@nimbus-cqrs/core"; const data = await withRetry( async (attempt) => { console.log(`Attempt ${attempt}`); const response = await fetch("https://api.example.com/resource"); if (!response.ok) { throw new Error(`HTTP ${response.status}`); } return response.json(); }, { maxRetries: 3, initialDelayMs: 500, maxDelayMs: 10_000, }, ); ``` On exhaustion, `withRetry` rethrows the last error. Total attempts equal `maxRetries + 1`. ## Options | Option | Type | Default | Description | | ---------------- | -------------------------------------------- | ------- | ---------------------------------------------------------------- | | `maxRetries` | `number` | `2` | Retries after the initial attempt | | `initialDelayMs` | `number` | `1000` | Base delay before the first retry | | `maxDelayMs` | `number` | `30000` | Cap for the exponential base delay (before jitter) | | `factor` | `number` | `2` | Exponential growth factor | | `jitterFactor` | `number` | `0.1` | Fraction of the base delay added as random jitter (`0` disables) | | `maxRetryTimeMs` | `number` | - | Optional wall-clock budget for the whole retry sequence | | `signal` | `AbortSignal` | - | Cancel waiting between retries and stop further attempts | | `shouldRetry` | `(context: RetryContext) => boolean` | - | Return `false` to stop retrying and rethrow | | `onRetry` | `(context: RetryContext) => void \| Promise` | - | Called before each retry delay | `RetryContext` includes `error`, `attempt` (1-based failed attempt), `retriesLeft`, and `delayMs`. ## Aborting Retries ### From inside the function Throw `RetryAbortedError` to stop without consuming further retries: ```typescript import { RetryAbortedError, withRetry } from "@nimbus-cqrs/core"; await withRetry(async () => { const response = await fetch(url); if (response.status === 404) { throw new RetryAbortedError("Resource not found"); } if (!response.ok) { throw new Error(`HTTP ${response.status}`); } return response.json(); }); ``` ### With AbortSignal ```typescript import { withRetry } from "@nimbus-cqrs/core"; const controller = new AbortController(); const promise = withRetry(() => doWork(), { maxRetries: 5, signal: controller.signal, }); // Later, e.g. on shutdown: controller.abort(new Error("Shutting down")); ``` ## Filtering Retriable Errors ```typescript import { withRetry } from "@nimbus-cqrs/core"; await withRetry(() => callApi(), { maxRetries: 5, shouldRetry: ({ error }) => !(error.name === "ValidationError"), onRetry: ({ attempt, delayMs, error }) => { console.warn(`Retry ${attempt} in ${delayMs}ms`, error.message); }, }); ``` ## calculateBackoffDelay `calculateBackoffDelay` is the shared exponential backoff helper used by `withRetry` and by EventSourcingDB connection reconnects: ```typescript import { calculateBackoffDelay } from "@nimbus-cqrs/core"; const delayMs = calculateBackoffDelay(1000, 0, { maxDelayMs: 30_000, jitterFactor: 0.1, }); ``` | Parameter | Type | Description | | ---------------- | -------- | ----------------------------------------------- | | `initialDelayMs` | `number` | Base delay before exponential scaling | | `attempt` | `number` | Zero-based retry index (`0` = first retry) | | `options` | `object` | Optional `maxDelayMs`, `factor`, `jitterFactor` | --- --- url: https://nimbus.overlap.at/guide/core/get-env.md description: >- getEnv loads environment variables, failing fast when a required one is missing and returning undefined for optional ones. --- # getEnv The `getEnv` function retrieves environment variables with validation. It throws an exception if any required variable is missing or empty, so your application fails fast with a clear error. Optional variables are returned as `undefined` instead. ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: ## Basic Usage ```typescript import { getEnv } from "@nimbus-cqrs/core"; const env = getEnv({ variables: ["DATABASE_URL", "API_KEY", "PORT"], }); console.log(env.PORT); ``` ## Function Signature ```typescript type GetEnvResult< Required extends readonly string[], Optional extends readonly string[], > = string extends Required[number] ? Record : { [Key in Required[number]]: string; } & { [Key in Exclude]: | string | undefined; }; getEnv({ variables?: Required, optionalVariables?: Optional, }): GetEnvResult ``` | Parameter | Type | Required | Description | | --------------------- | ---------- | -------- | ------------------------------------------------ | | `variables` | `string[]` | No | Environment variable names that must be set | | `optionalVariables` | `string[]` | No | Environment variable names that may be omitted | Required names written as an array literal are typed as `string`. Optional names are typed as `string | undefined`. A name listed in both arrays is required. Only the names you pass exist on the result, so a typo is a type error. Pass the names as array literals. If `variables` is a wide `string[]`, TypeScript can no longer tell those names apart, and every value is `string | undefined`. `getEnv({})` returns `{}`. ## Optional Variables ```typescript import { getEnv } from "@nimbus-cqrs/core"; const env = getEnv({ variables: ["SMTP_HOST", "SMTP_PORT", "SMTP_FROM"], optionalVariables: ["SMTP_USER", "SMTP_PASSWORD"], }); env.SMTP_HOST; // string env.SMTP_USER; // string | undefined const auth = env.SMTP_USER !== undefined && env.SMTP_PASSWORD !== undefined ? { user: env.SMTP_USER, pass: env.SMTP_PASSWORD } : undefined; ``` A missing or empty optional variable is `undefined`. It is not logged and does not throw. ## Error Handling If any required variable is missing or empty, `getEnv` throws a `GenericException` with details about all missing required variables: ```typescript import { getEnv } from "@nimbus-cqrs/core"; try { const env = getEnv({ variables: ["MISSING_VAR_1", "MISSING_VAR_2"], }); } catch (error) { // GenericException with: // - message: "Undefined environment variables" // - details: { undefinedVariables: ["MISSING_VAR_1", "MISSING_VAR_2"] } } ``` The error is also logged before throwing: ``` [Nimbus] ERROR :: Undefined environment variables { undefinedVariables: ["MISSING_VAR_1", "MISSING_VAR_2"] } ``` ## Use Cases ### Application Configuration ```typescript import { getEnv } from "@nimbus-cqrs/core"; const env = getEnv({ variables: ["NODE_ENV", "PORT", "DATABASE_URL", "REDIS_URL", "JWT_SECRET"], }); export const config = { nodeEnv: env.NODE_ENV, port: parseInt(env.PORT, 10), databaseUrl: env.DATABASE_URL, redisUrl: env.REDIS_URL, jwtSecret: env.JWT_SECRET, }; ``` ### MongoDB Connection ```typescript import { getEnv } from "@nimbus-cqrs/core"; import { MongoConnectionManager } from "@nimbus-cqrs/mongodb"; const env = getEnv({ variables: ["MONGO_URL", "MONGO_DB"], }); const mongoManager = MongoConnectionManager.getInstance(env.MONGO_URL, { mongoClientOptions: { appName: "my-app" }, }); export const getCollection = (name: string) => mongoManager.getCollection(env.MONGO_DB, name); ``` ### Repository Configuration ```typescript import { getEnv } from "@nimbus-cqrs/core"; import { MongoDBRepository } from "@nimbus-cqrs/mongodb"; import { mongoManager } from "./mongodb.ts"; class UserRepository extends MongoDBRepository { constructor() { const env = getEnv({ variables: ["MONGO_DB"] }); super( () => mongoManager.getCollection(env.MONGO_DB, "users"), UserSchema, "User", ); } } ``` ### External Service Configuration ```typescript import { getEnv } from "@nimbus-cqrs/core"; const env = getEnv({ variables: ["STRIPE_API_KEY", "STRIPE_WEBHOOK_SECRET"], }); export const stripeClient = new Stripe(env.STRIPE_API_KEY); export const webhookSecret = env.STRIPE_WEBHOOK_SECRET; ``` --- --- url: https://nimbus.overlap.at/guide/hono.md description: >- Hub for @nimbus-cqrs/hono — middleware and handlers bridging Nimbus observability, errors, and message routing to Hono HTTP apps. --- # Nimbus Hono Adapters and useful functionality to bridge Nimbus and [Hono](https://hono.dev/). * npm: [@nimbus-cqrs/hono](https://www.npmjs.com/package/@nimbus-cqrs/hono) ### npm ```bash npm install @nimbus-cqrs/hono ``` ### pnpm ```bash pnpm add @nimbus-cqrs/hono ``` ### Bun ```bash bun add @nimbus-cqrs/hono ``` ### Deno ```bash deno add npm:@nimbus-cqrs/hono ``` ## Example Application ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: --- --- url: https://nimbus.overlap.at/guide/hono/correlationid.md description: >- Hono middleware that reads or generates a ULID correlation ID per request for distributed tracing. --- # CorrelationID Middleware The CorrelationID middleware extracts a correlation ID from incoming request headers or generates a new one using ULID. This ID is stored in the Hono context and optionally added to response headers, enabling request tracing across your application. ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: ## Basic Usage ```typescript import { Hono } from "hono"; import { correlationId, getCorrelationId } from "@nimbus-cqrs/hono"; const app = new Hono(); // Add the middleware app.use(correlationId()); app.get("/", (c) => { const id = getCorrelationId(c); return c.json({ correlationId: id }); }); ``` ## Header Detection The middleware checks the following headers in order of priority: | Priority | Header Name | | -------- | ------------------ | | 1 | `x-correlation-id` | | 2 | `x-request-id` | | 3 | `request-id` | If none of these headers are present, a new ULID is generated. ## Configuration Options | Option | Type | Default | Description | | ---------------------- | --------- | -------------------- | ------------------------------------------ | | `addToResponseHeaders` | `boolean` | `true` | Add the correlation ID to response headers | | `responseHeaderName` | `string` | `"x-correlation-id"` | The header name to use in the response | ```typescript import { correlationId } from "@nimbus-cqrs/hono"; // Custom configuration app.use( correlationId({ addToResponseHeaders: true, responseHeaderName: "x-request-id", }) ); ``` ## Retrieving the Correlation ID Use the `getCorrelationId()` helper function to retrieve the correlation ID from the Hono context: ```typescript import { getCorrelationId } from "@nimbus-cqrs/hono"; app.get("/users/:id", async (c) => { const correlationId = getCorrelationId(c); // Use in logging logger.info({ message: "Fetching user", correlationId, }); // Pass to commands/queries const command = createCommand({ type: "get-user", correlationid: correlationId, data: { id: c.req.param("id") }, }); return c.json(await router.route(command)); }); ``` --- --- url: https://nimbus.overlap.at/guide/hono/logger.md description: >- Hono middleware that logs HTTP requests and responses with timing and optional OpenTelemetry spans. --- # Logger Middleware The Logger middleware logs HTTP requests and responses with timing information using the Nimbus logger. It optionally integrates with OpenTelemetry for distributed tracing. ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: ## Basic Usage ```typescript import { Hono } from "hono"; import { correlationId, logger } from "@nimbus-cqrs/hono"; const app = new Hono(); // Use correlationId middleware first to enable correlation ID in logs app.use(correlationId()); app.use(logger()); ``` ## Configuration Options | Option | Type | Default | Description | | --------------- | ---------- | ---------- | ------------------------------------------------------------------------ | | `enableTracing` | `boolean` | `true` | Enable OpenTelemetry tracing for requests | | `tracerName` | `string` | `"nimbus"` | The name of the tracer for OpenTelemetry | | `logLevel` | `LogLevel` | `"info"` | Severity used for request/response logs (`silent` skips those log lines) | ```typescript import { logger } from "@nimbus-cqrs/hono"; app.use( logger({ enableTracing: true, tracerName: "api", logLevel: "debug", }), ); ``` ## Log Output The middleware logs each request and response using the Nimbus logger at the configured `logLevel` (default `info`): **Request log:** ``` [API] INFO :: REQ: [GET] /users/123 ``` **Response log (with timing):** ``` [API] INFO :: RES: [GET] /users/123 - 45ms ``` Both logs include the correlation ID when the `correlationId` middleware is used. ## OpenTelemetry Tracing When `enableTracing` is set to `true`, the middleware: 1. **Extracts trace context** from incoming `traceparent` and `tracestate` headers 2. **Creates a server span** for the HTTP request 3. **Records span attributes** for observability 4. **Propagates context** so child spans can be created in handlers ### Span Attributes | Attribute | Description | | ------------------ | --------------------------------- | | `http.method` | The HTTP method (GET, POST, etc.) | | `url.path` | The request path | | `http.target` | The full request URL | | `correlation_id` | The correlation ID (if available) | | `http.status_code` | The response status code | ### Example with Tracing ```typescript import { Hono } from "hono"; import { correlationId, logger } from "@nimbus-cqrs/hono"; const app = new Hono(); app.use(correlationId()); app.use( logger({ enableTracing: true, tracerName: "api", }), ); app.get("/users/:id", async (c) => { // This handler runs within the HTTP span context // Any spans created here will be children of the HTTP span const user = await userRepository.findOne({ filter: { _id: c.req.param("id") }, }); return c.json(user); }); ``` ## Error Handling When an error occurs during request handling: * The span status is set to `ERROR` * The error message is recorded in the span * The exception is recorded for debugging * The error is re-thrown for the error handler to process --- --- url: https://nimbus.overlap.at/guide/hono/on-error.md description: >- Hono onError handler that maps Nimbus exceptions to structured JSON HTTP responses with correct status codes. --- # onError Handler The `handleError` function is an error handler for Hono applications that converts Nimbus exceptions to structured HTTP JSON responses. ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: ## Basic Usage ```typescript import { Hono } from "hono"; import { handleError } from "@nimbus-cqrs/hono"; const app = new Hono(); // Register the error handler app.onError(handleError); ``` ## Response Format When a Nimbus exception is thrown, the handler returns a JSON response with the following structure: ```json { "error": "EXCEPTION_NAME", "message": "Human-readable error message", "details": { ... } } ``` | Field | Description | | --------- | ------------------------------------------------------- | | `error` | The exception name (e.g., `NOT_FOUND`, `INVALID_INPUT`) | | `message` | The error message provided when throwing the exception | | `details` | Optional additional details (only included if provided) | ## Status Code Mapping The HTTP status code is taken directly from the exception's `statusCode` property: | Exception | Status Code | Response `error` | | ----------------------- | ----------- | ------------------- | | `GenericException` | 500 | `GENERIC_EXCEPTION` | | `InvalidInputException` | 400 | `INVALID_INPUT` | | `NotFoundException` | 404 | `NOT_FOUND` | | `UnauthorizedException` | 401 | `UNAUTHORIZED` | | `ForbiddenException` | 403 | `FORBIDDEN` | | Custom exceptions | (custom) | (custom name) | ## Logging Behavior The handler logs errors differently based on the status code: | Status Code | Log Level | Description | | ----------- | ---------- | -------------------------------------- | | 5xx | `error` | Server errors that need investigation | | 4xx | `debug` | Client errors, typically expected | | Unhandled | `critical` | Non-Nimbus errors, unexpected failures | ## Example: Exception Handling ```typescript import { Hono } from "hono"; import { handleError } from "@nimbus-cqrs/hono"; import { NotFoundException, InvalidInputException } from "@nimbus-cqrs/core"; const app = new Hono(); app.get("/users/:id", async (c) => { const user = await findUser(c.req.param("id")); if (!user) { throw new NotFoundException("User not found", { userId: c.req.param("id"), }); } return c.json(user); }); app.post("/users", async (c) => { const body = await c.req.json(); if (!body.email) { throw new InvalidInputException("Email is required", { field: "email", }); } const user = await createUser(body); return c.json(user, 201); }); app.onError(handleError); ``` ### Response Examples **NotFoundException (404):** ```json { "error": "NOT_FOUND", "message": "User not found", "details": { "userId": "123" } } ``` **InvalidInputException (400):** ```json { "error": "INVALID_INPUT", "message": "Email is required", "details": { "field": "email" } } ``` **Unhandled Error (500):** ```json { "error": "INTERNAL_SERVER_ERROR" } ``` ## Complete Application Setup ```typescript import { Hono } from "hono"; import { correlationId, handleError, logger } from "@nimbus-cqrs/hono"; import { setupLogger, parseLogLevel } from "@nimbus-cqrs/core"; setupLogger({ logLevel: parseLogLevel(process.env.LOG_LEVEL), }); const app = new Hono(); app.use(correlationId()); app.use(logger({ enableTracing: true })); // Your routes here app.get("/health", (c) => c.json({ status: "ok" })); // Error handler must be registered last app.onError(handleError); export default app; ``` --- --- url: https://nimbus.overlap.at/guide/hono/routing.md description: >- Hono route adapters that turn an HTTP request into a Nimbus command or query and return the handler result as JSON. --- # Route Adapter `routeCommand` and `routeQuery` connect a Hono route handler to a Nimbus message router. A handler should not build CloudEvents messages by hand. The adapter reads the request, fills in the correlation id, and hands a typed message to the router you pass in. The router validates it and calls the registered handler. The same commands stay reachable from a policy or a process manager, which call the router directly and skip HTTP. ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: ## Commands `routeCommand` reads the JSON body as `data`, sets `correlationid` from [`getCorrelationId`](/guide/hono/correlationid), routes the command, and returns the handler result as JSON. The status defaults to `200`. `source` identifies the system that builds the message. It belongs to your application, as does the router. ```typescript import { Hono } from "hono"; import { getRouter } from "@nimbus-cqrs/core"; import { correlationId, handleError, routeCommand } from "@nimbus-cqrs/hono"; const app = new Hono(); app.use(correlationId()); app.onError(handleError); app.post("/invite-user", (c) => { return routeCommand({ c, router: getRouter('MyCommandRouter'), source: "https://nimbus.overlap.at", type: INVITE_USER_COMMAND_TYPE, }); }); ``` A body that is not JSON throws `InvalidInputException`. With [`handleError`](/guide/hono/on-error) registered, that becomes HTTP `400`. Field validation stays on the command schema registered with the Nimbus router. `mapInputData` builds `data` from the Hono context. Use it when the command needs more than the JSON body, such as a request header. ```typescript app.post("/invite-user", (c) => { return routeCommand({ c, router: getRouter('MyCommandRouter'), source: "https://nimbus.overlap.at", type: INVITE_USER_COMMAND_TYPE, mapInputData: async (context) => { const body = await context.req.json(); return { ...body, idempotencyKey: context.req.header("idempotency-key"), }; }, }); }); ``` When `mapInputData` is set, the adapter does not read the body for you. `routeQuery` accepts the same function, so a query can copy a request header into `data` the same way. ## Queries `routeQuery` works the same way. The query string is `data` unless you pass `mapInputData`. ```typescript import { getRouter } from "@nimbus-cqrs/core"; import { routeQuery } from "@nimbus-cqrs/hono"; app.get("/orders", (c) => { return routeQuery({ c, router: getRouter('MyQueryRouter'), source: "https://nimbus.overlap.at", type: GET_ORDERS_QUERY_TYPE, }); }); ``` A request to `/orders?status=open` produces a query whose `data` is `{ status: "open" }`. Query parameter values arrive as strings. Pass `mapInputData` when the query schema needs another shape, such as numbers, or when a request header belongs in `data`: ```typescript app.get("/list-tickets", (c) => { return routeQuery({ c, router: getQueryRouter(), source: "https://nimbus.overlap.at", type: LIST_TICKETS_QUERY_TYPE, mapInputData: (context) => ({ status: context.req.query("status"), offset: Number(context.req.query("offset")), }), }); }); ``` ## Extension attributes Nimbus messages may carry [CloudEvents extension attributes](https://github.com/cloudevents/spec/blob/main/cloudevents/spec.md#extension-context-attributes). The adapter does not define any of its own. Pass them through `extensions`. Attribute names must be lowercase ASCII letters or digits. An application auth context is a good example for such an attribute. Middleware stores it on the Hono context. The route copies it onto the message. Commands and queries then read that attribute. They do not talk to HTTP. Omit `extensions` when the message has no extra attributes. ```typescript app.post("/create", authentication(), (c) => { return routeCommand({ c, router: getCommandRouter(), source: "https://nimbus.overlap.at", type: CREATE_TICKET_COMMAND_TYPE, extensions: { authcontext: getAuthContext(c) }, }); }); ``` ## Response The handler result is used for the JSON response body with a `200` status code by default. You can use `transformResponse` to alter the response body, status, or headers. `transformResponse` receives the handler result and returns a custom data object, an optional status, and optional headers. When `headers` does not include `Content-Type`, the response uses `application/json` and `data` is serialized as JSON. `application/json` and types ending in `+json` are serialized the same way. Any other `Content-Type` sends `data` as the body unchanged, so a string stays plain text and image bytes stay bytes. ```typescript app.post("/create", (c) => { return routeCommand({ c, router: getCommandRouter(), source: "https://nimbus.overlap.at", type: CREATE_TICKET_COMMAND_TYPE, transformResponse: (result) => ({ data: { id: result.ticketId }, statusCode: 201, headers: { location: `/tickets/${result.ticketId}`, 'cache-control': 'no-store', }, }), }); }); ``` A PNG download sends the bytes with their own content type: ```typescript transformResponse: (result) => ({ data: result.pngBytes, headers: { "Content-Type": "image/png" }, }), ``` `routeQuery` takes the same option. `mapInputData` and `transformResponse` may be async. --- --- url: https://nimbus.overlap.at/guide/eventsourcingdb.md description: >- Hub for @nimbus-cqrs/eventsourcingdb — client setup, read/write events, observers, and Nimbus event mapping. --- # Nimbus EventSourcingDB Package The EventSourcingDB package provides a seamless integration between Nimbus and [EventSourcingDB](https://www.eventsourcingdb.io/). It offers a managed client, event reading and writing with automatic Nimbus event mapping, event observers that feed checkpointed consumers with retry logic, and built-in OpenTelemetry tracing. * npm: [@nimbus-cqrs/eventsourcingdb](https://www.npmjs.com/package/@nimbus-cqrs/eventsourcingdb) The package requires the official [`eventsourcingdb`](https://www.npmjs.com/package/eventsourcingdb) SDK (version 2 or later) as a peer dependency. The SDK works with EventSourcingDB 1.3+ (v2 API) as well as older versions (v1 API) and detects the API at runtime. See [Client Setup](/guide/eventsourcingdb/client-setup#eventsourcingdb-versions) for details. ::: warning Upgrading from the `eventsourcingdb` 1.x SDK If you upgrade an existing application, read the [SDK migration guide](https://github.com/thenativeweb/eventsourcingdb-client-javascript#upgrading-from-version-1).\ For Nimbus users the relevant changes are the following. ::: * Server errors are `DbApiError` instances with a `code`. Replace checks like `error.message.includes("409")` with `error instanceof DbApiError && error.code === ErrorCode.preconditionViolated` (see [Write Events](/guide/eventsourcingdb/write-events#error-handling)). * Writes whose outcome is unknown throw an `OutcomeUnknownError` whose `cause` is the original error. * Observers no longer end quietly when the server closes the stream; Nimbus reconnects according to `connectionRetryOptions` (see [Event Observer](/guide/eventsourcingdb/event-observer#retry-options)). * Proxies in front of EventSourcingDB 1.3+ must allow the HTTP method `QUERY`. * `writeEvents` now returns the written events instead of `void`. ### npm ```bash npm install @nimbus-cqrs/eventsourcingdb ``` ### pnpm ```bash pnpm add @nimbus-cqrs/eventsourcingdb ``` ### Bun ```bash bun add @nimbus-cqrs/eventsourcingdb ``` ### Deno ```bash deno add npm:@nimbus-cqrs/eventsourcingdb ``` ## Example Application ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: --- --- url: https://nimbus.overlap.at/guide/eventsourcingdb/client-setup.md description: >- setupEventSourcingDBClient initializes a singleton EventSourcingDB client with connectivity checks and auth. --- # Client Setup The `setupEventSourcingDBClient` function initializes a singleton EventSourcingDB client that is used by all other functions in this package. It verifies connectivity and authenticates with the server before the application starts processing events. ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: ## Basic Usage ```typescript import { setupEventSourcingDBClient } from "@nimbus-cqrs/eventsourcingdb"; await setupEventSourcingDBClient({ url: new URL(process.env.ESDB_URL ?? ""), apiToken: process.env.ESDB_API_TOKEN ?? "", }); ``` ## Configuration Options | Option | Type | Description | | ---------------- | ----------------- | ------------------------------------------------------------------------------ | | `url` | `URL` | The URL of the EventSourcingDB server | | `apiToken` | `string` | The API token for authenticating with EventSourcingDB | | `stallTimeout` | `number` | Optional stall timeout in milliseconds (defaults to `30000`, see below) | | `eventObservers` | `EventObserver[]` | Optional array of event observers to start after initialization | ### Stall Timeout Every request fails once nothing arrives from the server for the duration of the stall timeout, for example because the server does not respond or a proxy keeps the connection open without passing anything through. Everything that arrives (events, rows, heartbeats) resets the timer, so a healthy long-running stream is never cut off and the time spent handling an event does not count. A stalled request throws a `ConnectionStalledError` from the `eventsourcingdb` package. For [event observers](/guide/eventsourcingdb/event-observer) this counts as a connection failure and triggers a reconnect. ```typescript await setupEventSourcingDBClient({ url: new URL(process.env.ESDB_URL ?? ""), apiToken: process.env.ESDB_API_TOKEN ?? "", stallTimeout: 10_000, }); ``` ## Initialization Behavior When `setupEventSourcingDBClient` is called, it performs the following steps: 1. Creates a new client instance with the provided URL and API token 2. Pings the EventSourcingDB server to verify connectivity 3. Validates the API token 4. Starts any provided event observers in the background If the connection or authentication fails, a `GenericException` is thrown and the error is logged. ## EventSourcingDB Versions The `eventsourcingdb` SDK (version 2 and later) talks to both the v2 API of EventSourcingDB 1.3+ and the v1 API of older versions so no extra configuration is required. ::: warning Proxies and load balancers Against EventSourcingDB 1.3 and later, all read operations (`readEvents`, `observeEvents`, EventQL queries, ...) use the HTTP method `QUERY` instead of `POST`. If a proxy or load balancer sits in front of EventSourcingDB, it has to let `QUERY` requests through. There is no fallback to `POST`. ::: ## Setup with Event Observers You can provide event observers that will automatically start observing events after the client is initialized. Each observer watches one subject and feeds every event to its consumers, which resume from their checkpoints: ```typescript import { InMemoryCheckpointStore } from "@nimbus-cqrs/core"; import { setupEventSourcingDBClient } from "@nimbus-cqrs/eventsourcingdb"; await setupEventSourcingDBClient({ url: new URL(process.env.ESDB_URL ?? ""), apiToken: process.env.ESDB_API_TOKEN ?? "", eventObservers: [ { name: "logging", subject: "/", recursive: true, checkpointStore: new InMemoryCheckpointStore(), consumers: [ { name: "logging.console", handles: () => true, handle: async (event) => { console.log("Received event:", event); }, }, ], }, ], }); ``` `setupEventSourcingDBClient` resolves once every observer has loaded its checkpoints and started observing. It does not wait for them to catch up. See the [Event Observer](/guide/eventsourcingdb/event-observer) documentation for details on configuring observers. ## Getting the Client After initialization, use `getEventSourcingDBClient` to access the singleton client instance anywhere in your application: ```typescript import { getEventSourcingDBClient } from "@nimbus-cqrs/eventsourcingdb"; const client = getEventSourcingDBClient(); ``` ::: tip You typically don't need to call `getEventSourcingDBClient` directly. The [`writeEvents`](/guide/eventsourcingdb/write-events) and [`readEvents`](/guide/eventsourcingdb/read-events) functions handle this internally. ::: ## Error Handling The setup function throws a `GenericException` in two cases: | Error | Cause | | ------------------ | -------------------------------------------- | | Connection failure | The EventSourcingDB server is unreachable | | Invalid API token | The provided API token could not be verified | ```typescript import { setupEventSourcingDBClient } from "@nimbus-cqrs/eventsourcingdb"; try { await setupEventSourcingDBClient({ url: new URL(process.env.ESDB_URL ?? ""), apiToken: process.env.ESDB_API_TOKEN ?? "", }); } catch (error) { // GenericException: // - "Could not connect to EventSourcingDB" // - "Invalid API token. Please check your API token." } ``` --- --- url: https://nimbus.overlap.at/guide/eventsourcingdb/write-events.md description: >- writeEvents appends Nimbus events to EventSourcingDB with mapping, trace context, and optional preconditions. --- # Write Events The `writeEvents` function persists one or more Nimbus events to EventSourcingDB. It automatically converts Nimbus events to EventSourcingDB event candidates, injects OpenTelemetry trace context, and supports preconditions for optimistic concurrency control. ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: ## Basic Usage ```typescript import { createEvent } from "@nimbus-cqrs/core"; import { writeEvents } from "@nimbus-cqrs/eventsourcingdb"; import { isSubjectPristine } from "eventsourcingdb"; const event = createEvent({ type: "at.overlap.nimbus.user-invited", source: "nimbus.overlap.at", correlationid: command.correlationid, subject: `/users/${id}`, data: { email: "john@example.com", firstName: "John", lastName: "Doe", invitedAt: new Date().toISOString(), }, }); const writtenEvents = await writeEvents( [event], [isSubjectPristine(event.subject)] ); ``` ## Function Parameters | Parameter | Type | Description | | --------------- | ---------------- | ---------------------------------------------------------------- | | `events` | `Event[]` | An array of Nimbus events to write | | `preconditions` | `Precondition[]` | Optional preconditions that must be met for the write to succeed | | `signal` | `AbortSignal` | Optional abort signal to cancel the write (see below) | ## Return Value `writeEvents` returns the written EventSourcingDB events (`Event[]` from the `eventsourcingdb` package), including the fields assigned by the server such as `id`, `time` and `hash`. The `id` of the last written event is the new revision of the subject. Hand it back to the client so it can pass it as `expectedRevision` to the next command, which then uses the `isSubjectOnEventId` precondition: ```typescript const writtenEvents = await writeEvents(events, [ isSubjectPristine(events[0].subject), ]); return { userId: state.id, revision: writtenEvents[writtenEvents.length - 1].id, }; ``` ## Preconditions EventSourcingDB supports the following preconditions. For full details, see the [Using Preconditions](https://docs.eventsourcingdb.io/getting-started/writing-events/#using-preconditions) section in the EventSourcingDB documentation. To use these preconditions, you can directly import them from the [`EventSourcingDB JavaScript SDK`](https://www.npmjs.com/package/eventsourcingdb). ## Error Handling `writeEvents` never retries a write on its own and passes the errors of the `eventsourcingdb` SDK through unchanged. ### Violated Preconditions When the server rejects a write, it throws a `DbApiError`. Its `code` names the error and can be compared with the constants of `ErrorCode`. A violated precondition is reported as `ErrorCode.preconditionViolated`, which is the basis for optimistic concurrency control: ```typescript import { Exception } from "@nimbus-cqrs/core"; import { writeEvents } from "@nimbus-cqrs/eventsourcingdb"; import { DbApiError, ErrorCode, isSubjectOnEventId } from "eventsourcingdb"; try { await writeEvents(events, [ isSubjectOnEventId(events[0].subject, command.data.expectedRevision), ]); } catch (error) { if ( error instanceof DbApiError && error.code === ErrorCode.preconditionViolated ) { throw new Exception( "CONFLICT", "The expected revision does not match the current revision anymore", { errorCode: "REVISION_CONFLICT" }, 409 ); } throw error; } ``` The same code is reported for EventSourcingDB versions before 1.3, since the SDK maps the HTTP `409` of the v1 API to `ErrorCode.preconditionViolated`. ### Unknown Outcome EventSourcingDB never stops a write halfway, but the response to a write can get lost, for example when the connection stalls or the request is aborted after it was sent. In this case `writeEvents` throws an `OutcomeUnknownError` whose `cause` holds the original error. The events may have been stored nonetheless, so read the subject back before writing them again: ```typescript import { OutcomeUnknownError } from "eventsourcingdb"; try { await writeEvents(events); } catch (error) { if (error instanceof OutcomeUnknownError) { // Find out whether the events were stored, for example by // reading the subject, before writing them again. } } ``` ### Cancellation Pass an `AbortSignal` as the third argument to cancel a write. Aborting before the request has been sent throws the abort reason and nothing is written. Aborting once the request has been sent does not undo the write; the call then throws an `OutcomeUnknownError` as described above. ```typescript const controller = new AbortController(); await writeEvents(events, undefined, controller.signal); ``` ## OpenTelemetry Tracing Every call to `writeEvents` is automatically wrapped in an OpenTelemetry span named `eventsourcingdb.writeEvents`. The current trace context (`traceparent` and `tracestate`) is injected into each event candidate, enabling end-to-end distributed tracing from the event writer to any [event observer](/guide/eventsourcingdb/event-observer) that processes the event. The following metrics are recorded: | Metric | Type | Labels | Description | | -------------------------------------------- | --------- | --------------------- | --------------------------------------- | | `eventsourcingdb_operation_total` | Counter | `operation`, `status` | Total number of write operations | | `eventsourcingdb_operation_duration_seconds` | Histogram | `operation` | Duration of write operations in seconds | | `eventsourcingdb_event_size_bytes` | Histogram | — | Size of each written event in bytes | --- --- url: https://nimbus.overlap.at/guide/eventsourcingdb/read-events.md description: >- readEvents streams events for a subject from EventSourcingDB; use event mapping to restore Nimbus event shapes. --- # Read Events The `readEvents` function reads events from EventSourcingDB for a given subject. It returns an async generator that yields raw EventSourcingDB events, which can be converted to Nimbus events using the [event mapping](/guide/eventsourcingdb/event-mapping) utilities. For full details on reading events, including reading from multiple subjects, reading in reverse order, reading specific ranges, and reading from the last event of a given type, see the [Reading Events](https://docs.eventsourcingdb.io/getting-started/reading-events/) section in the EventSourcingDB documentation. ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: ## Basic Usage ```typescript import { eventSourcingDBEventToNimbusEvent, readEvents, } from "@nimbus-cqrs/eventsourcingdb"; for await (const eventSourcingDBEvent of readEvents("/users/123", { recursive: false, })) { const event = eventSourcingDBEventToNimbusEvent(eventSourcingDBEvent); console.log(event); } ``` ## Function Parameters | Parameter | Type | Description | | --------- | ------------------- | ---------------------------------------- | | `subject` | `string` | The subject to read events for | | `options` | `ReadEventsOptions` | Options to control which events are read | | `signal` | `AbortSignal` | Optional abort signal to cancel the read | ## Rebuilding Aggregate State A common pattern in event sourcing is to rebuild an aggregate's state by replaying all of its events. This is used in command handlers to load the current state before making decisions: ```typescript import { eventSourcingDBEventToNimbusEvent, readEvents, writeEvents, } from "@nimbus-cqrs/eventsourcingdb"; import { isSubjectOnEventId } from "eventsourcingdb"; const acceptUserInvitationCommandHandler = async (command) => { let state: UserState = { id: command.data.id }; // Replay all events to rebuild the current state for await (const eventSourcingDBEvent of readEvents( `/users/${command.data.id}`, { recursive: false } )) { const event = eventSourcingDBEventToNimbusEvent(eventSourcingDBEvent); state = applyEventToUserState(state, event); } // Use the rebuilt state to make decisions const events = acceptUserInvitation(state, command); // Write new events with optimistic concurrency await writeEvents(events, [ isSubjectOnEventId(events[0].subject, command.data.expectedRevision), ]); }; ``` ## Cancellation Use an `AbortSignal` to cancel an in-progress read: ```typescript import { readEvents } from "@nimbus-cqrs/eventsourcingdb"; const controller = new AbortController(); // Cancel after 5 seconds setTimeout(() => controller.abort(), 5000); for await (const event of readEvents( "/users", { recursive: true }, controller.signal )) { console.log(event); } ``` ## OpenTelemetry Tracing Every call to `readEvents` is automatically wrapped in an OpenTelemetry span named `eventsourcingdb.readEvents`. The following metrics are recorded: | Metric | Type | Labels | Description | | -------------------------------------------- | --------- | --------------------- | -------------------------------------- | | `eventsourcingdb_operation_total` | Counter | `operation`, `status` | Total number of read operations | | `eventsourcingdb_operation_duration_seconds` | Histogram | `operation` | Duration of read operations in seconds | --- --- url: https://nimbus.overlap.at/guide/eventsourcingdb/event-observer.md description: >- An event observer watches one subject and feeds every event to its consumers (projections, policies, process managers, etc.) each resuming from its own checkpoint. --- # Event Observer An **event observer** is a background loop that watches one EventSourcingDB subject and hands every event to its **event consumers**. On startup it replays the events the consumers have not seen yet, then stays live for new ones. Observers reconnect with exponential backoff when the stream fails and retry consumer failures in place without tearing down the stream. A consumer is one named position in the stream. A read-model projection, a policy, an event handler and a process manager all have that shape and only what they do with the event differs. Each consumer owns a **checkpoint** in a [checkpoint store](/guide/core/checkpoint-store), so one of them can be rebuilt or halted without moving the others. For the underlying mechanics see the [Observing Events](https://docs.eventsourcingdb.io/getting-started/observing-events/) section in the EventSourcingDB documentation. ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: ## Basic Usage Event observers are typically configured as part of the [client setup](/guide/eventsourcingdb/client-setup): ```typescript import { InMemoryCheckpointStore } from "@nimbus-cqrs/core"; import { type EventConsumer, setupEventSourcingDBClient, } from "@nimbus-cqrs/eventsourcingdb"; const usersProjection: EventConsumer = { name: "iam.users", handles: (event) => event.type.startsWith("at.overlap.nimbus.user-"), handle: async (event) => { // load the document, fold the event in, save it }, }; await setupEventSourcingDBClient({ url: new URL(process.env.ESDB_URL ?? ""), apiToken: process.env.ESDB_API_TOKEN ?? "", eventObservers: [ { name: "iam", subject: "/users", recursive: true, checkpointStore: new InMemoryCheckpointStore(), consumers: [usersProjection], }, ], }); ``` You can also start an observer independently after the client has been initialized. `initEventObserver` resolves once the observer has loaded its checkpoints and started the loop, not once it has caught up: ```typescript import { initEventObserver } from "@nimbus-cqrs/eventsourcingdb"; const observer = await initEventObserver({ name: "iam", subject: "/users", recursive: true, checkpointStore, consumers: [usersProjection], }); observer.status().phase; // "catching-up" | "live" | "stopped" ``` Use the `InMemoryCheckpointStore` for tests and for consumers that rebuild their state on every start anyway. For anything that has to survive a restart use a persistent store such as the [MongoCheckpointStore](/guide/mongodb/checkpoint-store). ## EventObserver Options | Option | Type | Default | Description | | ------------------------ | ----------------- | ------------ | ------------------------------------------------------------------ | | `name` | `string` | *(required)* | Unique name; stored on every checkpoint and used for lookup | | `subject` | `string` | *(required)* | The subject to observe events for | | `recursive` | `boolean` | `false` | Whether to observe events recursively for all sub-subjects | | `consumers` | `EventConsumer[]` | *(required)* | The consumers, run in declaration order for every event | | `checkpointStore` | `CheckpointStore` | *(required)* | Where the consumers' checkpoints are persisted | | `connectionRetryOptions` | `RetryOptions` | see below | Retry options when the observe stream / connection fails | | `handlerRetryOptions` | `RetryOptions` | see below | Retry options when a consumer throws (in-place, no reconnect) | ## Event Consumers ```typescript import type { Event } from "@nimbus-cqrs/core"; import type { EventConsumer } from "@nimbus-cqrs/eventsourcingdb"; import type { Event as EventSourcingDBEvent } from "eventsourcingdb"; export const notifyAssignee: EventConsumer = { name: "ticketing.ticket.notify-assignee", dependsOn: ["ticketing.tickets"], handles: (event: Event) => event.type === TICKET_ASSIGNED_EVENT_TYPE, handle: async (event: Event, raw: EventSourcingDBEvent) => { // ... }, }; ``` | Property | Type | Description | | ----------- | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | | `name` | `string` | The checkpoint key. Unique across the whole application, not just within one observer. Renaming a consumer replays the subject from the beginning | | `handles` | `(event: Event) => boolean` | Whether the consumer handles this event. Unhandled events still advance the checkpoint | | `handle` | `(event: Event, raw: EventSourcingDBEvent) => Promise` | Handles one event. Receives the mapped Nimbus event and the original EventSourcingDB event | | `dependsOn` | `string[]` | Names of consumers on the same observer this one reads from. They have to be declared before it | | `startFrom` | `"checkpoint"` | `"head"` | `checkpoint` (default) resumes after the stored checkpoint, `head` starts at the newest event on every start, see [Live-only Consumers](#live-only-consumers) | ### How consumers share the stream * The observer resumes from the **lowest** position of its consumers. Consumers that are already further ahead skip the replayed events in memory. * For every event the consumers run **sequentially in declaration order**. A consumer that reads another consumer's read model is declared after it and lists it in `dependsOn`. * Every consumer advances its checkpoint on every event, handled or not, so a restart resumes exactly where it stopped. * Checkpoints are written after the consumers have run, so delivery is **at-least-once**. Consumers with side effects (mails, commands) have to be idempotent. ### Failures A consumer that throws **holds its position** while its siblings advance. The observer retries the event in place according to `handlerRetryOptions`. On the next retry the consumers that already finished the event skip it, so only the failing ones run again. Once the retries are exhausted the failing consumers are **halted**. They are skipped for the rest of the process lifetime, a critical log entry is written, and the checkpoint keeps the last event they finished together with a `failure` marker (`position`, `error`, `at`). A restart resumes at the event they could not handle. The observer itself moves on so the other consumers keep up. Consumers that `dependsOn` a failing consumer hold their position as well, and are halted together with it. That way a notification is never checkpointed past an event the projection it reads has not applied. If the failure happens outside a consumer (while mapping the event or writing checkpoints) the whole observer is in an unknown state and every consumer is halted. ### Live-only Consumers Some consumers only care about what happens now. For example, pushing updates to connected WebSocket or SSE clients, invalidating an in-memory cache, or feeding a live dashboard. Replaying history on restart would be wrong for them and the clients that would have received those updates are long gone. Declare them with `startFrom: "head"`. ```typescript export const pushTicketUpdates: EventConsumer = { name: "ticketing.push-updates", startFrom: "head", dependsOn: ["ticketing.tickets"], handles: (event) => event.type.startsWith(TICKET_EVENT_TYPE_PREFIX), handle: async (event) => { broadcast({ ticketId: event.subject.split("/").at(-1) }); }, }; ``` A `head` consumer starts at the newest event of the subject on **every** start, regardless of what its checkpoint store says. Events written while the process was down are never delivered to it. It still runs on the same stream as the checkpointed consumers of its observer and skips the replay in memory while they catch up, so one observer per subject is enough. Its checkpoint is written like any other so operators can see where it is, but the position is ignored on the next start. Resetting it therefore has no effect. `dependsOn` works only in one direction: A consumer that resumes from its checkpoint must not depend on a `head` consumer. The observer rejects that at start, since the dependency never built state for older events. A `head` consumer can still depend on a `checkpoint` consumer. The option covers "live only". To add a new checkpointed consumer to a long subject without backfilling it, seed its checkpoint with the current head once before the first deploy instead. `reset` only moves existing checkpoints, so use `save`: ```typescript await checkpointStore.save([ { consumer: "ticketing.audit", observer: "ticketing", position: headEventId }, ]); ``` ## Retry Options `connectionRetryOptions` and `handlerRetryOptions` share the same shape (defaults apply independently to each): | Option | Type | Default | Description | | --------------------- | -------- | ------- | ---------------------------------------------------- | | `maxRetries` | `number` | `3` | Maximum number of retries after the initial attempt | | `initialRetryDelayMs` | `number` | `3000` | Initial delay in milliseconds before the first retry | Both paths use **exponential backoff with jitter** (via the shared [`withRetry`](/guide/core/with-retry) / `calculateBackoffDelay` helpers from `@nimbus-cqrs/core`): * Base delay doubles with each attempt: `initialDelayMs * 2^attempt` * Random jitter of 0-30% is added to avoid thundering-herd effects **Connection retries** (`connectionRetryOptions`): * Used when the observe stream fails or disconnects * Observing never ends on its own. A stream that the server closes (for example during a restart or a rollback) or that stalls (see [stall timeout](/guide/eventsourcingdb/client-setup#stall-timeout)) counts as a connection failure and triggers a reconnect * After the initial attempt plus `maxRetries` reconnect attempts fail, a critical error is logged and the observer stops (`maxRetries + 1` failed attempts total). Its phase becomes `stopped` and its health check reports `error` * The connection retry counter resets when events start flowing again ::: tip Sizing connection retries Since every server-side stream close triggers a reconnect, size `connectionRetryOptions` for the longest outage you want an observer to survive, for example a rolling restart or a backup window of your EventSourcingDB deployment. With the defaults (`maxRetries: 3`, `initialRetryDelayMs: 3000`) an observer gives up after roughly 20 seconds of consecutive failures. ::: **Handler retries** (`handlerRetryOptions`): * Used when a consumer throws. Retries happen in-place without reconnecting * After the initial attempt plus `maxRetries` retries fail for an event, the failing consumers are halted (`maxRetries + 1` failed attempts total) * The observer then continues with the next event for the remaining consumers ```typescript await initEventObserver({ name: "iam", subject: "/users", recursive: true, checkpointStore, consumers: [usersProjection], connectionRetryOptions: { maxRetries: 5, initialRetryDelayMs: 1000, }, handlerRetryOptions: { maxRetries: 3, initialRetryDelayMs: 500, }, }); ``` ## Status and Health Every started observer is registered under its name. `getEventObserver(name)` returns the handle of one observer, `listEventObservers()` all of them in start order. ```typescript import { getEventObserver, listEventObservers, } from "@nimbus-cqrs/eventsourcingdb"; const status = getEventObserver("iam").status(); // { // name: "iam", // subject: "/users", // phase: "live", // consumers: [ // { name: "iam.users", position: "1842", halted: false }, // ], // } const unhealthy = listEventObservers() .map((observer) => observer.healthCheck()) .filter((health) => health.status !== "healthy"); ``` | Phase | Meaning | | ------------- | ------------------------------------------------------------------------------- | | `catching-up` | Replaying events that were already stored when the observer started | | `live` | Every event stored at startup has been processed, new events arrive as written | | `stopped` | Connection retries are exhausted and the observer gave up | `healthCheck()` returns `{ status: "error", details }` when the observer stopped or any consumer is halted, and `{ status: "healthy" }` otherwise. An observer that is still catching up is healthy. Wire it into your readiness or health endpoint next to the database checks. A halted projection leaves MongoDB and EventSourcingDB perfectly reachable, so those checks alone would stay green. Each consumer status carries its `position` (the id of the last event it finished, `null` before the first), whether it is `halted`, and the most recent `failure` if any (including one loaded from the checkpoint store at startup), so a consumer that failed in the previous run is visible until it succeeds again. ## Rebuilding a Consumer To replay a consumer from the beginning or move it to a specific event, reset its checkpoint with [`checkpointStore.reset(consumer, position?)`](/guide/core/checkpoint-store#reset) while the observer is **not running**. A running observer keeps its positions in memory and would overwrite the reset with its next checkpoint. On the next start the observer resumes from the new lowest checkpoint and consumers that are further ahead skip the replayed events. ## OpenTelemetry Tracing Each observed event is processed within an OpenTelemetry consumer span named `eventsourcingdb.observeEvent`. If the event carries a `traceparent` (injected by `writeEvents`), the span is linked to the original writer's trace, enabling end-to-end distributed tracing across the write and read sides. **Span attributes** (include identifying CloudEvents fields): * `cloudevents.event_id` * `cloudevents.event_type` * `cloudevents.event_subject` * `eventsourcingdb.observer.subject` * Handler retries add a `retry` span event (`attempt`, `delay_ms`) **Metrics** (labels use `subject` + `event_type` where an event is in scope; connection metrics use `subject` only — no `event_id` on metric labels): | Metric | Type | Labels | Description | | ---------------------------------------------------------- | --------- | --------------------------------- | -------------------------------------------------------------------- | | `eventsourcingdb_observer_events_handled_total` | Counter | `subject`, `event_type`, `status` | Events handled (`success`) or given up on after exhaustion (`skipped`) | | `eventsourcingdb_observer_handling_duration_seconds` | Histogram | `subject`, `event_type` | Handler duration in seconds (includes retries) | | `eventsourcingdb_observer_handler_retry_attempts_total` | Counter | `subject`, `event_type` | In-place handler retry attempts | | `eventsourcingdb_observer_connection_retry_attempts_total` | Counter | `subject` | Stream failures that schedule a reconnect | | `eventsourcingdb_observer_connection_reconnects_total` | Counter | `subject` | Successful reconnects (counted when events flow again after retries) | Replays are summarized in one debug log line per contiguous burst of events (count, duration, events per second, first and last event id) instead of one line per event. --- --- url: https://nimbus.overlap.at/guide/eventsourcingdb/event-mapping.md description: >- Utilities convert between Nimbus CloudEvents and EventSourcingDB records, preserving correlation ID and schemas. --- # Event Mapping The event mapping utilities convert between Nimbus events and EventSourcingDB events. When writing events, Nimbus metadata (correlation ID, data schema) is preserved alongside the payload. When reading events back, the original Nimbus event structure is restored. ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: ## How Events Are Stored When a Nimbus event is written to EventSourcingDB, its `data` field is wrapped in a structure that preserves Nimbus-specific metadata: ```typescript // Original Nimbus event data { email: "john@example.com", firstName: "John", lastName: "Doe", } // Stored in EventSourcingDB as { payload: { email: "john@example.com", firstName: "John", lastName: "Doe", }, nimbusMeta: { correlationid: "01JKXYZ...", dataschema: "https://example.com/schemas/user-invited", }, } ``` ## Types ### EventData The wrapper structure used to store Nimbus events in EventSourcingDB: ```typescript type EventData = { payload: Record; nimbusMeta: NimbusEventMetadata; }; ``` ### NimbusEventMetadata Metadata that Nimbus attaches to events stored in EventSourcingDB: ```typescript type NimbusEventMetadata = { correlationid: string; dataschema?: string; }; ``` ## Converting Nimbus Events to EventSourcingDB The `nimbusEventToEventSourcingDBEventCandidate` function converts a Nimbus event into an EventSourcingDB event candidate: ```typescript import { nimbusEventToEventSourcingDBEventCandidate } from "@nimbus-cqrs/eventsourcingdb"; const eventCandidate = nimbusEventToEventSourcingDBEventCandidate(nimbusEvent); ``` The conversion maps the following properties: | Nimbus Event | EventSourcingDB Event Candidate | | --------------- | ------------------------------- | | `source` | `source` | | `subject` | `subject` | | `type` | `type` | | `data` | `data.payload` | | `correlationid` | `data.nimbusMeta.correlationid` | | `dataschema` | `data.nimbusMeta.dataschema` | ::: tip You typically don't need to call this function directly. The [`writeEvents`](/guide/eventsourcingdb/write-events) function handles the conversion internally. ::: ## Converting EventSourcingDB Events to Nimbus The `eventSourcingDBEventToNimbusEvent` function converts an EventSourcingDB event back into a Nimbus event: ```typescript import { eventSourcingDBEventToNimbusEvent } from "@nimbus-cqrs/eventsourcingdb"; import type { Event } from "eventsourcingdb"; const handleEvent = (eventSourcingDBEvent: Event) => { const nimbusEvent = eventSourcingDBEventToNimbusEvent(eventSourcingDBEvent); console.log(nimbusEvent.correlationid); // Restored from nimbusMeta console.log(nimbusEvent.data); // Original payload }; ``` The function supports generic typing for specific event types: ```typescript import { Event } from "@nimbus-cqrs/core"; import { eventSourcingDBEventToNimbusEvent } from "@nimbus-cqrs/eventsourcingdb"; const event = eventSourcingDBEventToNimbusEvent(eventSourcingDBEvent); ``` ### Handling Non-Nimbus Events If the EventSourcingDB event was not written by Nimbus (i.e., it does not contain the `nimbusMeta` wrapper), the function gracefully handles this by: * Treating the entire `data` field as the payload * Generating a new correlation ID using ULID ## Type Guard The `isEventData` type guard checks whether event data conforms to the `EventData` structure: ```typescript import { isEventData } from "@nimbus-cqrs/eventsourcingdb"; if (isEventData(event.data)) { // event.data is typed as EventData console.log(event.data.payload); console.log(event.data.nimbusMeta.correlationid); } ``` --- --- url: https://nimbus.overlap.at/guide/mongodb.md description: >- Hub for @nimbus-cqrs/mongodb — connection manager, repository, CRUD+, MongoJSON, collection deployment, and checkpoint store. --- # Nimbus MongoDB Package The MongoDB package provides a simple and easy-to-use interface for working with MongoDB databases. * npm: [@nimbus-cqrs/mongodb](https://www.npmjs.com/package/@nimbus-cqrs/mongodb) ### npm ```bash npm install @nimbus-cqrs/mongodb ``` ### pnpm ```bash pnpm add @nimbus-cqrs/mongodb ``` ### Bun ```bash bun add @nimbus-cqrs/mongodb ``` ### Deno ```bash deno add npm:@nimbus-cqrs/mongodb ``` ## Example Application ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: --- --- url: https://nimbus.overlap.at/guide/mongodb/connection-manager.md description: >- MongoConnectionManager holds one long-lived MongoClient singleton with typed getDatabase and getCollection helpers. --- # Connection Manager The `MongoConnectionManager` is a thin singleton wrapper around a single long-lived `MongoClient`. The MongoDB Node driver already handles connection pooling, server monitoring, automatic reconnection and per-socket idle eviction, so the manager only adds the minimum on top: hold one client for the lifetime of the application and provide typed `getDatabase` / `getCollection` convenience methods. ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: ## Basic Usage ```typescript import { setupMongoConnectionManager } from "@nimbus-cqrs/mongodb"; import { getEnv } from "@nimbus-cqrs/core"; import { ServerApiVersion } from "mongodb"; export const initMongoDB = () => { const env = getEnv({ variables: ["MONGO_URL"], }); setupMongoConnectionManager({ name: "default", uri: env["MONGO_URL"], options: { appName: "nimbus-eventsourcing-demo", serverApi: { version: ServerApiVersion.v1, strict: false, deprecationErrors: true, }, }, }); }; const mongoManager = getMongoConnectionManager("default"); ``` ## Configuration `setupMongoConnectionManager` takes a MongoDB connection URI and an optional [`MongoClientOptions`](https://mongodb.github.io/node-mongodb-native/) object that is forwarded as-is to the underlying `MongoClient`. Optionally you can also specify a name for the connection manager. This is useful if you want to have multiple connections to different databases. If no name is specified, the connection manager will be named "default". Refer to the [MongoDB driver options reference](https://mongodb.github.io/node-mongodb-native/) for more information on the available options. Use `getMongoConnectionManager` to get the connection manager instance. ## Available Methods | Method | Return Type | Description | | ----------------------------------- | ----------------------------------------------------- | ------------------------------------------------------------- | | `getClient()` | `Promise` | Get the connected MongoDB client (lazy-connect on first call) | | `getDatabase(dbName)` | `Promise` | Get a database instance | | `getCollection(dbName, collection)` | `Promise` | Get a collection instance | | `healthCheck()` | `Promise<{ status: 'healthy' \| 'error'; details? }>` | Ping the server to verify the connection | | `close()` | `Promise` | Close the client and drain the pool (graceful shutdown) | ## Connection Management The manager creates a single `MongoClient` lazily on the first call to `getClient()` (or any of the helpers built on top of it). Concurrent first-callers share the same in-flight `connect()` promise, so only one connection is established. Everything beyond the initial `connect()` — pool growth/shrink, heartbeats, reconnects, retryable reads/writes — is delegated to the driver. ### Getting Resources ```typescript // Get a connected client const client = await getMongoConnectionManager().getClient(); // Get a database const db = await getMongoConnectionManager().getDatabase("myDatabase"); // Get a collection (most common) const usersCollection = await getMongoConnectionManager().getCollection( "myDatabase", "users" ); ``` ## Health Checks Use `healthCheck()` to verify the database connection: ```typescript app.get("/health", async (c) => { const dbHealth = await getMongoConnectionManager().healthCheck(); return c.json({ status: dbHealth.status === "healthy" ? "ok" : "error", database: dbHealth, }); }); ``` **Response format:** ```typescript // Healthy { status: "healthy" } // Error - `details` is the underlying error's `message`, or // "Unknown error occurred" when no message is available. { status: "error", details: "" } ``` ## Graceful Shutdown Call `close()` from your process shutdown handler so the driver can drain the pool cleanly: ```typescript import process from "node:process"; const shutdown = async () => { await getMongoConnectionManager().close(); process.exit(0); }; process.on("SIGTERM", shutdown); process.on("SIGINT", shutdown); ``` After `close()` resolves, the next call to `getClient()` will establish a fresh connection. ## Using with Repository The connection manager integrates seamlessly with the `MongoDBRepository` class: ```typescript import { MongoDBRepository } from "@nimbus-cqrs/mongodb"; import { mongoManager } from "./mongodb.ts"; import { User, UserSchema } from "./user.ts"; class UserRepository extends MongoDBRepository { constructor() { super( () => getMongoConnectionManager().getCollection( "myDatabase", "users" ), UserSchema, "User" ); } } export const userRepository = new UserRepository(); ``` ## Migration from 1.x `@nimbus-cqrs/mongodb` 2.0 simplifies the connection manager. If you are upgrading from 1.x: * The constructor signature is now flattened.\ From `MongoConnectionManager.getInstance(uri, { mongoClientOptions: { ... } })` to `MongoConnectionManager.getInstance(uri, { ... })`. Use the new functions `setupMongoConnectionManager` and `getMongoConnectionManager` instead. * The `connectionTimeout` option has been removed. The driver handles socket lifecycle via `maxIdleTimeMS` on the pool. * The `cleanup()` method has been removed.\ Delete any `setInterval(() => mongoManager.cleanup(), ...)` you set up. * The internal pre-flight `ping` on every `getClient()` call has been removed. If you relied on it for liveness, call `healthCheck()` explicitly (e.g. from a `/health` endpoint). * A new `close()` method is available for graceful shutdown. --- --- url: https://nimbus.overlap.at/guide/mongodb/repository.md description: >- MongoDBRepository is a type-safe base for collection CRUD with Zod validation, error mapping, and tracing. --- # Repository The `MongoDBRepository` is a type-safe base class for MongoDB CRUD operations. It provides a consistent interface for interacting with MongoDB collections while handling validation, error conversion, and document mapping. ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: ## Basic Usage Create a repository by extending `MongoDBRepository`: ```typescript import { MongoDBRepository } from "@nimbus-cqrs/mongodb"; import { z } from "zod"; import { mongoManager } from "./mongodb.ts"; // Define your entity schema const User = z.object({ _id: z.string(), email: z.string().email(), firstName: z.string(), lastName: z.string(), createdAt: z.string(), updatedAt: z.string(), }); type User = z.infer; // Create the repository class UserRepository extends MongoDBRepository { constructor() { super( () => mongoManager.getCollection("myDatabase", "users"), User, "User" ); } } export const userRepository = new UserRepository(); ``` ## Constructor Parameters | Parameter | Type | Description | | --------------- | --------------------------- | ------------------------------------------------- | | `getCollection` | `() => Promise` | Function that returns a MongoDB collection | | `entityType` | `ZodType` | Zod schema for validating and typing entities | | `entityName` | `string` (optional) | Name used in error messages (default: "Document") | ## Available Methods | Method | Parameters | Return Type | Description | | ---------------- | ------------------------------------------------------ | ----------------- | --------------------------- | | `findOne` | `{ filter }` | `Promise` | Find a single document | | `find` | `{ filter, limit?, skip?, sort?, project?, options? }` | `Promise` | Find multiple documents | | `countDocuments` | `{ filter, options? }` | `Promise` | Count matching documents | | `insertOne` | `{ item }` | `Promise` | Insert a single document | | `insertMany` | `{ items, options? }` | `Promise` | Insert multiple documents | | `replaceOne` | `{ item, options? }` | `Promise` | Replace a document by `_id` | | `replaceMany` | `{ items, options? }` | `Promise` | Replace multiple documents | | `deleteOne` | `{ item, options? }` | `Promise` | Delete a document by `_id` | | `deleteMany` | `{ items, options? }` | `Promise` | Delete multiple documents | ## Document Mapping Override the mapping methods to control how documents are converted between MongoDB format and your entity format: ```typescript import { Document, ObjectId } from "mongodb"; class UserRepository extends MongoDBRepository { constructor() { super( () => mongoManager.getCollection("myDatabase", "users"), User, "User" ); } // Convert MongoDB document to entity override _mapDocumentToEntity(doc: Document): User { return User.parse({ _id: doc._id.toString(), email: doc.email, firstName: doc.firstName, lastName: doc.lastName, createdAt: doc.createdAt.toISOString(), updatedAt: doc.updatedAt.toISOString(), }); } // Convert entity to MongoDB document override _mapEntityToDocument(user: User): Document { return { _id: new ObjectId(user._id), email: user.email, firstName: user.firstName, lastName: user.lastName, createdAt: new Date(user.createdAt), updatedAt: new Date(user.updatedAt), }; } } ``` ## Query Examples ### Finding Documents ```typescript // Find one by filter const user = await userRepository.findOne({ filter: { email: "john@example.com" }, }); // Find multiple with options const users = await userRepository.find({ filter: { lastName: "Doe" }, limit: 10, skip: 0, sort: { createdAt: -1 }, }); // Count documents const count = await userRepository.countDocuments({ filter: { lastName: "Doe" }, }); ``` ### Creating Documents ```typescript // Insert one const newUser = await userRepository.insertOne({ item: { _id: new ObjectId().toString(), email: "jane@example.com", firstName: "Jane", lastName: "Doe", createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), }, }); // Insert many const users = await userRepository.insertMany({ items: [user1, user2, user3], }); ``` ### Updating Documents ```typescript // Replace a document (must include _id) const updatedUser = await userRepository.replaceOne({ item: { ...existingUser, firstName: "Jonathan", updatedAt: new Date().toISOString(), }, }); ``` ### Deleting Documents ```typescript // Delete one const deletedUser = await userRepository.deleteOne({ item: user, }); // Delete many const deletedUsers = await userRepository.deleteMany({ items: [user1, user2], }); ``` ## Error Handling The repository automatically throws `NotFoundException` when: * `findOne` returns no results * `replaceOne` matches no documents * `deleteOne` deletes no documents The exception includes entity-specific error codes: ```typescript try { const user = await userRepository.findOne({ filter: { _id: "nonexistent" }, }); } catch (error) { // NotFoundException with: // - message: "User not found" // - details.errorCode: "USER_NOT_FOUND" } ``` ## Add Custom Methods Just add new methods to the repository class as needed for your use cases. For example if you need specific access patterns and want the consumer to be able to use them explicitly without having to provide filter logic. Also aggregation pipelines can be added to the repository as custom methods. ::: tip User the [CRUD+](/guide/mongodb/crud) methods provided by Nimbus to still have observability and error handling features baked in. ::: ```typescript import { aggregate, MongoDBRepository } from "@nimbus-cqrs/mongodb"; class UserRepository extends MongoDBRepository { // ... existing code ... // Add custom methods to find a user by email public async findByEmail(email: string): Promise { return this.findOne({ filter: { email } }); } // Add custom methods which uses an aggregation pipeline public async getUserGroups(): Promise { const collection = await this._getCollection(); const result = await aggregate({ collection, aggregation: [ { $group: { _id: "$group", users: { $push: "$$ROOT" }, }, }, ], mapDocument: (doc: Document) => { return { name: doc._id, users: doc.users.map((user: Document) => this._mapDocumentToEntity(user) ), }; }, outputType: UserGroup, }); return result; } } export const userRepository = new UserRepository(); ``` --- --- url: https://nimbus.overlap.at/guide/mongodb/crud.md description: >- Low-level traced MongoDB CRUD helpers with Nimbus exceptions — use directly or via MongoDBRepository. --- # CRUD+ The MongoDB package provides low-level CRUD functions for direct database operations. These functions are fully instrumented with OpenTelemetry tracing and metrics, and handle errors using Nimbus exceptions. ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: ## When to Use Use these low-level functions when: * You need operations not provided by `MongoDBRepository` * You want direct control over MongoDB operations * You're building custom repository methods For standard CRUD operations, prefer using the [Repository](/guide/mongodb/repository) class. ## Available Functions | Function | Description | | ------------------- | ----------------------------------------- | | `find` | Find multiple documents matching a filter | | `findOne` | Find a single document matching a filter | | `insertOne` | Insert a single document | | `insertMany` | Insert multiple documents | | `replaceOne` | Replace a single document | | `updateOne` | Update a single document | | `updateMany` | Update multiple documents | | `deleteOne` | Delete a single document | | `deleteMany` | Delete multiple documents | | `countDocuments` | Count documents matching a filter | | `bulkWrite` | Execute multiple write operations | | `aggregate` | Execute an aggregation pipeline | | `findOneAndUpdate` | Find and update a document atomically | | `findOneAndReplace` | Find and replace a document atomically | | `findOneAndDelete` | Find and delete a document atomically | ## Usage Examples ### Find Operations Functions that return typed data require `mapDocument` and `outputType` parameters for type-safe results. ```typescript import { find, findOne } from "@nimbus-cqrs/mongodb"; type User = { _id: string; email: string; name: string }; // Find multiple documents const users = await find({ collection, filter: { status: "active" }, limit: 10, skip: 0, sort: { createdAt: -1 }, mapDocument: (doc) => ({ _id: doc._id.toString(), email: doc.email, name: doc.name, }), outputType: UserSchema, }); // Find a single document const user = await findOne({ collection, filter: { email: "john@example.com" }, mapDocument: (doc) => ({ _id: doc._id.toString(), email: doc.email, name: doc.name, }), outputType: UserSchema, }); ``` ### Insert Operations ```typescript import { insertOne, insertMany } from "@nimbus-cqrs/mongodb"; // Insert a single document const result = await insertOne({ collection, document: { email: "john@example.com", name: "John Doe", createdAt: new Date(), }, }); // Insert multiple documents const results = await insertMany({ collection, documents: [ { email: "john@example.com", name: "John" }, { email: "jane@example.com", name: "Jane" }, ], }); ``` ### Update Operations ```typescript import { updateOne, updateMany, replaceOne } from "@nimbus-cqrs/mongodb"; // Update a single document const result = await updateOne({ collection, filter: { _id: userId }, update: { $set: { name: "New Name", updatedAt: new Date() } }, }); // Update multiple documents const results = await updateMany({ collection, filter: { status: "pending" }, update: { $set: { status: "processed" } }, }); // Replace a document entirely const replaced = await replaceOne({ collection, filter: { _id: userId }, replacement: { email: "new@example.com", name: "New Name", updatedAt: new Date(), }, }); ``` ### Delete Operations ```typescript import { deleteOne, deleteMany } from "@nimbus-cqrs/mongodb"; // Delete a single document const result = await deleteOne({ collection, filter: { _id: userId }, }); // Delete multiple documents const results = await deleteMany({ collection, filter: { status: "deleted" }, }); ``` ### Atomic Find-and-Modify Operations These functions return the document before or after modification, requiring `mapDocument` and `outputType` for type safety. ```typescript import { findOneAndUpdate, findOneAndReplace, findOneAndDelete, } from "@nimbus-cqrs/mongodb"; type User = { _id: string; email: string; loginCount: number }; // Find and update atomically const updated = await findOneAndUpdate({ collection, filter: { _id: userId }, update: { $inc: { loginCount: 1 } }, mapDocument: (doc) => ({ _id: doc._id.toString(), email: doc.email, loginCount: doc.loginCount, }), outputType: UserSchema, options: { returnDocument: "after" }, }); // Find and replace atomically const replaced = await findOneAndReplace({ collection, filter: { _id: userId }, replacement: newDocument, mapDocument: (doc) => ({ _id: doc._id.toString(), email: doc.email, loginCount: doc.loginCount, }), outputType: UserSchema, options: { returnDocument: "after" }, }); // Find and delete atomically const deleted = await findOneAndDelete({ collection, filter: { _id: userId }, mapDocument: (doc) => ({ _id: doc._id.toString(), email: doc.email, loginCount: doc.loginCount, }), outputType: UserSchema, }); ``` ### Aggregation The `aggregate` function executes a pipeline and maps results to typed output. ```typescript import { aggregate } from "@nimbus-cqrs/mongodb"; type CategoryCount = { category: string; count: number }; const results = await aggregate({ collection, aggregation: [ { $match: { status: "active" } }, { $group: { _id: "$category", count: { $sum: 1 } } }, { $sort: { count: -1 } }, ], mapDocument: (doc) => ({ category: doc._id, count: doc.count, }), outputType: CategoryCountSchema, }); ``` ### Bulk Write ```typescript import { bulkWrite } from "@nimbus-cqrs/mongodb"; const result = await bulkWrite({ collection, operations: [ { insertOne: { document: { name: "New Item" } } }, { updateOne: { filter: { _id: id1 }, update: { $set: { status: "updated" } }, }, }, { deleteOne: { filter: { _id: id2 } } }, ], }); ``` ### Count Documents ```typescript import { countDocuments } from "@nimbus-cqrs/mongodb"; const count = await countDocuments({ collection, filter: { status: "active" }, }); ``` ## Observability All CRUD functions are automatically instrumented with OpenTelemetry tracing and metrics. ### Tracing Each operation creates a span with the following attributes: | Attribute | Description | | ----------------------- | --------------------------------- | | `db.system` | Always `mongodb` | | `db.operation` | The operation name (e.g., `find`) | | `db.mongodb.collection` | The collection name | ### Metrics Two metrics are recorded for every operation: | Metric | Type | Labels | Description | | ------------------------------------ | --------- | ----------------------------------- | --------------------------------- | | `mongodb_operation_total` | Counter | `operation`, `collection`, `status` | Total number of operations | | `mongodb_operation_duration_seconds` | Histogram | `operation`, `collection` | Duration of operations in seconds | The `status` label is either `success` or `error`. ## Error Handling All functions use `handleMongoError` internally to convert MongoDB errors to Nimbus exceptions. See [handleMongoError](/guide/mongodb/handle-mongo-error) for details on error mapping. --- --- url: https://nimbus.overlap.at/guide/mongodb/mongo-json.md description: >- MongoJSON parse/stringify preserves MongoDB extended types (ObjectId, Date, etc.) in JSON round-trips. --- # MongoJSON `MongoJSON` provides parse and stringify functions with support for MongoDB data types. It allows you to serialize MongoDB filters and documents as JSON strings while preserving type information. ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: ## Basic Usage ```typescript import { MongoJSON } from "@nimbus-cqrs/mongodb"; // Parse a JSON string with MongoDB type prefixes const filter = MongoJSON.parse('{"_id": "objectId::507f1f77bcf86cd799439011"}'); // Result: { _id: ObjectId("507f1f77bcf86cd799439011") } // Stringify an object to JSON const json = MongoJSON.stringify({ name: "John", age: 30 }); // Result: '{"name":"John","age":30}' ``` ## Type Prefixes The `parse` function recognizes special prefixes to convert strings to MongoDB types: | Prefix | Converts To | Example | | ------------ | ----------- | -------------------------------------- | | `objectId::` | `ObjectId` | `"objectId::507f1f77bcf86cd799439011"` | | `date::` | `Date` | `"date::2024-01-15T10:30:00Z"` | | `int::` | `number` | `"int::42"` | | `double::` | `number` | `"double::19.99"` | ## Parse Examples ```typescript import { MongoJSON } from "@nimbus-cqrs/mongodb"; // ObjectId conversion const idFilter = MongoJSON.parse( '{"_id": "objectId::507f1f77bcf86cd799439011"}' ); // { _id: ObjectId("507f1f77bcf86cd799439011") } // Date conversion const dateFilter = MongoJSON.parse( '{"createdAt": {"$gte": "date::2024-01-01T00:00:00Z"}}' ); // { createdAt: { $gte: Date("2024-01-01T00:00:00Z") } } // Integer conversion const countFilter = MongoJSON.parse('{"count": {"$gt": "int::100"}}'); // { count: { $gt: 100 } } // Multiple types const complexFilter = MongoJSON.parse(`{ "_id": "objectId::507f1f77bcf86cd799439011", "price": {"$lte": "double::49.99"}, "createdAt": {"$gte": "date::2024-01-01T00:00:00Z"}, "quantity": {"$gt": "int::0"} }`); ``` ## Operator Blacklist For security, `MongoJSON.parse` blocks certain MongoDB operators by default: ```typescript // This will throw an error MongoJSON.parse('{"$where": "this.name === \\"admin\\""}'); // Error: Operator '$where' is not allowed // Custom blacklist MongoJSON.parse(jsonString, ["$where", "$expr"]); ``` The default blacklist includes `$where` to prevent code injection attacks. ## Use Case: API Filters `MongoJSON` is useful when accepting MongoDB filters from API requests: ```typescript import { MongoJSON } from "@nimbus-cqrs/mongodb"; app.get("/users", async (c) => { const filterParam = c.req.query("filter"); // Parse the filter from query string const filter = filterParam ? MongoJSON.parse(filterParam) : {}; const users = await userRepository.find({ filter }); return c.json(users); }); // Example request: // GET /users?filter={"status":"active","createdAt":{"$gte":"date::2024-01-01T00:00:00Z"}} ``` ## Error Handling `MongoJSON.parse` throws an `InvalidInputException` for: * Invalid JSON syntax * Blacklisted operators ```typescript import { MongoJSON } from "@nimbus-cqrs/mongodb"; try { const filter = MongoJSON.parse('{"invalid json}'); } catch (error) { // InvalidInputException with JSON parse error details } try { const filter = MongoJSON.parse('{"$where": "1===1"}'); } catch (error) { // Error: Operator '$where' is not allowed } ``` --- --- url: https://nimbus.overlap.at/guide/mongodb/handle-mongo-error.md description: >- handleMongoError maps MongoDB driver error codes to Nimbus exceptions for consistent application error handling. --- # handleMongoError The `handleMongoError` function converts MongoDB errors to Nimbus exceptions based on the error code. This provides consistent error handling across your application. ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: ## Basic Usage ```typescript import { handleMongoError } from "@nimbus-cqrs/mongodb"; try { await collection.insertOne(document); } catch (error) { throw handleMongoError(error); } ``` ## Error Code Mappings | MongoDB Code | Error Type | Nimbus Exception | Details Included | | ------------ | ------------------- | ----------------------- | ----------------- | | 121 | Document validation | `InvalidInputException` | `code`, `details` | | 2 | Bad value | `InvalidInputException` | Error message | | 11000 | Duplicate key | `InvalidInputException` | `keyValue` | | Other | Various | `GenericException` | Original error | ## Error Examples ### Duplicate Key Error (Code 11000) When inserting a document that violates a unique index: ```typescript try { await collection.insertOne({ email: "existing@example.com" }); } catch (error) { const exception = handleMongoError(error); // InvalidInputException with: // - message: "E11000 duplicate key error..." // - details: { keyValue: { email: "existing@example.com" } } } ``` ### Document Validation Error (Code 121) When a document fails schema validation: ```typescript try { await collection.insertOne({ name: 123 }); // name should be string } catch (error) { const exception = handleMongoError(error); // InvalidInputException with: // - message: "Document failed validation" // - details: { code: 121, details: { ... validation errors ... } } } ``` ### Bad Value Error (Code 2) When a query contains invalid values: ```typescript try { await collection.find({ $invalid: true }).toArray(); } catch (error) { const exception = handleMongoError(error); // InvalidInputException with original error message } ``` ### Other Errors All other MongoDB errors are wrapped in a `GenericException`: ```typescript try { await collection.find({}).toArray(); } catch (error) { const exception = handleMongoError(error); // GenericException with original error stack trace } ``` ## Integration with CRUD Functions All [CRUD functions](/guide/mongodb/crud) use `handleMongoError` internally: ```typescript import { insertOne } from "@nimbus-cqrs/mongodb"; try { await insertOne({ collection, document: { email: "duplicate@example.com" }, }); } catch (error) { // Error is already a Nimbus exception if (error.name === "INVALID_INPUT") { // Handle duplicate key or validation error } } ``` ## Custom Error Handling You can use `handleMongoError` in your own database operations: ```typescript import { handleMongoError } from "@nimbus-cqrs/mongodb"; import { GenericException } from "@nimbus-cqrs/core"; const customDatabaseOperation = async (collection: Collection) => { try { // Custom MongoDB operation const result = await collection .aggregate([ { $match: { status: "active" } }, { $group: { _id: "$category", total: { $sum: "$amount" } } }, ]) .toArray(); return result; } catch (error) { throw handleMongoError(error); } }; ``` ## Error Response in API When combined with the Hono [error handler](/guide/hono/on-error), MongoDB errors are automatically converted to HTTP responses: ```typescript // Duplicate key error becomes: // HTTP 400 { "error": "INVALID_INPUT", "message": "E11000 duplicate key error collection: db.users index: email_1 dup key: { email: \"existing@example.com\" }", "details": { "keyValue": { "email": "existing@example.com" } } } ``` --- --- url: https://nimbus.overlap.at/guide/mongodb/deploy-collection.md description: >- deployMongoCollection declaratively creates or updates collections with JSON schema validation and indexes. --- # Deploy Collection The `deployMongoCollection` function creates or updates MongoDB collections with schema validation and indexes. It provides a declarative way to manage your database schema. ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: ## Basic Usage ```typescript import { deployMongoCollection } from "@nimbus-cqrs/mongodb"; import { mongoManager } from "./mongodb.ts"; const USERS_COLLECTION = { name: "users", options: { validator: { $jsonSchema: { bsonType: "object", required: ["email", "firstName", "lastName"], properties: { email: { bsonType: "string" }, firstName: { bsonType: "string" }, lastName: { bsonType: "string" }, }, }, }, }, indexes: [ { key: { email: 1 }, unique: true }, { key: { lastName: 1, firstName: 1 } }, ], }; const client = await mongoManager.getClient(); await deployMongoCollection({ mongoClient: client, dbName: "myDatabase", collectionDefinition: USERS_COLLECTION, allowUpdateIndexes: true, }); ``` ## Function Parameters | Parameter | Type | Description | | ---------------------- | --------------------------- | ------------------------------------------------- | | `mongoClient` | `MongoClient` | A connected MongoDB client instance | | `dbName` | `string` | The name of the database | | `collectionDefinition` | `MongoCollectionDefinition` | The collection definition object | | `allowUpdateIndexes` | `boolean` | Whether to update indexes on existing collections | ## Collection Definition The `MongoCollectionDefinition` type defines the structure of a collection: ```typescript type MongoCollectionDefinition = { name: string; options?: CreateCollectionOptions; indexes?: IndexDescription[]; }; ``` | Property | Type | Description | | --------- | ------------------------- | --------------------------------------------- | | `name` | `string` | The name of the collection | | `options` | `CreateCollectionOptions` | MongoDB collection options (validation, etc.) | | `indexes` | `IndexDescription[]` | Array of index definitions | ## Behavior The function handles two scenarios: ### New Collection When the collection does not exist: 1. Creates the collection with the specified options 2. Creates all defined indexes ### Existing Collection When the collection already exists: 1. Updates collection options using `collMod` 2. If `allowUpdateIndexes` is `true`: * Creates any new indexes not present in the database * Drops any indexes not defined in the collection definition (except `_id_`) ## Index Management Indexes are automatically named based on their key fields if no name is provided: ```typescript // This index will be named "email_1" { key: { email: 1 } } // This index will be named "lastName_1_firstName_1" { key: { lastName: 1, firstName: 1 } } // Explicit name { key: { email: 1 }, name: "email_unique_idx", unique: true } ``` ## Deployment Script Create a script to deploy all collections: ```typescript import { deployMongoCollection } from "@nimbus-cqrs/mongodb"; import { setupLogger, parseLogLevel } from "@nimbus-cqrs/core"; import { mongoManager } from "./mongodb.ts"; import { USERS_COLLECTION } from "./collections/users.ts"; import { ORDERS_COLLECTION } from "./collections/orders.ts"; // Configure logging to see deployment progress setupLogger({ logLevel: parseLogLevel("info"), }); const collections = [USERS_COLLECTION, ORDERS_COLLECTION]; const deployCollections = async () => { const client = await mongoManager.getClient(); const dbName = process.env.MONGO_DB ?? "myDatabase"; for (const collection of collections) { await deployMongoCollection({ mongoClient: client, dbName, collectionDefinition: collection, allowUpdateIndexes: true, }); } console.log("All collections deployed successfully"); }; deployCollections().catch(console.error); ``` --- --- url: https://nimbus.overlap.at/guide/mongodb/checkpoint-store.md description: >- MongoCheckpointStore persists event consumer checkpoints in a MongoDB collection. --- # Checkpoint Store The `MongoCheckpointStore` is a [`CheckpointStore`](/guide/core/checkpoint-store) backed by a MongoDB collection. Pass it to an [event observer](/guide/eventsourcingdb/event-observer) so its consumers resume where they stopped after a restart. ::: tip An in Depth Example This guide also has an in depth example of a working application built with Nimbus. Combining DDD, CQRS and Event Sourcing. Check out the [In Depth Example](/guide/in-depth-example) page to learn how everything is connected and works out in a real-world application. ::: ## Usage ```typescript import { getEnv } from '@nimbus-cqrs/core'; import { getMongoConnectionManager, MONGO_CHECKPOINTS_COLLECTION, MongoCheckpointStore, } from "@nimbus-cqrs/mongodb"; const env = getEnv({ variables: ['MONGO_DB'] }); const getCheckpointCollection = () => { return getMongoConnectionManager().getCollection( env.MONGO_DB, MONGO_CHECKPOINTS_COLLECTION.name, ); }; export const checkpointStore = new MongoCheckpointStore(getCheckpointCollection); ``` The constructor takes a collection factory, the same shape the [Repository](/guide/mongodb/repository) uses, so the store can share your application's connection setup. ## Collection `MONGO_CHECKPOINTS_COLLECTION` is a `MongoCollectionDefinition` for the `nimbus_checkpoints` collection with a unique index on `consumer`. Deploy it together with your other collections using [deployMongoCollection](/guide/mongodb/deploy-collection). ::: warning Consumer names are application-wide The index is on the consumer name alone, not on observer and consumer. Two observers sharing a store therefore must not declare consumers with the same name, or they overwrite each other's checkpoint. Prefix consumer names with their domain or observer (for example `ticketing.tickets`) to keep them unique. ::: One document is stored per consumer: ```json { "consumer": "ticketing.tickets", "observer": "ticketing", "position": "1842", "updatedAt": { "$date": "2026-10-07T08:39:24.262Z" }, "failure": { "position": "1843", "error": "ZodError: Invalid input", "at": { "$date": "2026-10-07T08:40:01.010Z" } } } ``` Dates are stored as BSON dates and converted to ISO strings when read. `position` is stored as a string and never interpreted. ## Behaviour * `load` queries the given consumer names in one `find`. * `save` issues one unordered `bulkWrite` of upserts. An update without `failure` `$unset`s a stored failure marker. * `reset` `$set`s the new position or `$unset`s it, and always `$unset`s `failure`. A consumer without a document is left alone. Checkpoints are written after the consumers have run, not in the same transaction as the read model, so delivery is at-least-once. Consumers that write to MongoDB should apply events idempotently. ## Resetting from the Command Line Since `reset` has to run while the observer is stopped, a small CLI is the usual way to call it: ```typescript import { getMongoConnectionManager } from "@nimbus-cqrs/mongodb"; import { checkpointStore } from "./checkpoint-store.ts"; import { initMongoDB } from "./mongodb.ts"; const [consumer, position] = process.argv.slice(2); try { if (consumer === undefined || consumer === '') { throw new Error('Usage: reset-checkpoint [event-id]'); } await initMongoDB(); await checkpointStore.reset(consumer, position); process.exitCode = 0; } catch (error) { process.exitCode = 1; } finally { await getMongoConnectionManager().close(); } ``` Without a position the consumer replays the subject from the beginning on the next start and with one it resumes after that event.