The server makes a Sirannon registry available over HTTP and WebSocket. Registered operations define the SQL that callers can execute. Your authenticate hook identifies each caller before the server serves a database route or accepts a WebSocket upgrade.
Start a server
Install the optional uWebSockets.js peer as getting started shows, because listen() fails with SERVER_DEPENDENCY_MISSING when it can't load that peer.
The complete server.ts program below creates an orders table before it serves one registered read and one registered write. Set SIRANNON_TOKEN to a secret bearer credential before you start it. The program serves one operator and one database on loopback, so add authorisation for each database before you serve 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 server binds host 127.0.0.1 and port 9876 with acceptSql: false by default. Bind an address that other machines can reach only once you have the authentication, authorisation, and TLS that security describes.
Register the operations that callers can send
The program serves ordersByStatus and placeOrder under the orders database ID. When a caller sends the identifier of an operation with its arguments, the server builds the SQL and binds the arguments as parameters.
sharedOperations registers one set of operations for every database, including the databases that the registry opens later. An operation that you register for one database takes precedence over a shared operation with the same identifier. Registered operations explains the arguments that the server takes from the caller's identity and how to authorise each operation.
Identify the caller
authenticate receives a RequestContext with the method, the path, the headers, and the database ID where the route has one. Throw RequestDeniedError(status, code, message) to refuse a request. When the hook returns an identity, the server passes the request on to the next checks. A hook that returns an object shaped like a refusal fails with HOOK_ERROR.
When the hook throws an error that is not a RequestDeniedError, the server answers with a HOOK_ERROR that contains none of the details of that error. The server serves the health and capability routes without authentication. For every other route, authorise the database ID in the hook before a lifecycle resolver can open a file for that ID.
A Node.js client can send headers with a WebSocket upgrade, while a browser client has to send a short-lived credential in a subprotocol, as WebSocket authentication explains. When the server refuses an upgrade with 401 or 403, it closes the socket with 4401 or 4403 and a close reason that contains the structured refusal.
Cap the request size
maxBodyBytes caps each HTTP body and each WebSocket message at 1,048,576 bytes by default. Set it to a positive integer no larger than 4,294,967,295, because the server refuses any other value with INVALID_MAX_BODY_BYTES.
An HTTP request over the cap fails with PAYLOAD_TOO_LARGE, while the server closes a WebSocket with 1009 after a message over the cap. Size each load batch below this limit, counting the bytes that JSON adds.
Bound the WebSocket buffer
maxWebSocketBackpressureBytes caps the outbound data that the server buffers for each connection. By default, the cap is the larger of 16,777,216 bytes and maxBodyBytes. A cap that you set has to be at least maxBodyBytes and no larger than 4,294,967,295, because the server refuses any other value with INVALID_WS_BACKPRESSURE.
When a frame takes the buffer past that cap, the server closes the connection with 4290, after which a reconnecting client can restore its subscriptions. Treat a write that has no reply as uncertain, because the client learns the outcome of a write only from its reply.
A client can send messages as soon as the WebSocket handshake completes, while the server is opening the database of the connection. The server queues up to 256 of those messages, which together can contain up to four times maxBodyBytes of text. Once the database opens, the server answers the queued messages in order. When a client sends more than that before the database opens, the server closes the connection with 4290.
Four write shapes
- A registered write executes its predefined statements in one server transaction and returns one result for each 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 server accepts the last three shapes only with acceptSql: true. A load uses reduced durability by default. Bulk loading explains which writes a power cut can lose under that policy and which errors a failed restore of the policy raises.
Turn SQL back on
With acceptSql: true, the server serves the five SQL routes and the WebSocket messages that match them. Give this permission only to trusted callers who have to compose SQL. When the registry has no onBeforeSubscribe guard, a server with that setting also accepts subscriptions to ordinary tables.
The server sets no execution time limit on the SQL that a caller sends, so SQLite executes a slow statement from that caller until the statement finishes, while every caller that needs the same connection waits.
With SQL turned off, the server accepts a table subscription only through onBeforeSubscribe. It checks a registered live query in the same way as its registered read. The server lists query.sql in GET /capabilities only when it accepts SQL.
Read column details over HTTP
On a server with acceptSql: true, a query body can include "shape": "columns". The server then answers with the name, declaredType, table, column, and database of every result column, and with each row as an array in column order. It sets a field to null when SQLite or the driver doesn't report that field.
Because an array has one slot for each column, two columns that share a name, such as a.id and b.id in a join, both keep their values in that answer. For a body without shape, the server answers with { rows }, in which each row is an object, so the second id replaces the first. Send a body like this one to read both id columns of a join:
{ "sql": "SELECT a.id, b.id, a.label FROM items a JOIN items b ON a.parent = b.id", "shape": "columns", "maxRows": 500, "maxBytes": 1048576 }The body can also include maxRows and maxBytes, each a whole number from 0 to 2^53-1. The server then stops the read at whichever limit the rows reach first. It sets truncated to rows or bytes to show which limit stopped the read, or to null when the answer contains every row. It counts 8 bytes towards maxBytes for every value, to which it adds the length of the UTF-8 encoding of each TEXT value and the length of each BLOB, as Queries and transactions explains.
Over HTTP, the server answers 400 INVALID_REQUEST to a body that sets shape to any value other than columns, that sets a limit outside that range, or that sets either limit without shape. Over a WebSocket, it answers the same messages with an INVALID_MESSAGE error. The server also answers a WebSocket query message for a registered read with an INVALID_MESSAGE error when the message includes shape, maxRows, or maxBytes, because the server answers every registered read with { rows }.
Serve the backup routes
The backup routes start a capture, report the status and the chains, verify stored pieces, list the records that you can delete, and restore a database. Limit every backup route to operators by checking the method and the path in authenticate, because the server otherwise serves these routes to every identity that the hook accepts.
The server serves POST /db/:id/checkpoint whatever acceptSql is set to, so limit that route to operators in the same way. The server checkpoints the write-ahead log and answers { busy, framesInLog, framesCheckpointed, emptied } once the checkpoint ends. On a database with backups, the server answers only after a turn of the backup cycle ends, as Queries and transactions explains.
POST /db/:id/backup answers 202 before the capture finishes, so poll GET /db/:id/backup to learn when it completes. The cycle queues at most one turn behind the current one, so the server folds every later trigger into that queued turn.
The server leaves the path of the source database out of lastRun in the status. In lastError, the server replaces the message of an error from outside Sirannon with 'An unexpected error occurred'. It sends a fixed message for BACKUP_ERROR and BACKUP_DESTINATION_ERROR as well, because the messages of all those errors can include file paths on the server. Read the full error through db.backupStatus() in the server process.
The server answers every backup route with BACKUP_UNSUPPORTED for a database without backups and with DATABASE_NOT_FOUND for a missing database. Sirannon reports a failure at the destination with BACKUP_DESTINATION_ERROR and an incomplete chain with BACKUP_CHAIN_BROKEN.
Restore a database over the network
acceptBackupRestore is false by default. When you set it to true without authentication, createServer fails with INVALID_BACKUP_RESTORE. While the option is off, the restore route answers BACKUP_RESTORE_NOT_ACCEPTED before the server looks the database up.
The restore route accepts moment in epoch milliseconds and batchSize, a whole number from 1 to 4,096 that is 16 by default. Without moment, the server restores the newest backup that it can find. After the 202 answer, poll the status of the restore, in which the server leaves destPath, the path of the rebuilt file on the server, out of the report.
The server closes the database and captures its log before it rebuilds the file. It then discards the earlier state of the cycle so that the backup cycle starts a new full chain for the reopened database. During the replacement, the registry has no database under that ID, although the server answers the status route of the restore throughout from its record of the operation.
A second restore that starts during the first fails with BACKUP_RESTORE_IN_PROGRESS. When the rebuild succeeds and the reopen fails, the server reports state: 'done' with a separate reopenError, because the restored data is on disk. In that case, fix the cause of the reopen failure before you serve the database again. When the close fails, the server opens nothing under that ID so that a second runtime can't open the file over connections that may be active.
For an encrypted database, the server restores with the key loader that you configure, so store the key that encrypted the chosen chain. Restoring backups explains how to restore without the server. Encryption explains how to store keys.
Change encryption over the network
acceptEncryptionChange is false by default. When you set it to true without both authenticate and encryptionKeys, createServer fails with INVALID_ENCRYPTION_CHANGE.
An authorised caller posts { keyRef } to /db/:id/encryption. A string reference has 1 to 256 characters, while a keyRef of null changes the database to plaintext. The server resolves a string through encryptionKeys(databaseId, keyRef), so the request contains no raw key bytes.
The route answers 202, while the GET on the same path reports progress. Authorise both routes for operators, separately from your checks for data access. While the option is off, the server answers the change route with ENCRYPTION_CHANGE_NOT_ACCEPTED.
When the file swap completes, the status reports done even if the reopen fails, so check reopenError and store the destination key. Encryption describes the status fields, cancellation, recovery after a crash, and the limits under replication.
HTTP routes
The server URL-decodes database IDs and operation identifiers. It authenticates every request to a database route, while it serves the SQL, device sync, restore, and encryption routes only once you turn on their options.
| Method | Path | Description |
|---|---|---|
POST | /db/:id/query | The route executes a SELECT and returns { rows }, or { columns, rows, truncated } when the body sets shape to columns. It requires acceptSql. |
POST | /db/:id/query/:name | The route executes the registered read of that name and returns { rows }. |
POST | /db/:id/execute | The route executes a mutation and returns { changes, lastInsertRowId }. It requires acceptSql. |
POST | /db/:id/execute/:name | The route executes the registered write of that name in one transaction and returns { results }. |
POST | /db/:id/transaction | The route executes several statements in one transaction and returns { results }. It requires acceptSql. |
POST | /db/:id/batch | The route executes one statement with several parameter sets in one transaction and returns { results }. It requires acceptSql. |
POST | /db/:id/load | The route loads rows with relaxed durability and returns { rowsLoaded, changes }. It requires acceptSql. |
POST | /db/:id/changes | The route applies a device sync change batch and returns { applied, skipped, conflicts }. It requires acceptDeviceSync. |
POST | /db/:id/migrations | The route lists the applied migrations, with the up SQL of each version that a device lacks. It requires acceptDeviceSync. |
POST | /db/:id/snapshot | The route returns a snapshot manifest with the schema, the row count of each table, and the migration history. It requires acceptDeviceSync. |
POST | /db/:id/snapshot/page | The route returns one keyset-paginated page of the rows of a table, with a checksum that the device verifies. It requires acceptDeviceSync. |
POST | /db/:id/checkpoint | The route checkpoints the write-ahead log and returns { busy, framesInLog, framesCheckpointed, emptied } once the checkpoint ends. |
POST | /db/:id/backup | The route starts one turn of the backup cycle and answers 202 before the turn ends. |
GET | /db/:id/backup | The route reports what the cycle is doing and the results of its recent turns. |
GET | /db/:id/backup/chain | The route lists every chain at the backup destination, newest first. |
POST | /db/:id/backup/verify | The route reads one stored backup back and checks it against its record. It takes { name }. |
POST | /db/:id/backup/safe-to-delete | The route lists the records that no restore needs. It takes an optional { restorableFrom }. |
POST | /db/:id/backup/restore | The route rebuilds the database from a moment and answers 202. It requires acceptBackupRestore. |
GET | /db/:id/backup/restore | The route reports the state and the result of that restore. |
GET | /db/:id/cluster | The route reports routing and authority metadata. It returns 404 when you configure no getClusterStatus or when authorizeClusterStatus refuses. |
POST | /db/:id/encryption | The route starts an encryption change through a key reference. It requires acceptEncryptionChange. |
GET | /db/:id/encryption | The route reports the encryption status and the progress of a change. |
GET | /capabilities | The route lists the capabilities that the server announces and the registry digest. The list includes the sync. capabilities once you set acceptDeviceSync. |
GET | /health | The route reports liveness. |
GET | /health/ready | The route reports readiness with the status of each database. |
The replication execution target enforces the readConcern that a read can include and the writeConcern that a write can include. The server answers NOT_FOUND for a route that doesn't exist.
The package includes an OpenAPI 3.1 description of these routes as @delali/sirannon-db/openapi.json and an AsyncAPI 3.0 description of the WebSocket protocol as @delali/sirannon-db/asyncapi.json. Point an API client generator or a request-testing tool at either file. Sirannon generates the route methods of the Python client and the Go client from these files.
WebSocket protocol
Connect to ws://host:port/db/:id for local development, or to wss:// with TLS. Every request contains a type and an id that the client chooses and that the server repeats in its reply.
When the client offers subprotocols, it has to include sirannon.v1. The server selects that identifier and refuses an incompatible offer with UNSUPPORTED_SUBPROTOCOL. Because the server selects the public identifier, the upgrade response contains none of the credentials that the client sends in a subprotocol.
Inbound type | Fields | Reply |
|---|---|---|
query | sql, params?, readConcern? | { type: 'result', data: { rows } } |
query | sql, params?, readConcern?, shape: 'columns', maxRows?, maxBytes? | { type: 'result', data: { columns, rows, truncated } } |
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, while the server can send a staged device stream a packed changes frame with several events in order. A live frame contains splices, replacement rows, or a notice to revalidate. An error frame contains a code and a message.
The server accepts up to 500 table identifiers in a tables subscription, which has to include a device ID. It accepts device subscriptions and acknowledgements only with acceptDeviceSync. It refuses an acknowledgement with DEVICE_NOT_SUBSCRIBED when the device has no subscription on that connection.
The protocol encodes sequence numbers as decimal strings. Subscription resumption covers the checks on a cursor. Device sync covers staged transactions, acknowledgement windows, and expired cursors.
The server accepts one complete transaction in each request, so no network transaction locks the writer across two messages from a client.
Stop after outstanding requests finish
Await server.close() before sirannon.shutdown(). The server stops listening and ends its subscriptions at once, while it can answer the requests in progress before it closes their connections.
The server counts an HTTP answer as finished only once uWebSockets.js accepts the whole body for sending. server.close() therefore waits, up to its deadline, until the server sends every answer, on HTTP and WebSocket connections alike. When a read is in progress as the close starts, the client receives its whole answer, provided that the server sends that answer before the deadline.
The close deadline is 30,000 milliseconds by default. server.close({ timeoutMs }) accepts an integer from 0 to 2,147,483,647, where a value of zero makes the server end every connection at once. The server refuses any other value with INVALID_CLOSE_TIMEOUT.
The server closes a WebSocket with 1001 once it answers every request on that socket and empties its outbound buffer, while at the deadline it ends every connection that is open. When a client sends a new HTTP request on an existing connection during the close, the server closes that connection, while it answers a new WebSocket request with HANDLER_CLOSED. The server ends an upload with an incomplete body at once.
With replication, configure resolveExecutionTarget, getReplicationStatus, getClusterStatus, and authorizeClusterStatus as coordinator failover shows. Point readiness checks at /health/ready and liveness checks at /health.