Skip to main content
examples/miomock is this repository’s example Sonamu application. It searches projects with OpenSearch, and its integration has every piece an application needs: migrations, an opt-in switch, a search definition, marking in the models, store identity initialization, the worker lifecycle, a search API that re-checks permissions, a web page that branches on status codes, an administrative CLI, and two test setups. This page shows them in the order a developer adds them. Code blocks are excerpts; open the file named in the title for the whole thing.

Dependencies and migrations

examples/miomock/api/package.json depends on @sonamu-kit/opensearch (the workspace package) and @opensearch-project/opensearch. Two migrations install the package schema with the same function: 20261112205310_install_search_schema.ts and 20261113024500_upgrade_search_schema_v2.ts both call installSearchSchema(knex).
api/src/migrations/20261113024500_upgrade_search_schema_v2.ts
installSearchSchema applies only the versions that are missing. On a fresh database the first migration already installs up to version 2 and the second does nothing; on a database at version 1 the second applies version 2. The schema has no entities, so the Sonamu migrator never diffs it and sonamu.lock does not list it. The down of both migrations throws, so a rollback never deletes the ledger, the target records or the origin record.

The switch and configuration

Search is an opt-in feature switched by environment variables. The switch module imports nothing, so sonamu.config.ts can read it without loading the package.
api/src/search/switch.ts
The synchronization handle uses Sonamu’s write database as the primary, with the namespace miomock. resolveSonamuPrimary returns DB.getDB("w") and refuses it when it is a transaction.
api/src/search/index.ts
The search runtime (query handle and lifecycle) is built when its module is evaluated, but importing it never throws: a configuration error is kept and thrown on first use, at search or start time. This keeps tools such as sonamu sync, which import the models, from failing (see the import warning in Setup).

The search definition

The definition is built with defineSonamuSearch under the logical key projects. The document holds the name, description, status, tag names, milestone names and member employee IDs; the worker validates each projection against this schema.
api/src/search/projects.definition.ts
materialize runs the model’s findMany and a milestone query in the worker’s snapshot, and returns a tombstone ({ state: "deleted" }) for a project that no longer exists.
api/src/search/projects.definition.ts
member_employee_ids is used only as a search filter. Permissions are re-checked on the primary after the search, so a stale value never lets a project the caller must not see into the response. When the document changes, raise projectionVersion and keep the old version in PREVIOUS_PROJECTION_VERSIONS until its target is retired, so the worker and search still handle the old target during the rebuild.

Marking

The models collect the changed project IDs inside the domain transaction and mark them once, with every affected ID. With search disabled, no statement runs. With search enabled and no target registered yet, marking fails the transaction.
api/src/search/synchronization.ts
initialize() is idempotent and reads on its own pool connection, outside the transaction. These are the paths that change a project document and how each is marked. Rows deleted by a foreign key CASCADE are deleted by the database without marking, so the model reads the affected projects first, in the same transaction, and marks them. Deleting an employee shows how a path handles a CASCADE:
api/src/application/employee/employee.model.ts

Initializing the store identity

Sonamu calls lifecycle.onStart only after the server starts listening, so a write arriving in between would fail with store-identity-uninitialized. The example therefore pins the store identity in a Fastify onReady hook, which runs before listen. If initialization fails (no schema, another database, a wrong setting), the server fails to start before it accepts a request. The runtime is imported lazily, so with search disabled nothing is loaded and sonamu.config.ts does not pull in the models.
api/src/search/startup.ts
api/src/sonamu.config.ts
markProjectsChanged also calls initialize() before marking; once the identity is pinned, it reads nothing again.

The lifecycle and the worker

lifecycle.onStart and onShutdown in sonamu.config.ts start and stop search. The search runtime creates a createSearchLifecycle named miomock-search, and MIOMOCK_SEARCH_WORKER turns its worker on. The worker gets its own client, which the lifecycle creates for each generation and closes when that generation’s worker stops.
api/src/search/runtime.ts
project.model.ts imports the runtime module, so the development server’s HMR re-evaluates it with the model. The lifecycle with the same name stops the previous generation’s worker and starts a new one with the new definitions, so there is always one worker. The event listener logs drains that indexed or quarantined something, drains that did not index everything (as a warning), cooldowns, quarantined documents, paused targets, hash mismatches, reclaimed leases, lost target fences, refused drains (error), and state changes. Empty drains are not logged. A lost fence and a store mismatch are logged as errors, with a comment that tells the operator what to run: sonamu search confirm-ownership if this is the original store, adopt-store on a copy.
api/src/search/runtime.ts

