@noego/sqlego 0.0.0-stage → 0.0.1-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/server.ts ADDED
@@ -0,0 +1,723 @@
1
+ import { Database, type SQLQueryBindings } from 'bun:sqlite';
2
+ import { rmSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { Result, Trust } from '@noego/trust';
5
+ import {
6
+ PROTOCOL_VERSION,
7
+ encodeFrame,
8
+ errorMessage,
9
+ fromJson,
10
+ parseRequest,
11
+ parseRows,
12
+ splitFrames,
13
+ toJson,
14
+ transactionControl,
15
+ type BatchResult,
16
+ type BeginResult,
17
+ type HelloResult,
18
+ type QueryResult,
19
+ type Request,
20
+ type Response,
21
+ type RunResult,
22
+ type SqlParams,
23
+ type SqlValue,
24
+ type Statement,
25
+ type StatusResult,
26
+ type TransactionEndResult,
27
+ type TransactionMode,
28
+ type TransactionStatus,
29
+ } from './protocol.ts';
30
+ import { resolvePaths, type FilePaths, type ServerMeta } from './paths.ts';
31
+ import { VERSION } from './version.ts';
32
+
33
+ export type ServerOptions = Readonly<{
34
+ file: string;
35
+ /** Exit this long after the last client disconnects. */
36
+ idleTimeoutMs: number;
37
+ /** Pragmas applied on open, in order (e.g. `journal_mode = WAL`). */
38
+ pragmas?: readonly string[];
39
+ log?: (message: string, fields?: Record<string, unknown>) => void;
40
+ /**
41
+ * Default and ceiling for a client transaction's lease: the transaction is
42
+ * rolled back when no request for it arrives within this long. A client may
43
+ * ask for a shorter lease in `begin`, never a longer one. Default 10 000.
44
+ */
45
+ txLeaseMs?: number;
46
+ /** Hard cap on how long one transaction may stay open, renewed or not. Default 60 000. */
47
+ txMaxDurationMs?: number;
48
+ /** How long another client's request waits behind an open transaction before failing with `tx-busy`. Default 30 000. */
49
+ txQueueTimeoutMs?: number;
50
+ }>;
51
+
52
+ /**
53
+ * Applied in order on open. `auto_vacuum` must precede anything that writes
54
+ * the first page (journal_mode = WAL does), and only binds on a file with no
55
+ * pages yet: a brand-new file gets incremental vacuum, an existing file keeps
56
+ * whatever it was created with. Callers override with `--pragma`.
57
+ */
58
+ export const DEFAULT_PRAGMAS: readonly string[] = ['auto_vacuum = INCREMENTAL', 'journal_mode = WAL', 'busy_timeout = 5000'];
59
+
60
+ export const DEFAULT_TX_LEASE_MS = 10_000;
61
+ export const DEFAULT_TX_MAX_DURATION_MS = 60_000;
62
+ export const DEFAULT_TX_QUEUE_TIMEOUT_MS = 30_000;
63
+
64
+ type SqliteFailure = { readonly kind: 'sqlite'; readonly message: string };
65
+ type BadRequest = { readonly kind: 'bad-request'; readonly message: string };
66
+ type TransactionFailure = { readonly kind: 'tx-expired' | 'tx-invalid'; readonly message: string };
67
+ type CleanupFailure = { readonly kind: 'cleanup-failed'; readonly message: string };
68
+ type WriteFailure = { readonly kind: 'write-failed'; readonly message: string };
69
+
70
+ const sqliteFailure = (cause: unknown): SqliteFailure => ({ kind: 'sqlite', message: errorMessage(cause) });
71
+ const cleanupFailure = (cause: unknown): CleanupFailure => ({ kind: 'cleanup-failed', message: errorMessage(cause) });
72
+ const writeFailure = (cause: unknown): WriteFailure => ({ kind: 'write-failed', message: errorMessage(cause) });
73
+ const badRequest = (message: string) => Result.err<BadRequest>({ kind: 'bad-request', message });
74
+
75
+ /**
76
+ * Carries one statement's failure out of a `db.transaction` callback: bun:sqlite
77
+ * rolls the transaction back only when that callback throws.
78
+ */
79
+ class BatchStatementFailed extends Error {
80
+ readonly failure: SqliteFailure;
81
+
82
+ constructor(failure: SqliteFailure) {
83
+ super(failure.message);
84
+ this.failure = failure;
85
+ }
86
+ }
87
+
88
+ /**
89
+ * `outbound` holds bytes the kernel buffer refused (null when there are none).
90
+ * Bun's `socket.write` returns the byte count it accepted and drops the rest,
91
+ * so a large result followed by another frame corrupts the stream unless the
92
+ * remainder is carried and flushed on `drain`.
93
+ */
94
+ type Connection = { id: number; buffer: string; outbound: Buffer | null; socket: ServerSocket };
95
+
96
+ /** Each socket carries its connection in Bun's typed `data` slot: null until `open` assigns it. */
97
+ type ServerSocket = import('bun').Socket<Connection | null>;
98
+
99
+ /** The one transaction a client may hold open; it lives and dies with `connection`. */
100
+ type OpenTransaction = {
101
+ id: number;
102
+ connection: Connection;
103
+ startedAt: number;
104
+ lastRequestAt: number;
105
+ leaseMs: number;
106
+ leaseTimer: ReturnType<typeof setTimeout>;
107
+ maxTimer: ReturnType<typeof setTimeout>;
108
+ };
109
+
110
+ /** A request from another client, held until the open transaction ends (or its wait runs out). */
111
+ type QueuedRequest = { connection: Connection; request: Request; timer: ReturnType<typeof setTimeout> };
112
+
113
+ /** How a transaction ended, kept so a late request for it gets a precise answer. */
114
+ type EndedTransaction = { code: 'tx-expired' | 'tx-invalid'; message: string };
115
+
116
+ const REMEMBERED_ENDINGS = 32;
117
+
118
+ /**
119
+ * The single owner of one SQLite file. Every request from every client runs,
120
+ * in arrival order, on this process's one connection; SQLite's write lock is
121
+ * therefore never contended from outside this process.
122
+ *
123
+ * While a client holds a transaction, that client's statements run at once
124
+ * and every other client's statements wait in arrival order; the transaction
125
+ * cannot outlive its socket, its lease, or the server's hard cap.
126
+ */
127
+ export class SqlegoServer {
128
+ readonly paths: FilePaths;
129
+ private readonly db: Database;
130
+ private readonly options: ServerOptions;
131
+ private readonly startedAt = Date.now();
132
+ private readonly connections = new Map<number, Connection>();
133
+ private listener: import('bun').UnixSocketListener<Connection | null> | null = null;
134
+ private idleTimer: ReturnType<typeof setTimeout> | null = null;
135
+ private idleSince: number | null = null;
136
+ private nextConnectionId = 1;
137
+ private nextTransactionId = 1;
138
+ private requestsServed = 0;
139
+ private stopping = false;
140
+ private transaction: OpenTransaction | null = null;
141
+ private readonly queue: QueuedRequest[] = [];
142
+ private readonly ended = new Map<number, EndedTransaction>();
143
+ private readonly log: NonNullable<ServerOptions['log']>;
144
+
145
+ private constructor(options: ServerOptions, paths: FilePaths, db: Database) {
146
+ this.options = options;
147
+ this.paths = paths;
148
+ this.db = db;
149
+ this.log = options.log ?? (() => undefined);
150
+ }
151
+
152
+ /** Opens (creating if needed) the database file and applies the pragmas. */
153
+ static open(options: ServerOptions) {
154
+ const paths = resolvePaths(options.file);
155
+ if (!paths.ok) return paths;
156
+ const db = Trust.try(
157
+ () => {
158
+ mkdirSync(path.dirname(paths.value.file), { recursive: true });
159
+ const opened = new Database(paths.value.file, { create: true, strict: false });
160
+ for (const pragma of options.pragmas ?? DEFAULT_PRAGMAS) opened.exec(`PRAGMA ${pragma}`);
161
+ return opened;
162
+ },
163
+ (cause) => ({ kind: 'open-failed', message: `cannot open ${paths.value.file}: ${errorMessage(cause)}` }),
164
+ );
165
+ if (!db.ok) return db;
166
+ return Result.ok(new SqlegoServer(options, paths.value, db.value));
167
+ }
168
+
169
+ /** Binds the socket and publishes meta. Clients can connect once this returns ok. */
170
+ listen() {
171
+ const meta: ServerMeta = {
172
+ file: this.paths.file, socket: this.paths.socket, pid: process.pid, serverVersion: VERSION, startedAt: this.startedAt,
173
+ };
174
+ const metaJson = toJson(meta);
175
+ if (!metaJson.ok) return Result.err({ kind: 'listen-failed', message: `cannot encode server meta: ${metaJson.error.message}` });
176
+ const bound = Trust.try(
177
+ () => {
178
+ if (existsSync(this.paths.socket)) rmSync(this.paths.socket, { force: true });
179
+ this.listener = Bun.listen<Connection | null>({
180
+ unix: this.paths.socket,
181
+ data: null,
182
+ socket: {
183
+ open: (socket) => this.onOpen(socket),
184
+ data: (socket, data) => this.onData(socket, data),
185
+ close: (socket) => this.onClose(socket),
186
+ drain: (socket) => this.onDrain(socket),
187
+ error: (socket, error) => this.onSocketError(socket, error),
188
+ },
189
+ });
190
+ writeFileSync(this.paths.meta, metaJson.value);
191
+ },
192
+ (cause) => ({ kind: 'listen-failed', message: `cannot listen on ${this.paths.socket}: ${errorMessage(cause)}` }),
193
+ );
194
+ if (!bound.ok) return bound;
195
+ this.armIdleTimer();
196
+ this.log('listening', { file: this.paths.file, socket: this.paths.socket, pid: process.pid, idleTimeoutMs: this.options.idleTimeoutMs });
197
+ return Result.ok(undefined);
198
+ }
199
+
200
+ /** Graceful stop: refuse new work, drop clients, release the file, remove socket/meta/lock. Every step is attempted. */
201
+ stop(reason: string): void {
202
+ if (this.stopping) return;
203
+ this.stopping = true;
204
+ this.log('stopping', { reason, clients: this.connections.size, requestsServed: this.requestsServed });
205
+ if (this.idleTimer) clearTimeout(this.idleTimer);
206
+ if (this.transaction) this.endTransaction('server stopping', 'tx-expired', true);
207
+ for (const queued of this.queue.splice(0)) clearTimeout(queued.timer);
208
+ // Socket file first: a client that connects after this point falls through
209
+ // to claim-and-spawn instead of racing a closing server.
210
+ this.reportCleanup('remove socket', Trust.try(() => rmSync(this.paths.socket, { force: true }), cleanupFailure));
211
+ this.reportCleanup('remove meta', Trust.try(() => rmSync(this.paths.meta, { force: true }), cleanupFailure));
212
+ this.reportCleanup('remove lock', Trust.try(() => rmSync(this.paths.lock, { force: true }), cleanupFailure));
213
+ for (const connection of this.connections.values()) {
214
+ this.reportCleanup('end connection', Trust.try(() => connection.socket.end(), cleanupFailure));
215
+ }
216
+ const listener = this.listener;
217
+ if (listener) this.reportCleanup('stop listener', Trust.try(() => listener.stop(true), cleanupFailure));
218
+ this.reportCleanup('close database', Trust.try(() => this.db.close(), cleanupFailure));
219
+ }
220
+
221
+ status(): StatusResult {
222
+ return {
223
+ file: this.paths.file,
224
+ socket: this.paths.socket,
225
+ pid: process.pid,
226
+ serverVersion: VERSION,
227
+ protocol: PROTOCOL_VERSION,
228
+ clients: this.connections.size,
229
+ uptimeMs: Date.now() - this.startedAt,
230
+ idleMs: this.idleSince === null ? null : Date.now() - this.idleSince,
231
+ idleTimeoutMs: this.options.idleTimeoutMs,
232
+ requestsServed: this.requestsServed,
233
+ transaction: this.transactionStatus(),
234
+ };
235
+ }
236
+
237
+ private transactionStatus(): TransactionStatus | null {
238
+ const open = this.transaction;
239
+ if (!open) return null;
240
+ const now = Date.now();
241
+ return {
242
+ txId: open.id,
243
+ ageMs: now - open.startedAt,
244
+ idleMs: now - open.lastRequestAt,
245
+ leaseMs: open.leaseMs,
246
+ maxDurationMs: this.txMaxDurationMs(),
247
+ queued: this.queue.length,
248
+ };
249
+ }
250
+
251
+ private txLeaseMs(): number {
252
+ return this.options.txLeaseMs ?? DEFAULT_TX_LEASE_MS;
253
+ }
254
+
255
+ private txMaxDurationMs(): number {
256
+ return this.options.txMaxDurationMs ?? DEFAULT_TX_MAX_DURATION_MS;
257
+ }
258
+
259
+ private txQueueTimeoutMs(): number {
260
+ return this.options.txQueueTimeoutMs ?? DEFAULT_TX_QUEUE_TIMEOUT_MS;
261
+ }
262
+
263
+ /** Shutdown is best effort: a step that fails is logged and the rest still run. */
264
+ private reportCleanup(step: string, outcome: Result<unknown, CleanupFailure>): void {
265
+ if (!outcome.ok && outcome.error.kind === 'cleanup-failed') this.log('cleanup failed', { step, error: outcome.error.message });
266
+ }
267
+
268
+ private onOpen(socket: ServerSocket): void {
269
+ if (this.stopping) {
270
+ this.reportCleanup('refuse connection', Trust.try(() => socket.end(), cleanupFailure));
271
+ return;
272
+ }
273
+ const id = this.nextConnectionId++;
274
+ const connection: Connection = { id, buffer: '', outbound: null, socket };
275
+ this.connections.set(id, connection);
276
+ socket.data = connection;
277
+ this.disarmIdleTimer();
278
+ }
279
+
280
+ private onClose(socket: ServerSocket): void {
281
+ const connection = socket.data;
282
+ if (!connection) return;
283
+ this.connections.delete(connection.id);
284
+ // A waiting request from a client that left has nobody to answer.
285
+ for (let index = this.queue.length - 1; index >= 0; index -= 1) {
286
+ if (this.queue[index].connection === connection) clearTimeout(this.queue.splice(index, 1)[0].timer);
287
+ }
288
+ if (this.transaction && this.transaction.connection === connection) {
289
+ this.endTransaction(`client ${connection.id} disconnected`, 'tx-expired', true);
290
+ this.drainQueue();
291
+ }
292
+ if (this.connections.size === 0 && !this.stopping) this.armIdleTimer();
293
+ }
294
+
295
+ private onSocketError(socket: ServerSocket, error: Error): void {
296
+ this.log('socket error', { error: error.message });
297
+ this.onClose(socket);
298
+ }
299
+
300
+ private onData(socket: ServerSocket, data: Buffer): void {
301
+ const connection = socket.data;
302
+ if (!connection) return;
303
+ const { frames, rest } = splitFrames(connection.buffer + data.toString('utf8'));
304
+ connection.buffer = rest;
305
+ for (const frame of frames) {
306
+ if (this.stopping) return;
307
+ this.accept(connection, frame);
308
+ }
309
+ }
310
+
311
+ /** Parses one frame and either serves it now or holds it behind another client's transaction. */
312
+ private accept(connection: Connection, frame: string): void {
313
+ const parsed = this.parseFrame(frame);
314
+ if (!parsed.ok) return this.reply(connection, { id: parsed.error.id, ok: false, error: { code: 'bad-request', message: parsed.error.message } });
315
+ const request = parsed.value;
316
+ if (this.mustWait(connection, request)) {
317
+ const timer = setTimeout(() => this.expireQueued(connection, request), this.txQueueTimeoutMs());
318
+ this.queue.push({ connection, request, timer });
319
+ return;
320
+ }
321
+ this.serve(connection, request);
322
+ }
323
+
324
+ /** A frame's request; a malformed one is a bad request answered on the id it carried (-1 when it had none). */
325
+ private parseFrame(frame: string) {
326
+ const json = fromJson(frame);
327
+ if (!json.ok) return Result.err({ kind: 'bad-request' as const, id: -1, message: `malformed frame: ${json.error.message}` });
328
+ const parsed = parseRequest(json.value);
329
+ if (!parsed.ok) return Result.err({ kind: 'bad-request' as const, id: parsed.error.id, message: parsed.error.message });
330
+ return parsed;
331
+ }
332
+
333
+ /**
334
+ * Statements from a client other than the transaction's owner wait until it
335
+ * ends. Its own requests, and anything that is not a statement (`hello`,
336
+ * `status`, `stop`), go through at once; so does a statement naming a
337
+ * `txId`, which can only be answered with a transaction error.
338
+ */
339
+ private mustWait(connection: Connection, request: Request): boolean {
340
+ const open = this.transaction;
341
+ if (!open || open.connection === connection) return false;
342
+ switch (request.op) {
343
+ case 'query':
344
+ case 'run': return request.txId === undefined;
345
+ case 'batch':
346
+ case 'begin': return true;
347
+ default: return false;
348
+ }
349
+ }
350
+
351
+ private expireQueued(connection: Connection, request: Request): void {
352
+ const index = this.queue.findIndex((queued) => queued.request === request);
353
+ if (index < 0) return;
354
+ this.queue.splice(index, 1);
355
+ const waited = this.txQueueTimeoutMs();
356
+ this.reply(connection, {
357
+ id: request.id, ok: false,
358
+ error: { code: 'tx-busy', message: `another client's transaction kept this ${request.op} waiting for ${waited} ms` },
359
+ });
360
+ }
361
+
362
+ /** Serves held requests in arrival order until one of them opens a new transaction. */
363
+ private drainQueue(): void {
364
+ while (this.queue.length > 0 && this.transaction === null && !this.stopping) {
365
+ const next = this.queue.shift();
366
+ if (!next) return;
367
+ clearTimeout(next.timer);
368
+ this.serve(next.connection, next.request);
369
+ }
370
+ }
371
+
372
+ private serve(connection: Connection, request: Request): void {
373
+ this.requestsServed += 1;
374
+ const response = this.respond(connection, request);
375
+ this.reply(connection, response);
376
+ if (response.ok && request.op === 'stop') {
377
+ this.stop('client request');
378
+ setTimeout(() => process.exit(0), 20);
379
+ return;
380
+ }
381
+ // A commit, rollback or expiry may have freed the file for whoever was waiting.
382
+ this.drainQueue();
383
+ }
384
+
385
+ /** Decides every failure of one request into a wire response. */
386
+ private respond(connection: Connection, request: Request): Response {
387
+ if (this.stopping) return { id: request.id, ok: false, error: { code: 'shutting-down', message: 'server is shutting down' } };
388
+ const outcome = this.execute(connection, request);
389
+ if (outcome.ok) return { id: request.id, ok: true, result: outcome.value };
390
+ switch (outcome.error.kind) {
391
+ case 'bad-request': return { id: request.id, ok: false, error: { code: 'bad-request', message: outcome.error.message } };
392
+ case 'protocol-mismatch': return { id: request.id, ok: false, error: { code: 'protocol-mismatch', message: outcome.error.message } };
393
+ case 'sqlite': return { id: request.id, ok: false, error: { code: 'sqlite', message: outcome.error.message } };
394
+ case 'tx-expired': return { id: request.id, ok: false, error: { code: 'tx-expired', message: outcome.error.message } };
395
+ case 'tx-invalid': return { id: request.id, ok: false, error: { code: 'tx-invalid', message: outcome.error.message } };
396
+ default: {
397
+ const unhandled: never = outcome.error;
398
+ return unhandled;
399
+ }
400
+ }
401
+ }
402
+
403
+ private execute(connection: Connection, request: Request) {
404
+ switch (request.op) {
405
+ case 'hello': return this.hello(request.protocol);
406
+ case 'query':
407
+ case 'run': return this.statement(connection, request.op, request.sql, request.params, request.txId);
408
+ case 'batch': return this.batch(connection, request.statements);
409
+ case 'begin': return this.begin(connection, request.mode ?? 'deferred', request.leaseMs);
410
+ case 'commit': return this.finish(connection, request.txId, 'commit');
411
+ case 'rollback': return this.finish(connection, request.txId, 'rollback');
412
+ case 'status': return Result.ok(this.status());
413
+ case 'stop': return Result.ok({ stopping: true });
414
+ default: {
415
+ const unhandled: never = request;
416
+ return unhandled;
417
+ }
418
+ }
419
+ }
420
+
421
+ private hello(protocol: number) {
422
+ if (protocol !== PROTOCOL_VERSION) {
423
+ return Result.err({ kind: 'protocol-mismatch', message: `server speaks protocol ${PROTOCOL_VERSION}, client sent ${protocol}` });
424
+ }
425
+ const hello: HelloResult = { serverVersion: VERSION, protocol: PROTOCOL_VERSION, file: this.paths.file, pid: process.pid };
426
+ return Result.ok(hello);
427
+ }
428
+
429
+ /**
430
+ * One `query` or `run`. Outside a transaction no transaction-control SQL is
431
+ * accepted at all: a stray `BEGIN` would silently wrap every client's later
432
+ * statements. Inside one, savepoints are SQL but the transaction itself ends
433
+ * only through `commit`/`rollback`, so the server always knows its state.
434
+ */
435
+ private statement(connection: Connection, op: 'query' | 'run', sql: string, params: SqlParams | undefined, txId: number | undefined) {
436
+ const control = transactionControl(sql);
437
+ if (txId === undefined) {
438
+ if (control !== null) {
439
+ return badRequest(`${control.toUpperCase()} is not allowed as a plain ${op}: open a transaction with begin and end it with commit or rollback`);
440
+ }
441
+ return this.runStatement(op, sql, params);
442
+ }
443
+ const owned = this.ownedTransaction(connection, txId);
444
+ if (!owned.ok) return owned;
445
+ if (control === 'begin' || control === 'commit' || control === 'rollback') {
446
+ return badRequest(`${control.toUpperCase()} is not allowed inside transaction ${txId}: end it with commit or rollback`);
447
+ }
448
+ const outcome = this.runStatement(op, sql, params);
449
+ this.afterTransactionStatement(owned.value);
450
+ return outcome;
451
+ }
452
+
453
+ private runStatement(op: 'query' | 'run', sql: string, params: SqlParams | undefined) {
454
+ return op === 'query' ? this.query(sql, params) : this.run(sql, params);
455
+ }
456
+
457
+ /** SQLite aborts a transaction by itself on some errors; the server must not believe it is still open. */
458
+ private afterTransactionStatement(open: OpenTransaction): void {
459
+ if (!this.db.inTransaction) {
460
+ this.endTransaction('SQLite aborted the transaction', 'tx-expired', false);
461
+ return;
462
+ }
463
+ this.renewLease(open);
464
+ }
465
+
466
+ private query(sql: string, params?: SqlParams) {
467
+ const fetched = Trust.try(
468
+ (): unknown => {
469
+ const statement = this.db.query(sql);
470
+ return params === undefined ? statement.all() : statement.all(...bindings(params));
471
+ },
472
+ sqliteFailure,
473
+ );
474
+ if (!fetched.ok) return fetched;
475
+ const rows = parseRows(fetched.value);
476
+ if (!rows.ok) return Result.err<SqliteFailure>({ kind: 'sqlite', message: `unexpected row shape: ${rows.error.message}` });
477
+ const result: QueryResult = { rows: rows.value };
478
+ return Result.ok(result);
479
+ }
480
+
481
+ private run(sql: string, params?: SqlParams) {
482
+ return Trust.try(
483
+ () => {
484
+ const statement = this.db.query(sql);
485
+ const outcome = params === undefined ? statement.run() : statement.run(...bindings(params));
486
+ const result: RunResult = { changes: outcome.changes, lastInsertRowid: outcome.lastInsertRowid };
487
+ return result;
488
+ },
489
+ sqliteFailure,
490
+ );
491
+ }
492
+
493
+ /** All statements in one transaction; any failure rolls the whole batch back. */
494
+ private batch(connection: Connection, statements: readonly Statement[]) {
495
+ if (statements.length === 0) return badRequest('batch requires a non-empty statements array');
496
+ if (this.transaction && this.transaction.connection === connection) {
497
+ return badRequest(`batch is not allowed while this connection holds transaction ${this.transaction.id}: run the statements in it instead`);
498
+ }
499
+ for (const [index, item] of statements.entries()) {
500
+ const control = transactionControl(item.sql);
501
+ if (control !== null) return badRequest(`statements[${index}]: ${control.toUpperCase()} is not allowed in a batch, which is already one transaction`);
502
+ }
503
+ return Trust.try(
504
+ () => {
505
+ const transaction = this.db.transaction((items: readonly Statement[]) => items.map((item) => this.batchItem(item)));
506
+ const result: BatchResult = { results: transaction(statements) };
507
+ return result;
508
+ },
509
+ (cause) => (cause instanceof BatchStatementFailed ? cause.failure : sqliteFailure(cause)),
510
+ );
511
+ }
512
+
513
+ /** One statement of a batch, inside its transaction: a failure must throw so bun:sqlite rolls back. */
514
+ private batchItem(item: Statement): RunResult | QueryResult {
515
+ const outcome = item.mode === 'query' ? this.query(item.sql, item.params) : this.run(item.sql, item.params);
516
+ if (outcome.ok) return outcome.value;
517
+ //trust:accept bun:sqlite rolls a transaction back only when its callback throws; batch() turns this back into a Result
518
+ throw new BatchStatementFailed(outcome.error);
519
+ }
520
+
521
+ /* ------------------------------------------------------------------ *
522
+ * Leased transactions
523
+ * ------------------------------------------------------------------ */
524
+
525
+ private begin(connection: Connection, mode: TransactionMode, requestedLeaseMs: number | undefined) {
526
+ const open = this.transaction;
527
+ if (open) {
528
+ // Any other owner's `begin` is queued in accept(); only the owner reaches here.
529
+ return Result.err<TransactionFailure>({ kind: 'tx-invalid', message: `transaction ${open.id} is already open on this connection` });
530
+ }
531
+ const started = Trust.try(() => this.db.exec(mode === 'immediate' ? 'BEGIN IMMEDIATE' : 'BEGIN'), sqliteFailure);
532
+ if (!started.ok) return started;
533
+ const leaseMs = Math.min(requestedLeaseMs ?? this.txLeaseMs(), this.txLeaseMs());
534
+ const maxDurationMs = this.txMaxDurationMs();
535
+ const id = this.nextTransactionId++;
536
+ const now = Date.now();
537
+ const transaction: OpenTransaction = {
538
+ id,
539
+ connection,
540
+ startedAt: now,
541
+ lastRequestAt: now,
542
+ leaseMs,
543
+ leaseTimer: setTimeout(() => this.onLeaseExpired(id), leaseMs),
544
+ maxTimer: setTimeout(() => this.onMaxDuration(id), maxDurationMs),
545
+ };
546
+ this.transaction = transaction;
547
+ this.log('transaction opened', { txId: id, connection: connection.id, mode, leaseMs, maxDurationMs });
548
+ const result: BeginResult = { txId: id, leaseMs, maxDurationMs };
549
+ return Result.ok(result);
550
+ }
551
+
552
+ private finish(connection: Connection, txId: number, how: 'commit' | 'rollback') {
553
+ const owned = this.ownedTransaction(connection, txId);
554
+ if (!owned.ok) return owned;
555
+ const result: TransactionEndResult = { txId };
556
+ if (how === 'rollback') {
557
+ this.endTransaction('rolled back by client', 'tx-invalid', true);
558
+ return Result.ok(result);
559
+ }
560
+ const committed = Trust.try(() => this.db.exec('COMMIT'), sqliteFailure);
561
+ // A COMMIT that fails leaves the transaction open in SQLite; the client
562
+ // asked for it to end, so it does — by rollback — and learns why.
563
+ this.endTransaction(committed.ok ? 'committed' : `commit failed: ${committed.error.message}`, 'tx-invalid', !committed.ok);
564
+ if (!committed.ok) return committed;
565
+ return Result.ok(result);
566
+ }
567
+
568
+ /** The open transaction `txId` held by `connection`, or the precise reason there is none. */
569
+ private ownedTransaction(connection: Connection, txId: number) {
570
+ const open = this.transaction;
571
+ if (open && open.id === txId && open.connection === connection) return Result.ok(open);
572
+ const ending = this.ended.get(txId);
573
+ if (ending) return Result.err<TransactionFailure>({ kind: ending.code, message: ending.message });
574
+ if (open && open.id === txId) {
575
+ return Result.err<TransactionFailure>({ kind: 'tx-invalid', message: `transaction ${txId} belongs to another connection` });
576
+ }
577
+ return Result.err<TransactionFailure>({ kind: 'tx-invalid', message: `no open transaction ${txId} on this connection` });
578
+ }
579
+
580
+ private renewLease(open: OpenTransaction): void {
581
+ open.lastRequestAt = Date.now();
582
+ clearTimeout(open.leaseTimer);
583
+ open.leaseTimer = setTimeout(() => this.onLeaseExpired(open.id), open.leaseMs);
584
+ }
585
+
586
+ private onLeaseExpired(txId: number): void {
587
+ const open = this.transaction;
588
+ if (!open || open.id !== txId) return;
589
+ this.endTransaction(`no request for ${open.leaseMs} ms (lease expired)`, 'tx-expired', true);
590
+ this.drainQueue();
591
+ }
592
+
593
+ private onMaxDuration(txId: number): void {
594
+ const open = this.transaction;
595
+ if (!open || open.id !== txId) return;
596
+ this.endTransaction(`open for ${this.txMaxDurationMs()} ms (max duration reached)`, 'tx-expired', true);
597
+ this.drainQueue();
598
+ }
599
+
600
+ /**
601
+ * Closes the open transaction: stops its timers, rolls SQLite back when
602
+ * asked (and still inside one), and remembers how it ended so a late request
603
+ * for its id gets `code`. Callers drain the queue afterwards.
604
+ */
605
+ private endTransaction(reason: string, code: EndedTransaction['code'], rollback: boolean): void {
606
+ const open = this.transaction;
607
+ if (!open) return;
608
+ this.transaction = null;
609
+ clearTimeout(open.leaseTimer);
610
+ clearTimeout(open.maxTimer);
611
+ if (rollback && this.db.inTransaction) {
612
+ const rolledBack = Trust.try(() => this.db.exec('ROLLBACK'), sqliteFailure);
613
+ if (!rolledBack.ok && rolledBack.error.kind === 'sqlite') this.log('rollback failed', { txId: open.id, error: rolledBack.error.message });
614
+ }
615
+ this.remember(open.id, { code, message: `transaction ${open.id} ended: ${reason}` });
616
+ this.log('transaction ended', { txId: open.id, connection: open.connection.id, reason, ageMs: Date.now() - open.startedAt });
617
+ }
618
+
619
+ private remember(txId: number, ending: EndedTransaction): void {
620
+ this.ended.set(txId, ending);
621
+ while (this.ended.size > REMEMBERED_ENDINGS) {
622
+ const oldest = this.ended.keys().next();
623
+ if (oldest.done) break;
624
+ this.ended.delete(oldest.value);
625
+ }
626
+ }
627
+
628
+ /* ------------------------------------------------------------------ *
629
+ * Replies
630
+ * ------------------------------------------------------------------ */
631
+
632
+ /**
633
+ * Sends one response. A response that cannot be encoded is answered with an
634
+ * error frame for the same id; a connection that cannot be written to is dropped.
635
+ */
636
+ private reply(connection: Connection, response: Response): void {
637
+ const encoded = encodeFrame(response);
638
+ const frame = encoded.ok
639
+ ? encoded
640
+ : encodeFrame({ id: response.id, ok: false, error: { code: 'encode-failed', message: encoded.error.message } });
641
+ if (!frame.ok) {
642
+ if (frame.error.kind === 'encode-failed') this.dropConnection(connection, `cannot encode response ${response.id}: ${frame.error.message}`);
643
+ return;
644
+ }
645
+ const sent = this.send(connection, frame.value);
646
+ if (!sent.ok && sent.error.kind === 'write-failed') this.dropConnection(connection, sent.error.message);
647
+ }
648
+
649
+ private dropConnection(connection: Connection, why: string): void {
650
+ this.log('dropping connection', { connection: connection.id, error: why });
651
+ connection.outbound = null;
652
+ this.reportCleanup('drop connection', Trust.try(() => connection.socket.end(), cleanupFailure));
653
+ }
654
+
655
+ /** Queues behind any unflushed bytes so frames never interleave. */
656
+ private send(connection: Connection, frame: string) {
657
+ const queued = Trust.try(
658
+ () => {
659
+ const bytes = Buffer.from(frame, 'utf8');
660
+ connection.outbound = connection.outbound === null ? bytes : Buffer.concat([connection.outbound, bytes]);
661
+ },
662
+ writeFailure,
663
+ );
664
+ if (!queued.ok) return queued;
665
+ return this.flush(connection);
666
+ }
667
+
668
+ private onDrain(socket: ServerSocket): void {
669
+ const connection = socket.data;
670
+ if (!connection) return;
671
+ const flushed = this.flush(connection);
672
+ if (!flushed.ok && flushed.error.kind === 'write-failed') this.dropConnection(connection, flushed.error.message);
673
+ }
674
+
675
+ private flush(connection: Connection) {
676
+ return Trust.try(
677
+ () => {
678
+ const pending = connection.outbound;
679
+ if (pending === null) return;
680
+ const written = connection.socket.write(pending);
681
+ connection.outbound = written >= pending.length ? null : pending.subarray(Math.max(written, 0));
682
+ },
683
+ writeFailure,
684
+ );
685
+ }
686
+
687
+ /* ------------------------------------------------------------------ *
688
+ * Idle exit
689
+ * ------------------------------------------------------------------ */
690
+
691
+ private armIdleTimer(): void {
692
+ this.idleSince = Date.now();
693
+ if (this.idleTimer) clearTimeout(this.idleTimer);
694
+ this.idleTimer = setTimeout(() => this.onIdle(), this.options.idleTimeoutMs);
695
+ }
696
+
697
+ /** Never while a client is connected or a transaction is open (its owner is connected, but the guard is explicit). */
698
+ private onIdle(): void {
699
+ if (this.connections.size > 0 || this.transaction !== null) return;
700
+ this.stop('idle');
701
+ process.exit(0);
702
+ }
703
+
704
+ private disarmIdleTimer(): void {
705
+ this.idleSince = null;
706
+ if (this.idleTimer) {
707
+ clearTimeout(this.idleTimer);
708
+ this.idleTimer = null;
709
+ }
710
+ }
711
+ }
712
+
713
+ /**
714
+ * bun:sqlite binds positional params from an array spread and named params
715
+ * from one object argument. Every SqlValue is a binding bun:sqlite accepts;
716
+ * `params` itself was checked by `parseSqlParams` when the frame arrived. This
717
+ * only tells the array form from the object form, which `Array.isArray`
718
+ * cannot narrow on a readonly array without widening it to `any[]`.
719
+ */
720
+ //trust:validator_function
721
+ function bindings(params: SqlParams): SQLQueryBindings[] {
722
+ return Array.isArray(params) ? (params as SqlValue[]) : [params as Record<string, SqlValue>];
723
+ }