Without a limit, SQLite executes a statement until the statement finishes, while every caller that needs the same connection waits. When you set executionTimeoutMs on a call, SQLite stops the statement once that many milliseconds pass. Sirannon then rolls back the call's transaction and fails the call with an ExecutionTimeoutError whose code is EXECUTION_TIMEOUT. Sirannon stores none of the call's writes, so you can retry the call.
Sirannon accepts executionTimeoutMs from 0.4.8 onwards, and only on the better-sqlite3 driver, which stops a statement through the SQLite build in @delali/sirannon-sqlite.
Turn on time limits in the driver
Install the native SQLite build beside Sirannon:
pnpm add -E @delali/sirannon-db @delali/sirannon-sqliteCreate the driver with betterSqlite3({ executionTimeouts: true }). With that option, the driver opens every database through @delali/sirannon-sqlite, whose build of SQLite can interrupt a statement, so the driver reports executionTimeouts: true in driver.capabilities. Sirannon executes a call without a limit on that driver in the same way as on betterSqlite3().
The complete reports.ts program below creates a temporary database of orders and totals them by region under a limit of 2,000 milliseconds. It then queries a report that never ends, under a limit of 250 milliseconds.
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { ExecutionTimeoutError, Sirannon } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
interface RegionTotal {
region: string
total: number
}
const ENDLESS_REPORT_SQL = 'WITH RECURSIVE day(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM day) SELECT count(*) AS days FROM day'
const directory = await mkdtemp(join(tmpdir(), 'sirannon-reports-'))
const sirannon = new Sirannon({ driver: betterSqlite3({ executionTimeouts: true }) })
try {
const db = await sirannon.open('shop', join(directory, 'shop.db'))
await db.execute('CREATE TABLE orders (id INTEGER PRIMARY KEY, region TEXT NOT NULL, total INTEGER NOT NULL)')
await db.executeBatch('INSERT INTO orders (id, region, total) VALUES (?, ?, ?)', [
[1, 'eu-west', 4200],
[2, 'ap-south', 1800],
[3, 'eu-west', 900],
[4, 'sa-east', 3100],
])
const totals = await db.query<RegionTotal>('SELECT region, sum(total) AS total FROM orders GROUP BY region ORDER BY region', [], {
executionTimeoutMs: 2000,
})
console.log(JSON.stringify(totals, (_key: string, value: unknown): unknown => typeof value === 'number' ? Number(value.toFixed(2)) : value, 2))
try {
await db.query(ENDLESS_REPORT_SQL, [], { executionTimeoutMs: 250 })
} catch (error: unknown) {
if (!(error instanceof ExecutionTimeoutError)) throw error
console.log(error.code)
}
} finally {
try {
await sirannon.shutdown()
} finally {
await rm(directory, { recursive: true, force: true })
}
}The recursive statement counts days without an end, so SQLite stops it once 250 milliseconds pass. Sirannon raises an ExecutionTimeoutError with the code EXECUTION_TIMEOUT and executes the next call on that database at once.
Choose the calls and the limit
You can pass executionTimeoutMs to query, queryOne, queryWithColumns, execute, executeBatch, executeTransaction, transaction, and bulkLoad. Sirannon measures the limit from the moment that it starts to execute the call on its connection, so it leaves out of the limit any wait for the writer before the call starts.
Set the limit to a whole number of milliseconds from 1 to 2,147,483,647, which is the longest delay that a JavaScript timer supports. Before it executes a statement, Sirannon refuses any other value, a string included, with INVALID_EXECUTION_TIMEOUT on every driver.
Roll back a transaction that takes too long
The next version of reports.ts refunds part of the first order in a transaction with a limit of 250 milliseconds. After its two writes, the callback passes the endless report to tx.query, so SQLite stops that read and Sirannon rolls back both writes. Green marks each line that is new in this step.
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { ExecutionTimeoutError, Sirannon } from '@delali/sirannon-db'
import { ExecutionTimeoutError, Sirannon, type Transaction } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
interface RegionTotal {
region: string
total: number
}
const ENDLESS_REPORT_SQL = 'WITH RECURSIVE day(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM day) SELECT count(*) AS days FROM day'
const directory = await mkdtemp(join(tmpdir(), 'sirannon-reports-'))
const sirannon = new Sirannon({ driver: betterSqlite3({ executionTimeouts: true }) })
try {
const db = await sirannon.open('shop', join(directory, 'shop.db'))
await db.execute('CREATE TABLE orders (id INTEGER PRIMARY KEY, region TEXT NOT NULL, total INTEGER NOT NULL)')
await db.execute('CREATE TABLE refunds (id INTEGER PRIMARY KEY, order_id INTEGER NOT NULL, amount INTEGER NOT NULL)')
await db.executeBatch('INSERT INTO orders (id, region, total) VALUES (?, ?, ?)', [
[1, 'eu-west', 4200],
[2, 'ap-south', 1800],
[3, 'eu-west', 900],
[4, 'sa-east', 3100],
])
const totals = await db.query<RegionTotal>('SELECT region, sum(total) AS total FROM orders GROUP BY region ORDER BY region', [], {
executionTimeoutMs: 2000,
})
console.log(JSON.stringify(totals, (_key: string, value: unknown): unknown => typeof value === 'number' ? Number(value.toFixed(2)) : value, 2))
try {
await db.query(ENDLESS_REPORT_SQL, [], { executionTimeoutMs: 250 })
} catch (error: unknown) {
if (!(error instanceof ExecutionTimeoutError)) throw error
console.log(error.code)
}
try {
await db.transaction(async (tx: Transaction): Promise<void> => {
await tx.execute('INSERT INTO refunds (order_id, amount) VALUES (?, ?)', [1, 700])
await tx.execute('UPDATE orders SET total = total - ? WHERE id = ?', [700, 1])
await tx.query(ENDLESS_REPORT_SQL)
}, { executionTimeoutMs: 250 })
} catch (error: unknown) {
if (!(error instanceof ExecutionTimeoutError)) throw error
console.log(error.code)
}
const refunds = await db.queryOne<{ count: number }>('SELECT count(*) AS count FROM refunds')
const firstOrder = await db.queryOne<{ total: number }>('SELECT total FROM orders WHERE id = ?', [1])
console.log(JSON.stringify({ refunds: refunds?.count, firstOrderTotal: firstOrder?.total }, (_key: string, value: unknown): unknown => typeof value === 'number' ? Number(value.toFixed(2)) : value, 2))
} finally {
try {
await sirannon.shutdown()
} finally {
await rm(directory, { recursive: true, force: true })
}
}The program prints no refund and the original total of 4,200 for the first order, because Sirannon rolls back the refund together with the update. In a transaction, Sirannon counts every statement against the one limit, together with the time that your callback spends between statements. Sirannon checks the time left before each statement and again before COMMIT, but it never interrupts a COMMIT. Sirannon therefore commits none of the writes of a call that it fails with EXECUTION_TIMEOUT.
Once SQLite stops one statement of a transaction, Sirannon refuses every later statement of that transaction with EXECUTION_TIMEOUT and rolls the transaction back, even when your callback catches the error and returns.
Inside a transaction callback with a limit, Sirannon applies the time that the callback has left to every read and write that you make through db as well. Sirannon adds a write through db to the callback's transaction, so when SQLite stops that write, Sirannon rolls back the whole transaction, including the writes that your callback made through tx before it.
Keep a timeout away from other callers' writes
Sirannon can combine the writes of several callers into one commit. However, it commits a write with a limit alone, because SQLite rolls back the whole transaction when it stops a write, and in a shared commit that rollback can undo the writes of other callers. Sirannon goes on combining the writes that have no limit.
With the writer worker, Sirannon applies the call's limit to each statement that the worker thread executes for the call, so SQLite stops a write inside the worker as it does on the main thread. Sirannon interrupts no statement at the worker's writeTimeoutMs deadline, which is why it can fail a write after that deadline with the indeterminate WRITER_WORKER_TIMEOUT. Set executionTimeoutMs on a long write so that SQLite stops the write inside the worker and Sirannon fails the call with the definite EXECUTION_TIMEOUT.
Recognise a driver that can't stop a statement
The other drivers report executionTimeouts: false, as does betterSqlite3() without the option. On those drivers, Sirannon refuses with EXECUTION_TIMEOUT_UNSUPPORTED every call that has a limit, before it executes a statement, so it never starts the callback of a transaction with a limit.
With executionTimeouts: true, the better-sqlite3 driver fails open with EXECUTION_TIMEOUT_UNSUPPORTED when it can't find @delali/sirannon-sqlite or a build of that package for the platform, or when the build that it loads can't interrupt a statement. For a platform without a published build, compile the native module from the native/sqlite directory of the release and pass its path as sqliteBindingPath, as Drivers explains.
See what a client receives from the server
The server sets no execution time limit on the statements that a client sends, whether the client sends SQL or calls a registered operation. When the server receives an ExecutionTimeoutError while it handles a request, as it can when you throw that error from a hook, the server answers the HTTP request with 422. Over HTTP and over WebSocket, the server sends a fixed message and no details for that code, because SQLite words the error differently depending on where it stops the statement.
The server answers INVALID_EXECUTION_TIMEOUT with 400 and EXECUTION_TIMEOUT_UNSUPPORTED with 501. It sends a fixed message for EXECUTION_TIMEOUT_UNSUPPORTED as well, because the message on the server can include the path of the SQLite build. Every code and status is in Error codes.