Networked access

Registered operations

Define server-side SQL, derive ownership arguments from authentication, and call reads and writes through typed references.

Registered operations let a client call a predefined read or write by its identifier. The server builds the SQL and binds the declared arguments. The server accepts SQL from the network only when the operator sets acceptSql: true.

Define a read

The statement function of a read returns one SQL statement and its parameters. args lists the values that a caller has to supply. columns lists the identifiers of the returned columns for code generation, and Sirannon checks none of their types at runtime.

The complete operations.ts file limits both reads to the rows of the authenticated owner. It also defines a write that inserts an order and increments a counter in one transaction.

operations.ts
import { type OperationArguments, type OperationRegistry, type OperationStatement, RequestDeniedError } from '@delali/sirannon-db'
 
export interface Identity {
  userId: string
}
 
export const operations: OperationRegistry<Identity> = {
  orders: {
    reads: {
      ordersByStatus: {
        args: ['status'],
        fromIdentity: { ownerId: 'userId' },
        columns: ['id', 'total', 'status'],
        statement: ({ status, ownerId }: OperationArguments): OperationStatement => {
          if (typeof status !== 'string') throw new RequestDeniedError(400, 'INVALID_ARGUMENT', 'A status string is required')
          return {
            sql: 'SELECT id, total, status FROM orders WHERE owner_id = ? AND status = ? ORDER BY id',
            params: [ownerId, status],
          }
        },
      },
      myOrders: {
        fromIdentity: { ownerId: 'userId' },
        columns: ['id', 'total', 'status'],
        statement: ({ ownerId }: OperationArguments): OperationStatement => ({
          sql: 'SELECT id, total, status FROM orders WHERE owner_id = ? ORDER BY id',
          params: [ownerId],
        }),
      },
    },
    writes: {
      placeOrder: {
        args: ['total'],
        fromIdentity: { ownerId: 'userId' },
        statements: ({ total, ownerId }: OperationArguments): OperationStatement[] => {
          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 (owner_id, total, status) VALUES (?, ?, ?)', params: [ownerId, total, 'pending'] },
            { sql: 'UPDATE counters SET orders = orders + 1 WHERE id = 1' },
          ]
        },
      },
    },
  },
}

A request that leaves out a declared argument fails with MISSING_ARGUMENT, while a request with an undeclared argument fails with ARGUMENT_NOT_ALLOWED. These checks confirm that each argument is present but leave its type unchecked, so validate each value inside the operation, as ordersByStatus and placeOrder do.

A read without columns can derive them from its statement only when it takes no caller or identity arguments. For any other read, the generated code types the row as an open record.

Add a write

The statements function of a write returns one statement or an array. The server executes the array in one transaction and returns one result for each statement, in order. When the counter update fails, SQLite rolls the order insert back as well.

The insert in the example lets SQLite allocate the ID. When the client receives no reply to a write, check the orders before the caller sends the write again, because a retry can insert a second order. Give each write an operation ID from your application when automatic retries have to be idempotent.

Fill an argument from the caller's identity

fromIdentity: { ownerId: 'userId' } takes ownerId from the identity that authenticate returns. A caller that supplies ownerId receives ARGUMENT_NOT_ALLOWED, so only the server sets that argument. When the identity lacks the field, the call fails with IDENTITY_REQUIRED.

OperationRegistry<Identity> checks the identity field names at compile time. The SQL has to use the derived owner in its condition as well, because a query without that condition can return the rows of another account to an authenticated caller.

Serve the registry

Save the complete server.ts beside operations.ts, and provide a secret SIRANNON_TOKEN for the application account of the example. The server creates its tables before it serves the registry. It leaves the SQL, device sync, backup restore, and encryption change routes off, and its authenticate hook refuses the backup, encryption, and checkpoint routes to the application credential.

server.ts
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'
import { type Identity, operations } from './operations.js'
 
const token = process.env.SIRANNON_TOKEN
if (!token) throw new Error('Set SIRANNON_TOKEN to a secret application credential')
const expected = Buffer.from(`Bearer ${token}`)
 
await mkdir('./data', { recursive: true })
const sirannon = new Sirannon({ driver: betterSqlite3() })
const db = await sirannon.open('orders', './data/registered-orders.db')
await db.execute('CREATE TABLE IF NOT EXISTS orders (id INTEGER PRIMARY KEY, owner_id TEXT NOT NULL, total INTEGER NOT NULL, status TEXT NOT NULL)')
await db.execute('CREATE TABLE IF NOT EXISTS counters (id INTEGER PRIMARY KEY CHECK (id = 1), orders INTEGER NOT NULL)')
await db.executeBatch('INSERT OR IGNORE INTO orders (id, owner_id, total, status) VALUES (?, ?, ?, ?)', [
  [1, 'u_buyer', 4999, 'pending'],
  [2, 'u_other_buyer', 12500, 'pending'],
  [3, 'u_buyer', 890, 'shipped'],
])
await db.execute('INSERT OR IGNORE INTO counters (id, orders) VALUES (1, 3)')
 
