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 request a predefined read or write by its identifier. The server constructs the SQL and binds the declared arguments. SQL from the network remains disabled unless the operator enables it separately.

Name a read

A read's statement returns one SQL statement and its parameters. args declares the values that a caller must supply. columns describes returned column identifiers for code generation; it does not validate their runtime types.

The complete operations.ts file scopes both reads to an authenticated owner. It also defines a write that inserts an order and increments a counter atomically.

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' },
          ]
        },
      },
    },
  },
}

Missing caller arguments fail with MISSING_ARGUMENT; undeclared arguments fail with ARGUMENT_NOT_ALLOWED. Argument presence checks do not establish that a total or status has the required value type, so validate those values in the operation's application code.

A read without columns can derive them from its statement only when it takes no caller or identity arguments. Otherwise the generated row remains open.

Add a write

A write's statements returns one statement or an array. The server executes the array in one transaction and returns a result per statement in order. If the counter update fails, the order insert rolls back too.

The example's insert uses an automatically allocated ID. A caller must reconcile a lost reply before repeating it, because a retry can insert another order. Use an application operation ID when automatic retries need idempotency.

Fill an argument from the caller's identity

fromIdentity: { ownerId: 'userId' } obtains ownerId from the identity returned by authentication. A caller that supplies ownerId receives ARGUMENT_NOT_ALLOWED. Missing required identity data fails with IDENTITY_REQUIRED.

OperationRegistry<Identity> checks identity field identifiers at compile time. The SQL must also use the derived owner in the relevant condition. An unscoped query can return another account's rows even when the request authenticated successfully.

Serve the registry

Save the complete server.ts beside operations.ts. Provide a secret SIRANNON_TOKEN for the example's application account. The server creates its tables before serving the registry, with SQL, device sync, and operator replacement routes disabled.

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_maria', 4999, 'pending'],
  [2, 'u_ravi', 12500, 'pending'],
  [3, 'u_maria', 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') {
      throw new RequestDeniedError(403, 'FORBIDDEN', 'Route access refused')
    }
    return { userId: 'u_maria' }
  },
})
 
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 must match the opened ID. Looking up an operation under another database fails with UNKNOWN_QUERY.

For a deployed service, connect authentication to the application's session system and apply database authorisation before automatic opening. Security covers row subscriptions, snapshots, operator routes, and browser credentials.

Call an operation by name

Both client transports accept an operationRef. A plain string passed to query or execute means SQL, so use a reference to invoke 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 rows for u_maria only. Repeated executions add orders, so this example has no fixed result panel. Code generation derives the references from the registry.

Reach an operation over HTTP or WebSocket

HTTP uses POST /db/:id/query/:name for reads and POST /db/:id/execute/:name for writes. The body contains args and an optional read or write concern.

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

The server resolves identity-derived arguments using the identity established for the request or socket upgrade. Keep credentials short-lived and rebuild a client when its authentication expires.

Announce what the server serves

GET /capabilities reports query.named and the registry digest when operations exist. It adds query.sql for SQL access and the sync.* capabilities for device sync. This endpoint skips authentication.

The digest covers the database IDs, operation kinds and identifiers, and declared caller and identity arguments, including shared operations. Editing statement SQL alone leaves that contract digest unchanged.

A live-query subscription with a mismatched digest fails with REGISTRY_MISMATCH. The SDK refreshes capabilities once and retries, then reports a second refusal. Coordinate registry and generated-client changes during deployment.

Serve the same operations on every database

sharedOperations defines a common set for every database, including files opened after startup. A database-specific operation takes precedence when both sets define the same identifier.

Shared operations provides the complete tenant resolver, schema setup, authenticated server, and client example. It authorises the database ID before resolving a customer's file.

What each refusal means

CodeHTTPMeaning
UNKNOWN_QUERY404The database and shared sets contain no matching operation.
MISSING_ARGUMENT400The request omits a declared argument.
ARGUMENT_NOT_ALLOWED400The request includes an undeclared or identity-derived argument.
IDENTITY_REQUIRED401The required identity value is absent.
REGISTRY_MISMATCH409The live-query contract digest differs.
SQL_NOT_ACCEPTED403The server refuses network SQL.

Error codes covers the other refusals and worker failures.