Sirannon provides hooks to guard operations and metrics callbacks to observe their work. Its lifecycle manager can open a database for each tenant on demand and close inactive handles.
Open a tenant database with hooks and metrics
The complete tenants.ts example below uses createTenantResolver to restrict identifiers before constructing a path. Query hooks accept only the statements declared in the application, while the driver binds each argument separately from the SQL.
import { mkdir } from 'node:fs/promises'
import { createTenantResolver, type QueryHookContext, type QueryMetrics, Sirannon } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
const createTasks = 'CREATE TABLE IF NOT EXISTS tasks (id INTEGER PRIMARY KEY, title TEXT NOT NULL)'
const insertTask = 'INSERT INTO tasks (id, title) VALUES (?, ?) ON CONFLICT(id) DO NOTHING'
const selectTasks = 'SELECT id, title FROM tasks ORDER BY id'
const allowedStatements = new Set([createTasks, insertTask, selectTasks])
const beforeQuery = (context: QueryHookContext): void => {
if (!allowedStatements.has(context.sql)) throw new Error('Statement is outside the application allowlist')
}
const queryComplete = (report: QueryMetrics): void => {
console.log({
databaseId: report.databaseId,
durationMs: report.durationMs,
rowsReturned: report.rowsReturned,
changes: report.changes,
error: report.error,
})
}
await mkdir('./data/tenants', { recursive: true })
const sirannon = new Sirannon({
driver: betterSqlite3(),
metrics: { onQueryComplete: queryComplete },
lifecycle: {
autoOpen: { resolver: createTenantResolver({ basePath: './data/tenants' }) },
idleTimeout: 300_000,
maxOpen: 50,
},
})
sirannon.onBeforeQuery(beforeQuery)
sirannon.onAfterQuery(console.log)
sirannon.onDatabaseOpen(console.log)
sirannon.onDatabaseClose(console.log)
try {
const db = await sirannon.resolve('tenant-42')
if (!db) throw new Error('Tenant identifier was refused')
await db.execute(createTasks)
await db.execute(insertTask, [1, 'Prepare the release notes'])
console.log(await db.query(selectTasks))
} finally {
await sirannon.shutdown()
}The logged durations depend on the host, so this example has no fixed result panel. In a service, replace console logging with your metrics collector and avoid logging SQL arguments or secrets.
Refuse work before it executes
The registry provides onBeforeQuery, onAfterQuery, onBeforeConnect, onDatabaseOpen, and onDatabaseClose. Each registrar returns a function that removes the hook. A hook registered on the registry applies to every database that it opens; a database also accepts query hooks directly.
Query and connection hooks execute synchronously. A before-query or before-connect hook that returns a promise fails the statement or open. The observer hooks, onAfterQuery, onDatabaseOpen, and onDatabaseClose, leave the operation and later hooks unaffected when they throw or return a promise.
Query hooks also execute for each statement made through a transaction callback's Transaction handle. For a callback statement, onAfterQuery receives the error from that statement. For a failed executeTransaction, each statement's after-hook receives the transaction error.
Exact statement matching, as used above, restricts the local query API. Searching SQL for a word such as DROP cannot enforce access control, because callers can change casing or add comments. For network access, register the operations that callers may invoke and authenticate each request.
The constructor's hooks option accepts onBeforeSubscribe, onBeforeSnapshot, and onBeforePush. These hooks can be asynchronous, and the server waits for them before serving the request. They receive the authenticated identity, so an application can check which tables the caller may access. See security.
Measure statements and change delivery
onQueryComplete receives databaseId, sql, and durationMs. A successful read includes rowsReturned, a successful write includes changes, and a failed statement includes error: true.
With betterSqlite3({ rowCounts: true }), the report also includes rowsRead and rowsWritten. Live-query reads include source: 'live'. A worker timeout can delay the report until the worker answers, so the callback need not coincide with the caller's completion. See usage metering for the distinction between zero and absent counts.
onConnectionOpen and onConnectionClose receive the database identifier, path, and pool reader count. A close reports zero readers. onCDCEvent receives the database identifier, table, operation, and subscriber count for each delivered change, including delivery to server subscriptions.
Metrics callbacks execute synchronously. Sirannon ignores an error or returned promise from a metrics callback, so use a short callback and monitor failures in the collector separately.
Restrict paths and close idle handles
createTenantResolver accepts lowercase letters, digits, underscores, and hyphens, with a letter or digit first. It appends .db under basePath. A separator, capital letter, or file name longer than 255 characters causes the resolver to return undefined.
Derive the tenant identifier from the authenticated session. resolve returns an already-open database before consulting the resolver, so register identifiers only for files that those callers may access. Restrict filesystem writes under basePath to the application account, because the filesystem can follow a symbolic link there.
The HTTP server rejects absolute and traversal identifiers with 400 INVALID_REQUEST before resolving them. A resolver refusal produces 404 DATABASE_NOT_FOUND, so a client must handle both responses.
resolve reuses an open handle or opens a file through the resolver. The lifecycle manager closes a database after idleTimeout and evicts the least recently used eligible handle when it reaches maxOpen. If every handle is active at that cap, opening another database fails with MAX_DATABASES.
The registry's migrations option applies the schema before a newly opened tenant becomes available. A failed migration leaves that tenant unregistered, so a later open can retry. The migrations guide describes migration sources and recovery.