The search API

ProjectModel.searchIndexed is the search API. It throws SearchDisabledException when search is disabled and UnauthorizedException when the caller is not signed in; otherwise it searches as the caller.
api/src/application/project/project.model.ts
A project is visible to users who are member employees of that project and to users whose role is admin. Deleted or banned users, and ordinary users with no employee record, see nothing. The index may lag behind memberships, deletes and edits, so the search follows the same order as the package example and must run outside a transaction.
api/src/search/project-search.ts
  1. Read the scope the caller may see now from the primary, just before the search.
  2. Search with that scope as a terms filter. A non-member sends an empty list so nothing matches; only an admin has no filter.
  3. Read the scope again, since it may have changed during the search, and check the returned IDs against the current rows and memberships on the primary.
  4. Return the current database rows, not the indexed content, in search order, and drop a field’s highlight if the indexed text differs from the current text.
Highlights are wrapped in private-use characters (HIGHLIGHT_START, HIGHLIGHT_END) instead of HTML tags. User text inside a fragment is not escaped, so the page must never render a fragment as HTML.
api/src/search/project-search.ts

Errors and HTTP status

lifecycle.onError in sonamu.config.ts turns search errors into a status code and a message rendered in the request’s locale.
api/src/search/errors.ts
The response body also carries code, reason (only a string reason; the rest of details stays on the server) and retryable, but the generated web client (SonamuError) drops the body’s code and reason and keeps only the status and the message. The web page therefore branches on the status code, and the API’s and the page’s status tables must change together.

The web page

web/src/routes/admin/projects/search.tsx is the search page (/admin/projects/search). It maps status codes to page states.
web/src/routes/admin/projects/search.tsx
The page states are checking the session, sign-in required, no query, no results, and a result list with “load more”; each failure kind shows its own message. For an expired cursor the page says the next page is no longer available and asks the user to start again. It does not claim the results changed, because a cursor also expires at the end of its lifetime when nothing changed. An expired cursor and an unexpected error restart the search, and a temporary outage offers a retry. Only for an index that is not ready (409) and a temporary outage (503) does the page show the server’s localized message as a detail. If fetching the next page fails, the results so far stay and the message appears below them. Highlight fragments are split on the marker characters and rendered as text.
web/src/routes/admin/projects/search.tsx

The administrative CLI

