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, sosonamu.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
sonamu sync, which import the models, from failing (see the import warning in Setup).
The search definition
The definition is built withdefineSonamuSearch 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 callslifecycle.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
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
- Read the scope the caller may see now from the primary, just before the search.
- Search with that scope as a
termsfilter. A non-member sends an empty list so nothing matches; only an admin has no filter. - 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.
- 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.
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
web/src/routes/admin/projects/search.tsx
The administrative CLI
The administrative commands are the package’ssonamu 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
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.
initon 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--executeit prints the plan for a key without a target and the open build, and changes nothing.cutoverwithout--executeprints the blockers; with it, the package refuses while any remain.drainis for development and runs worker drains until one finds nothing to do.adopt-storeprints its next steps (restart-processes,resume,backfill,cutover) and the number of detached targets. Restart the processes, then create the new target withresume,backfillandcutover.- When a command is refused because the store binding does not match, the failure’s
hintnames both commands:sonamu search adopt-storeif this database is a copy or restore of another one,sonamu search confirm-ownershipif 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
src/search/testing/global-setup.ignore.ts) does the following:
- Starts an OpenSearch container (
MIOMOCK_OPENSEARCH_IMAGE,opensearchproject/opensearch:3.5.0by default). - Clones
miomock_testintomiomock_search_itwithCREATE DATABASE … TEMPLATE … STRATEGY FILE_COPYand installs the package schema.FILE_COPYis needed because the PostgreSQL 15+ default (WAL_LOG) does not copy PGroonga index files, and later writes toprojectswould fail. - 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. - Clones that database again into
miomock_search_it_copyand leaves it unadopted for the store binding tests. Teardown drops the cloned databases (including the namemiomock_search_it_copy_moved, which a test renames the copy to) and stops the container.
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 fromexamples/miomock/api.
Start PostgreSQL and OpenSearch. This OpenSearch runs with the security plugin disabled and is for local development only:
sonamu migrate and the sonamu search commands need the build:
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