@noego/sqlego 0.1.4 → 0.1.6-dev.0

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 CHANGED
@@ -1,7 +1,11 @@
1
- import { Database, type SQLQueryBindings, type Statement as SqliteStatement } from 'bun:sqlite';
1
+ import { Database, type SQLQueryBindings } from 'bun:sqlite';
2
2
  import { rmSync, writeFileSync, existsSync, mkdirSync, statSync } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { Result, Trust } from '@noego/trust';
5
+ import { ReaderPool, sharedReaderPool, type ReaderOutcome, type ReaderRows } from './reader_pool.ts';
6
+
7
+ export { ReaderPool, DEFAULT_READERS, DEFAULT_READER_QUEUE_LIMIT, type ReaderPoolOptions } from './reader_pool.ts';
8
+ import { StatementCache, sqliteFailure, stepStatement, type SqliteFailure } from './statement_cache.ts';
5
9
  import {
6
10
  FrameReader,
7
11
  PROTOCOL_VERSION,
@@ -60,6 +64,13 @@ export type ServerOptions = Readonly<{
60
64
  * released at once, clients or not. Default 5 000.
61
65
  */
62
66
  fileCheckMs?: number;
67
+ /**
68
+ * The reader workers opted-in plain reads of a WAL file run on (see
69
+ * `reader_pool.ts`). Default: the process's shared pool, sized by
70
+ * `SQLEGO_READERS` / `SQLEGO_READER_QUEUE`. A pool of size 0 keeps every
71
+ * read on the owner thread's readonly connection.
72
+ */
73
+ readerPool?: ReaderPool;
63
74
  }>;
64
75
 
65
76
  /**
@@ -77,7 +88,6 @@ export const DEFAULT_TX_MAX_DURATION_MS = 60_000;
77
88
  export const DEFAULT_TX_QUEUE_TIMEOUT_MS = 30_000;
78
89
  export const DEFAULT_FILE_CHECK_MS = 5_000;
79
90
 
80
- type SqliteFailure = { readonly kind: 'sqlite'; readonly message: string; readonly code?: string };
81
91
  type BadRequest = { readonly kind: 'bad-request'; readonly message: string };
82
92
  type TransactionFailure = { readonly kind: 'tx-expired' | 'tx-invalid'; readonly message: string };
83
93
  type CleanupFailure = { readonly kind: 'cleanup-failed'; readonly message: string };
@@ -96,119 +106,49 @@ type Executed = { reader: boolean; rows: unknown; changes: number; lastInsertRow
96
106
  type Counters = { changes: number; total: number; lastInsertRowid: number | bigint };
97
107
  type TxControl = ReturnType<typeof transactionControl>;
98
108
 
99
- const sqliteFailure = (cause: unknown): SqliteFailure => ({
100
- kind: 'sqlite', message: errorMessage(cause),
101
- code: typeof cause === 'object' && cause !== null && 'code' in cause && typeof cause.code === 'string' ? cause.code : undefined,
102
- });
103
109
  const cleanupFailure = (cause: unknown): CleanupFailure => ({ kind: 'cleanup-failed', message: errorMessage(cause) });
104
110
  const writeFailure = (cause: unknown): WriteFailure => ({ kind: 'write-failed', message: errorMessage(cause) });
105
111
  const badRequest = (message: string) => Result.err<BadRequest>({ kind: 'bad-request', message });
106
112
 
107
- /** Distinct statements each connection keeps prepared; past this, the least recently used is finalized. */
108
- const STATEMENT_CACHE_SIZE = 256;
113
+ /** A detached read answered past this long (queue and execution together) is logged with its timing. */
114
+ const SLOW_DETACHED_READ_MS = 250;
115
+ /** How long a stopping file waits for the reader workers to close their handles on it. */
116
+ const READER_CLOSE_WAIT_MS = 250;
117
+ /** A close that found the handle lock busy never ran; it is retried this often, this many times. */
118
+ const CLOSE_RETRY_MS = 500;
119
+ const CLOSE_RETRY_LIMIT = 60;
109
120
 
110
- type PreparedStatement = SqliteStatement<unknown, SQLQueryBindings[]>;
121
+ /** The requests that may run detached: one plain read-shaped statement, no transaction. */
122
+ type DetachedRequest = Extract<Request, { op: 'query' | 'run' | 'statement' }>;
111
123
 
112
124
  /**
113
- * The prepared statements one connection reuses. Every statement handed out
114
- * here is finalized here, when evicted and by `clear()` before the connection
115
- * closes, never left to garbage collection: bun:sqlite's `close()` is
116
- * sqlite3_close_v2, which keeps a connection with an unfinalized statement
117
- * open, descriptors and all, until that statement is collected. bun:sqlite's
118
- * own `db.query()` cache cannot serve: it keeps its first 20 statements and
119
- * returns every later one uncached and unfinalized (2026-10-17: owners kept
120
- * thousands of descriptors on released, deleted files).
121
- *
122
- * SQL with a `*` anywhere is prepared for one use and finalized after it,
123
- * never cached. Its result columns (`SELECT *`, `t.*`, `RETURNING *`) follow
124
- * the schema, and a reused bun:sqlite statement keeps the column names it
125
- * last read whenever the schema changes without bun:sqlite seeing it: on the
126
- * reader after the writer's DDL, on the writer after a rollback undoes DDL
127
- * (2026-10-18, Bun 1.3.6: a cached `SELECT *` on the reader left out a column
128
- * the writer had just added). A column named in the SQL cannot change that
129
- * way; one that no longer exists fails when SQLite prepares the statement again.
125
+ * `frames` reads the request frames of this socket from its raw bytes (see
126
+ * `FrameReader.pushBytes`). `outbound` holds, in order, the bytes the kernel
127
+ * buffer refused (empty when there are none). Bun's `socket.write` returns
128
+ * the byte count it accepted and drops the rest, so a large result followed
129
+ * by another frame corrupts the stream unless the remainder is carried and
130
+ * flushed on `drain`. It is a list, not one Buffer grown by concatenation:
131
+ * a client that stopped reading while thousands of replies went out (a
132
+ * mass `tx-busy` expiry) made every reply re-copy the whole backlog, and
133
+ * the owner stalled for seconds.
130
134
  */
131
- class StatementCache {
132
- private readonly statements = new Map<string, PreparedStatement>();
133
- private readonly db: Database;
134
- private readonly onFinalizeFailed: (message: string) => void;
135
- private used = 0;
136
-
137
- constructor(db: Database, onFinalizeFailed: (message: string) => void) {
138
- this.db = db;
139
- this.onFinalizeFailed = onFinalizeFailed;
140
- }
141
-
142
- /** How many statements `use` has run on this connection, failed ones included. */
143
- get runs(): number {
144
- return this.used;
145
- }
146
-
135
+ type Connection = {
136
+ id: number;
137
+ frames: FrameReader;
138
+ outbound: Buffer[];
147
139
  /**
148
- * Runs `work` on the prepared statement for `sql` and returns its outcome;
149
- * SQL that SQLite cannot prepare is a sqlite failure.
140
+ * Reply frames not yet handed to the socket. Replies produced in one turn
141
+ * (every request of a pipelined burst, a drained queue) are joined and
142
+ * written once, from a microtask, instead of one write per reply.
150
143
  */
151
- use<T, E>(sql: string, work: (statement: PreparedStatement) => Result<T, E>) {
152
- this.used += 1;
153
- if (sql.includes('*')) return this.useOnce(sql, work);
154
- const prepared = this.prepare(sql);
155
- if (!prepared.ok) return prepared;
156
- return work(prepared.value);
157
- }
158
-
159
- /** Finalizes every statement, so the connection can then close for real. */
160
- clear(): void {
161
- for (const statement of this.statements.values()) this.finalize(statement);
162
- this.statements.clear();
163
- }
164
-
165
- /** The cached statement for `sql`, prepared on first use. */
166
- private prepare(sql: string) {
167
- const cached = this.statements.get(sql);
168
- if (cached !== undefined) {
169
- // Re-inserted so the first key is always the least recently used.
170
- this.statements.delete(sql);
171
- this.statements.set(sql, cached);
172
- return Result.ok(cached);
173
- }
174
- const prepared = Trust.try((): PreparedStatement => this.db.prepare<unknown, SQLQueryBindings[]>(sql), sqliteFailure);
175
- if (!prepared.ok) return prepared;
176
- this.statements.set(sql, prepared.value);
177
- if (this.statements.size > STATEMENT_CACHE_SIZE) this.evictLeastRecentlyUsed();
178
- return prepared;
179
- }
180
-
181
- /** `use` for SQL that is never cached: prepared, run, finalized. */
182
- private useOnce<T, E>(sql: string, work: (statement: PreparedStatement) => Result<T, E>) {
183
- const prepared = Trust.try((): PreparedStatement => this.db.prepare<unknown, SQLQueryBindings[]>(sql), sqliteFailure);
184
- if (!prepared.ok) return prepared;
185
- const outcome = work(prepared.value);
186
- this.finalize(prepared.value);
187
- return outcome;
188
- }
189
-
190
- private evictLeastRecentlyUsed(): void {
191
- const oldest = this.statements.entries().next();
192
- if (oldest.done) return;
193
- const [sql, statement] = oldest.value;
194
- this.statements.delete(sql);
195
- this.finalize(statement);
196
- }
197
-
198
- private finalize(statement: PreparedStatement): void {
199
- const finalized = Trust.try(() => statement.finalize(), sqliteFailure);
200
- if (!finalized.ok && finalized.error.kind === 'sqlite') this.onFinalizeFailed(finalized.error.message);
201
- }
202
- }
144
+ pending: string[];
145
+ flushScheduled: boolean;
146
+ socket: ServerSocket;
147
+ detachedPlain: boolean;
148
+ };
203
149
 
204
- /**
205
- * `frames` reads the request frames of this socket from its raw bytes (see
206
- * `FrameReader.pushBytes`). `outbound` holds bytes the kernel buffer refused
207
- * (null when there are none). Bun's `socket.write` returns the byte count it
208
- * accepted and drops the rest, so a large result followed by another frame
209
- * corrupts the stream unless the remainder is carried and flushed on `drain`.
210
- */
211
- type Connection = { id: number; frames: FrameReader; outbound: Buffer | null; socket: ServerSocket; detachedPlain: boolean };
150
+ /** At most this many bytes of a connection's backlog are joined into one write. */
151
+ const FLUSH_JOIN_BYTES = 64 * 1024;
212
152
 
213
153
  /** Each socket carries its connection in Bun's typed `data` slot: null until `open` assigns it. */
214
154
  type ServerSocket = import('bun').Socket<Connection | null>;
@@ -225,7 +165,13 @@ type OpenTransaction = {
225
165
  };
226
166
 
227
167
  /** A request from another client, held until the open transaction ends (or its wait runs out). */
228
- type QueuedRequest = { connection: Connection; request: Request; timer: ReturnType<typeof setTimeout> };
168
+ type QueuedRequest = {
169
+ connection: Connection;
170
+ request: Request;
171
+ timer: ReturnType<typeof setTimeout>;
172
+ /** Served, expired, or abandoned by its client: then only waiting to be skipped by the drain. */
173
+ settled: boolean;
174
+ };
229
175
 
230
176
  /** How a transaction ended, kept so a late request for it gets a precise answer. */
231
177
  type EndedTransaction = { code: 'tx-expired' | 'tx-invalid'; message: string };
@@ -281,9 +227,21 @@ export class SqlegoServer {
281
227
  * stale. (BEGIN, COMMIT and ROLLBACK, run past the cache, never move it.)
282
228
  */
283
229
  private lastTotal: Readonly<{ total: number; runs: number }> | null = null;
230
+ /** Where opted-in plain reads of this (WAL) file run; disabled, they run on `reader` in this thread. */
231
+ private readonly readers: ReaderPool;
232
+ /** The writer's `busy_timeout`, for the workers' connections to match. */
233
+ private readonly busyTimeoutMs: number;
234
+ /** Opted-in plain reads of this file: run on a worker, or on the in-thread reader (pool disabled, full, or failed). */
235
+ private pooledReads = 0;
236
+ private inlineReads = 0;
284
237
 
238
+ /**
239
+ * `detached-plain`: a WAL file with a readonly connection. `reader-pool`:
240
+ * such reads leave the owner thread (a pool of size 0 keeps them on it).
241
+ */
285
242
  get capabilities(): readonly string[] {
286
- return this.reader ? ['detached-plain'] : [];
243
+ if (!this.reader) return [];
244
+ return this.readers.enabled ? ['detached-plain', 'reader-pool'] : ['detached-plain'];
287
245
  }
288
246
  private readonly options: ServerOptions;
289
247
  private readonly startedAt = Date.now();
@@ -299,17 +257,29 @@ export class SqlegoServer {
299
257
  private requestsServed = 0;
300
258
  private stopping = false;
301
259
  private transaction: OpenTransaction | null = null;
302
- private readonly queue: QueuedRequest[] = [];
260
+ /**
261
+ * Held requests in arrival order, settled ones included until the drain
262
+ * reaches them: an expiry or a client leaving settles its entries in
263
+ * place, so neither searches nor splices the queue (with tens of thousands
264
+ * waiting, mass expiry was quadratic and froze the owner for seconds).
265
+ * `waiting` counts the unsettled ones.
266
+ */
267
+ private queue: QueuedRequest[] = [];
268
+ private waiting = 0;
269
+ /** Whether `drainQueue` is running, so the drain `serve` asks for inside it is left to the running loop. */
270
+ private draining = false;
303
271
  private readonly ended = new Map<number, EndedTransaction>();
304
272
  private readonly log: NonNullable<ServerOptions['log']>;
305
273
 
306
- private constructor(options: ServerOptions, paths: FilePaths, db: Database, pragmas: readonly string[], reader: Database | null) {
274
+ private constructor(options: ServerOptions, paths: FilePaths, db: Database, pragmas: readonly string[], reader: Database | null, busyTimeoutMs: number, readers: ReaderPool) {
307
275
  this.options = options;
308
276
  this.paths = paths;
309
277
  this.db = db;
310
278
  this.reader = reader;
311
279
  this.pragmas = pragmas;
280
+ this.busyTimeoutMs = busyTimeoutMs;
312
281
  this.log = options.log ?? (() => undefined);
282
+ this.readers = readers;
313
283
  const finalizeFailed = (message: string) => this.log('finalize failed', { error: message });
314
284
  this.statements = new StatementCache(db, finalizeFailed);
315
285
  this.readerStatements = reader ? new StatementCache(reader, finalizeFailed) : null;
@@ -320,32 +290,30 @@ export class SqlegoServer {
320
290
  const paths = resolvePaths(options.file);
321
291
  if (!paths.ok) return paths;
322
292
  const pragmas = options.pragmas ?? DEFAULT_PRAGMAS;
323
- const db = Trust.try(
293
+ // Handles open and close under the pool's lock, never alongside a worker's (see `ReaderPool.withOpenLock`).
294
+ const readers = options.readerPool ?? sharedReaderPool(options.log);
295
+ const openFailed = (cause: unknown) => ({ kind: 'open-failed' as const, message: `cannot open ${paths.value.file}: ${errorMessage(cause)}` });
296
+ const db = readers.withOpenLock(() => Trust.try(
324
297
  () => {
325
298
  mkdirSync(path.dirname(paths.value.file), { recursive: true });
326
299
  // safeIntegers: SQLite integers arrive as bigint so `statement`/`exec`
327
300
  // can return all 64 bits; `query`/`run`/`batch` still send JSON numbers.
328
301
  return new Database(paths.value.file, { create: true, strict: false, safeIntegers: true });
329
302
  },
330
- (cause) => ({ kind: 'open-failed', message: `cannot open ${paths.value.file}: ${errorMessage(cause)}` }),
331
- );
303
+ openFailed,
304
+ ), openFailed);
332
305
  if (!db.ok) return db;
333
306
  const configured = Trust.try(
334
307
  () => {
335
308
  for (const pragma of pragmas) db.value.exec(`PRAGMA ${pragma}`);
336
309
  },
337
- (cause) => ({ kind: 'open-failed', message: `cannot open ${paths.value.file}: ${errorMessage(cause)}` }),
310
+ openFailed,
311
+ );
312
+ const openedReader = !configured.ok ? configured : openReader(db.value, paths.value.file, readers);
313
+ const server = new SqlegoServer(
314
+ options, paths.value, db.value, [...pragmas],
315
+ openedReader.ok ? openedReader.value.reader : null, openedReader.ok ? openedReader.value.busyTimeoutMs : 5000, readers,
338
316
  );
339
- let reader: Database | null = null;
340
- const openedReader = !configured.ok ? configured : Trust.try(() => {
341
- const mode = db.value.query('PRAGMA journal_mode').values()[0]?.[0];
342
- if (String(mode).toLowerCase() !== 'wal') return;
343
- reader = new Database(paths.value.file, { readonly: true, safeIntegers: true });
344
- const timeout = db.value.query('PRAGMA busy_timeout').values()[0]?.[0] ?? 5000;
345
- reader.exec(`PRAGMA busy_timeout = ${Number(timeout)}`);
346
- reader.exec('PRAGMA query_only = ON');
347
- }, (cause) => ({ kind: 'open-failed', message: `cannot open reader for ${paths.value.file}: ${errorMessage(cause)}` }));
348
- const server = new SqlegoServer(options, paths.value, db.value, [...pragmas], reader);
349
317
  if (!openedReader.ok) {
350
318
  // No socket/metadata has been created yet; only the connections opened here must go.
351
319
  server.closeConnections();
@@ -433,8 +401,16 @@ export class SqlegoServer {
433
401
  if (this.idleTimer) clearTimeout(this.idleTimer);
434
402
  if (this.fileCheckTimer) clearTimeout(this.fileCheckTimer);
435
403
  if (this.transaction) this.endTransaction('server stopping', 'tx-expired', true);
436
- for (const queued of this.queue.splice(0)) clearTimeout(queued.timer);
404
+ for (const queued of this.queue) clearTimeout(queued.timer);
405
+ this.queue = [];
406
+ this.waiting = 0;
437
407
  for (const connection of this.connections.values()) {
408
+ // Replies still waiting for their microtask (the reply to this `stop`
409
+ // among them) go out before the socket ends, as they did when every
410
+ // reply was written at once.
411
+ const queued = this.flushPending(connection);
412
+ const flushed = queued.ok ? this.flush(connection) : queued;
413
+ if (!flushed.ok && flushed.error.kind === 'write-failed') this.log('flush before stop failed', { connection: connection.id, error: flushed.error.message });
438
414
  this.reportCleanup('end connection', Trust.try(() => connection.socket.end(), cleanupFailure));
439
415
  }
440
416
  this.closeConnections();
@@ -467,6 +443,12 @@ export class SqlegoServer {
467
443
  * checkpoints the WAL and removes it, which a readonly one cannot do.
468
444
  */
469
445
  private closeConnections(): void {
446
+ // The workers' handles first, waited for (bounded): a worker still
447
+ // holding the file when the writer closes would leave the WAL for the
448
+ // next opener to checkpoint. A worker in a long read answers late.
449
+ if (this.reader && this.readers.enabled && !this.readers.releaseSync(this.paths.file, READER_CLOSE_WAIT_MS)) {
450
+ this.log('reader workers still hold the file', { file: this.paths.file, waitedMs: READER_CLOSE_WAIT_MS });
451
+ }
470
452
  if (this.reader) this.closeConnection('reader', this.reader, this.readerStatements);
471
453
  this.closeConnection('database', this.db, this.statements);
472
454
  }
@@ -479,12 +461,37 @@ export class SqlegoServer {
479
461
  * "database is locked") is logged and the deferred close still runs, so the
480
462
  * file is released no later than that statement is collected.
481
463
  */
482
- private closeConnection(name: 'reader' | 'database', database: Database, statements: StatementCache | null): void {
464
+ private closeConnection(name: 'reader' | 'database', database: Database, statements: StatementCache | null, attempt = 0): void {
483
465
  statements?.clear();
484
- const closed = Trust.try(() => database.close(true), cleanupFailure);
466
+ // Set only when the handle lock could not be taken: the close itself never ran, so it is retried later.
467
+ let lockBusy = false;
468
+ const busy = (cause: unknown): CleanupFailure => {
469
+ lockBusy = true;
470
+ return cleanupFailure(cause);
471
+ };
472
+ const closed = this.readers.withOpenLock(() => Trust.try(() => database.close(true), cleanupFailure), busy);
485
473
  if (closed.ok) return;
474
+ if (lockBusy) {
475
+ this.retryClose(name, database, closed, attempt);
476
+ return;
477
+ }
486
478
  this.reportCleanup(`close ${name} (deferred: a statement is still unfinalized)`, closed);
487
- this.reportCleanup(`close ${name}`, Trust.try(() => database.close(), cleanupFailure));
479
+ const plain = this.readers.withOpenLock(() => Trust.try(() => database.close(), cleanupFailure), busy);
480
+ if (lockBusy) {
481
+ this.retryClose(name, database, plain, attempt);
482
+ return;
483
+ }
484
+ this.reportCleanup(`close ${name}`, plain);
485
+ }
486
+
487
+ /** Retries a close that found the handle lock busy, so a stopped file's handles are not abandoned in a live owner. */
488
+ private retryClose(name: 'reader' | 'database', database: Database, failure: Result<unknown, CleanupFailure>, attempt: number): void {
489
+ if (attempt >= CLOSE_RETRY_LIMIT) {
490
+ this.reportCleanup(`close ${name} (handle lock still busy after ${attempt} retries; abandoned)`, failure);
491
+ return;
492
+ }
493
+ this.reportCleanup(`close ${name} (handle lock busy; retry ${attempt + 1} of ${CLOSE_RETRY_LIMIT} scheduled)`, failure);
494
+ setTimeout(() => this.closeConnection(name, database, null, attempt + 1), CLOSE_RETRY_MS);
488
495
  }
489
496
 
490
497
  status(): StatusResult {
@@ -503,6 +510,8 @@ export class SqlegoServer {
503
510
  idleTimeoutMs: this.options.idleTimeoutMs,
504
511
  requestsServed: this.requestsServed,
505
512
  transaction: this.transactionStatus(),
513
+ readers: this.reader ? this.readers.status() : null,
514
+ detachedReads: { pooled: this.pooledReads, inline: this.inlineReads },
506
515
  };
507
516
  }
508
517
 
@@ -516,7 +525,7 @@ export class SqlegoServer {
516
525
  idleMs: now - open.lastRequestAt,
517
526
  leaseMs: open.leaseMs,
518
527
  maxDurationMs: this.txMaxDurationMs(),
519
- queued: this.queue.length,
528
+ queued: this.waiting,
520
529
  };
521
530
  }
522
531
 
@@ -543,7 +552,7 @@ export class SqlegoServer {
543
552
  return;
544
553
  }
545
554
  const id = this.nextConnectionId++;
546
- const connection: Connection = { id, frames: new FrameReader(), outbound: null, socket, detachedPlain: false };
555
+ const connection: Connection = { id, frames: new FrameReader(), outbound: [], pending: [], flushScheduled: false, socket, detachedPlain: false };
547
556
  this.connections.set(id, connection);
548
557
  socket.data = connection;
549
558
  this.disarmIdleTimer();
@@ -554,8 +563,10 @@ export class SqlegoServer {
554
563
  if (!connection) return;
555
564
  this.connections.delete(connection.id);
556
565
  // A waiting request from a client that left has nobody to answer.
557
- for (let index = this.queue.length - 1; index >= 0; index -= 1) {
558
- if (this.queue[index].connection === connection) clearTimeout(this.queue.splice(index, 1)[0].timer);
566
+ if (this.waiting > 0) {
567
+ for (const queued of this.queue) {
568
+ if (queued.connection === connection) this.settleQueued(queued);
569
+ }
559
570
  }
560
571
  if (this.transaction && this.transaction.connection === connection) {
561
572
  this.endTransaction(`client ${connection.id} disconnected`, 'tx-expired', true);
@@ -583,18 +594,30 @@ export class SqlegoServer {
583
594
  const parsed = this.parseFrame(frame);
584
595
  if (!parsed.ok) return this.reply(connection, { id: parsed.error.id, ok: false, error: { code: 'bad-request', message: parsed.error.message } });
585
596
  const request = parsed.value;
586
- if (this.reader && this.isDetachedRead(connection, request)) {
587
- const outcome = this.execute(connection, request, this.reader);
597
+ const detached = this.reader ? this.detachedRead(connection, request) : null;
598
+ if (this.reader && detached !== null) {
599
+ // On a worker when the pool takes it: answered from `onDetachedRead`.
600
+ if (this.submitDetachedRead(connection, detached)) return;
601
+ this.inlineReads += 1;
602
+ const outcome = this.execute(connection, detached, this.reader);
588
603
  // A write-shaped CTE is retried only when SQLite refused it as readonly.
589
604
  // All other failures (including TEMP-table misses) must be returned once.
590
605
  if (outcome.ok || outcome.error.kind !== 'sqlite' || outcome.error.code !== 'SQLITE_READONLY') {
591
- this.serve(connection, request, outcome);
606
+ this.serve(connection, detached, outcome);
592
607
  return;
593
608
  }
594
609
  }
610
+ this.serveOrHold(connection, request);
611
+ }
612
+
613
+ /** Serves the request now, or holds it behind another client's transaction. */
614
+ private serveOrHold(connection: Connection, request: Request): void {
595
615
  if (this.mustWait(connection, request)) {
596
- const timer = setTimeout(() => this.expireQueued(connection, request), this.txQueueTimeoutMs());
597
- this.queue.push({ connection, request, timer });
616
+ const queued: QueuedRequest = {
617
+ connection, request, settled: false, timer: setTimeout(() => this.expireQueued(queued), this.txQueueTimeoutMs()),
618
+ };
619
+ this.queue.push(queued);
620
+ this.waiting += 1;
598
621
  return;
599
622
  }
600
623
  this.serve(connection, request);
@@ -629,20 +652,107 @@ export class SqlegoServer {
629
652
  }
630
653
  }
631
654
 
632
- private isDetachedRead(connection: Connection, request: Request): boolean {
633
- if (!connection.detachedPlain) return false;
634
- if (request.op !== 'query' && request.op !== 'run' && request.op !== 'statement') return false;
635
- if (request.txId !== undefined) return false;
636
- const pieces = splitSqlStatements(request.sql);
637
- if (pieces.length !== 1) return false;
638
- const body = pieces[0].replace(/^(?:\s+|--[^\n]*\n?|\/\*[\s\S]*?\*\/)+/, '');
639
- return /^(SELECT|WITH|VALUES|EXPLAIN)\b/i.test(body);
655
+ /** The request as a detached read, or null when it is not one (not opted in, another op, in a transaction, or not read-shaped). */
656
+ private detachedRead(connection: Connection, request: Request): DetachedRequest | null {
657
+ if (!connection.detachedPlain) return null;
658
+ if (request.op !== 'query' && request.op !== 'run' && request.op !== 'statement') return null;
659
+ if (request.txId !== undefined) return null;
660
+ return sqlShape(request.sql).detachedRead ? request : null;
661
+ }
662
+
663
+ /**
664
+ * Hands a detached read to the pool; false when the pool did not take it
665
+ * (disabled, or its queue is full) and the caller must read in-thread.
666
+ * `statement` runs the one statement the text holds (its shape was
667
+ * checked by `isDetachedRead`); `query`/`run` send the text as it came,
668
+ * as their writer path does.
669
+ */
670
+ private submitDetachedRead(connection: Connection, request: DetachedRequest): boolean {
671
+ // `run` discards rows: a worker would materialize and clone the whole result for nothing, so it stays in-thread on `statement.run()`.
672
+ if (!this.readers.enabled || request.op === 'run') return false;
673
+ const sql = request.op === 'statement' ? sqlShape(request.sql).pieces[0] : request.sql;
674
+ const params: SQLQueryBindings[] = request.params === undefined ? [] : bindings(request.params);
675
+ const taken = this.readers.submit({
676
+ file: this.paths.file, busyTimeoutMs: this.busyTimeoutMs, sql, params,
677
+ onDone: (outcome) => this.onDetachedRead(connection, request, outcome),
678
+ });
679
+ if (taken) this.pooledReads += 1;
680
+ return taken;
681
+ }
682
+
683
+ /**
684
+ * A detached read is back from its worker. Rows are answered as they ran.
685
+ * `SQLITE_READONLY` (a write-shaped CTE) goes to the writer under the
686
+ * normal queueing rules, as the in-thread path does. A failed worker is
687
+ * the pool's problem, not the client's: the read runs again in-thread.
688
+ * Any other failure is answered as-is, once.
689
+ */
690
+ private onDetachedRead(connection: Connection, request: DetachedRequest, outcome: ReaderOutcome): void {
691
+ const settled = Trust.decide(outcome, {
692
+ 'worker-failed': (error) => ({ retry: error.message }),
693
+ sqlite: (error) => ({ failure: error }),
694
+ }).value;
695
+ // A departed client's request must not run again, least of all as a write.
696
+ if (!this.connections.has(connection.id)) return;
697
+ if ('retry' in settled) {
698
+ this.log('detached read fell back in-thread', { connection: connection.id, error: settled.retry });
699
+ if (this.stopping || !this.reader) {
700
+ this.serve(connection, request);
701
+ return;
702
+ }
703
+ this.inlineReads += 1;
704
+ const retried = this.execute(connection, request, this.reader);
705
+ if (retried.ok || retried.error.kind !== 'sqlite' || retried.error.code !== 'SQLITE_READONLY') {
706
+ this.serve(connection, request, retried);
707
+ return;
708
+ }
709
+ this.serveOrHold(connection, request);
710
+ return;
711
+ }
712
+ if ('failure' in settled) {
713
+ if (settled.failure.code === 'SQLITE_READONLY') {
714
+ this.serveOrHold(connection, request);
715
+ return;
716
+ }
717
+ this.serve(connection, request, Result.err<SqliteFailure>(settled.failure));
718
+ return;
719
+ }
720
+ if (settled.queueMs + settled.roundTripMs >= SLOW_DETACHED_READ_MS) {
721
+ this.log('slow detached read', {
722
+ connection: connection.id, op: request.op, queueMs: Math.round(settled.queueMs), execMs: Math.round(settled.execMs),
723
+ roundTripMs: Math.round(settled.roundTripMs), sql: request.sql.slice(0, 200),
724
+ });
725
+ }
726
+ this.serve(connection, request, this.detachedResult(request.op, settled));
727
+ }
728
+
729
+ private detachedResult(op: DetachedRequest['op'], rows: ReaderRows) {
730
+ switch (op) {
731
+ case 'query': {
732
+ const parsed = parseRows(rows.rows);
733
+ if (!parsed.ok) return Result.err<SqliteFailure>({ kind: 'sqlite', message: `unexpected row shape: ${parsed.error.message}` });
734
+ const result: QueryResult = { rows: parsed.value };
735
+ return Result.ok<QueryResult | RunResult | StatementWireResult>(result);
736
+ }
737
+ case 'run': {
738
+ const result: RunResult = { changes: 0, lastInsertRowid: 0 };
739
+ return Result.ok<QueryResult | RunResult | StatementWireResult>(result);
740
+ }
741
+ case 'statement': {
742
+ const executed: Executed = { reader: rows.reader, rows: rows.rows, changes: 0, lastInsertRowid: 0 };
743
+ return this.encodeExecuted(Result.ok(executed));
744
+ }
745
+ default: {
746
+ const unhandled: never = op;
747
+ return unhandled;
748
+ }
749
+ }
640
750
  }
641
751
 
642
- private expireQueued(connection: Connection, request: Request): void {
643
- const index = this.queue.findIndex((queued) => queued.request === request);
644
- if (index < 0) return;
645
- this.queue.splice(index, 1);
752
+ private expireQueued(queued: QueuedRequest): void {
753
+ if (queued.settled) return;
754
+ this.settleQueued(queued);
755
+ const { connection, request } = queued;
646
756
  const waited = this.txQueueTimeoutMs();
647
757
  this.reply(connection, {
648
758
  id: request.id, ok: false,
@@ -650,13 +760,42 @@ export class SqlegoServer {
650
760
  });
651
761
  }
652
762
 
653
- /** Serves held requests in arrival order until one of them opens a new transaction. */
763
+ /**
764
+ * Takes a held request out of the wait, in place. The settled entries are
765
+ * dropped from the array once none is waiting, or once they are most of a
766
+ * large one, so a queue that keeps expiring behind a long transaction stays
767
+ * bounded by what is actually waiting.
768
+ */
769
+ private settleQueued(queued: QueuedRequest): void {
770
+ if (queued.settled) return;
771
+ queued.settled = true;
772
+ clearTimeout(queued.timer);
773
+ this.waiting -= 1;
774
+ if (this.waiting === 0) this.queue = [];
775
+ else if (this.queue.length > 1_024 && this.waiting * 2 < this.queue.length) this.queue = this.queue.filter((entry) => !entry.settled);
776
+ }
777
+
778
+ /**
779
+ * Serves held requests in arrival order until one of them opens a new
780
+ * transaction. Not re-entrant: `serve` drains after every request, and
781
+ * when that nested drain served the next waiter itself, draining N waiters
782
+ * nested N calls deep — about 5 000 requests queued behind one transaction
783
+ * overflowed the stack, and every waiting client was dropped as
784
+ * "cannot encode response". A nested call returns and the outer loop goes on.
785
+ */
654
786
  private drainQueue(): void {
655
- while (this.queue.length > 0 && this.transaction === null && !this.stopping) {
656
- const next = this.queue.shift();
657
- if (!next) return;
658
- clearTimeout(next.timer);
659
- this.serve(next.connection, next.request);
787
+ if (this.draining) return;
788
+ this.draining = true;
789
+ try {
790
+ while (this.waiting > 0 && this.transaction === null && !this.stopping) {
791
+ const next = this.queue.shift();
792
+ if (!next) return;
793
+ if (next.settled) continue;
794
+ this.settleQueued(next);
795
+ this.serve(next.connection, next.request);
796
+ }
797
+ } finally {
798
+ this.draining = false;
660
799
  }
661
800
  }
662
801
 
@@ -781,7 +920,7 @@ export class SqlegoServer {
781
920
  * as `query`/`run`.
782
921
  */
783
922
  private unifiedStatement(connection: Connection, sql: string, params: SqlParams | undefined, txId: number | undefined, db = this.db) {
784
- const pieces = splitSqlStatements(sql);
923
+ const { pieces } = sqlShape(sql);
785
924
  if (pieces.length === 0) return badRequest('statement needs one SQL statement; the text has none');
786
925
  if (pieces.length > 1) return badRequest(`statement takes one SQL statement, the text has ${pieces.length}: use exec for several`);
787
926
  const piece = pieces[0];
@@ -795,8 +934,8 @@ export class SqlegoServer {
795
934
  * hidden after a harmless first statement is refused just like a leading one.
796
935
  */
797
936
  private exec(connection: Connection, sql: string, txId: number | undefined) {
798
- const pieces = splitSqlStatements(sql);
799
- return this.scoped(connection, 'exec', txId, pieces.map((piece) => transactionControl(piece)), () => this.runScript(pieces));
937
+ const { pieces, controls } = sqlShape(sql);
938
+ return this.scoped(connection, 'exec', txId, controls, () => this.runScript(pieces));
800
939
  }
801
940
 
802
941
  /**
@@ -858,9 +997,11 @@ export class SqlegoServer {
858
997
  () => {
859
998
  const outcome = params === undefined ? statement.run() : statement.run(...bindings(params));
860
999
  // safeIntegers may report either counter as bigint; `run` keeps answering with numbers.
1000
+ // Converted here, as the encoder's bigint replacer used to on the wire (the same bytes),
1001
+ // so the reply has no bigint left and is encoded without the replacer.
861
1002
  const result: RunResult = db === this.reader
862
1003
  ? { changes: 0, lastInsertRowid: 0 }
863
- : { changes: Number(outcome.changes), lastInsertRowid: outcome.lastInsertRowid };
1004
+ : { changes: Number(outcome.changes), lastInsertRowid: Number(outcome.lastInsertRowid) };
864
1005
  return result;
865
1006
  },
866
1007
  sqliteFailure,
@@ -917,15 +1058,7 @@ export class SqlegoServer {
917
1058
  * result columns steps to its end in `all()` just as in `run()`.
918
1059
  */
919
1060
  private step(sql: string, args: SQLQueryBindings[], db: Database) {
920
- return this.statementsOf(db).use(sql, (statement) => Trust.try(
921
- () => {
922
- const rows: unknown = statement.all(...args);
923
- const columns: unknown = statement.columnNames;
924
- if (!Array.isArray(columns)) throw new Error('SQLite returned invalid column metadata');
925
- return { reader: columns.length > 0, rows };
926
- },
927
- sqliteFailure,
928
- ));
1061
+ return stepStatement(this.statementsOf(db), sql, args);
929
1062
  }
930
1063
 
931
1064
  /** The writer's `total_changes()` now: `lastTotal` while no statement has run since, else read. */
@@ -1150,27 +1283,54 @@ export class SqlegoServer {
1150
1283
  if (frame.error.kind === 'encode-failed') this.dropConnection(connection, `cannot encode response ${response.id}: ${frame.error.message}`);
1151
1284
  return;
1152
1285
  }
1153
- const sent = this.send(connection, frame.value);
1154
- if (!sent.ok && sent.error.kind === 'write-failed') this.dropConnection(connection, sent.error.message);
1286
+ // Written from a microtask (see `send`); a write that fails there drops the connection.
1287
+ this.send(connection, frame.value);
1155
1288
  }
1156
1289
 
1157
1290
  private dropConnection(connection: Connection, why: string): void {
1158
1291
  this.log('dropping connection', { connection: connection.id, error: why });
1159
- connection.outbound = null;
1292
+ connection.outbound = [];
1293
+ connection.pending = [];
1160
1294
  this.reportCleanup('drop connection', Trust.try(() => connection.socket.end(), cleanupFailure));
1161
1295
  }
1162
1296
 
1163
- /** Queues behind any unflushed bytes so frames never interleave. */
1164
- private send(connection: Connection, frame: string) {
1165
- const queued = Trust.try(
1297
+ /**
1298
+ * Queues one frame behind every frame before it, so frames never
1299
+ * interleave, and schedules one write for everything queued this turn.
1300
+ */
1301
+ private send(connection: Connection, frame: string): void {
1302
+ connection.pending.push(frame);
1303
+ if (connection.flushScheduled) return;
1304
+ connection.flushScheduled = true;
1305
+ queueMicrotask(() => {
1306
+ const flushed = this.flushPending(connection);
1307
+ if (!flushed.ok && flushed.error.kind === 'write-failed') this.dropConnection(connection, flushed.error.message);
1308
+ });
1309
+ }
1310
+
1311
+ /**
1312
+ * Hands the queued frames to the socket: behind unflushed bytes when there
1313
+ * are any (they wait for `drain`, which a refused write always brings),
1314
+ * else as one string write, keeping only what the kernel refused.
1315
+ */
1316
+ private flushPending(connection: Connection) {
1317
+ connection.flushScheduled = false;
1318
+ if (connection.pending.length === 0) return Result.ok(undefined);
1319
+ const text = connection.pending.length === 1 ? connection.pending[0] : connection.pending.join('');
1320
+ connection.pending = [];
1321
+ if (!this.connections.has(connection.id)) return Result.ok(undefined);
1322
+ return Trust.try(
1166
1323
  () => {
1167
- const bytes = Buffer.from(frame, 'utf8');
1168
- connection.outbound = connection.outbound === null ? bytes : Buffer.concat([connection.outbound, bytes]);
1324
+ if (connection.outbound.length > 0) {
1325
+ connection.outbound.push(Buffer.from(text, 'utf8'));
1326
+ return;
1327
+ }
1328
+ const written = connection.socket.write(text);
1329
+ const length = Buffer.byteLength(text, 'utf8');
1330
+ if (written < length) connection.outbound.push(Buffer.from(text, 'utf8').subarray(Math.max(written, 0)));
1169
1331
  },
1170
1332
  writeFailure,
1171
1333
  );
1172
- if (!queued.ok) return queued;
1173
- return this.flush(connection);
1174
1334
  }
1175
1335
 
1176
1336
  private onDrain(socket: ServerSocket): void {
@@ -1180,13 +1340,27 @@ export class SqlegoServer {
1180
1340
  if (!flushed.ok && flushed.error.kind === 'write-failed') this.dropConnection(connection, flushed.error.message);
1181
1341
  }
1182
1342
 
1343
+ /**
1344
+ * Writes the unflushed bytes in order until the kernel refuses some. Small
1345
+ * chunks are joined up to `FLUSH_JOIN_BYTES` per write, so each byte is
1346
+ * copied a bounded number of times however long the backlog grew.
1347
+ */
1183
1348
  private flush(connection: Connection) {
1184
1349
  return Trust.try(
1185
1350
  () => {
1186
- const pending = connection.outbound;
1187
- if (pending === null) return;
1188
- const written = connection.socket.write(pending);
1189
- connection.outbound = written >= pending.length ? null : pending.subarray(Math.max(written, 0));
1351
+ const chunks = connection.outbound;
1352
+ while (chunks.length > 0) {
1353
+ let take = 1;
1354
+ let size = chunks[0].length;
1355
+ while (take < chunks.length && size + chunks[take].length <= FLUSH_JOIN_BYTES) size += chunks[take++].length;
1356
+ const bytes = take === 1 ? chunks[0] : Buffer.concat(chunks.slice(0, take), size);
1357
+ const written = Math.max(connection.socket.write(bytes), 0);
1358
+ chunks.splice(0, take);
1359
+ if (written < bytes.length) {
1360
+ chunks.unshift(bytes.subarray(written));
1361
+ return;
1362
+ }
1363
+ }
1190
1364
  },
1191
1365
  writeFailure,
1192
1366
  );
@@ -1296,6 +1470,39 @@ export class SqlegoServer {
1296
1470
  }
1297
1471
  }
1298
1472
 
1473
+ /** How the owner classifies one SQL text: its statements, the transaction control each starts with, and whether it may run detached. */
1474
+ type SqlShape = Readonly<{ pieces: readonly string[]; controls: readonly TxControl[]; detachedRead: boolean }>;
1475
+
1476
+ /** Distinct SQL texts whose shape is remembered; past this, the oldest is forgotten. */
1477
+ const SQL_SHAPE_CACHE_SIZE = 512;
1478
+ /** Longer texts (migrations, scripts) are classified each time and never held. */
1479
+ const SQL_SHAPE_MAX_LENGTH = 4_096;
1480
+ const sqlShapes = new Map<string, SqlShape>();
1481
+
1482
+ /**
1483
+ * The shape of `sql`. It depends only on the text, and applications send the
1484
+ * same few statements over and over, so short texts are classified once and
1485
+ * reused: splitting them was most of the owner's own work per point read.
1486
+ */
1487
+ function sqlShape(sql: string): SqlShape {
1488
+ const cached = sqlShapes.get(sql);
1489
+ if (cached !== undefined) return cached;
1490
+ const pieces = splitSqlStatements(sql);
1491
+ const shape: SqlShape = {
1492
+ pieces,
1493
+ controls: pieces.map((piece) => transactionControl(piece)),
1494
+ detachedRead: pieces.length === 1 && /^(SELECT|WITH|VALUES|EXPLAIN)\b/i.test(pieces[0].replace(/^(?:\s+|--[^\n]*\n?|\/\*[\s\S]*?\*\/)+/, '')),
1495
+ };
1496
+ if (sql.length <= SQL_SHAPE_MAX_LENGTH) {
1497
+ if (sqlShapes.size >= SQL_SHAPE_CACHE_SIZE) {
1498
+ const oldest = sqlShapes.keys().next();
1499
+ if (!oldest.done) sqlShapes.delete(oldest.value);
1500
+ }
1501
+ sqlShapes.set(sql, shape);
1502
+ }
1503
+ return shape;
1504
+ }
1505
+
1299
1506
  /**
1300
1507
  * Refuses transaction-control statements: all of them outside a transaction
1301
1508
  * (a stray `BEGIN` or `SAVEPOINT` would wrap every client's later statements),
@@ -1345,3 +1552,38 @@ function parseCounters(input: unknown) {
1345
1552
  function bindings(params: SqlParams): SQLQueryBindings[] {
1346
1553
  return Array.isArray(params) ? (params as SqlValue[]) : [params as Record<string, SqlValue>];
1347
1554
  }
1555
+
1556
+ type OpenedReader = Readonly<{ reader: Database | null; busyTimeoutMs: number }>;
1557
+ type OpenFailed = Readonly<{ kind: 'open-failed'; message: string }>;
1558
+
1559
+ /**
1560
+ * The in-thread readonly connection of a WAL file (null for any other
1561
+ * journal mode), with the writer's `busy_timeout` for it and the workers.
1562
+ * Opened under the pool's open/close lock, like every handle of the process.
1563
+ */
1564
+ function openReader(db: Database, file: string, readers: ReaderPool): Result<OpenedReader, OpenFailed> {
1565
+ const failed = (cause: unknown): OpenFailed => ({ kind: 'open-failed', message: `cannot open reader for ${file}: ${errorMessage(cause)}` });
1566
+ const probed = Trust.try((): number | null => {
1567
+ const mode = db.query('PRAGMA journal_mode').values()[0]?.[0];
1568
+ if (String(mode).toLowerCase() !== 'wal') return null;
1569
+ // A readonly connection cannot open a WAL database whose `-wal` and
1570
+ // `-shm` files do not exist yet (SQLITE_CANTOPEN, "unable to open
1571
+ // database file"); the writer's first read transaction creates them,
1572
+ // so a brand-new file is read once here before any reader opens it.
1573
+ db.query('SELECT count(*) AS n FROM sqlite_master').get();
1574
+ return Number(db.query('PRAGMA busy_timeout').values()[0]?.[0] ?? 5000);
1575
+ }, failed);
1576
+ if (!probed.ok) return probed;
1577
+ const busyTimeoutMs = probed.value;
1578
+ if (busyTimeoutMs === null) return Result.ok<OpenedReader>({ reader: null, busyTimeoutMs: 5000 });
1579
+ const opened = readers.withOpenLock(() => Trust.try(() => {
1580
+ const reader = new Database(file, { readonly: true, safeIntegers: true });
1581
+ reader.exec(`PRAGMA busy_timeout = ${busyTimeoutMs}`);
1582
+ reader.exec('PRAGMA query_only = ON');
1583
+ // Its first read transaction happens here, not on a client's read (see `reader_worker.ts`'s `open`).
1584
+ reader.query('SELECT count(*) AS n FROM sqlite_master').get();
1585
+ return reader;
1586
+ }, failed), failed);
1587
+ if (!opened.ok) return opened;
1588
+ return Result.ok<OpenedReader>({ reader: opened.value, busyTimeoutMs });
1589
+ }