Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

nodeSqliteClient.ts

1,118 lines41.2 KB

1import * as NodeSqlite from "node:sqlite";
2import * as NodeUtil from "node:util";
3import * as NodeWorkerThreads from "node:worker_threads";
4​
5import * as Cache from "effect/Cache";
6import * as Clock from "effect/Clock";
7import * as Duration from "effect/Duration";
8import * as Effect from "effect/Effect";
9import * as Result from "effect/Result";
10import * as Exit from "effect/Exit";
11import * as Fiber from "effect/Fiber";
12import { identity } from "effect/Function";
13import * as Layer from "effect/Layer";
14import * as Option from "effect/Option";
15import * as Predicate from "effect/Predicate";
16import * as References from "effect/References";
17import * as Schema from "effect/Schema";
18import * as Scheduler from "effect/Scheduler";
19import * as Scope from "effect/Scope";
20import * as Semaphore from "effect/Semaphore";
21import * as Context from "effect/Context";
22import * as Stream from "effect/Stream";
23import * as Tracer from "effect/Tracer";
24import * as Reactivity from "effect/reactivity/Reactivity";
25import * as Client from "effect/sql/SqlClient";
26import type { Borrower, Connection } from "effect/sql/SqlConnection";
27import { SqlError, classifySqliteError } from "effect/sql/SqlError";
28import * as Statement from "effect/sql/Statement";
29​
30const ATTR_DB_SYSTEM_NAME = "db.system.name";
31​
32export interface SqliteClientConfig {
33 readonly filename: string;
34 readonly readonly?: boolean | undefined;
35 readonly spanAttributes?: Record<string, unknown> | undefined;
36 /** Ignored for in-memory databases, which cannot share a second connection. */
37 readonly readerWorker?: boolean | undefined;
38 /** Runs the writer and WAL checkpoints off the event loop. Ignored for in-memory databases. */
39 readonly writerWorker?: boolean | undefined;
41​
42// SqlClient masks transaction acquisition, so readOnly carries the caller's interruption policy.
43const ReadOnly = Context.Reference<typeof Effect.interruptible | undefined>(
44 "@t3tools/shared/nodeSqliteClient/ReadOnly",
45 { defaultValue: () => undefined },
46);
47​
48/** Wrap the whole transaction; existing write transactions retain the writer, and writes on the reader fail as readonly. */
49export const readOnly = <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
50 Effect.uninterruptibleMask((restore) =>
51 restore(Effect.provideService(effect, ReadOnly, restore)),
52 );
53​
54interface Acquired {
55 readonly connection: "writer" | "reader";
56 readonly lockWaitMs: number;
58​
59interface ConnectionOwner {
60 readonly fiberId: number;
61 readonly name: string;
62 readonly traceId?: string;
63 readonly spanId?: string;
65​
66const connectionOwner = (fiber: Fiber.Fiber<unknown, unknown>): ConnectionOwner => {
67 const current = Context.getOrUndefined(fiber.context, Tracer.ParentSpan);
68 if (current?._tag !== "Span") return { fiberId: fiber.id, name: "untraced" };
69 let span: Tracer.Span = current;
70 while (span.name === "sqlite" || span.name === "sql.transaction") {
71 const parent: Tracer.AnySpan | undefined = Option.getOrUndefined(span.parent);
72 if (parent?._tag !== "Span") break;
73 span = parent;
74 }
75 return { fiberId: fiber.id, name: span.name, traceId: span.traceId, spanId: span.spanId };
76};
77​
78const annotateAcquired = (
79 fiber: Fiber.Fiber<unknown, unknown>,
80 acquired: Acquired | undefined,
81 ownerAtWaitStart?: ConnectionOwner,
82) => {
83 const span = Context.getOrUndefined(fiber.context, Tracer.ParentSpan);
84 if (span?._tag !== "Span" || acquired === undefined) return;
85 span.attribute("db.connection", acquired.connection);
86 span.attribute("db.lock_wait_ms", acquired.lockWaitMs);
87 if (ownerAtWaitStart !== undefined) {
88 span.attribute("db.lock_owner_at_start.fiber_id", ownerAtWaitStart.fiberId);
89 span.attribute("db.lock_owner_at_start.name", ownerAtWaitStart.name);
90 if (ownerAtWaitStart.traceId !== undefined) {
91 span.attribute("db.lock_owner_at_start.trace_id", ownerAtWaitStart.traceId);
92 }
93 if (ownerAtWaitStart.spanId !== undefined) {
94 span.attribute("db.lock_owner_at_start.span_id", ownerAtWaitStart.spanId);
95 }
96 }
97};
98​
99const TransactionAcquire = Context.Reference<
100 | {
101 acquired?: Acquired;
102 ownerAtWaitStart: ConnectionOwner | undefined;
103 restore: typeof Effect.interruptible | undefined;
104 }
105 | undefined
106>("@t3tools/shared/nodeSqliteClient/TransactionAcquire", { defaultValue: () => undefined });
107​
108export class UnsupportedNodeSqliteVersionError extends Schema.TaggedError<UnsupportedNodeSqliteVersionError>()(
109 "UnsupportedNodeSqliteVersionError",
110 {
111 nodeVersion: Schema.String,
112 requirement: Schema.String,
113 },
114) {
115 override get message(): string {
116 return `Node.js ${this.nodeVersion} is missing required node:sqlite APIs. Upgrade to ${this.requirement}.`;
117 }
119​
120export class UnsupportedNodeSqliteOperationError extends Schema.TaggedError<UnsupportedNodeSqliteOperationError>()(
121 "UnsupportedNodeSqliteOperationError",
122 {},
123) {
124 override get message(): string {
125 return "Node SQLite does not support executeStream.";
126 }
128​
129const checkNodeSqliteCompat = Effect.fn("checkNodeSqliteCompat")(function () {
130 const parts = process.versions.node.split(".").map(Number);
131 const major = parts[0] ?? 0;
132 const minor = parts[1] ?? 0;
133 const supported = (major === 22 && minor >= 16) || (major === 23 && minor >= 11) || major >= 24;
134​
135 if (!supported) {
136 return Effect.die(
137 new UnsupportedNodeSqliteVersionError({
138 nodeVersion: process.versions.node,
139 requirement: "Node.js >=22.16, >=23.11, or >=24",
140 }),
141 );
142 }
143 return Effect.void;
144});
145​
146// node:sqlite supplies errcode; classifySqliteError expects errno.
147const classifyError = (cause: unknown, message: string, operation: string) => {
148 if (
149 Predicate.hasProperty(cause, "errcode") &&
150 typeof cause.errcode === "number" &&
151 !Predicate.hasProperty(cause, "errno")
152 ) {
153 Object.assign(cause, { errno: cause.errcode });
154 }
155 return classifySqliteError(cause, { message, operation });
156};
157​
158// SQLite retains text/blob bindings until rebind or finalization; node:sqlite cannot clear them.
159const LARGE_BINDING_SIZE = 64 * 1024;
160​
161const isBlob = (value: unknown): value is ArrayBufferView | ArrayBufferLike =>
162 ArrayBuffer.isView(value) || NodeUtil.types.isAnyArrayBuffer(value);
163​
164const bindingSize = (value: unknown): number => {
165 if (typeof value === "string") {
166 return value.length;
167 }
168 return isBlob(value) ? value.byteLength : 0;
169};
170​
171const hasLargeBinding = (params: ReadonlyArray<unknown>): boolean => {
172 try {
173 let size = 0;
174 for (const param of params) {
175 if (
176 (typeof param === "object" || typeof param === "function") &&
177 param !== null &&
178 !isBlob(param)
179 ) {
180 // Named parameters may be callable objects; read data properties only to avoid invoking getters twice.
181 for (const property of Object.values(Object.getOwnPropertyDescriptors(param))) {
182 if (!property.enumerable) continue;
183 if (!("value" in property)) return true;
184 size += bindingSize(property.value);
185 }
186 } else {
187 size += bindingSize(param);
188 }
189 }
190 return size > LARGE_BINDING_SIZE;
191 } catch {
192 return true;
193 }
194};
195​
196// A reader refuses a database outside WAL mode with this code; retrying cannot change that.
197const NOT_WAL = "ERR_SQLITE_NOT_WAL";
198​
199// Inline worker source also runs in bundles and single-executable builds without module files.
200const workerSource = `
201const { parentPort, workerData } = require("node:worker_threads");
202const { DatabaseSync } = require("node:sqlite");
203const describe = (error) => ({
204 message: String(error && error.message ? error.message : error),
205 code: error && error.code,
206 errcode: error && error.errcode,
207 errstr: error && error.errstr,
208});
209let db;
210try {
211 // A read-only open cannot be undone by SQL, unlike PRAGMA query_only.
212 const next = new DatabaseSync(workerData.filename, {
213 readOnly: workerData.readOnly,
214 allowExtension: workerData.allowExtension,
215 });
216 next.exec("PRAGMA busy_timeout = 5000;");
217 // Reads the header, so a file that is not a database fails here rather than on first use.
218 const mode = String(next.prepare("PRAGMA journal_mode").get().journal_mode).toLowerCase();
219 // Without WAL a reader's shared lock blocks the writer's commits, so refuse.
220 if (workerData.requireWal && mode !== "wal") {
221 throw Object.assign(new Error("database uses journal_mode " + mode + ", not wal"), { code: ${JSON.stringify(NOT_WAL)} });
222 }
223 db = next;
224 parentPort.postMessage({ type: "ready" });
225} catch (error) {
226 parentPort.postMessage({ type: "unavailable", ...describe(error) });
228const statements = new Map();
229const prepare = (sql, cached) => {
230 if (!cached) return db.prepare(sql);
231 let statement = statements.get(sql);
232 if (statement === undefined) {
233 statement = db.prepare(sql);
234 if (statements.size >= workerData.prepareCacheSize) statements.delete(statements.keys().next().value);
235 } else {
236 statements.delete(sql);
237 }
238 statements.set(sql, statement);
239 return statement;
240};
241parentPort.on("message", (request) => {
242 if (request.type === "close") {
243 // Closing lets SQLite checkpoint and remove the WAL, which terminating would skip.
244 try {
245 if (db !== undefined) db.close();
246 } catch {}
247 parentPort.close();
248 return;
249 }
250 const { id, sql, params, cached, values, raw, safeIntegers, received } = request;
251 let operation = "open";
252 let iterator;
253 try {
254 if (db === undefined) throw new Error("database connection is unavailable");
255 operation = "prepare";
256 const statement = prepare(sql, cached);
257 operation = "execute";
258 statement.setReadBigInts(safeIntegers);
259 if (statement.columns().length > 0) {
260 statement.setReturnArrays(values);
261 let rows = [];
262 let bytes = 0;
263 let pendingBatch = false;
264 iterator = statement.iterate(...params);
265 for (const row of iterator) {
266 let rowBytes = 0;
267 for (const key in row) {
268 const value = row[key];
269 rowBytes += typeof value === "string" ? value.length * 2
270 : ArrayBuffer.isView(value) ? value.byteLength : 8;
271 }
272 if (rows.length > 0 && (rows.length >= 16384 || bytes + rowBytes > 8 * 1024 * 1024)) {
273 // Build the next batch during receipt, but allow only one unacknowledged message.
274 if (pendingBatch) Atomics.wait(received, 0, 0);
275 Atomics.store(received, 0, 0);
276 parentPort.postMessage({ id, rows, more: true });
277 rows = [];
278 bytes = 0;
279 pendingBatch = true;
280 }
281 rows.push(row);
282 bytes += rowBytes;
283 }
284 if (pendingBatch) Atomics.wait(received, 0, 0);
285 parentPort.postMessage({ id, rows });
286 } else {
287 const result = statement.run(...params);
288 parentPort.postMessage({ id, rows: raw ? result : [] });
289 }
290 } catch (error) {
291 // A step that throws leaves its statement active; an active write blocks every later COMMIT.
292 try {
293 iterator?.return();
294 } catch {}
295 // A failed iterator can report its previous SQLite error when the statement is reused.
296 statements.delete(sql);
297 parentPort.postMessage({ id, error: { operation, ...describe(error) } });
298 }
299});
300`;
301​
302interface WorkerRequest {
303 readonly sql: string;
304 readonly params: ReadonlyArray<unknown>;
305 readonly cached: boolean;
306 readonly values: boolean;
307 readonly raw: boolean;
309​
310interface WorkerFailure {
311 readonly message: string;
312 readonly code?: unknown;
313 readonly errcode?: unknown;
314 readonly errstr?: unknown;
316​
317type WorkerStartup =
318 | { readonly type: "ready" }
319 | ({ readonly type: "unavailable" } & WorkerFailure);
320​
321type WorkerReply =
322 | { readonly id: number; readonly rows: ReadonlyArray<any>; readonly more?: boolean }
323 | {
324 readonly id: number;
325 readonly error: WorkerFailure & { readonly operation: "open" | "prepare" | "execute" };
326 };
327​
328const workerFailureMessages = {
329 open: "Failed to open database",
330 prepare: "Failed to prepare statement",
331 execute: "Failed to execute statement",
332} as const;
333​
334const failed = (cause: unknown, message: string, operation: string) =>
335 new SqlError({ reason: classifyError(cause, message, operation) });
336​
337const failedWith = (
338 { message, code, errcode, errstr }: WorkerFailure,
339 operation: keyof typeof workerFailureMessages,
340) =>
341 failed(
342 Object.assign(new Error(message), { code, errcode, errstr }),
343 workerFailureMessages[operation],
344 operation,
345 );
346​
347// Read-transaction cleanup succeeds after worker exit because it can no longer change anything.
348const endsReadTransaction = (sql: string) => /^\s*ROLLBACK\b|^\s*COMMIT\b/i.test(sql);
349​
350// WAL readers run concurrently; one worker serialized every read behind the slowest transaction.
351const READER_POOL_SIZE = 4;
352const READER_STARTUP_TIMEOUT = Duration.seconds(10);
353const READER_RETRY_DELAY = Duration.seconds(1);
354const READER_RETRY_MAX_DELAY = Duration.minutes(1);
355​
356// Bind transactions to one worker; fail after its exit instead of resuming outside the transaction on a replacement.
357const makeWorkerConnection = Effect.fnUntraced(function* (options: {
358 readonly filename: string;
359 readonly role: "reader" | "writer";
360 readonly readOnly: boolean;
361 readonly onReply?: () => void;
362}) {
363 const label = options.role === "reader" ? "Database reader" : "Database writer";
364 const readOnly = options.readOnly;
365 let current:
366 | {
367 readonly worker: NodeWorkerThreads.Worker;
368 readonly connection: Connection;
369 readonly started: Promise<WorkerStartup>;
370 }
371 | undefined;
372 let nextRequestId = 0;
373 // A replacement writer would lose the pragmas callers set on it, such as foreign_keys.
374 let writerStopped: string | undefined;
375​
376 const start = () => {
377 const worker = new NodeWorkerThreads.Worker(workerSource, {
378 eval: true,
379 workerData: {
380 filename: options.filename,
381 readOnly,
382 requireWal: options.role === "reader",
383 allowExtension: false,
384 prepareCacheSize: 200,
385 },
386 });
387 let announce: (startup: WorkerStartup) => void = () => {};
388 const started = new Promise<WorkerStartup>((resolve) => {
389 announce = resolve;
390 });
391 let stoppedMessage: string | undefined;
392 const pending = new Map<
393 number,
394 {
395 readonly endsTransaction: boolean;
396 readonly received: Int32Array;
397 readonly rows: Array<unknown>;
398 readonly resume: (reply: WorkerReply) => void;
399 }
400 >();
401 const stop = (message: string) => {
402 stoppedMessage = message;
403 if (options.role === "writer") writerStopped = message;
404 announce({ type: "unavailable", message });
405 if (current?.worker === worker) current = undefined;
406 for (const [id, request] of pending) {
407 request.resume(
408 request.endsTransaction
409 ? { id, rows: [] }
410 : { id, error: { operation: "execute", message } },
411 );
412 }
413 pending.clear();
414 };
415 worker.on("message", (reply: WorkerReply | WorkerStartup) => {
416 if ("type" in reply) {
417 announce(reply);
418 if (pending.size === 0) worker.unref();
419 return;
420 }
421 const request = pending.get(reply.id);
422 if (request === undefined) return;
423 if ("rows" in reply && reply.more) {
424 for (const row of reply.rows) request.rows.push(row);
425 Atomics.store(request.received, 0, 1);
426 Atomics.notify(request.received, 0);
427 return;
428 }
429 pending.delete(reply.id);
430 if (pending.size === 0) worker.unref();
431 options.onReply?.();
432 if ("rows" in reply && request.rows.length > 0) {
433 for (const row of reply.rows) request.rows.push(row);
434 request.resume({ id: reply.id, rows: request.rows });
435 } else {
436 request.resume(reply);
437 }
438 });
439 worker.on("error", (cause) => stop(`${label} failed: ${cause.message}`));
440 worker.on("exit", (code) => stop(`${label} exited with code ${code}`));
441​
442 const request = (input: WorkerRequest) =>
443 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
444 // A COMMIT that never reached a writer must fail; only its ROLLBACK is moot.
445 const endsTransaction = readOnly
446 ? endsReadTransaction(input.sql)
447 : /^\s*ROLLBACK\b/i.test(input.sql);
448 if (stoppedMessage !== undefined) {
449 return endsTransaction
450 ? Effect.succeed([])
451 : Effect.fail(failedWith({ message: stoppedMessage }, "execute"));
452 }
453 const safeIntegers = Boolean(Context.get(fiber.context, Client.SafeIntegers));
454 const reply = Effect.callback<ReadonlyArray<any>, SqlError>((resume) => {
455 const id = nextRequestId++;
456 const received = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
457 pending.set(id, {
458 endsTransaction,
459 received,
460 rows: [],
461 resume: (reply) =>
462 resume(
463 "rows" in reply
464 ? Effect.succeed(reply.rows)
465 : Effect.fail(failedWith(reply.error, reply.error.operation)),
466 ),
467 });
468 if (pending.size === 1) worker.ref();
469 const cached = input.cached && !hasLargeBinding(input.params);
470 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
471 worker.postMessage({ id, safeIntegers, ...input, cached, received });
472 });
473 // A posted write runs to the end, as it did on the event loop; the caller and its lock
474 // must not move on while the worker is still applying it. Reads stay cancellable.
475 return options.role === "writer" ? Effect.uninterruptible(reply) : reply;
476 });
477​
478 const connection = identity<Connection>({
479 execute(sql, params, rowTransform) {
480 const effect = request({ sql, params, cached: true, values: false, raw: false });
481 return rowTransform ? Effect.map(effect, rowTransform) : effect;
482 },
483 executeRaw(sql, params) {
484 return request({ sql, params, cached: true, values: false, raw: true });
485 },
486 executeValues(sql, params) {
487 return request({ sql, params, cached: true, values: true, raw: false });
488 },
489 executeValuesUnprepared(sql, params) {
490 return request({ sql, params: params ?? [], cached: false, values: true, raw: false });
491 },
492 executeUnprepared(sql, params, rowTransform) {
493 // Read snapshots need deferred BEGIN; readonly connections reject IMMEDIATE and EXCLUSIVE.
494 const statement = readOnly && /^\s*BEGIN\b/i.test(sql) ? "BEGIN" : sql;
495 const effect = request({
496 sql: statement,
497 params: params ?? [],
498 cached: false,
499 values: false,
500 raw: false,
501 });
502 return rowTransform ? Effect.map(effect, rowTransform) : effect;
503 },
504 executeStream(_sql, _params) {
505 return Stream.die(new UnsupportedNodeSqliteOperationError());
506 },
507 });
508 current = { worker, connection, started };
509 return current;
510 };
511​
512 yield* Effect.addFinalizer(() =>
513 Effect.promise(async () => {
514 const open = current;
515 if (open === undefined) return;
516 if (options.role === "writer") {
517 await new Promise<void>((resolve) => {
518 open.worker.once("exit", () => resolve());
519 open.worker.ref();
520 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
521 open.worker.postMessage({ type: "close" });
522 });
523 }
524 await open.worker.terminate();
525 }),
526 );
527​
528 const retire = (worker: NodeWorkerThreads.Worker) => {
529 if (current?.worker === worker) current = undefined;
530 void worker.terminate();
531 };
532​
533 return Effect.suspend((): Effect.Effect<Connection, SqlError> => {
534 if (current === undefined && writerStopped !== undefined) {
535 return Effect.fail(failedWith({ message: writerStopped }, "execute"));
536 }
537 let entry: NonNullable<typeof current>;
538 try {
539 entry = current ?? start();
540 } catch (cause) {
541 return Effect.fail(failed(cause, workerFailureMessages.open, "open"));
542 }
543 const started = Effect.promise(() => entry.started);
544 return Effect.flatMap(
545 Effect.withFiber((fiber) => {
546 const restore = Context.get(fiber.context, ReadOnly) ?? identity;
547 // Readers fall back to the writer; the writer has no fallback, so a slow disk only delays it.
548 return restore(
549 options.role === "reader"
550 ? Effect.timeoutOption(started, READER_STARTUP_TIMEOUT)
551 : Effect.asSome(started),
552 );
553 }),
554 (startup): Effect.Effect<Connection, SqlError> => {
555 const outcome = Option.getOrUndefined(startup);
556 if (outcome?.type === "ready") {
557 // A late ready event must not hand out a worker retired by another acquire timeout.
558 return current === entry
559 ? Effect.succeed(entry.connection)
560 : Effect.fail(failedWith({ message: `${label} stopped while starting` }, "open"));
561 }
562 retire(entry.worker);
563 return Effect.fail(
564 failedWith(
565 outcome ?? {
566 message: `${label} did not open the database within ${Duration.toMillis(READER_STARTUP_TIMEOUT)} ms`,
567 },
568 "open",
569 ),
570 );
571 },
572 );
573 });
574});
575​
576const startFailure = (error: SqlError) => {
577 const cause = error.reason.cause;
578 return {
579 reason: cause instanceof Error ? cause.message : error.message,
580 permanent: Predicate.hasProperty(cause, "code") && cause.code === NOT_WAL,
581 };
582};
583​
584// A reader that cannot start turns off the whole pool, so routing never picks a dead slot, until
585// one background retry starts it again.
586const makeReader = Effect.fnUntraced(function* (filename: string, pool: { unavailable: boolean }) {
587 const acquire = yield* makeWorkerConnection({ filename, role: "reader", readOnly: true });
588 const scope = yield* Effect.scope;
589 const context = yield* Effect.context<never>();
590​
591 const recover = (delay: Duration.Duration): Effect.Effect<void> =>
592 Effect.sleep(delay).pipe(
593 Effect.andThen(acquire),
594 Effect.matchEffect({
595 onSuccess: () =>
596 Effect.suspend(() => {
597 pool.unavailable = false;
598 return Effect.logInfo(
599 "SQLite reader worker available again; reads use the reader workers",
600 );
601 }),
602 onFailure: (error) => {
603 const { reason, permanent } = startFailure(error);
604 return permanent
605 ? Effect.logInfo(
606 "SQLite reader worker retries stopped permanently; reads use the writer",
607 { reason },
608 )
609 : recover(Duration.min(Duration.times(delay, 2), READER_RETRY_MAX_DELAY));
610 },
611 }),
612 );
613​
614 return Effect.suspend((): Effect.Effect<Connection | undefined> =>
615 pool.unavailable
616 ? Effect.undefined
617 : acquire.pipe(
618 Effect.map((connection) => (pool.unavailable ? undefined : connection)),
619 Effect.catch((error) => {
620 if (pool.unavailable) return Effect.undefined;
621 pool.unavailable = true;
622 const { reason, permanent } = startFailure(error);
623 // Pool state belongs to the client: never log or retry with the failed read's services.
624 return Effect.logWarning("SQLite reader worker unavailable; reads use the writer", {
625 reason,
626 }).pipe(
627 Effect.andThen(
628 permanent ? Effect.void : Effect.forkIn(recover(READER_RETRY_DELAY), scope),
629 ),
630 Effect.updateContext((_: Context.Context<never>) => context),
631 Effect.as(undefined),
632 );
633 }),
634 ),
635 );
636});
637​
638// A checkpoint copies WAL pages into the database and syncs it. On the writer's thread every
639// write would wait for that sync, so a second connection checkpoints beside the writes.
640const CHECKPOINT_FRAMES = 1000;
641const CHECKPOINT_IDLE_MS = 100;
642// If checkpoints fall behind constant writes, the writer checkpoints itself, delaying writes only.
643const WRITER_BACKSTOP_FRAMES = 10_000;
644​
645const checkpointWorkerSource = `
646const { parentPort, workerData } = require("node:worker_threads");
647const { DatabaseSync } = require("node:sqlite");
648let db;
649let frames;
650let passive;
651let idle;
652const check = (force) => {
653 if (db === undefined) {
654 db = new DatabaseSync(workerData.filename);
655 db.exec("PRAGMA busy_timeout = 5000;");
656 // macOS requires F_FULLFSYNC to flush the drive cache.
657 db.exec("PRAGMA checkpoint_fullfsync = ON;");
658 frames = db.prepare("PRAGMA wal_checkpoint(NOOP)");
659 passive = db.prepare("PRAGMA wal_checkpoint(PASSIVE)");
660 }
661 const before = frames.get();
662 let state = before;
663 if (state.log - state.checkpointed >= workerData.frames || (force && state.log > state.checkpointed)) {
664 passive.get();
665 state = frames.get();
666 }
667 // The WAL restarts only once every frame is checkpointed, so catch up when writes pause.
668 // A reader pinning the WAL stops progress; the next write retries instead of a timer loop.
669 const progressed = !force || state.checkpointed > before.checkpointed;
670 if (state.log > state.checkpointed && progressed) {
671 idle = setTimeout(() => run(true), workerData.idleMs);
672 }
673 parentPort.postMessage({ type: "checked", log: state.log, checkpointed: state.checkpointed });
674};
675const run = (force) => {
676 clearTimeout(idle);
677 try {
678 check(force);
679 } catch (error) {
680 parentPort.postMessage({ type: "failed", message: String(error && error.message ? error.message : error) });
681 }
682};
683parentPort.on("message", () => run(false));
684`;
685​
686const sqliteVersion = () => {
687 const db = new NodeSqlite.DatabaseSync(":memory:");
688 try {
689 return String(db.prepare("SELECT sqlite_version() AS version").get()?.version);
690 } finally {
691 db.close();
692 }
693};
694​
695// Returns the writer's per-statement notification, or undefined when the writer checkpoints alone.
696const startCheckpointWorker = Effect.fnUntraced(function* (filename: string) {
697 const warn = (reason: string) =>
698 Effect.logWarning("SQLite checkpoint worker unavailable; the writer checkpoints its own WAL", {
699 reason,
700 });
701 const version = sqliteVersion();
702 const [major = 0, minor = 0] = version.split(".").map(Number);
703 // Older SQLite treats NOOP as PASSIVE, so counting frames would checkpoint on every write.
704 if (major < 3 || (major === 3 && minor < 51)) {
705 yield* warn(`SQLite ${version} has no NOOP checkpoint`);
706 return undefined;
707 }
708 const started = Result.try(
709 () =>
710 new NodeWorkerThreads.Worker(checkpointWorkerSource, {
711 eval: true,
712 workerData: { filename, frames: CHECKPOINT_FRAMES, idleMs: CHECKPOINT_IDLE_MS },
713 }),
714 );
715 if (Result.isFailure(started)) {
716 yield* warn(String(started.failure));
717 return undefined;
718 }
719 const worker = started.success;
720 worker.unref();
721 const runFork = Effect.runForkWith(yield* Effect.context<never>());
722 let stopped = false;
723 const stop = (reason: string) => {
724 if (stopped) return;
725 stopped = true;
726 void worker.terminate();
727 runFork(warn(reason));
728 };
729 worker.on("message", (message: { readonly type?: unknown; readonly message?: unknown }) => {
730 if (message?.type === "failed") stop(String(message.message));
731 });
732 worker.on("error", (cause) => stop(cause.message));
733 worker.on("exit", (code) => stop(`exited with code ${code}`));
734 yield* Effect.addFinalizer(() =>
735 Effect.promise(() => {
736 stopped = true;
737 return worker.terminate();
738 }),
739 );
740 let scheduled = false;
741 return () => {
742 if (stopped || scheduled) return;
743 scheduled = true;
744 // One check per event-loop turn is enough, however many statements finished in it.
745 setImmediate(() => {
746 scheduled = false;
747 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
748 if (!stopped) worker.postMessage(0);
749 });
750 };
751});
752​
753const make = Effect.fn("makeWithDatabase")(function* (
754 options: SqliteClientConfig,
755): Effect.fn.Return<Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity> {
756 yield* checkNodeSqliteCompat();
757​
758 const compiler = Statement.makeCompilerSqlite();
759 const isFileDatabase = options.filename !== ":memory:" && options.filename !== "";
760​
761 const makeConnection = Effect.gen(function* () {
762 const scope = yield* Effect.scope;
763 const db = yield* Effect.try({
764 try: () =>
765 new NodeSqlite.DatabaseSync(options.filename, {
766 readOnly: options.readonly ?? false,
767 allowExtension: false,
768 }),
769 catch: (cause) =>
770 new SqlError({
771 reason: classifyError(cause, "Failed to open database", "open"),
772 }),
773 });
774 yield* Scope.addFinalizer(
775 scope,
776 Effect.try({
777 try: () => db.close(),
778 catch: (cause) =>
779 new SqlError({
780 reason: classifyError(cause, "Failed to close database", "close"),
781 }),
782 }).pipe(Effect.orDie),
783 );
784 const statementReaderCache = new WeakMap<NodeSqlite.StatementSync, boolean>();
785 const hasRows = (statement: NodeSqlite.StatementSync): boolean => {
786 const cached = statementReaderCache.get(statement);
787 if (cached !== undefined) {
788 return cached;
789 }
790 const value = statement.columns().length > 0;
791 statementReaderCache.set(statement, value);
792 return value;
793 };
794​
795 const prepare = (sql: string) =>
796 Effect.try({
797 try: () => db.prepare(sql),
798 catch: (cause) =>
799 new SqlError({
800 reason: classifyError(cause, "Failed to prepare statement", "prepare"),
801 }),
802 });
803​
804 const prepareCache = yield* Cache.makeWith(prepare, {
805 capacity: 200,
806 // A transient prepare failure must not outlive the lock or missing schema.
807 timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.minutes(10) : Duration.zero),
808 });
809​
810 const statementFor = (sql: string, params: ReadonlyArray<unknown>) =>
811 hasLargeBinding(params) ? prepare(sql) : Cache.get(prepareCache, sql);
812​
813 const runStatement = (
814 statement: NodeSqlite.StatementSync,
815 params: ReadonlyArray<unknown>,
816 mode: "rows" | "raw" | "values" = "rows",
817 ) =>
818 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
819 let arrays = false;
820 let result: Exit.Exit<ReadonlyArray<unknown>, SqlError>;
821 try {
822 statement.setReadBigInts(Boolean(Context.get(fiber.context, Client.SafeIntegers)));
823 if (hasRows(statement)) {
824 arrays = mode === "values";
825 if (arrays) statement.setReturnArrays(true);
826 result = Exit.succeed(statement.all(...(params as any)));
827 } else {
828 const value = statement.run(...(params as any));
829 result = Exit.succeed(
830 mode === "raw" ? (value as unknown as ReadonlyArray<unknown>) : [],
831 );
832 }
833 } catch (cause) {
834 result = Exit.fail(
835 new SqlError({
836 reason: classifyError(cause, "Failed to execute statement", "execute"),
837 }),
838 );
839 }
840 if (arrays) {
841 try {
842 statement.setReturnArrays(false);
843 } catch (cause) {
844 return Exit.die(
845 new SqlError({
846 reason: classifyError(
847 cause,
848 "Failed to reset statement result mode",
849 "resetResultMode",
850 ),
851 }),
852 );
853 }
854 }
855 return result;
856 });
857​
858 const run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
859 Effect.flatMap(statementFor(sql, params), (statement) =>
860 runStatement(statement, params, raw ? "raw" : "rows"),
861 );
862 const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
863 Effect.flatMap(statementFor(sql, params), (statement) =>
864 runStatement(statement, params, "values"),
865 );
866​
867 return identity<Connection>({
868 execute(sql, params, rowTransform) {
869 return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params);
870 },
871 executeRaw(sql, params) {
872 return run(sql, params, true);
873 },
874 executeValues(sql, params) {
875 return runValues(sql, params);
876 },
877 executeValuesUnprepared(sql, params) {
878 return Effect.flatMap(prepare(sql), (statement) =>
879 runStatement(statement, params ?? [], "values"),
880 );
881 },
882 executeUnprepared(sql, params, rowTransform) {
883 const effect = prepare(sql).pipe(
884 Effect.flatMap((statement) => runStatement(statement, params ?? [])),
885 );
886 return rowTransform ? Effect.map(effect, rowTransform) : effect;
887 },
888 executeStream(_sql, _params) {
889 return Stream.die(new UnsupportedNodeSqliteOperationError());
890 },
891 });
892 });
893​
894 const semaphore = yield* Semaphore.make(1);
895 const writerWorker = options.writerWorker === true && isFileDatabase;
896 let checkpointAfterWrite: (() => void) | undefined;
897 const writerConnection: Effect.Effect<Connection, SqlError> = writerWorker
898 ? yield* makeWorkerConnection({
899 filename: options.filename,
900 role: "writer",
901 readOnly: options.readonly ?? false,
902 onReply: () => checkpointAfterWrite?.(),
903 })
904 : Effect.succeed(yield* makeConnection);
905 // Opening now fails the layer for a file that is not a database, not its first query.
906 const opened = yield* writerConnection;
907 // Started after the writer, so it stops first and the writer's close can checkpoint.
908 if (writerWorker && options.readonly !== true) {
909 checkpointAfterWrite = yield* startCheckpointWorker(options.filename);
910 if (checkpointAfterWrite !== undefined) {
911 yield* opened.executeUnprepared(
912 `PRAGMA wal_autocheckpoint = ${WRITER_BACKSTOP_FRAMES}`,
913 [],
914 undefined,
915 );
916 }
917 }
918 const readerPool = { unavailable: false };
919 const readers =
920 options.readerWorker && isFileDatabase
921 ? yield* Effect.forEach(Array.from({ length: READER_POOL_SIZE }), () =>
922 Effect.map(
923 Effect.all([makeReader(options.filename, readerPool), Semaphore.make(1)]),
924 ([acquire, lock]) => ({
925 acquire,
926 lock,
927 claimed: false,
928 }),
929 ),
930 )
931 : [];
932 // One permit per slot, so a queued read waits for any reader, not one it picked while all were busy.
933 const readerAdmission = yield* Semaphore.make(readers.length);
934​
935 interface Target {
936 readonly name: Acquired["connection"];
937 readonly lock: Semaphore.Semaphore;
938 readonly connection: Connection;
939 }
940 const writer = Effect.map(writerConnection, (connection): Target => ({
941 name: "writer",
942 lock: semaphore,
943 connection,
944 }));
945 let activeWriter: ConnectionOwner | undefined;
946 // Callers must run route uninterruptibly and pass `claimed` a finalizer that runs `release` once.
947 // Waits use the caller's `restore`, not readOnly's, which may have been captured outside a mask.
948 const route = (
949 claimed: (release: Effect.Effect<void>) => Effect.Effect<void>,
950 restore: typeof Effect.interruptible,
951 ) =>
952 Effect.withFiber((fiber): Effect.Effect<Target, SqlError> => {
953 if (readers.length === 0 || readerPool.unavailable || !Context.get(fiber.context, ReadOnly)) {
954 return writer;
955 }
956 const claim = Effect.andThen(
957 restore(readerAdmission.take(1)),
958 Effect.suspend(() => {
959 // Holding a permit leaves a slot idle; the lowest wins, so idle slots never start a worker.
960 const reader = readers.find((slot) => !slot.claimed)!;
961 reader.claimed = true;
962 const release = Effect.andThen(
963 Effect.sync(() => {
964 reader.claimed = false;
965 }),
966 readerAdmission.release(1),
967 );
968 return Effect.as(claimed(release), reader);
969 }),
970 );
971 return Effect.flatMap(
972 // A scheduler yield after taking the permit must not precede its release finalizer.
973 Effect.provideService(claim, Scheduler.PreventSchedulerYield, true),
974 (reader) =>
975 Effect.flatMap(
976 Effect.provideService(reader.acquire, ReadOnly, restore),
977 (readerConnection) =>
978 readerConnection === undefined
979 ? writer
980 : Effect.succeed<Target>({
981 name: "reader",
982 lock: reader.lock,
983 connection: readerConnection,
984 }),
985 ),
986 );
987 });
988​
989 const acquired = (
990 target: { readonly name: Acquired["connection"] },
991 clock: Clock.Clock,
992 start: bigint,
993 ): Acquired => ({
994 connection: target.name,
995 lockWaitMs: Number((clock.monotonicTimeNanosUnsafe() - start) / 1000n) / 1000,
996 });
997​
998 const borrower: Borrower = (use) =>
999 Effect.uninterruptibleMask((restore) => {
1000 let release: Effect.Effect<void> = Effect.void;
1001 const claimed = (next: Effect.Effect<void>) =>
1002 Effect.sync(() => {
1003 release = next;
1004 });
1005 // Started before routing, so lock wait includes waiting for reader admission.
1006 return Effect.withFiber((fiber) => {
1007 const start = fiber.getRef(Clock.Clock).monotonicTimeNanosUnsafe();
1008 return Effect.flatMap(route(claimed, restore), (target) =>
1009 restore(borrowTarget(target, use, start)),
1010 );
1011 }).pipe(Effect.ensuring(Effect.suspend(() => release)));
1012 });
1013 const borrowTarget = <A, E, R>(
1014 target: Target,
1015 use: (connection: Connection) => Effect.Effect<A, E, R>,
1016 start: bigint,
1017 ): Effect.Effect<A, E, R> =>
1018 Effect.withFiber((fiber) => {
1019 const clock = fiber.getRef(Clock.Clock);
1020 const ownerAtWaitStart = target.name === "writer" ? activeWriter : undefined;
1021 const owner = target.name === "writer" ? connectionOwner(fiber) : undefined;
1022 const useConnection = Effect.suspend(() => {
1023 if (target.name === "writer") activeWriter = owner;
1024 if (
1025 fiber.getRef(References.TracerEnabled) &&
1026 fiber.getRef(Statement.SpanPropagationEnabled)
1027 ) {
1028 annotateAcquired(fiber, acquired(target, clock, start), ownerAtWaitStart);
1030 return use(target.connection);
1031 });
1032 const useOwnedConnection =
1033 target.name === "writer"
1034 ? Effect.onExit(useConnection, () =>
1035 Effect.sync(() => {
1036 if (activeWriter === owner) activeWriter = undefined;
1037 }),
1039 : useConnection;
1040 return target.lock.withPermits(1)(useOwnedConnection);
1041 });
1042 const claimedUntilScopeCloses = (release: Effect.Effect<void>) =>
1043 Effect.withFiber((fiber) =>
1044 Scope.addFinalizer(Context.getUnsafe(fiber.context, Scope.Scope), release),
1045 );
1046 // Started before routing, so lock wait includes waiting for reader admission.
1047 const transactionAcquirer = Effect.uninterruptibleMask((maskRestore) =>
1048 Effect.withFiber((fiber) => {
1049 const start = fiber.getRef(Clock.Clock).monotonicTimeNanosUnsafe();
1050 const pending = fiber.getRef(TransactionAcquire);
1051 const restore = pending?.restore ?? maskRestore;
1052 return Effect.flatMap(route(claimedUntilScopeCloses, restore), (target) => {
1053 const scope = Context.getUnsafe(fiber.context, Scope.Scope);
1054 const clock = fiber.getRef(Clock.Clock);
1055 const ownerAtWaitStart = target.name === "writer" ? activeWriter : undefined;
1056 const owner = target.name === "writer" ? connectionOwner(fiber) : undefined;
1057 const acquire = Effect.tap(restore(target.lock.take(1)), () => {
1058 if (target.name === "writer") activeWriter = owner;
1059 if (pending !== undefined) {
1060 pending.acquired = acquired(target, clock, start);
1061 pending.ownerAtWaitStart = ownerAtWaitStart;
1063 return Scope.addFinalizer(
1064 scope,
1065 Effect.sync(() => {
1066 if (target.name === "writer" && activeWriter === owner) activeWriter = undefined;
1067 }).pipe(Effect.andThen(target.lock.release(1))),
1068 );
1069 });
1070 return Effect.as(
1071 // A scheduler yield after taking the permit must not precede its release finalizer.
1072 Effect.provideService(acquire, Scheduler.PreventSchedulerYield, true),
1073 target.connection,
1074 );
1075 });
1076 }),
1077 );
1078​
1079 const client = yield* Client.make({
1080 driver: "node:sqlite",
1081 acquirer: transactionAcquirer,
1082 borrower,
1083 compiler,
1084 transactionAcquirer,
1085 // BEGIN IMMEDIATE avoids read-then-write SQLITE_BUSY_SNAPSHOT, which busy_timeout cannot resolve.
1086 beginTransaction: options.readonly === true ? "BEGIN" : "BEGIN IMMEDIATE",
1087 spanAttributes: [
1088 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
1089 [ATTR_DB_SYSTEM_NAME, "sqlite"],
1090 ],
1091 });
1092 const withTransaction = client.withTransaction;
1093 return Object.assign(client, {
1094 withTransaction: <A, E, R>(effect: Effect.Effect<A, E, R>) =>
1095 Effect.uninterruptibleMask((restore) => {
1096 // SqlClient masks setup; acquisition must preserve the caller's interruptibility.
1097 const pending: {
1098 acquired?: Acquired;
1099 ownerAtWaitStart: ConnectionOwner | undefined;
1100 restore: typeof Effect.interruptible | undefined;
1101 } = {
1102 ownerAtWaitStart: undefined,
1103 restore,
1104 };
1105 const body = Effect.withFiber<A, E, R>((fiber) => {
1106 annotateAcquired(fiber, pending.acquired, pending.ownerAtWaitStart);
1107 pending.restore = undefined;
1108 return effect;
1109 });
1110 return restore(
1111 withTransaction(body).pipe(Effect.provideService(TransactionAcquire, pending)),
1112 );
1113 }),
1114 });
1115});
1116​
1117export const layer = (config: SqliteClientConfig): Layer.Layer<Client.SqlClient, SqlError> =>
1118 Layer.effect(Client.SqlClient, make(config)).pipe(Layer.provide(Reactivity.layer));