SirannonClient connects to one Sirannon server over HTTP or WebSocket. The server executes database operations over either transport, while only the WebSocket transport delivers change subscriptions and live queries. A Python or Go program connects through the Python client or the Go client.
The complete client.ts program below connects to the authenticated server.ts from the server guide. Start that server first, then give this Node.js process the same SIRANNON_TOKEN.
Connect and read
Pass an http:// or https:// base URL for either transport, because the client derives the WebSocket URL when it needs one. operationRef declares the identifier of a registered operation together with the types of its arguments and its rows.
import { type LiveUpdate, operationRef } from '@delali/sirannon-db'
import { SirannonClient } from '@delali/sirannon-db/client'
interface Order {
id: number
total: number
status: string
}
const token = process.env.SIRANNON_TOKEN
if (!token) throw new Error('Set SIRANNON_TOKEN to the server operator credential')
const ordersByStatus = operationRef<{ status: string }, Order>('ordersByStatus')
const placeOrder = operationRef<{ total: number }>('placeOrder')
const client = new SirannonClient('http://127.0.0.1:9876', {
transport: 'websocket',
headers: { Authorization: `Bearer ${token}` },
autoReconnect: true,
})
try {
const db = client.database('orders')
const before = await db.query(ordersByStatus, { status: 'pending' })
console.log('Pending orders before the write:', before.length)
const pending = await db.live(ordersByStatus, { status: 'pending' })
const delivered = Promise.withResolvers<void>()
const deadline = setTimeout((): void => delivered.reject(new Error('Live delivery exceeded the example deadline')), 5000)
const unsubscribe = pending.subscribe((_update: LiveUpdate<Order>): void => {
const state = pending.getState()
if (state.status === 'error') delivered.reject(state.error)
if (state.status === 'ready' && state.rows.length > before.length) delivered.resolve()
})
try {
console.log(await db.execute(placeOrder, { total: 2400 }))
await delivered.promise
console.log(pending.getState())
} finally {
clearTimeout(deadline)
unsubscribe()
await pending.close()
}
} finally {
client.close()
}The values that the program prints depend on the orders that the server stores, so this example has no fixed result panel. query returns an array, so check its first element for undefined when you expect one row.
When you declare a reference by hand, TypeScript checks your code against its types, although the client validates none of the rows at runtime. The code generator derives the references and the registry digest from the definitions on the server.
Send a write
execute(operation, args) calls a registered write. The server executes the statements of that write in one transaction and returns one result for each statement.
The registry refuses a missing argument with MISSING_ARGUMENT and an undeclared argument with ARGUMENT_NOT_ALLOWED. The server fills an argument that you declare through fromIdentity from its authenticated context, so only the server sets that argument.
When the client loses the reply to a disconnect, it cannot learn whether the write committed. Give each write an idempotency key, or make the write idempotent, when a caller can retry after a disconnect.
Subscribe to changes
await db.on(table).subscribe(callback, options?) opens a feed of the row changes on a table. Call unsubscribe() on the returned handle to close that feed.
An ordinary table subscription can deliver rows that no registered read returns. The server therefore accepts such a subscription only with acceptSql: true or with an onBeforeSubscribe hook that authorises the table and the filter. The server in the linked guide accepts no SQL, so the client.ts program subscribes through a registered live query.
Use SubscribeOptions.onError to receive failures of your callback, malformed change frames, and a refusal from the server while the client restores the subscription. When the server refuses during that restore, the client reports the error and ends the subscription. After a temporary connection failure, however, the client can reconnect.
The client calls onReset when the server can't replay the stream from the earlier cursor, so reload the state of your application before you treat the stream that continues as current. Subscription resumption explains durable cursors and epochs.
Follow a result as its rows change
db.live(operation, args) opens a registered read as a live query and returns a handle with getState(), subscribe(), and close().
The server sends the first rows and then sends each change as a splice. During a disconnect, the client serves the earlier rows and reports that those rows can be out of date. When the client reconnects, it opens the registered read again and replaces those rows with the server's fresh answer.
After a registry mismatch, the client refreshes the capabilities once and tries again, so the query fails only when the server refuses it a second time. The client serves live queries and row subscriptions only over the WebSocket transport, so over HTTP they fail with TRANSPORT_ERROR.
Send a statement
A server with acceptSql: true also answers the client methods query(sql, params), execute(sql, params), transaction(statements), batch(sql, paramsBatch), load(sql, paramsBatch, durability?, checkpoint?), and queryWithColumns(sql, params?, options?).
transaction(statements) sends a fixed array of statements in one request, so the server locks its writer for the length of that one request only. The server executes a batch as one statement with several parameter sets in one transaction.
The client caches the answer of GET /capabilities. When that answer lists no query.sql, the client refuses SQL with SQL_NOT_ACCEPTED before it sends the statement. An older server answers NOT_FOUND from its capability route, in which case the client sends the SQL and that server accepts or refuses it. Once you close the client, it aborts any capability fetch in progress and refuses later requests.
Bind parameters separately from the SQL, because the client encodes large integers and BLOBs in parameters so that both transports deliver them exactly, as value encoding explains.
Read column details over the network
queryWithColumns(sql, params?, options?) returns the details of every result column, with each row as an array of values in column order. When a join selects both a.id and b.id, each row therefore contains both values. Pass maxRows or maxBytes in the options when someone else writes the statement, such as a person who types SQL into a console, so that the server sends no more rows or bytes in one answer than your process can take. The options can also include a readConcern.
Each entry of columns has name, declaredType, table, column, and database. The server sets a field to null when the column comes from an expression or when the server's driver can't report that field, as Queries and transactions explains. Set each limit to a whole number from 0 to 2^53-1, because the client refuses any other value with INVALID_ARGUMENT before it sends the request. The client refuses an answer with INVALID_RESPONSE when a row is wider or narrower than its columns, or when a value is an integer outside the 64-bit range of SQLite or a malformed BLOB. A TopologyAwareClient routes the read in the same way that it routes every other read.
Checkpoint the database on the server
db.checkpoint() asks the server to checkpoint the write-ahead log and returns busy, framesInLog, framesCheckpointed, and emptied. A busy value of true means that another connection, such as a reader with an open transaction, stopped the checkpoint. The client sends the checkpoint over HTTP whichever transport you choose, while the topology transport sends it to the primary. The server serves the route whatever acceptSql is set to, so the server's authenticate hook has to limit it to operators, as the server guide shows.
On a database with backups, the server answers only after a turn of the backup cycle ends. Because that turn can include a full copy, the wait can last as long as that copy takes. The client applies requestTimeout to the checkpoint on both transports, so raise it when a full copy of the database takes longer than the timeout.
Import a large dataset
loadAll(sql, rows, options?) accepts an iterable or an asynchronous iterable and sends the rows in batches, one after another. It returns the totals of rowsLoaded and changes.
The server restores the configured durability after each batch before it replies. With the final batch, the client asks for a checkpoint, which the server skips on a database with continuous backups. Every encoded batch has to fit within maxBodyBytes. Bulk loading includes a complete import example and the durability policies that a load can use.
Ask for a fresher read
A client for a single server can pass { readConcern: { level: 'linearizable' } }, or another concern that the server supports, as the options argument of a query. A replication execution target enforces that concern, while Sirannon gives no distributed guarantee for a plain core database.
Topology-aware routing chooses a node through one concern for the whole client. It refuses a concern on a single call with INVALID_ARGUMENT so that every call gets the one level that the routing enforces.
When the server refuses your credential
The server closes a refused WebSocket upgrade with 4401 for a caller without credentials and with 4403 for a caller without permission. The client turns these codes into UNAUTHORIZED and FORBIDDEN. It treats every application code from 4000 to 4099, these two included, as a final refusal of the credential.
After such a refusal, the client opens no new connection and fails every later call with the refusal. Get a fresh credential and construct a new client to connect again. After any other disconnect, the client reconnects while autoReconnect is on.
The server closes a connection with 4290 when its outbound buffer passes the limit, and with 1001 during a graceful shutdown. The client treats neither code as a refusal of the credential.
Client options
| Option | Default | Behaviour |
|---|---|---|
transport | 'websocket' | The client also accepts 'http'. |
headers | none | The client adds these headers to HTTP requests and, on Node.js and Bun, to WebSocket upgrades. |
webSocketProtocols | none | The client offers a string or an array of credential subprotocols after sirannon.v1. |
autoReconnect | true | The WebSocket transport reconnects after a temporary disconnect. |
reconnectInterval | 1000 | The value sets the reconnect delay in milliseconds. |
requestTimeout | 30000 | The value sets, in milliseconds, how long the client waits for each WebSocket reply and for a checkpoint on either transport. A value of zero removes the deadline. |
A browser WebSocket has no API for custom headers, so a browser client with headers and no webSocketProtocols fails at construction with INVALID_ARGUMENT. Send an HTTP bearer credential through the headers and a short-lived ticket through the subprotocols, as security explains.
Each subprotocol has to be a distinct, non-empty HTTP token, so a space, a comma, or a quotation mark fails validation. Standard base64 can include / and =, so encode a ticket in base64url without padding. An error about an invalid header or subprotocol gives the position of the entry without repeating its credential.
TopologyAwareClient takes the routing options, such as endpoints and readPreference, and fails at construction with INVALID_ARGUMENT when one of them is invalid. Leave the topology entry point out of browser bundles.
client.close() closes the transport of every database and cancels the capability checks, after which every later call fails with TRANSPORT_ERROR. Handle errors through the exported RemoteError class and its code. Leave credentials and internal error details out of the messages that your users see.