Skip to main content
This page covers what you do once when you add the package to an application: install it, install the PostgreSQL schema, grant roles, create the OpenSearch client and the synchronization handle, and choose limits. Creating indexes is covered in Index administration.

Installation

Installing the package changes nothing in Sonamu; it acts only when the application creates handles and calls them. sonamu is an optional peer dependency, needed only for the /sonamu entry point.

Entry points

Installing the schema

Install the package’s tables by calling installSearchSchema 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_search unless you pass another name as { schema } in the second argument. public, information_schema, and names starting with pg_ 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 SearchSchemaVersionMismatch if 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 }. storeId is 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 the public 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_id and target rows as its source, but a different origin. To run a worker or remote administrative operations on a clone, adopt it with adoptCopiedStore first; until then they stop with SearchStoreMismatch (store-origin-changed). The search integration tests in the miomock walkthrough do this.

Rolling back

The example’s down 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 REVOKE by 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 SearchConfigurationError with details.reason duplicate-role. public and roles starting with pg_ are rejected (reserved-role).
When one login role needs two groups, for example an API server that marks and searches, create a separate non-login role per group, pass those to applySearchGrants, and make the application’s login role a member of both. Here chat_app is a login role created with the default INHERIT:
The example grants the four groups to four such roles:
search/administration.ts
The integration tests run this example as is against a real database. The same test file checks that a login role that is a member of both the capture and the query role can run 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.
The example’s client.ts also builds the query handle (createSonamuSearchQueries). A query handle checks at construction that its cursor signing secret is at least 32 bytes, so if SEARCH_CURSOR_SECRET is missing or short, importing client.ts throws SearchConfigurationError in every process that imports it. That includes the example’s administrative commands (administration.ts), which import it for SEARCH_NAMESPACE. Provide the secret wherever administrative commands, migration tooling, or scripts run, or move shared constants such as the namespace into a module that builds no query handle.

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() reads store_id once 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 } throws SearchTimeout.
  • The expectedStoreId option pins it from the start. Its value is the storeId that installSearchSchema returned. initialize() then only checks that the value it reads is the same, and throws SearchStoreMismatch if not.
Pin the identity before the server accepts requests. Sonamu calls 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
An API process whose worker runs in another process registers the hook in plugins.custom:
sonamu.api-only.config.ts
With 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. 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