@noego/sqlego 0.1.5 → 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/README.md +49 -5
- package/dist/index.d.ts +1 -1
- package/dist/index.js +43 -9
- package/dist/protocol.d.ts +36 -0
- package/package.json +6 -6
- 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
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A bounded pool of reader workers (`reader_worker.ts`) shared by every file
|
|
3
|
+
* an owner process serves. Opted-in plain reads of WAL files run here, each
|
|
4
|
+
* on a worker's own readonly connection, instead of on the owner thread:
|
|
5
|
+
* SQL on the owner thread is synchronous, so before this a slow read on one
|
|
6
|
+
* file stalled the writer and every other file sharing the process (the
|
|
7
|
+
* second readonly connection ran on the same thread and bought isolation
|
|
8
|
+
* from the writer's transaction, not parallelism).
|
|
9
|
+
*
|
|
10
|
+
* Bounded on both sides. `size` workers at most, started on demand and kept;
|
|
11
|
+
* each runs one read at a time, so at most `size` reads execute at once.
|
|
12
|
+
* Reads past that wait in one FIFO queue up to `queueLimit` entries; a read
|
|
13
|
+
* arriving at a full queue is not taken (`submit` returns false) and the
|
|
14
|
+
* owner runs it on its in-thread reader as it always did — the pool can only
|
|
15
|
+
* add capacity, never refuse a read that was served before it existed.
|
|
16
|
+
*
|
|
17
|
+
* Every read is timed: how long it waited for a worker (`queueMs`) and how
|
|
18
|
+
* long SQLite took on the worker (`execMs`); `status()` keeps the counts and
|
|
19
|
+
* the worst of each, so saturation shows as queue time, a slow statement as
|
|
20
|
+
* execution time.
|
|
21
|
+
*
|
|
22
|
+
* A worker that fails (an `error` event; a thread that exits) fails only the
|
|
23
|
+
* read it was running, with `worker-failed`; the slot is freed and the next
|
|
24
|
+
* read starts a fresh worker. Workers are unreferenced: an idle owner exits
|
|
25
|
+
* as before. `release(file)` closes the file on every worker and settles
|
|
26
|
+
* once each has done so, so the writer's close is the file's last.
|
|
27
|
+
*/
|
|
28
|
+
import type { SQLQueryBindings } from 'bun:sqlite';
|
|
29
|
+
import { Result } from '@noego/trust';
|
|
30
|
+
import { errorMessage } from './protocol.ts';
|
|
31
|
+
import type { ReaderWorkerReply, ReaderWorkerRequest } from './reader_worker.ts';
|
|
32
|
+
import type { SqliteFailure } from './statement_cache.ts';
|
|
33
|
+
|
|
34
|
+
export type ReaderPoolOptions = Readonly<{
|
|
35
|
+
/** Workers at most; `0` disables the pool (every opted-in read runs on the in-thread reader). */
|
|
36
|
+
size: number;
|
|
37
|
+
/** Reads waiting for a worker at most; past it `submit` refuses and the owner reads in-thread. */
|
|
38
|
+
queueLimit: number;
|
|
39
|
+
log?: (message: string, fields?: Record<string, unknown>) => void;
|
|
40
|
+
}>;
|
|
41
|
+
|
|
42
|
+
export const DEFAULT_READERS = 2;
|
|
43
|
+
export const DEFAULT_READER_QUEUE_LIMIT = 256;
|
|
44
|
+
|
|
45
|
+
/** A read as the pool ran it: its rows, and where its time went. */
|
|
46
|
+
export type ReaderRows = Readonly<{ reader: boolean; rows: unknown; queueMs: number; execMs: number; roundTripMs: number }>;
|
|
47
|
+
export type WorkerFailure = Readonly<{ kind: 'worker-failed'; message: string }>;
|
|
48
|
+
export type ReaderOutcome = Result<ReaderRows, SqliteFailure | WorkerFailure>;
|
|
49
|
+
|
|
50
|
+
export type ReaderJob = Readonly<{
|
|
51
|
+
file: string;
|
|
52
|
+
busyTimeoutMs: number;
|
|
53
|
+
sql: string;
|
|
54
|
+
params: SQLQueryBindings[];
|
|
55
|
+
/** Called once, on the owner thread, with the outcome; never with a throw. */
|
|
56
|
+
onDone: (outcome: ReaderOutcome) => void;
|
|
57
|
+
}>;
|
|
58
|
+
|
|
59
|
+
/** What `status` reports about the pool; counters are per process, since the pool is. */
|
|
60
|
+
export type ReaderPoolStatus = Readonly<{
|
|
61
|
+
size: number;
|
|
62
|
+
queueLimit: number;
|
|
63
|
+
/** Workers started so far and still alive. */
|
|
64
|
+
workers: number;
|
|
65
|
+
/** Workers running a read now. */
|
|
66
|
+
busy: number;
|
|
67
|
+
/** Reads waiting for a worker now. */
|
|
68
|
+
queued: number;
|
|
69
|
+
/** Reads the pool completed (failed ones included). */
|
|
70
|
+
served: number;
|
|
71
|
+
/** Reads refused for a full queue (the owner ran them in-thread). */
|
|
72
|
+
refused: number;
|
|
73
|
+
/** Reads that failed because their worker failed. */
|
|
74
|
+
failed: number;
|
|
75
|
+
/** Workers that failed and were replaced. */
|
|
76
|
+
restarts: number;
|
|
77
|
+
queueMsMax: number;
|
|
78
|
+
execMsMax: number;
|
|
79
|
+
}>;
|
|
80
|
+
|
|
81
|
+
type InFlight = { id: number; job: ReaderJob; queuedAt: number; startedAt: number };
|
|
82
|
+
type Slot = { worker: Worker; busy: InFlight | null; closes: Map<number, () => void>; alive: boolean };
|
|
83
|
+
|
|
84
|
+
/** Bun's standalone executables mount their bundle at this virtual root (`B:/~BUN/` on Windows). */
|
|
85
|
+
const COMPILED_URL = /\/\$bunfs\/|~BUN/;
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Where the worker's module is: in a compiled binary the entry registered at
|
|
89
|
+
* build time, by its source-relative name; from source, the module beside this one.
|
|
90
|
+
*/
|
|
91
|
+
export function readerWorkerSpecifier(moduleUrl: string = import.meta.url): string {
|
|
92
|
+
return COMPILED_URL.test(moduleUrl) ? './reader_worker.ts' : new URL('./reader_worker.ts', moduleUrl).href;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export class ReaderPool {
|
|
96
|
+
readonly options: ReaderPoolOptions;
|
|
97
|
+
private readonly slots: Slot[] = [];
|
|
98
|
+
private readonly queue: Array<{ job: ReaderJob; queuedAt: number }> = [];
|
|
99
|
+
/**
|
|
100
|
+
* One lock for every open and close of a SQLite handle in this process,
|
|
101
|
+
* workers and owner thread alike (0 free, 1 held). Two threads opening
|
|
102
|
+
* handles on one WAL file at the same moment contended in the compiled
|
|
103
|
+
* owner: without `busy_timeout` about 40% of such opens failed "database
|
|
104
|
+
* is locked" (probe, Bun 1.3.6 / SQLite 3.51.0); with it, about 1 in 30
|
|
105
|
+
* handles answered its first statements wrongly ("no such table" for a
|
|
106
|
+
* committed table, "another row available", "Cannot use a closed
|
|
107
|
+
* database"). Opens are rare and take a millisecond; serializing them
|
|
108
|
+
* costs nothing a client can see.
|
|
109
|
+
*/
|
|
110
|
+
private readonly openLock = new SharedArrayBuffer(4);
|
|
111
|
+
private nextId = 1;
|
|
112
|
+
private served = 0;
|
|
113
|
+
private refused = 0;
|
|
114
|
+
private failed = 0;
|
|
115
|
+
private restarts = 0;
|
|
116
|
+
private queueMsMax = 0;
|
|
117
|
+
private execMsMax = 0;
|
|
118
|
+
private readonly log: NonNullable<ReaderPoolOptions['log']>;
|
|
119
|
+
|
|
120
|
+
constructor(options: ReaderPoolOptions) {
|
|
121
|
+
this.options = { ...options, size: Math.max(0, Math.floor(options.size)), queueLimit: Math.max(0, Math.floor(options.queueLimit)) };
|
|
122
|
+
this.log = options.log ?? (() => undefined);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
get enabled(): boolean {
|
|
126
|
+
return this.options.size > 0;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Runs `work` — an owner-thread open or close of a SQLite handle — holding
|
|
131
|
+
* the open/close lock the workers hold for theirs (see `openLock`). Waits
|
|
132
|
+
* in bounded slices; a worker's open or close holds it for a millisecond.
|
|
133
|
+
*/
|
|
134
|
+
withOpenLock<T, E>(work: () => Result<T, E>, failed: (cause: unknown) => E): Result<T, E> {
|
|
135
|
+
const flag = new Int32Array(this.openLock);
|
|
136
|
+
const deadline = performance.now() + 1000;
|
|
137
|
+
while (Atomics.compareExchange(flag, 0, 0, 1) !== 0) {
|
|
138
|
+
const remaining = deadline - performance.now();
|
|
139
|
+
if (remaining <= 0) return Result.err(failed(new Error('SQLite handle lock unavailable; refusing unsafe concurrent open/close')));
|
|
140
|
+
Atomics.wait(flag, 0, 1, Math.min(100, remaining));
|
|
141
|
+
}
|
|
142
|
+
try {
|
|
143
|
+
return work();
|
|
144
|
+
} finally {
|
|
145
|
+
Atomics.store(flag, 0, 0);
|
|
146
|
+
Atomics.notify(flag, 0, 1);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Takes the read, or refuses it: the pool is disabled, or its queue is
|
|
152
|
+
* full. A refused read is the caller's to run; `onDone` is never called for it.
|
|
153
|
+
*/
|
|
154
|
+
submit(job: ReaderJob): boolean {
|
|
155
|
+
if (!this.enabled) return false;
|
|
156
|
+
const idle = this.idleSlot();
|
|
157
|
+
if (idle !== null) {
|
|
158
|
+
this.start(idle, job, performance.now());
|
|
159
|
+
return true;
|
|
160
|
+
}
|
|
161
|
+
if (this.queue.length >= this.options.queueLimit) {
|
|
162
|
+
this.refused += 1;
|
|
163
|
+
return false;
|
|
164
|
+
}
|
|
165
|
+
this.queue.push({ job, queuedAt: performance.now() });
|
|
166
|
+
return true;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Closes `file` on every worker; settles once each has, or at once when none holds it (no worker was started). */
|
|
170
|
+
release(file: string): Promise<void> {
|
|
171
|
+
this.cancelQueuedFile(file);
|
|
172
|
+
const acks: Promise<void>[] = [];
|
|
173
|
+
for (const slot of this.slots) {
|
|
174
|
+
if (!slot.alive) continue;
|
|
175
|
+
const id = this.nextId++;
|
|
176
|
+
acks.push(new Promise<void>((settle) => {
|
|
177
|
+
slot.closes.set(id, settle);
|
|
178
|
+
const request: ReaderWorkerRequest = { kind: 'close', id, file, openLock: this.openLock };
|
|
179
|
+
this.post(slot, request);
|
|
180
|
+
}));
|
|
181
|
+
}
|
|
182
|
+
return Promise.all(acks).then(() => undefined);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Closes `file` on every worker and waits, on this thread, until each has
|
|
187
|
+
* done so or `timeoutMs` has passed: the owner closes its writer right
|
|
188
|
+
* after, and the file's last connection to close is the one that
|
|
189
|
+
* checkpoints and removes the WAL. A worker busy with a long read answers
|
|
190
|
+
* the close only after it, so the wait is bounded; false says a worker
|
|
191
|
+
* had not closed in time (the next opener checkpoints instead).
|
|
192
|
+
*/
|
|
193
|
+
releaseSync(file: string, timeoutMs: number): boolean {
|
|
194
|
+
this.cancelQueuedFile(file);
|
|
195
|
+
const flags: { slot: Slot; flag: Int32Array }[] = [];
|
|
196
|
+
for (const slot of this.slots) {
|
|
197
|
+
if (!slot.alive) continue;
|
|
198
|
+
const id = this.nextId++;
|
|
199
|
+
const signal = new SharedArrayBuffer(4);
|
|
200
|
+
flags.push({ slot, flag: new Int32Array(signal) });
|
|
201
|
+
// The reply still arrives as a message; it is taken as an acknowledgement nobody waits for.
|
|
202
|
+
slot.closes.set(id, () => undefined);
|
|
203
|
+
const request: ReaderWorkerRequest = { kind: 'close', id, file, openLock: this.openLock, signal };
|
|
204
|
+
this.post(slot, request);
|
|
205
|
+
}
|
|
206
|
+
const deadline = performance.now() + timeoutMs;
|
|
207
|
+
let all = true;
|
|
208
|
+
for (const { slot, flag } of flags) {
|
|
209
|
+
const remaining = deadline - performance.now();
|
|
210
|
+
if (Atomics.load(flag, 0) === 0 && (remaining <= 0 || Atomics.wait(flag, 0, 0, remaining) === 'timed-out')) {
|
|
211
|
+
all = false;
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
// A worker that could not close keeps its handle; retiring it is the only release left.
|
|
215
|
+
if (Atomics.load(flag, 0) === 2) {
|
|
216
|
+
all = false;
|
|
217
|
+
this.dropSlot(slot, `reader close failed for ${file}`);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return all;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
private cancelQueuedFile(file: string): void {
|
|
224
|
+
const cancelled = this.queue.filter((entry) => entry.job.file === file);
|
|
225
|
+
for (let index = this.queue.length - 1; index >= 0; index -= 1) {
|
|
226
|
+
if (this.queue[index].job.file === file) this.queue.splice(index, 1);
|
|
227
|
+
}
|
|
228
|
+
for (const entry of cancelled) {
|
|
229
|
+
entry.job.onDone(Result.err<SqliteFailure>({ kind: 'sqlite', code: 'SQLITE_ABORT', message: 'reader file released before queued read started' }));
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Stops every worker now: reads in flight fail with `worker-failed`, queued ones too. The pool starts fresh workers afterwards. */
|
|
234
|
+
terminate(reason: string): void {
|
|
235
|
+
// Take the queue first: dropSlot dispatches, and must not hand queued reads to replacement workers.
|
|
236
|
+
const waiting = this.queue.splice(0);
|
|
237
|
+
for (const slot of [...this.slots]) this.dropSlot(slot, `terminated: ${reason}`);
|
|
238
|
+
for (const entry of waiting) entry.job.onDone(Result.err<WorkerFailure>({ kind: 'worker-failed', message: `reader pool terminated: ${reason}` }));
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
status(): ReaderPoolStatus {
|
|
242
|
+
return {
|
|
243
|
+
size: this.options.size,
|
|
244
|
+
queueLimit: this.options.queueLimit,
|
|
245
|
+
workers: this.slots.length,
|
|
246
|
+
busy: this.slots.filter((slot) => slot.busy !== null).length,
|
|
247
|
+
queued: this.queue.length,
|
|
248
|
+
served: this.served,
|
|
249
|
+
refused: this.refused,
|
|
250
|
+
failed: this.failed,
|
|
251
|
+
restarts: this.restarts,
|
|
252
|
+
queueMsMax: this.queueMsMax,
|
|
253
|
+
execMsMax: this.execMsMax,
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** An idle worker, a new one while fewer than `size` exist, or null when all are busy. */
|
|
258
|
+
private idleSlot(): Slot | null {
|
|
259
|
+
for (const slot of this.slots) {
|
|
260
|
+
if (slot.busy === null) return slot;
|
|
261
|
+
}
|
|
262
|
+
if (this.slots.length >= this.options.size) return null;
|
|
263
|
+
return this.spawn();
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
private spawn(): Slot {
|
|
267
|
+
const worker = new Worker(readerWorkerSpecifier());
|
|
268
|
+
const slot: Slot = { worker, busy: null, closes: new Map(), alive: true };
|
|
269
|
+
worker.addEventListener('message', (event: MessageEvent) => this.onMessage(slot, event.data));
|
|
270
|
+
worker.addEventListener('error', (event: ErrorEvent) => this.dropSlot(slot, `worker error: ${event.message || errorMessage(event.error)}`));
|
|
271
|
+
worker.addEventListener('close', () => this.dropSlot(slot, 'worker exited'));
|
|
272
|
+
// An idle owner must still exit on its own; the workers never hold it.
|
|
273
|
+
worker.unref();
|
|
274
|
+
this.slots.push(slot);
|
|
275
|
+
return slot;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
private start(slot: Slot, job: ReaderJob, queuedAt: number): void {
|
|
279
|
+
const inFlight: InFlight = { id: this.nextId++, job, queuedAt, startedAt: performance.now() };
|
|
280
|
+
slot.busy = inFlight;
|
|
281
|
+
const request: ReaderWorkerRequest = {
|
|
282
|
+
kind: 'read', id: inFlight.id, file: job.file, busyTimeoutMs: job.busyTimeoutMs, sql: job.sql, params: job.params, openLock: this.openLock,
|
|
283
|
+
};
|
|
284
|
+
this.post(slot, request);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** Every request is plain data (strings, numbers, validated SQL values), which structured clone always takes. */
|
|
288
|
+
private post(slot: Slot, request: ReaderWorkerRequest): void {
|
|
289
|
+
slot.worker.postMessage(request);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
private onMessage(slot: Slot, data: unknown): void {
|
|
293
|
+
const reply = parseReply(data);
|
|
294
|
+
if (reply === null) {
|
|
295
|
+
this.dropSlot(slot, 'reader worker sent a malformed reply');
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
const ack = slot.closes.get(reply.id);
|
|
299
|
+
if (ack !== undefined) {
|
|
300
|
+
slot.closes.delete(reply.id);
|
|
301
|
+
ack();
|
|
302
|
+
if (!reply.ok) {
|
|
303
|
+
this.log('reader close failed', { error: reply.message });
|
|
304
|
+
// The worker still holds the handle: retire it so a stopped or replaced file is never read through it.
|
|
305
|
+
this.dropSlot(slot, `reader close failed: ${reply.message}`);
|
|
306
|
+
}
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
const inFlight = slot.busy;
|
|
310
|
+
if (inFlight === null || inFlight.id !== reply.id) {
|
|
311
|
+
this.dropSlot(slot, `reader worker answered ${reply.id} out of turn`);
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
slot.busy = null;
|
|
315
|
+
this.served += 1;
|
|
316
|
+
const now = performance.now();
|
|
317
|
+
const queueMs = inFlight.startedAt - inFlight.queuedAt;
|
|
318
|
+
this.queueMsMax = Math.max(this.queueMsMax, queueMs);
|
|
319
|
+
// A handle the worker could not open or warm is not the read's failure: the
|
|
320
|
+
// owner runs the read itself, as after a failed worker (counted as such).
|
|
321
|
+
if (!reply.ok && reply.transient === true) this.failed += 1;
|
|
322
|
+
const outcome: ReaderOutcome = !reply.ok
|
|
323
|
+
? reply.transient === true
|
|
324
|
+
? Result.err<WorkerFailure>({ kind: 'worker-failed', message: reply.message })
|
|
325
|
+
: Result.err<SqliteFailure>({ kind: 'sqlite', message: reply.message, code: reply.code })
|
|
326
|
+
: reply.kind !== 'rows'
|
|
327
|
+
? Result.err<WorkerFailure>({ kind: 'worker-failed', message: 'reader worker answered a read with a close acknowledgement' })
|
|
328
|
+
: Result.ok<ReaderRows>({ reader: reply.reader, rows: reply.rows, queueMs, execMs: reply.execMs, roundTripMs: now - inFlight.startedAt });
|
|
329
|
+
if (outcome.ok) this.execMsMax = Math.max(this.execMsMax, outcome.value.execMs);
|
|
330
|
+
this.dispatch();
|
|
331
|
+
inFlight.job.onDone(outcome);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** Hands the oldest waiting read to an idle worker. */
|
|
335
|
+
private dispatch(): void {
|
|
336
|
+
while (this.queue.length > 0) {
|
|
337
|
+
const idle = this.idleSlot();
|
|
338
|
+
if (idle === null) return;
|
|
339
|
+
const next = this.queue.shift();
|
|
340
|
+
if (!next) return;
|
|
341
|
+
this.start(idle, next.job, next.queuedAt);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** Forgets a failed worker: its read fails, its pending closes settle, and the next read starts a new worker. */
|
|
346
|
+
private dropSlot(slot: Slot, why: string): void {
|
|
347
|
+
if (!slot.alive) return;
|
|
348
|
+
slot.alive = false;
|
|
349
|
+
const at = this.slots.indexOf(slot);
|
|
350
|
+
if (at >= 0) this.slots.splice(at, 1);
|
|
351
|
+
this.restarts += 1;
|
|
352
|
+
this.log('reader worker dropped', { error: why });
|
|
353
|
+
slot.worker.terminate();
|
|
354
|
+
for (const ack of slot.closes.values()) ack();
|
|
355
|
+
slot.closes.clear();
|
|
356
|
+
const inFlight = slot.busy;
|
|
357
|
+
slot.busy = null;
|
|
358
|
+
if (inFlight !== null) {
|
|
359
|
+
this.served += 1;
|
|
360
|
+
this.failed += 1;
|
|
361
|
+
inFlight.job.onDone(Result.err<WorkerFailure>({ kind: 'worker-failed', message: `reader worker failed: ${why}` }));
|
|
362
|
+
}
|
|
363
|
+
this.dispatch();
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
//trust:validator_function
|
|
368
|
+
function parseReply(input: unknown): ReaderWorkerReply | null {
|
|
369
|
+
if (typeof input !== 'object' || input === null) return null;
|
|
370
|
+
const fields = input as Readonly<Record<string, unknown>>;
|
|
371
|
+
if (typeof fields.id !== 'number' || typeof fields.ok !== 'boolean') return null;
|
|
372
|
+
if (!fields.ok) {
|
|
373
|
+
if (typeof fields.message !== 'string') return null;
|
|
374
|
+
return {
|
|
375
|
+
id: fields.id, ok: false, message: fields.message,
|
|
376
|
+
code: typeof fields.code === 'string' ? fields.code : undefined,
|
|
377
|
+
transient: fields.transient === true,
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
if (fields.kind === 'closed') return { id: fields.id, ok: true, kind: 'closed' };
|
|
381
|
+
if (fields.kind !== 'rows' || typeof fields.reader !== 'boolean' || typeof fields.execMs !== 'number') return null;
|
|
382
|
+
return { id: fields.id, ok: true, kind: 'rows', reader: fields.reader, rows: fields.rows, execMs: fields.execMs };
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
let shared: ReaderPool | null = null;
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* The process's one pool, sized on first use: `SQLEGO_READERS` workers
|
|
389
|
+
* (default 2) and `SQLEGO_READER_QUEUE` waiting reads (default 256). Every
|
|
390
|
+
* file an owner process serves shares it, so the bound is per process.
|
|
391
|
+
*/
|
|
392
|
+
export function sharedReaderPool(log?: ReaderPoolOptions['log']): ReaderPool {
|
|
393
|
+
if (shared === null) {
|
|
394
|
+
shared = new ReaderPool({
|
|
395
|
+
size: envNumber('SQLEGO_READERS', DEFAULT_READERS),
|
|
396
|
+
queueLimit: envNumber('SQLEGO_READER_QUEUE', DEFAULT_READER_QUEUE_LIMIT),
|
|
397
|
+
log,
|
|
398
|
+
});
|
|
399
|
+
}
|
|
400
|
+
return shared;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function envNumber(name: string, fallback: number): number {
|
|
404
|
+
const raw = process.env[name];
|
|
405
|
+
if (raw === undefined || raw.trim() === '') return fallback;
|
|
406
|
+
const parsed = Number(raw);
|
|
407
|
+
return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
|
|
408
|
+
}
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One reader worker: a thread of the owner process that holds its own
|
|
3
|
+
* readonly connection to each WAL file it is asked to read, and runs plain
|
|
4
|
+
* reads there, so a long read never occupies the owner thread (where the
|
|
5
|
+
* writer and every file's socket live) and several reads run at once.
|
|
6
|
+
*
|
|
7
|
+
* Spoken to only by `reader_pool.ts`, over `postMessage`. One message in,
|
|
8
|
+
* one reply out, in order; a `close` for a file finalizes its statements and
|
|
9
|
+
* closes its handle, so the owner's last connection to the file can
|
|
10
|
+
* checkpoint and remove the WAL. The worker opens a file on its first read
|
|
11
|
+
* of it, readonly with safe integers, `busy_timeout` as the writer has it,
|
|
12
|
+
* and `query_only = ON`: exactly the in-thread reader's settings.
|
|
13
|
+
*
|
|
14
|
+
* Built into the compiled binary as its own entry (`scripts/build.ts`), and
|
|
15
|
+
* started from source by its module URL (`reader_pool.ts`).
|
|
16
|
+
*/
|
|
17
|
+
import { Database, type SQLQueryBindings } from 'bun:sqlite';
|
|
18
|
+
import { Result, Trust } from '@noego/trust';
|
|
19
|
+
import { StatementCache, sqliteFailure, stepStatement, type SqliteFailure } from './statement_cache.ts';
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* What the pool sends. `openLock` is the process's one open/close lock (see
|
|
23
|
+
* `ReaderPool.withOpenLock`): opening or closing a handle on this file
|
|
24
|
+
* happens under it, never at the same time as another thread's.
|
|
25
|
+
*/
|
|
26
|
+
export type ReaderWorkerRequest =
|
|
27
|
+
| Readonly<{ kind: 'read'; id: number; file: string; busyTimeoutMs: number; sql: string; params: SQLQueryBindings[]; openLock: SharedArrayBuffer }>
|
|
28
|
+
/** `signal`, when given, is set to 1 (closed) or 2 (close failed) and notified once the close is settled: the owner thread waits on it synchronously while stopping the file. */
|
|
29
|
+
| Readonly<{ kind: 'close'; id: number; file: string; openLock: SharedArrayBuffer; signal?: SharedArrayBuffer }>;
|
|
30
|
+
|
|
31
|
+
/** What the worker answers; `id` is the request's. */
|
|
32
|
+
export type ReaderWorkerReply =
|
|
33
|
+
| Readonly<{ id: number; ok: true; kind: 'rows'; reader: boolean; rows: unknown; execMs: number }>
|
|
34
|
+
| Readonly<{ id: number; ok: true; kind: 'closed' }>
|
|
35
|
+
/** `transient`: the handle could not be opened or warmed this time; the read is the owner's to run and the next request opens again. */
|
|
36
|
+
| Readonly<{ id: number; ok: false; message: string; code?: string; transient?: boolean }>;
|
|
37
|
+
|
|
38
|
+
type OpenFile = { db: Database; statements: StatementCache };
|
|
39
|
+
|
|
40
|
+
const files = new Map<string, OpenFile>();
|
|
41
|
+
|
|
42
|
+
/** `postMessage` to the owner thread; a worker's global scope is its own `self`. */
|
|
43
|
+
declare const self: Worker;
|
|
44
|
+
|
|
45
|
+
//trust:validator_function
|
|
46
|
+
function parseRequest(input: unknown): ReaderWorkerRequest | null {
|
|
47
|
+
if (typeof input !== 'object' || input === null) return null;
|
|
48
|
+
const fields = input as Readonly<Record<string, unknown>>;
|
|
49
|
+
if (typeof fields.id !== 'number' || typeof fields.file !== 'string' || !(fields.openLock instanceof SharedArrayBuffer)) return null;
|
|
50
|
+
if (fields.kind === 'close') {
|
|
51
|
+
return { kind: 'close', id: fields.id, file: fields.file, openLock: fields.openLock, signal: fields.signal instanceof SharedArrayBuffer ? fields.signal : undefined };
|
|
52
|
+
}
|
|
53
|
+
if (fields.kind !== 'read' || typeof fields.sql !== 'string' || typeof fields.busyTimeoutMs !== 'number' || !Array.isArray(fields.params)) return null;
|
|
54
|
+
// The owner thread built `params` with `bindings()` from validated SqlValues; structured clone keeps them as they were.
|
|
55
|
+
return {
|
|
56
|
+
kind: 'read', id: fields.id, file: fields.file, busyTimeoutMs: fields.busyTimeoutMs, sql: fields.sql,
|
|
57
|
+
params: fields.params as SQLQueryBindings[], openLock: fields.openLock,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Runs `work` holding the process's open/close lock (see
|
|
63
|
+
* `ReaderPool.withOpenLock` for what it guards). Waits in bounded slices so
|
|
64
|
+
* a holder that died never parks this thread for good.
|
|
65
|
+
*/
|
|
66
|
+
function underOpenLock<T, E>(openLock: SharedArrayBuffer, work: () => Result<T, E>): Result<T, E | SqliteFailure> {
|
|
67
|
+
const flag = new Int32Array(openLock);
|
|
68
|
+
const deadline = performance.now() + 1000;
|
|
69
|
+
while (Atomics.compareExchange(flag, 0, 0, 1) !== 0) {
|
|
70
|
+
const remaining = deadline - performance.now();
|
|
71
|
+
if (remaining <= 0) return Result.err<SqliteFailure>({ kind: 'sqlite', code: 'SQLITE_BUSY', message: 'SQLite handle lock unavailable; refusing unsafe concurrent open/close' });
|
|
72
|
+
Atomics.wait(flag, 0, 1, Math.min(100, remaining));
|
|
73
|
+
}
|
|
74
|
+
try {
|
|
75
|
+
return work();
|
|
76
|
+
} finally {
|
|
77
|
+
Atomics.store(flag, 0, 0);
|
|
78
|
+
Atomics.notify(flag, 0, 1);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function open(file: string, busyTimeoutMs: number, openLock: SharedArrayBuffer) {
|
|
83
|
+
const known = files.get(file);
|
|
84
|
+
if (known !== undefined) return Result.ok(known);
|
|
85
|
+
const opened = underOpenLock(openLock, () => {
|
|
86
|
+
const db = Trust.try(() => {
|
|
87
|
+
const handle = new Database(file, { readonly: true, safeIntegers: true });
|
|
88
|
+
handle.exec(`PRAGMA busy_timeout = ${Math.max(0, Math.floor(busyTimeoutMs))}`);
|
|
89
|
+
handle.exec('PRAGMA query_only = ON');
|
|
90
|
+
return handle;
|
|
91
|
+
}, sqliteFailure);
|
|
92
|
+
if (!db.ok) return db;
|
|
93
|
+
const warmed = warm(db.value);
|
|
94
|
+
if (!warmed.ok) {
|
|
95
|
+
const closed = Trust.try(() => db.value.close(), sqliteFailure);
|
|
96
|
+
if (!closed.ok) return Result.err<SqliteFailure>({ kind: 'sqlite', message: `${warmed.error.message}; and then: ${closed.error.message}`, code: warmed.error.code });
|
|
97
|
+
return warmed;
|
|
98
|
+
}
|
|
99
|
+
return db;
|
|
100
|
+
});
|
|
101
|
+
if (!opened.ok) return opened;
|
|
102
|
+
const entry: OpenFile = { db: opened.value, statements: new StatementCache(opened.value, () => undefined) };
|
|
103
|
+
files.set(file, entry);
|
|
104
|
+
return Result.ok(entry);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* A fresh readonly handle's first statement, run here rather than for a
|
|
109
|
+
* client. In the compiled owner, a handle opened on a new worker thread
|
|
110
|
+
* while another worker was inside a long statement on the same file
|
|
111
|
+
* failed its first statements about once in 30 (Bun 1.3.6, SQLite 3.51.0,
|
|
112
|
+
* THREADSAFE=2; not reproduced outside the owner): "no such table: t" for a
|
|
113
|
+
* table committed and acknowledged long before, "no such table:
|
|
114
|
+
* sqlite_master", "another row available", "no more rows available";
|
|
115
|
+
* immediate retries on the handle failed the same way, while a handle
|
|
116
|
+
* opened for the next request, milliseconds later, behaved. So a handle
|
|
117
|
+
* that fails here is closed and the read reported transient: the owner
|
|
118
|
+
* runs it on its own reader, and this worker opens the file afresh next time.
|
|
119
|
+
*/
|
|
120
|
+
function warm(db: Database) {
|
|
121
|
+
return Trust.try(
|
|
122
|
+
() => {
|
|
123
|
+
const statement = db.prepare('SELECT count(*) AS n FROM sqlite_master');
|
|
124
|
+
statement.get();
|
|
125
|
+
statement.finalize();
|
|
126
|
+
},
|
|
127
|
+
sqliteFailure,
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function read(request: Extract<ReaderWorkerRequest, { kind: 'read' }>): ReaderWorkerReply {
|
|
132
|
+
const opened = open(request.file, request.busyTimeoutMs, request.openLock);
|
|
133
|
+
if (!opened.ok) {
|
|
134
|
+
return { id: request.id, ok: false, message: `cannot open reader for ${request.file}: ${opened.error.message}`, code: opened.error.code, transient: true };
|
|
135
|
+
}
|
|
136
|
+
const startedAt = performance.now();
|
|
137
|
+
const stepped = stepStatement(opened.value.statements, request.sql, request.params);
|
|
138
|
+
const execMs = performance.now() - startedAt;
|
|
139
|
+
if (!stepped.ok) return { id: request.id, ok: false, message: stepped.error.message, code: stepped.error.code };
|
|
140
|
+
return { id: request.id, ok: true, kind: 'rows', reader: stepped.value.reader, rows: stepped.value.rows, execMs };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Finalizes and closes the file's handle (see `SqlegoServer.closeConnection` for why `close(true)` first). */
|
|
144
|
+
function close(request: Extract<ReaderWorkerRequest, { kind: 'close' }>): ReaderWorkerReply {
|
|
145
|
+
const known = files.get(request.file);
|
|
146
|
+
if (known === undefined) return { id: request.id, ok: true, kind: 'closed' };
|
|
147
|
+
// `close(true)` refuses while a statement is unfinalized; the plain close then releases the file once it is collected.
|
|
148
|
+
// The entry is dropped only once the lock is held, so a failed acquisition leaves the handle for a retried release.
|
|
149
|
+
const closed = underOpenLock(request.openLock, () => {
|
|
150
|
+
files.delete(request.file);
|
|
151
|
+
known.statements.clear();
|
|
152
|
+
return Trust.decide(
|
|
153
|
+
Trust.try(() => known.db.close(true), sqliteFailure),
|
|
154
|
+
{ sqlite: () => Trust.try(() => known.db.close(), sqliteFailure) },
|
|
155
|
+
).value ?? Result.ok(undefined);
|
|
156
|
+
});
|
|
157
|
+
if (closed !== undefined && !closed.ok) {
|
|
158
|
+
return { id: request.id, ok: false, message: `cannot close reader for ${request.file}: ${closed.error.message}`, code: closed.error.code };
|
|
159
|
+
}
|
|
160
|
+
return { id: request.id, ok: true, kind: 'closed' };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
//trust:validator_function
|
|
164
|
+
function requestId(input: unknown): number {
|
|
165
|
+
if (typeof input !== 'object' || input === null) return -1;
|
|
166
|
+
const id = (input as Readonly<Record<string, unknown>>).id;
|
|
167
|
+
return typeof id === 'number' ? id : -1;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
self.onmessage = (event: MessageEvent) => {
|
|
171
|
+
const data: unknown = event.data;
|
|
172
|
+
const request = parseRequest(data);
|
|
173
|
+
if (request === null) {
|
|
174
|
+
const reply: ReaderWorkerReply = { id: requestId(data), ok: false, message: 'reader worker received a malformed request' };
|
|
175
|
+
self.postMessage(reply);
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
if (request.kind === 'read') {
|
|
179
|
+
self.postMessage(read(request));
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
const reply = close(request);
|
|
183
|
+
if (request.signal !== undefined) {
|
|
184
|
+
const flag = new Int32Array(request.signal);
|
|
185
|
+
Atomics.store(flag, 0, reply.ok ? 1 : 2);
|
|
186
|
+
Atomics.notify(flag, 0);
|
|
187
|
+
}
|
|
188
|
+
self.postMessage(reply);
|
|
189
|
+
};
|