@noego/sqlego 0.1.5 → 0.1.6-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/README.md +49 -5
- package/dist/index.d.ts +1 -1
- package/dist/index.js +44 -10
- package/dist/protocol.d.ts +36 -0
- package/package.json +7 -7
- package/src/cli.ts +12 -2
- package/src/index.ts +1 -0
- package/src/protocol.ts +56 -0
- package/src/reader_pool.ts +408 -0
- package/src/reader_worker.ts +189 -0
- package/src/server.ts +228 -137
- package/src/statement_cache.ts +131 -0
package/src/server.ts
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
|
-
import { Database, type SQLQueryBindings
|
|
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,110 +106,20 @@ 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
|
-
/**
|
|
108
|
-
const
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
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.
|
|
130
|
-
*/
|
|
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
|
-
|
|
147
|
-
/**
|
|
148
|
-
* Runs `work` on the prepared statement for `sql` and returns its outcome;
|
|
149
|
-
* SQL that SQLite cannot prepare is a sqlite failure.
|
|
150
|
-
*/
|
|
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
|
-
}
|
|
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;
|
|
197
120
|
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
if (!finalized.ok && finalized.error.kind === 'sqlite') this.onFinalizeFailed(finalized.error.message);
|
|
201
|
-
}
|
|
202
|
-
}
|
|
121
|
+
/** The requests that may run detached: one plain read-shaped statement, no transaction. */
|
|
122
|
+
type DetachedRequest = Extract<Request, { op: 'query' | 'run' | 'statement' }>;
|
|
203
123
|
|
|
204
124
|
/**
|
|
205
125
|
* `frames` reads the request frames of this socket from its raw bytes (see
|
|
@@ -307,9 +227,21 @@ export class SqlegoServer {
|
|
|
307
227
|
* stale. (BEGIN, COMMIT and ROLLBACK, run past the cache, never move it.)
|
|
308
228
|
*/
|
|
309
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;
|
|
310
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
|
+
*/
|
|
311
242
|
get capabilities(): readonly string[] {
|
|
312
|
-
|
|
243
|
+
if (!this.reader) return [];
|
|
244
|
+
return this.readers.enabled ? ['detached-plain', 'reader-pool'] : ['detached-plain'];
|
|
313
245
|
}
|
|
314
246
|
private readonly options: ServerOptions;
|
|
315
247
|
private readonly startedAt = Date.now();
|
|
@@ -339,13 +271,15 @@ export class SqlegoServer {
|
|
|
339
271
|
private readonly ended = new Map<number, EndedTransaction>();
|
|
340
272
|
private readonly log: NonNullable<ServerOptions['log']>;
|
|
341
273
|
|
|
342
|
-
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) {
|
|
343
275
|
this.options = options;
|
|
344
276
|
this.paths = paths;
|
|
345
277
|
this.db = db;
|
|
346
278
|
this.reader = reader;
|
|
347
279
|
this.pragmas = pragmas;
|
|
280
|
+
this.busyTimeoutMs = busyTimeoutMs;
|
|
348
281
|
this.log = options.log ?? (() => undefined);
|
|
282
|
+
this.readers = readers;
|
|
349
283
|
const finalizeFailed = (message: string) => this.log('finalize failed', { error: message });
|
|
350
284
|
this.statements = new StatementCache(db, finalizeFailed);
|
|
351
285
|
this.readerStatements = reader ? new StatementCache(reader, finalizeFailed) : null;
|
|
@@ -356,32 +290,30 @@ export class SqlegoServer {
|
|
|
356
290
|
const paths = resolvePaths(options.file);
|
|
357
291
|
if (!paths.ok) return paths;
|
|
358
292
|
const pragmas = options.pragmas ?? DEFAULT_PRAGMAS;
|
|
359
|
-
|
|
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(
|
|
360
297
|
() => {
|
|
361
298
|
mkdirSync(path.dirname(paths.value.file), { recursive: true });
|
|
362
299
|
// safeIntegers: SQLite integers arrive as bigint so `statement`/`exec`
|
|
363
300
|
// can return all 64 bits; `query`/`run`/`batch` still send JSON numbers.
|
|
364
301
|
return new Database(paths.value.file, { create: true, strict: false, safeIntegers: true });
|
|
365
302
|
},
|
|
366
|
-
|
|
367
|
-
);
|
|
303
|
+
openFailed,
|
|
304
|
+
), openFailed);
|
|
368
305
|
if (!db.ok) return db;
|
|
369
306
|
const configured = Trust.try(
|
|
370
307
|
() => {
|
|
371
308
|
for (const pragma of pragmas) db.value.exec(`PRAGMA ${pragma}`);
|
|
372
309
|
},
|
|
373
|
-
|
|
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,
|
|
374
316
|
);
|
|
375
|
-
let reader: Database | null = null;
|
|
376
|
-
const openedReader = !configured.ok ? configured : Trust.try(() => {
|
|
377
|
-
const mode = db.value.query('PRAGMA journal_mode').values()[0]?.[0];
|
|
378
|
-
if (String(mode).toLowerCase() !== 'wal') return;
|
|
379
|
-
reader = new Database(paths.value.file, { readonly: true, safeIntegers: true });
|
|
380
|
-
const timeout = db.value.query('PRAGMA busy_timeout').values()[0]?.[0] ?? 5000;
|
|
381
|
-
reader.exec(`PRAGMA busy_timeout = ${Number(timeout)}`);
|
|
382
|
-
reader.exec('PRAGMA query_only = ON');
|
|
383
|
-
}, (cause) => ({ kind: 'open-failed', message: `cannot open reader for ${paths.value.file}: ${errorMessage(cause)}` }));
|
|
384
|
-
const server = new SqlegoServer(options, paths.value, db.value, [...pragmas], reader);
|
|
385
317
|
if (!openedReader.ok) {
|
|
386
318
|
// No socket/metadata has been created yet; only the connections opened here must go.
|
|
387
319
|
server.closeConnections();
|
|
@@ -511,6 +443,12 @@ export class SqlegoServer {
|
|
|
511
443
|
* checkpoints the WAL and removes it, which a readonly one cannot do.
|
|
512
444
|
*/
|
|
513
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
|
+
}
|
|
514
452
|
if (this.reader) this.closeConnection('reader', this.reader, this.readerStatements);
|
|
515
453
|
this.closeConnection('database', this.db, this.statements);
|
|
516
454
|
}
|
|
@@ -523,12 +461,37 @@ export class SqlegoServer {
|
|
|
523
461
|
* "database is locked") is logged and the deferred close still runs, so the
|
|
524
462
|
* file is released no later than that statement is collected.
|
|
525
463
|
*/
|
|
526
|
-
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 {
|
|
527
465
|
statements?.clear();
|
|
528
|
-
|
|
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);
|
|
529
473
|
if (closed.ok) return;
|
|
474
|
+
if (lockBusy) {
|
|
475
|
+
this.retryClose(name, database, closed, attempt);
|
|
476
|
+
return;
|
|
477
|
+
}
|
|
530
478
|
this.reportCleanup(`close ${name} (deferred: a statement is still unfinalized)`, closed);
|
|
531
|
-
this.
|
|
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);
|
|
532
495
|
}
|
|
533
496
|
|
|
534
497
|
status(): StatusResult {
|
|
@@ -547,6 +510,8 @@ export class SqlegoServer {
|
|
|
547
510
|
idleTimeoutMs: this.options.idleTimeoutMs,
|
|
548
511
|
requestsServed: this.requestsServed,
|
|
549
512
|
transaction: this.transactionStatus(),
|
|
513
|
+
readers: this.reader ? this.readers.status() : null,
|
|
514
|
+
detachedReads: { pooled: this.pooledReads, inline: this.inlineReads },
|
|
550
515
|
};
|
|
551
516
|
}
|
|
552
517
|
|
|
@@ -629,15 +594,24 @@ export class SqlegoServer {
|
|
|
629
594
|
const parsed = this.parseFrame(frame);
|
|
630
595
|
if (!parsed.ok) return this.reply(connection, { id: parsed.error.id, ok: false, error: { code: 'bad-request', message: parsed.error.message } });
|
|
631
596
|
const request = parsed.value;
|
|
632
|
-
|
|
633
|
-
|
|
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);
|
|
634
603
|
// A write-shaped CTE is retried only when SQLite refused it as readonly.
|
|
635
604
|
// All other failures (including TEMP-table misses) must be returned once.
|
|
636
605
|
if (outcome.ok || outcome.error.kind !== 'sqlite' || outcome.error.code !== 'SQLITE_READONLY') {
|
|
637
|
-
this.serve(connection,
|
|
606
|
+
this.serve(connection, detached, outcome);
|
|
638
607
|
return;
|
|
639
608
|
}
|
|
640
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 {
|
|
641
615
|
if (this.mustWait(connection, request)) {
|
|
642
616
|
const queued: QueuedRequest = {
|
|
643
617
|
connection, request, settled: false, timer: setTimeout(() => this.expireQueued(queued), this.txQueueTimeoutMs()),
|
|
@@ -678,11 +652,101 @@ export class SqlegoServer {
|
|
|
678
652
|
}
|
|
679
653
|
}
|
|
680
654
|
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
if (
|
|
684
|
-
if (request.
|
|
685
|
-
|
|
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
|
+
}
|
|
686
750
|
}
|
|
687
751
|
|
|
688
752
|
private expireQueued(queued: QueuedRequest): void {
|
|
@@ -994,15 +1058,7 @@ export class SqlegoServer {
|
|
|
994
1058
|
* result columns steps to its end in `all()` just as in `run()`.
|
|
995
1059
|
*/
|
|
996
1060
|
private step(sql: string, args: SQLQueryBindings[], db: Database) {
|
|
997
|
-
return this.statementsOf(db)
|
|
998
|
-
() => {
|
|
999
|
-
const rows: unknown = statement.all(...args);
|
|
1000
|
-
const columns: unknown = statement.columnNames;
|
|
1001
|
-
if (!Array.isArray(columns)) throw new Error('SQLite returned invalid column metadata');
|
|
1002
|
-
return { reader: columns.length > 0, rows };
|
|
1003
|
-
},
|
|
1004
|
-
sqliteFailure,
|
|
1005
|
-
));
|
|
1061
|
+
return stepStatement(this.statementsOf(db), sql, args);
|
|
1006
1062
|
}
|
|
1007
1063
|
|
|
1008
1064
|
/** The writer's `total_changes()` now: `lastTotal` while no statement has run since, else read. */
|
|
@@ -1496,3 +1552,38 @@ function parseCounters(input: unknown) {
|
|
|
1496
1552
|
function bindings(params: SqlParams): SQLQueryBindings[] {
|
|
1497
1553
|
return Array.isArray(params) ? (params as SqlValue[]) : [params as Record<string, SqlValue>];
|
|
1498
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
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import type { Database, SQLQueryBindings, Statement as SqliteStatement } from 'bun:sqlite';
|
|
2
|
+
import { Result, Trust } from '@noego/trust';
|
|
3
|
+
import { errorMessage } from './protocol.ts';
|
|
4
|
+
|
|
5
|
+
/** A statement SQLite refused or failed; `code` is SQLite's result code name (`SQLITE_READONLY`) when it gave one. */
|
|
6
|
+
export type SqliteFailure = { readonly kind: 'sqlite'; readonly message: string; readonly code?: string };
|
|
7
|
+
|
|
8
|
+
export const sqliteFailure = (cause: unknown): SqliteFailure => ({
|
|
9
|
+
kind: 'sqlite', message: errorMessage(cause),
|
|
10
|
+
code: typeof cause === 'object' && cause !== null && 'code' in cause && typeof cause.code === 'string' ? cause.code : undefined,
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
/** Distinct statements each connection keeps prepared; past this, the least recently used is finalized. */
|
|
14
|
+
export const STATEMENT_CACHE_SIZE = 256;
|
|
15
|
+
|
|
16
|
+
export type PreparedStatement = SqliteStatement<unknown, SQLQueryBindings[]>;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The prepared statements one connection reuses. Every statement handed out
|
|
20
|
+
* here is finalized here, when evicted and by `clear()` before the connection
|
|
21
|
+
* closes, never left to garbage collection: bun:sqlite's `close()` is
|
|
22
|
+
* sqlite3_close_v2, which keeps a connection with an unfinalized statement
|
|
23
|
+
* open, descriptors and all, until that statement is collected. bun:sqlite's
|
|
24
|
+
* own `db.query()` cache cannot serve: it keeps its first 20 statements and
|
|
25
|
+
* returns every later one uncached and unfinalized (2026-10-17: owners kept
|
|
26
|
+
* thousands of descriptors on released, deleted files).
|
|
27
|
+
*
|
|
28
|
+
* SQL with a `*` anywhere is prepared for one use and finalized after it,
|
|
29
|
+
* never cached. Its result columns (`SELECT *`, `t.*`, `RETURNING *`) follow
|
|
30
|
+
* the schema, and a reused bun:sqlite statement keeps the column names it
|
|
31
|
+
* last read whenever the schema changes without bun:sqlite seeing it: on the
|
|
32
|
+
* reader after the writer's DDL, on the writer after a rollback undoes DDL
|
|
33
|
+
* (2026-10-18, Bun 1.3.6: a cached `SELECT *` on the reader left out a column
|
|
34
|
+
* the writer had just added). A column named in the SQL cannot change that
|
|
35
|
+
* way; one that no longer exists fails when SQLite prepares the statement again.
|
|
36
|
+
*
|
|
37
|
+
* Shared by the owner thread (its writer and in-thread reader) and every
|
|
38
|
+
* reader worker (one cache per file it has open).
|
|
39
|
+
*/
|
|
40
|
+
export class StatementCache {
|
|
41
|
+
private readonly statements = new Map<string, PreparedStatement>();
|
|
42
|
+
private readonly db: Database;
|
|
43
|
+
private readonly onFinalizeFailed: (message: string) => void;
|
|
44
|
+
private used = 0;
|
|
45
|
+
|
|
46
|
+
constructor(db: Database, onFinalizeFailed: (message: string) => void) {
|
|
47
|
+
this.db = db;
|
|
48
|
+
this.onFinalizeFailed = onFinalizeFailed;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** How many statements `use` has run on this connection, failed ones included. */
|
|
52
|
+
get runs(): number {
|
|
53
|
+
return this.used;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Runs `work` on the prepared statement for `sql` and returns its outcome;
|
|
58
|
+
* SQL that SQLite cannot prepare is a sqlite failure.
|
|
59
|
+
*/
|
|
60
|
+
use<T, E>(sql: string, work: (statement: PreparedStatement) => Result<T, E>) {
|
|
61
|
+
this.used += 1;
|
|
62
|
+
if (sql.includes('*')) return this.useOnce(sql, work);
|
|
63
|
+
const prepared = this.prepare(sql);
|
|
64
|
+
if (!prepared.ok) return prepared;
|
|
65
|
+
return work(prepared.value);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Finalizes every statement, so the connection can then close for real. */
|
|
69
|
+
clear(): void {
|
|
70
|
+
for (const statement of this.statements.values()) this.finalize(statement);
|
|
71
|
+
this.statements.clear();
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The cached statement for `sql`, prepared on first use. */
|
|
75
|
+
private prepare(sql: string) {
|
|
76
|
+
const cached = this.statements.get(sql);
|
|
77
|
+
if (cached !== undefined) {
|
|
78
|
+
// Re-inserted so the first key is always the least recently used.
|
|
79
|
+
this.statements.delete(sql);
|
|
80
|
+
this.statements.set(sql, cached);
|
|
81
|
+
return Result.ok(cached);
|
|
82
|
+
}
|
|
83
|
+
const prepared = Trust.try((): PreparedStatement => this.db.prepare<unknown, SQLQueryBindings[]>(sql), sqliteFailure);
|
|
84
|
+
if (!prepared.ok) return prepared;
|
|
85
|
+
this.statements.set(sql, prepared.value);
|
|
86
|
+
if (this.statements.size > STATEMENT_CACHE_SIZE) this.evictLeastRecentlyUsed();
|
|
87
|
+
return prepared;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** `use` for SQL that is never cached: prepared, run, finalized. */
|
|
91
|
+
private useOnce<T, E>(sql: string, work: (statement: PreparedStatement) => Result<T, E>) {
|
|
92
|
+
const prepared = Trust.try((): PreparedStatement => this.db.prepare<unknown, SQLQueryBindings[]>(sql), sqliteFailure);
|
|
93
|
+
if (!prepared.ok) return prepared;
|
|
94
|
+
const outcome = work(prepared.value);
|
|
95
|
+
this.finalize(prepared.value);
|
|
96
|
+
return outcome;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
private evictLeastRecentlyUsed(): void {
|
|
100
|
+
const oldest = this.statements.entries().next();
|
|
101
|
+
if (oldest.done) return;
|
|
102
|
+
const [sql, statement] = oldest.value;
|
|
103
|
+
this.statements.delete(sql);
|
|
104
|
+
this.finalize(statement);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
private finalize(statement: PreparedStatement): void {
|
|
108
|
+
const finalized = Trust.try(() => statement.finalize(), sqliteFailure);
|
|
109
|
+
if (!finalized.ok && finalized.error.kind === 'sqlite') this.onFinalizeFailed(finalized.error.message);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Steps one statement on `db` through `all()`, then reads its columns: when
|
|
115
|
+
* another connection changed the schema, SQLite prepares the statement again
|
|
116
|
+
* as it steps, and only then do its columns match the rows. Read before the
|
|
117
|
+
* step they were the old ones, and `SELECT *` on the reader dropped the
|
|
118
|
+
* columns the writer had just added (2026-10-18). A statement without
|
|
119
|
+
* result columns steps to its end in `all()` just as in `run()`.
|
|
120
|
+
*/
|
|
121
|
+
export function stepStatement(statements: StatementCache, sql: string, args: SQLQueryBindings[]) {
|
|
122
|
+
return statements.use(sql, (statement) => Trust.try(
|
|
123
|
+
() => {
|
|
124
|
+
const rows: unknown = statement.all(...args);
|
|
125
|
+
const columns: unknown = statement.columnNames;
|
|
126
|
+
if (!Array.isArray(columns)) throw new Error('SQLite returned invalid column metadata');
|
|
127
|
+
return { reader: columns.length > 0, rows };
|
|
128
|
+
},
|
|
129
|
+
sqliteFailure,
|
|
130
|
+
));
|
|
131
|
+
}
|