The administrative commands are the package’s sonamu search commands; Index administration lists them with their approval rule, output and exit codes. sonamu.config.ts registers the plugin and imports the setup module only when a search command runs:
api/src/sonamu.config.ts
api/src/search/cli-setup.ts
The setup works regardless of MIOMOCK_SEARCH_ENABLED. It reads OPENSEARCH_URL only when a command needs OpenSearch, so inspect, backfill, suspend, remark, retry-quarantined, adopt-store and the cutover dry run run without it. The admin values are MIOMOCK_SEARCH_ADMIN_SETTINGS from search/admin.ts, which the application’s own administrative handle (createMiomockSearchAdmin) also uses, and the worker limits come from searchWorkerLimits(), as the worker’s do. The CLI runs the built code, so build the API before the first command and again after every change to the search code. Run every command from examples/miomock/api, with OPENSEARCH_URL set for the commands that need OpenSearch (http://localhost:9200 for the local container). Without a terminal, a command that changes state needs --execute --confirm; on a terminal the CLI asks instead. init and cutover without --execute only print a dry run.
The first target (plan, create, register, backfill, cutover), then its state:
After a definition change (open a rebuild build, fill it, check the blockers, cut over, and retire the old target once the grace period has passed):
A source restore (suspend capture, resume with a new epoch, fill, cut over):
A paused target (verification scan, resume):
Adopt a copied database, or confirm ownership of the same store:
  • init on a key without a target plans, creates and registers one, then backfills the first build and cuts it over. On a key with a target it opens a rebuild build for the current definition (or returns the open build with the same fingerprint) and prints the next steps (backfill, cutover, retire-old). Without --execute it prints the plan for a key without a target and the open build, and changes nothing.
  • cutover without --execute prints the blockers; with it, the package refuses while any remain. drain is for development and runs worker drains until one finds nothing to do.
  • adopt-store prints its next steps (restart-processes, resume, backfill, cutover) and the number of detached targets. Restart the processes, then create the new target with resume, backfill and cutover.
  • When a command is refused because the store binding does not match, the failure’s hint names both commands: sonamu search adopt-store if this database is a copy or restore of another one, sonamu search confirm-ownership if it is the same store (renamed, restored in place, moved to another server).

Tests

The default test suite (mise exec -- pnpm --filter miomock-api test) excludes *.search.test.ts and runs with search disabled, because managed search cannot be used inside Sonamu’s transactional test fixture. search-disabled.test.ts checks that, with search disabled, saving a project runs no package statement and server start and shutdown create no connection, statement or timer, and that with search enabled but no OPENSEARCH_URL, importing the modules succeeds and start fails. errors.test.ts checks the HTTP status of each error class. The search integration tests are the *.search.test.ts files, run separately with mise exec -- pnpm --filter miomock-api test:search. They need Docker, because the setup starts its own OpenSearch container, and the local PostgreSQL with the miomock_test database. The worker reads committed rows over other connections, so these tests use neither Sonamu’s test transaction nor test mode. The files share one database and index and run one at a time, in file name order.
api/vitest.search.config.ts
The global setup (src/search/testing/global-setup.ignore.ts) does the following:
  1. Starts an OpenSearch container (MIOMOCK_OPENSEARCH_IMAGE, opensearchproject/opensearch:3.5.0 by default).
  2. Clones miomock_test into miomock_search_it with CREATE DATABASE … TEMPLATE … STRATEGY FILE_COPY and installs the package schema. FILE_COPY is needed because the PostgreSQL 15+ default (WAL_LOG) does not copy PGroonga index files, and later writes to projects would fail.
  3. Adopts that database with adoptCopiedStore, then plans and registers the first target. The clone inherits the source’s store identity and coexists with the source, so it is a copy: without adoption the worker and administrative operations would stop, and confirming ownership instead would make two databases claim the same index. The first build stays open; the tests backfill it and cut it over.
  4. Clones that database again into miomock_search_it_copy and leaves it unadopted for the store binding tests. Teardown drops the cloned databases (including the name miomock_search_it_copy_moved, which a test renames the copy to) and stops the container.
The two CLI test files run sonamu search through the CLI’s real entry point (node_modules/@sonamu-kit/cli/bin/sonamu.js) in a separate process, so the worker in the test process keeps running. src/search/testing/cli.ts adds --json --non-interactive, and --execute --confirm where a command needs approval. It also sets VITEST=true, which makes the CLI read src/sonamu.config.ts through the TypeScript loader instead of the build, so these tests need no pnpm build. The worker’s stage time limits are lowered to 10 seconds, so the wait for indexing (INDEXING_WAIT_MS in testing/helpers.ts) is bounded by 1 s + 2 × (10 s + 10 s) = 41 s: the drain already running at commit, one poll interval, and the drain that takes the mark. That is less than half of the 2-minute lease.

Running it locally

Run every command from examples/miomock/api. Start PostgreSQL and OpenSearch. This OpenSearch runs with the security plugin disabled and is for local development only:
Build the project, then run the migrations, which include the package schema. The CLI reads the built project, so both sonamu migrate and the sonamu search commands need the build:
Create the first target and cut over:
Start the server with search and the worker enabled:
The order matters. Marking on a server with search enabled fails closed: without a registered target, a project save transaction does not commit (SearchNotConfigured or SearchNoWriteTarget). Create the first target with init before you enable search. With more than 1,000 projects (maxPendingDocuments in RECOMMENDED_CUTOVER), init’s cutover can be refused because of the backlog; then drain it with sonamu search drain --execute --confirm, or start the server with the worker, and run sonamu search cutover --execute --confirm. Once the server is up, sign in to the web app and open /admin/projects/search.

Next steps

Overview

Guarantees and moving parts

Index administration

The rules of the administrative operations the CLI calls