Installation
sonamu is an optional peer dependency, needed only for the /sonamu entry point.
Entry points
Installing the schema
Install the package’s tables by callinginstallSearchSchema from an application migration. Nothing else creates the schema, server start included. Write the migration by hand in Sonamu’s Knex migration directory (src/migrations).
migrations/20260101000000_install_search_schema.ts
installSearchSchema:
- Uses the schema
sonamu_searchunless you pass another name as{ schema }in the second argument.public,information_schema, and names starting withpg_are rejected. - Is safe to run repeatedly. It skips versions already applied and applies every missing version in order in one call, so a migration written for version 1 installs the current version (2) on a fresh database.
- Records this database’s origin (system identifier, database OID, name) in the store, in the same transaction, on the call that applies version 2, a fresh installation included. The worker and remote administrative operations use this record to recognize copies. Running it again on a schema already at version 2 does not record the origin again; what this means for a copy made while the schema was at version 1 is in Recovery runbooks.
- Changes nothing and throws
SearchSchemaVersionMismatchif the installed schema is newer than the package, has a different checksum, or has a gap in its version history. - Runs inside a savepoint when the Knex it receives is a transaction (a Knex migration is), and on failure rolls back only the installation. That transaction must be READ COMMITTED.
- Returns
{ schema, applied, current, storeId }.storeIdis the store identity described below.
checkSearchSchema(knex) changes nothing; it only reads the installation status (ok, missing, behind, ahead, checksum-mismatch). Runtime handles do not run this check, so a missing schema shows up as SearchSchemaMissing when an actual statement fails.
Relation to Sonamu’s migrator
Sonamu’s migrator compares only tables that have entities and reads only thepublic schema. sonamu_search has no entities and lives outside public, so the migrator never generates a migration for it. Do not create foreign keys between application tables and package tables.
Test databases and fixtures:
- Test databases are cloned from a template database, and fixture sync copies the whole database with
pg_dump/pg_restore --no-acl. The package schema and its ledger rows travel with the copy; role grants (GRANT) do not. - A cloned database has the same
store_idand target rows as its source, but a different origin. To run a worker or remote administrative operations on a clone, adopt it withadoptCopiedStorefirst; until then they stop withSearchStoreMismatch(store-origin-changed). The search integration tests in the miomock walkthrough do this.
Rolling back
The example’sdown throws instead of dropping the schema, because the ledger’s revisions and the pending intents cannot be recovered once they are gone. If the schema really has to go, an operator drops it by hand (DROP SCHEMA sonamu_search CASCADE, as the error message says), and every target is then rebuilt from scratch.
Roles and grants
applySearchGrants(knex, { roles }) grants least privilege on the package schema to four role groups.
Every group also receives usage on the schema and read access to
schema_versions and store. No group can create objects in the schema or change schema_versions or store.
Rules of applySearchGrants:
- Run it as the schema owner (the role that ran the migration). In PostgreSQL, a GRANT from a role that is not the owner completes without an error and grants nothing.
- It only adds privileges and never revokes. To take a role out of a group, an operator runs
REVOKEby hand. - It runs only when the installed schema matches the package version exactly, and it runs in one transaction. If a role does not exist, it throws
SearchConfigurationError(SQLSTATE 42704) and changes nothing. - A role name may appear in one group only; the same role in two groups throws
SearchConfigurationErrorwithdetails.reasonduplicate-role.publicand roles starting withpg_are rejected (reserved-role).
applySearchGrants, and make the application’s login role a member of both. Here chat_app is a login role created with the default INHERIT:
search/administration.ts
markChanged and the catalog read, and is still refused writes to the worker tables. To review the GRANT statements without running them, render them with renderSearchGrantsSql(options).
applySearchGrants does not touch privileges outside the package schema. The worker role separately needs SELECT on the application tables its projections read.
Client
createSearchClient wraps an OpenSearch SDK client that the application creates. Query handles, the worker, and the administrative handle all take this wrapper. The same example module also creates the synchronization handle described in the next section.
search/client.ts
Configure authentication, such as AWS SigV4 signing, on the SDK client that
createClient returns; the package only sends requests through that client’s transport. Read credentials and signing keys from environment variables, not from code. checkConnection() checks the connection with GET / and, on failure, returns the error in its report instead of throwing.
Synchronization handle and store identity
createPostgresSynchronization creates the handle that records intents inside domain transactions (searchSynchronization above). createSonamuSynchronization wraps it for Sonamu’s transaction context (chatSearchSync).
In a Sonamu application, pass
resolveSonamuPrimary as getPrimaryDatabase. It returns DB.getDB("w") and throws SearchConfigurationError if that is a transaction, as it is in Sonamu test mode while a test transaction is open.
Store identity and initialize()
Installing the schema creates one store identity (store_id) in the store table. markChanged works only after the synchronization handle has pinned that identity. Before that, it throws SearchConfigurationError with details.reason store-identity-uninitialized and retryable true, and puts the transaction in a failed state, so the domain write does not commit.
The identity is never inferred from the caller’s transaction. Pin it in one of two ways:
initialize()readsstore_idonce from the configured primary and pins it. Calling it again is fine, concurrent calls share one read, and after a failure the next call reads again. Aborting the wait with{ signal }throwsSearchTimeout.- The
expectedStoreIdoption pins it from the start. Its value is thestoreIdthatinstallSearchSchemareturned.initialize()then only checks that the value it reads is the same, and throwsSearchStoreMismatchif not.
server.lifecycle.onStart after the server starts listening, so if you rely on createSearchLifecycle’s onStart to await initialize(), a write that arrives between listen and the end of initialization fails with the error above. Either await initialize() in a Fastify onReady hook, which finishes before listening starts and keeps the server from starting if it fails, or configure expectedStoreId in the deployment. The example’s startup.ts provides both; use createPinnedSearchSynchronization instead of searchSynchronization, never both.
search/startup.ts
plugins.custom:
sonamu.api-only.config.ts
createSearchLifecycle, add the same hook to close the gap right after listen; initialize() reads only once however often it is called. A process that only runs the worker never marks, so it needs no identity (Indexing worker).
Once pinned, the identity is checked on every markChanged: the database of the transaction it receives must carry the same identity, and a transaction from another database is refused with SearchStoreMismatch (store-mismatch). This keeps intents out of a database the worker does not read. When a copy is adopted and its store identity changes, processes that pinned the old identity are refused the same way, so restart them. Marking does not check the origin (copy detection), so marking continues on a copy that has not been adopted.
Recommended values
Required options have no defaults. Instead, the root entry point exports recommended values as constants. Spread a constant and override only what you need.
Values of
RECOMMENDED_WORKER_LIMITS and their reasons:
An application that writes out its own complete limits object must include
maxInFlightBytes, statementTimeoutMs, and fenceRenewIntervalMs; all three are required.
The values interlock. The relationships createIndexer checks are in the limits table of Indexing worker; the ones you must keep yourself when you change a value (workerBounds, read lifetimes, the admin lease, the stop deadline) are under “Relationships between values” in Operations.
Next steps
Search definitions
Projections, mappings, fingerprints
Transactional indexing
Marking changes together with domain writes