const server = createServer<Identity>(sirannon, {
  host: '127.0.0.1',
  port: 9876,
  operations,
  authenticate: (context: RequestContext): Identity => {
    const received = Buffer.from(context.headers.authorization ?? '')
    if (received.length !== expected.length || !timingSafeEqual(received, expected)) {
      throw new RequestDeniedError(401, 'UNAUTHORIZED', 'Sign in to access orders')
    }
    const resource = context.path.split('/')[3]
    if (context.databaseId !== 'orders' || resource === 'backup' || resource === 'encryption' || resource === 'checkpoint') {
      throw new RequestDeniedError(403, 'FORBIDDEN', 'Route access refused')
    }
    return { userId: 'u_buyer' }
  },
})
 
const stop = async (): Promise<void> => {
  try {
    await server.close()
  } finally {
    await sirannon.shutdown()
  }
}
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 database key in the registry has to match the ID of the opened database, because the server looks each operation up under that ID and answers UNKNOWN_QUERY for any other.

For a deployed service, connect authenticate to the session system of your application, and authorise the database before a lifecycle resolver opens it. Security covers row subscriptions, snapshots, operator routes, and browser credentials.

Call an operation by name

Both client transports accept an operationRef. A plain string that you pass to query or execute is SQL, so pass a reference to call a registered operation.

Start the server above, then execute this complete client.ts file with the same token.

client.ts
import { 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 application credential')
 
const ordersByStatus = operationRef<{ status: string }, Order>('ordersByStatus')
const myOrders = operationRef<Record<string, never>, Order>('myOrders')
const placeOrder = operationRef<{ total: number }>('placeOrder')
const client = new SirannonClient('http://127.0.0.1:9876', {
  transport: 'http',
  headers: { Authorization: `Bearer ${token}` },
})
 
try {
  const db = client.database('orders')
  console.log(await db.query(ordersByStatus, { status: 'pending' }))
  console.log(await db.execute(placeOrder, { total: 2400 }))
  console.log(await db.query(myOrders, {}))
} finally {
  client.close()
}

Both reads return only the rows of u_buyer. Each execution adds an order, so this example has no fixed result panel. Code generation derives the references from the registry.

Reach an operation over HTTP or WebSocket

Over HTTP, a client sends a read to POST /db/:id/query/:name and a write to POST /db/:id/execute/:name, with args and an optional read or write concern in the body.

A WebSocket request contains type: 'query' or type: 'execute', a request ID, the name of the operation, and its args. A subscription to a registered read opens a live query.

The server fills the identity arguments from the identity that authenticate returns for the request or for the WebSocket upgrade. Keep credentials short-lived, and build a new client when its credential expires.

Announce what the server serves

GET /capabilities lists query.named and the registry digest when the server registers operations. It adds query.sql when the server accepts SQL, and the sync. capabilities when the server serves device sync. The server answers this route without authentication.

The digest covers the database IDs, the kinds and identifiers of the operations, and their declared caller and identity arguments, including those of shared operations. A change to the SQL of a statement alone leaves the digest unchanged.

A live-query subscription that sends a digest other than the server's fails with REGISTRY_MISMATCH. The SDK fetches the capabilities again and retries once, then reports a second refusal to your code. Deploy a registry change together with the client code that you generate from it.

Serve the same operations on every database

sharedOperations defines a common set for every database, including a file that the registry opens after startup. When both sets define the same identifier, the operation of the database takes precedence.

Shared operations contains the complete tenant resolver, schema setup, authenticated server, and client example. That example authorises the database ID before it resolves the file of a customer.

What each refusal means

CodeHTTPMeaning
UNKNOWN_QUERY404The database and shared sets contain no matching operation.
MISSING_ARGUMENT400The request leaves out a declared argument.
ARGUMENT_NOT_ALLOWED400The request includes an undeclared argument or one that the server fills from the identity.
IDENTITY_REQUIRED401The identity lacks a field that the operation fills from it.
REGISTRY_MISMATCHWebSocket onlyThe digest that a live query sends differs from the digest of the server.
SQL_NOT_ACCEPTED403The server accepts SQL over the network only with acceptSql: true.

Error codes covers the other refusals and worker failures.