The server exposes a Sirannon registry through HTTP and WebSocket. Registered operations define the SQL that callers can execute, while authentication identifies each caller before database routes and WebSocket upgrades.
Start a server
Install the optional uWebSockets.js peer through getting started. listen() fails with SERVER_DEPENDENCY_MISSING if it cannot load that peer.
The complete server.ts example creates an orders table before serving its registered read and write. Set SIRANNON_TOKEN to a secret bearer credential. This example serves one operator and one database on loopback; add application-specific database authorisation before serving several accounts.
import { timingSafeEqual } from 'node:crypto'
import { mkdir } from 'node:fs/promises'
import { type RequestContext, RequestDeniedError, Sirannon } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
import { createServer } from '@delali/sirannon-db/server'
const token = process.env.SIRANNON_TOKEN
if (!token) throw new Error('Set SIRANNON_TOKEN to a secret operator credential')
const expected = Buffer.from(`Bearer ${token}`)
const authenticate = (context: RequestContext): { role: string } => {
const received = Buffer.from(context.headers.authorization ?? '')
if (received.length !== expected.length || !timingSafeEqual(received, expected)) {
throw new RequestDeniedError(401, 'UNAUTHORIZED', 'Operator credential required')
}
return { role: 'operator' }
}
await mkdir('./data', { recursive: true })
const sirannon = new Sirannon({ driver: betterSqlite3() })
const db = await sirannon.open('orders', './data/documented-orders.db')
await db.execute('CREATE TABLE IF NOT EXISTS orders (id INTEGER PRIMARY KEY, total INTEGER NOT NULL CHECK (total >= 0), status TEXT NOT NULL)')
await db.watch('orders')
const server = createServer(sirannon, {
host: '127.0.0.1',
port: 9876,
authenticate,
operations: {
orders: {
reads: {
ordersByStatus: {
args: ['status'],
columns: ['id', 'total', 'status'],
statement: ({ status }: Record<string, unknown>): { sql: string; params: unknown[] } => {
if (typeof status !== 'string') throw new RequestDeniedError(400, 'INVALID_ARGUMENT', 'A status string is required')
return { sql: 'SELECT id, total, status FROM orders WHERE status = ? ORDER BY id', params: [status] }
},
},
},
writes: {
placeOrder: {
args: ['total'],
statements: ({ total }: Record<string, unknown>): { sql: string; params: unknown[] }[] => {
if (typeof total !== 'number' || !Number.isSafeInteger(total) || total < 0) {
throw new RequestDeniedError(400, 'INVALID_ARGUMENT', 'A non-negative safe integer total is required')
}
return [{ sql: 'INSERT INTO orders (total, status) VALUES (?, ?)', params: [total, 'pending'] }]
},
},
},
},
},
})
const close = async (): Promise<void> => {
try {
await server.close()
} finally {
await sirannon.shutdown()
}
}
let stopping: Promise<void> | undefined
const stop = (): Promise<void> => {
stopping ??= close()
return stopping
}
const handleSignal = (): void => {
stop().catch((error: unknown): void => {
console.error(error)
process.exitCode = 1
})
}
process.once('SIGINT', handleSignal)
process.once('SIGTERM', handleSignal)
try {
await server.listen()
} catch (error: unknown) {
await stop()
throw error
}The defaults are host 127.0.0.1, port 9876, and acceptSql: false. Bind an externally reachable address only with the authentication, authorisation, and TLS setup described in security.
Register what callers may run
The example serves ordersByStatus and placeOrder under the orders database ID. Callers send operation identifiers and arguments; the server constructs and parameterises the SQL.
sharedOperations can register a common set for every database, including databases opened later. A database-specific operation takes precedence over a shared operation with the same identifier. Registered operations covers identity-derived arguments and operation authorisation.
Choose a port and identify the caller
authenticate receives a RequestContext with the method, path, headers, and database ID where applicable. Throw RequestDeniedError(status, code, message) to refuse a request. Returning a refusal-shaped object fails with HOOK_ERROR; an identity return value grants access to the next checks.
An unexpected authentication error produces a sanitised HOOK_ERROR. Health and capability endpoints skip authentication. Authorise database IDs before a lifecycle resolver can open a file for them.
Node clients can send headers during a WebSocket upgrade. Browser clients need a short-lived subprotocol credential; see WebSocket authentication. A 401 or 403 upgrade refusal closes with 4401 or 4403 and includes the structured refusal in the close reason.
Cap the request size
maxBodyBytes caps HTTP bodies and WebSocket messages. It defaults to 1,048,576 bytes and must be a positive integer no larger than 4,294,967,295. Invalid values fail with INVALID_MAX_BODY_BYTES.
An oversized request fails with PAYLOAD_TOO_LARGE; an oversized WebSocket message closes with 1009. Size each load batch below this limit, including JSON overhead.
Bound the WebSocket buffer
maxWebSocketBackpressureBytes caps buffered outbound data per connection. Its default is the larger of 16,777,216 bytes and maxBodyBytes. An explicit bound must be at least maxBodyBytes and no larger than 4,294,967,295; invalid values fail with INVALID_WS_BACKPRESSURE.
If a frame would exceed that buffer bound, the server closes the connection with 4290. A reconnecting SDK client can restore its subscriptions. The client must treat an outstanding write without a reply as uncertain, because a disconnected response does not establish whether the write committed.
Four write shapes
- A registered write executes its predefined statements in one server transaction and returns one result per statement.
- A SQL transaction executes a fixed array of different statements atomically.
- A batch executes one statement with several parameter sets atomically.
- A load imports rows under a temporary durability policy and restores the configured policy afterwards.
The last three forms require acceptSql: true. A load defaults to reduced durability; bulk loading explains the power-loss trade-off and restoration errors.
Turn SQL back on
acceptSql: true enables the five SQL routes and their WebSocket equivalents. Keep this permission for trusted callers who need to compose SQL. It also permits ordinary table subscriptions when the registry has no onBeforeSubscribe guard.
With SQL disabled, a table subscription requires onBeforeSubscribe. A registered live query remains subject to its registered read's checks. GET /capabilities announces query.sql only when the server accepts SQL.
Serve the backup routes
Backup routes can trigger capture, inspect status and chains, verify stored pieces, calculate safe deletions, and restore a database. Reserve every backup route for an operator through authenticate, using the request method and path. Authentication without route authorisation permits every accepted identity to reach these operations.
POST /db/:id/backup returns 202 before capture finishes. Poll GET /db/:id/backup for completion. One additional turn can queue behind a current turn; further triggers join that queued turn.
A database without configured backups returns BACKUP_UNSUPPORTED on backup operations. A missing database returns DATABASE_NOT_FOUND. Destination failures use BACKUP_DESTINATION_ERROR, while an incomplete chain uses BACKUP_CHAIN_BROKEN.
Restore a database over the network
acceptBackupRestore defaults to false. Enabling it requires authentication, or construction fails with INVALID_BACKUP_RESTORE. While disabled, the restore route returns BACKUP_RESTORE_NOT_ACCEPTED before database lookup.
The request accepts moment in epoch milliseconds and batchSize from 1 to 4,096, defaulting to 16. Omitting moment selects the newest available backup. Poll the restore status after the 202 response.
The server closes the database and captures its log before rebuilding. It discards earlier cycle state so that the reopened database starts a fresh full chain. During replacement, the registry has no database under that ID. The restore status route remains available because it reads the server's operation record.
A second concurrent restore fails with BACKUP_RESTORE_IN_PROGRESS. After rebuilding successfully, failure to reopen reports state: 'done' with a separate reopenError. The restored data is already on disk; correct the reopen failure before serving it again. A failed close leaves the ID closed so that a second runtime cannot open over connections that may remain active.
For an encrypted database, the server restores with its configured key loader. Retain the key required by the chosen chain. Restoring backups explains offline restore and encryption explains key retention.
Change encryption over the network
acceptEncryptionChange defaults to false. Enabling it requires both authenticate and encryptionKeys, or construction fails with INVALID_ENCRYPTION_CHANGE.
An authorised caller posts { keyRef } to /db/:id/encryption. A string reference contains 1 to 256 characters; null requests plaintext. The server resolves a string through encryptionKeys(databaseId, keyRef), so raw key bytes stay outside the request.
The route returns 202, and its matching GET reports progress. Authorise both routes for operators separately from data access. A disabled change route fails with ENCRYPTION_CHANGE_NOT_ACCEPTED.
A completed file swap reports done even if reopening fails. Check reopenError and retain the destination key. Encryption describes status fields, cancellation, crash recovery, and replication restrictions.
HTTP routes
The server URL-decodes database IDs and operation identifiers. Every database route passes through authentication. SQL, device sync, restore, and encryption changes also require their respective options.
| Method | Path | Description |
|---|---|---|
POST | /db/:id/query | Executes a SELECT and returns { rows }. Needs acceptSql. |
POST | /db/:id/query/:name | Runs the registered read of that name and returns { rows }. |
POST | /db/:id/execute | Executes a mutation and returns { changes, lastInsertRowId }. Needs acceptSql. |
POST | /db/:id/execute/:name | Runs the registered write of that name in one transaction and returns { results }. |
POST | /db/:id/transaction | Executes many statements atomically in one transaction and returns { results }. Needs acceptSql. |
POST | /db/:id/batch | Applies one statement over many parameter sets in one transaction and returns { results }. Needs acceptSql. |
POST | /db/:id/load | Bulk-loads rows with relaxed durability and returns { rowsLoaded, changes }. Needs acceptSql. |
POST | /db/:id/changes | Applies a device sync change batch and returns { applied, skipped, conflicts }. Needs acceptDeviceSync. |
POST | /db/:id/migrations | Lists the applied migrations, attaching the up SQL for the versions that a device lacks. Needs acceptDeviceSync. |
POST | /db/:id/snapshot | Returns a snapshot manifest with the schema, per-table row counts, and migration history. Needs acceptDeviceSync. |
POST | /db/:id/snapshot/page | Returns one keyset-paginated page of a table's rows, with a checksum that the device verifies. Needs acceptDeviceSync. |
POST | /db/:id/backup | Takes one turn of the backup cycle and answers 202 without waiting for it. |
GET | /db/:id/backup | Reports what the cycle is doing and what its recent turns produced. |
GET | /db/:id/backup/chain | Lists every chain the backup destination holds, newest first. |
POST | /db/:id/backup/verify | Reads one stored backup back and checks it against its record. Takes { name }. |
POST | /db/:id/backup/safe-to-delete | Lists the records no restore still needs. Takes an optional { restorableFrom }. |
POST | /db/:id/backup/restore | Rebuilds the database from a moment and answers 202. Needs acceptBackupRestore. |
GET | /db/:id/backup/restore | Reports how that restore went. |
GET | /db/:id/cluster | Reports routing and authority metadata, and returns 404 when no getClusterStatus is configured or authorizeClusterStatus refuses. |
POST | /db/:id/encryption | Starts an encryption change through a key reference. Needs acceptEncryptionChange. |
GET | /db/:id/encryption | Reports encryption status and change progress. |
GET | /capabilities | Lists the capabilities that the server announces and the registry digest. The sync. capabilities appear only once you set acceptDeviceSync. |
GET | /health | Reports liveness. |
GET | /health/ready | Reports readiness with per-database status. |
A read can supply readConcern, and a write can supply writeConcern. The replication execution target enforces these options. A route that does not exist returns NOT_FOUND.
WebSocket protocol
Connect to ws://host:port/db/:id for local development, or wss:// with TLS. Every request supplies a client-selected id and a type; replies repeat that ID.
If offering subprotocols, include sirannon.v1. The server selects that identifier and rejects an incompatible offer with UNSUPPORTED_SUBPROTOCOL. Selecting the public identifier keeps a credential subprotocol out of the upgrade response.
Inbound type | Fields | Reply |
|---|---|---|
query | sql, params?, readConcern? | { type: 'result', data: { rows } } |
query | name, args?, readConcern? | { type: 'result', data: { rows } } |
execute | sql, params? | { type: 'result', data: { changes, lastInsertRowId } } |
execute | name, args?, writeConcern? | { type: 'result', data: { results } } |
transaction | statements, writeConcern? | { type: 'result', data: { results } } |
batch | sql, paramsBatch, writeConcern? | { type: 'result', data: { results } } |
load | sql, paramsBatch, durability?, checkpoint? | { type: 'result', data: { rowsLoaded, changes } } |
subscribe | table or tables, filter?, sinceSeq?, epoch?, deviceId?, schemaVersion?, stagedStream? | { type: 'subscribed', seq, epoch, resync?, maxUnacknowledgedChanges? }, then change or changes events |
subscribe | name, args?, registryDigest? | { type: 'subscribed', rows }, then live messages |
unsubscribe | none | { type: 'unsubscribed' } |
ack | deviceId, seq | { type: 'result', data: { acked: true, seq } } |
A change frame contains one event. A staged device stream can receive a packed changes frame containing ordered events. live frames contain splices, replacement rows, or a revalidation notice. error frames contain a code and message.
A tables subscription accepts up to 500 table identifiers and requires a device ID. Device subscriptions and acknowledgements require acceptDeviceSync. An acknowledgement for a device absent from that connection fails with DEVICE_NOT_SUBSCRIBED.
Sequence numbers use decimal strings. Subscription resumption covers cursor validation, while device sync covers staged transactions, acknowledgement windows, and cursor expiry.
The server accepts a complete transaction per request. It provides no interactive network transaction that keeps the writer locked between client messages.
Stop after outstanding requests finish
Await server.close() before sirannon.shutdown(). The server stops listening and stops subscriptions immediately. Requests already executing can reply before the server closes their connections.
The default close deadline is 30,000 milliseconds. server.close({ timeoutMs }) accepts an integer from 0 to 2,147,483,647; zero ends connections immediately. Invalid values fail with INVALID_CLOSE_TIMEOUT.
A WebSocket closes with 1001 after its requests reply and its outbound buffer empties. At the deadline, the server ends remaining connections. New HTTP work on an existing connection loses that connection, while new WebSocket requests receive HANDLER_CLOSED. Uploads whose bodies are incomplete end immediately.
With replication, configure resolveExecutionTarget, getReplicationStatus, getClusterStatus, and authorizeClusterStatus as coordinator failover shows. Readiness checks use /health/ready; liveness checks use /health.