Open History to see the last commit
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;
40}
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;
57}
58
59interface ConnectionOwner {
60 readonly fiberId: number;
61 readonly name: string;
62 readonly traceId?: string;
63 readonly spanId?: string;
64}
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 }
118}
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 }
127}
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) });
227}
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, savepoints } = request;
251 let operation = "open";
252 let iterator;
253 try {
254 if (db === undefined) throw new Error("database connection is unavailable");
255 operation = "execute";
256 for (const savepoint of savepoints) db.exec(savepoint);
257 operation = "prepare";
258 const statement = prepare(sql, cached);
259 operation = "execute";
260 statement.setReadBigInts(safeIntegers);
261 if (statement.columns().length > 0) {
262 statement.setReturnArrays(values);
263 let rows = [];
264 let bytes = 0;
265 let pendingBatch = false;
266 iterator = statement.iterate(...params);
267 for (const row of iterator) {
268 let rowBytes = 0;
269 for (const key in row) {
270 const value = row[key];
271 rowBytes += typeof value === "string" ? value.length * 2
272 : ArrayBuffer.isView(value) ? value.byteLength : 8;
273 }
274 if (rows.length > 0 && (rows.length >= 16384 || bytes + rowBytes > 8 * 1024 * 1024)) {
275 // Build the next batch during receipt, but allow only one unacknowledged message.
276 if (pendingBatch) Atomics.wait(received, 0, 0);
277 Atomics.store(received, 0, 0);
278 parentPort.postMessage({ id, rows, more: true });
279 rows = [];
280 bytes = 0;
281 pendingBatch = true;
282 }
283 rows.push(row);
284 bytes += rowBytes;
285 }
286 if (pendingBatch) Atomics.wait(received, 0, 0);
287 parentPort.postMessage({ id, rows });
288 } else {
289 // A discarded result is read as BigInt: see the same line in the in-process client.
290 if (!raw) statement.setReadBigInts(true);
291 const result = statement.run(...params);
292 parentPort.postMessage({ id, rows: raw ? result : [] });
293 }
294 } catch (error) {
295 // A step that throws leaves its statement active; an active write blocks every later COMMIT.
296 try {
297 iterator?.return();
298 } catch {}
299 // A failed iterator can report its previous SQLite error when the statement is reused.
300 statements.delete(sql);
301 parentPort.postMessage({ id, error: { operation, ...describe(error) } });
302 }
303});
304`;
305
306interface WorkerRequest {
307 readonly sql: string;
308 readonly params: ReadonlyArray<unknown>;
309 readonly cached: boolean;
310 readonly values: boolean;
311 readonly raw: boolean;
312}
313
314interface WorkerFailure {
315 readonly message: string;
316 readonly code?: unknown;
317 readonly errcode?: unknown;
318 readonly errstr?: unknown;
319}
320
321type WorkerStartup =
322 | { readonly type: "ready" }
323 | ({ readonly type: "unavailable" } & WorkerFailure);
324
325type WorkerReply =
326 | { readonly id: number; readonly rows: ReadonlyArray<any>; readonly more?: boolean }
327 | {
328 readonly id: number;
329 readonly error: WorkerFailure & { readonly operation: "open" | "prepare" | "execute" };
330 };
331
332const workerFailureMessages = {
333 open: "Failed to open database",
334 prepare: "Failed to prepare statement",
335 execute: "Failed to execute statement",
336} as const;
337
338const failed = (cause: unknown, message: string, operation: string) =>
339 new SqlError({ reason: classifyError(cause, message, operation) });
340
341const failedWith = (
342 { message, code, errcode, errstr }: WorkerFailure,
343 operation: keyof typeof workerFailureMessages,
344) =>
345 failed(
346 Object.assign(new Error(message), { code, errcode, errstr }),
347 workerFailureMessages[operation],
348 operation,
349 );
350
351// Read-transaction cleanup succeeds after worker exit because it can no longer change anything.
352const endsReadTransaction = (sql: string) => /^\s*ROLLBACK\b|^\s*COMMIT\b/i.test(sql);
353
354// WAL readers run concurrently; one worker serialized every read behind the slowest transaction.
355const READER_POOL_SIZE = 4;
356const READER_STARTUP_TIMEOUT = Duration.seconds(10);
357const READER_RETRY_DELAY = Duration.seconds(1);
358const READER_RETRY_MAX_DELAY = Duration.minutes(1);
359
360// Bind transactions to one worker; fail after its exit instead of resuming outside the transaction on a replacement.
361const makeWorkerConnection = Effect.fnUntraced(function* (options: {
362 readonly filename: string;
363 readonly role: "reader" | "writer";
364 readonly readOnly: boolean;
365 readonly onReply?: () => void;
366}) {
367 const label = options.role === "reader" ? "Database reader" : "Database writer";
368 const readOnly = options.readOnly;
369 let current:
370 | {
371 readonly worker: NodeWorkerThreads.Worker;
372 readonly connection: Connection;
373 readonly started: Promise<WorkerStartup>;
374 }
375 | undefined;
376 let nextRequestId = 0;
377 // Materialize nested savepoints with the next statement; empty jobs need no worker round trip.
378 const pendingSavepoints: string[] = [];
379 // A replacement writer would lose the pragmas callers set on it, such as foreign_keys.
380 let writerStopped: string | undefined;
381
382 const start = () => {
383 const worker = new NodeWorkerThreads.Worker(workerSource, {
384 eval: true,
385 workerData: {
386 filename: options.filename,
387 readOnly,
388 requireWal: options.role === "reader",
389 allowExtension: false,
390 prepareCacheSize: 200,
391 },
392 });
393 let announce: (startup: WorkerStartup) => void = () => {};
394 const started = new Promise<WorkerStartup>((resolve) => {
395 announce = resolve;
396 });
397 let stoppedMessage: string | undefined;
398 const pending = new Map<
399 number,
400 {
401 readonly endsTransaction: boolean;
402 readonly received: Int32Array;
403 readonly rows: Array<unknown>;
404 readonly resume: (reply: WorkerReply) => void;
405 }
406 >();
407 const stop = (message: string) => {
408 stoppedMessage = message;
409 if (options.role === "writer") writerStopped = message;
410 announce({ type: "unavailable", message });
411 if (current?.worker === worker) current = undefined;
412 for (const [id, request] of pending) {
413 request.resume(
414 request.endsTransaction
415 ? { id, rows: [] }
416 : { id, error: { operation: "execute", message } },
417 );
418 }
419 pending.clear();
420 };
421 worker.on("message", (reply: WorkerReply | WorkerStartup) => {
422 if ("type" in reply) {
423 announce(reply);
424 if (pending.size === 0) worker.unref();
425 return;
426 }
427 const request = pending.get(reply.id);
428 if (request === undefined) return;
429 if ("rows" in reply && reply.more) {
430 for (const row of reply.rows) request.rows.push(row);
431 Atomics.store(request.received, 0, 1);
432 Atomics.notify(request.received, 0);
433 return;
434 }
435 pending.delete(reply.id);
436 if (pending.size === 0) worker.unref();
437 options.onReply?.();
438 if ("rows" in reply && request.rows.length > 0) {
439 for (const row of reply.rows) request.rows.push(row);
440 request.resume({ id: reply.id, rows: request.rows });
441 } else {
442 request.resume(reply);
443 }
444 });
445 worker.on("error", (cause) => stop(`${label} failed: ${cause.message}`));
446 worker.on("exit", (code) => stop(`${label} exited with code ${code}`));
447
448 const request = (input: WorkerRequest) =>
449 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
450 // A COMMIT that never reached a writer must fail; only its ROLLBACK is moot.
451 const endsTransaction = readOnly
452 ? endsReadTransaction(input.sql)
453 : /^\s*ROLLBACK\b/i.test(input.sql);
454 if (stoppedMessage !== undefined) {
455 return endsTransaction
456 ? Effect.succeed([])
457 : Effect.fail(failedWith({ message: stoppedMessage }, "execute"));
458 }
459 const safeIntegers = Boolean(Context.get(fiber.context, Client.SafeIntegers));
460 const reply = Effect.callback<ReadonlyArray<any>, SqlError>((resume) => {
461 const id = nextRequestId++;
462 const received = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
463 pending.set(id, {
464 endsTransaction,
465 received,
466 rows: [],
467 resume: (reply) =>
468 resume(
469 "rows" in reply
470 ? Effect.succeed(reply.rows)
471 : Effect.fail(failedWith(reply.error, reply.error.operation)),
472 ),
473 });
474 if (pending.size === 1) worker.ref();
475 const cached = input.cached && !hasLargeBinding(input.params);
476 const message = {
477 id,
478 safeIntegers,
479 ...input,
480 cached,
481 received,
482 savepoints: [...pendingSavepoints],
483 };
484 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
485 worker.postMessage(message);
486 // An unsent savepoint must stay queued, or its rollback would target an older sibling's.
487 pendingSavepoints.length = 0;
488 });
489 // A posted write runs to the end, as it did on the event loop; the caller and its lock
490 // must not move on while the worker is still applying it. Reads stay cancellable.
491 return options.role === "writer" ? Effect.uninterruptible(reply) : reply;
492 });
493
494 const connection = identity<Connection>({
495 execute(sql, params, rowTransform) {
496 const effect = request({ sql, params, cached: true, values: false, raw: false });
497 return rowTransform ? Effect.map(effect, rowTransform) : effect;
498 },
499 executeRaw(sql, params) {
500 return request({ sql, params, cached: true, values: false, raw: true });
501 },
502 executeValues(sql, params) {
503 return request({ sql, params, cached: true, values: true, raw: false });
504 },
505 executeValuesUnprepared(sql, params) {
506 return request({ sql, params: params ?? [], cached: false, values: true, raw: false });
507 },
508 executeUnprepared(sql, params, rowTransform) {
509 // Read snapshots need deferred BEGIN; readonly connections reject IMMEDIATE and EXCLUSIVE.
510 const statement = readOnly && /^\s*BEGIN\b/i.test(sql) ? "BEGIN" : sql;
511 const effect = Effect.suspend(() => {
512 if (!readOnly && /^SAVEPOINT effect_sql_\d+$/.test(statement)) {
513 pendingSavepoints.push(statement);
514 return Effect.succeed([]);
515 }
516 const rollback = /^ROLLBACK TO SAVEPOINT (effect_sql_\d+)$/.exec(statement);
517 if (rollback !== null) {
518 const pending = pendingSavepoints.lastIndexOf(`SAVEPOINT ${rollback[1]}`);
519 if (pending !== -1) {
520 pendingSavepoints.splice(pending);
521 return Effect.succeed([]);
522 }
523 }
524 if (statement === "COMMIT" || statement === "ROLLBACK") pendingSavepoints.length = 0;
525 return request({
526 sql: statement,
527 params: params ?? [],
528 cached: false,
529 values: false,
530 raw: false,
531 });
532 });
533 return rowTransform ? Effect.map(effect, rowTransform) : effect;
534 },
535 executeStream(_sql, _params) {
536 return Stream.die(new UnsupportedNodeSqliteOperationError());
537 },
538 });
539 current = { worker, connection, started };
540 return current;
541 };
542
543 yield* Effect.addFinalizer(() =>
544 Effect.promise(async () => {
545 const open = current;
546 if (open === undefined) return;
547 if (options.role === "writer") {
548 await new Promise<void>((resolve) => {
549 open.worker.once("exit", () => resolve());
550 open.worker.ref();
551 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
552 open.worker.postMessage({ type: "close" });
553 });
554 }
555 await open.worker.terminate();
556 }),
557 );
558
559 const retire = (worker: NodeWorkerThreads.Worker) => {
560 if (current?.worker === worker) current = undefined;
561 void worker.terminate();
562 };
563
564 return Effect.suspend((): Effect.Effect<Connection, SqlError> => {
565 if (current === undefined && writerStopped !== undefined) {
566 return Effect.fail(failedWith({ message: writerStopped }, "execute"));
567 }
568 let entry: NonNullable<typeof current>;
569 try {
570 entry = current ?? start();
571 } catch (cause) {
572 return Effect.fail(failed(cause, workerFailureMessages.open, "open"));
573 }
574 const started = Effect.promise(() => entry.started);
575 return Effect.flatMap(
576 Effect.withFiber((fiber) => {
577 const restore = Context.get(fiber.context, ReadOnly) ?? identity;
578 // Readers fall back to the writer; the writer has no fallback, so a slow disk only delays it.
579 return restore(
580 options.role === "reader"
581 ? Effect.timeoutOption(started, READER_STARTUP_TIMEOUT)
582 : Effect.asSome(started),
583 );
584 }),
585 (startup): Effect.Effect<Connection, SqlError> => {
586 const outcome = Option.getOrUndefined(startup);
587 if (outcome?.type === "ready") {
588 // A late ready event must not hand out a worker retired by another acquire timeout.
589 return current === entry
590 ? Effect.succeed(entry.connection)
591 : Effect.fail(failedWith({ message: `${label} stopped while starting` }, "open"));
592 }
593 retire(entry.worker);
594 return Effect.fail(
595 failedWith(
596 outcome ?? {
597 message: `${label} did not open the database within ${Duration.toMillis(READER_STARTUP_TIMEOUT)} ms`,
598 },
599 "open",
600 ),
601 );
602 },
603 );
604 });
605});
606
607const startFailure = (error: SqlError) => {
608 const cause = error.reason.cause;
609 return {
610 reason: cause instanceof Error ? cause.message : error.message,
611 permanent: Predicate.hasProperty(cause, "code") && cause.code === NOT_WAL,
612 };
613};
614
615// A reader that cannot start turns off the whole pool, so routing never picks a dead slot, until
616// one background retry starts it again.
617const makeReader = Effect.fnUntraced(function* (filename: string, pool: { unavailable: boolean }) {
618 const acquire = yield* makeWorkerConnection({ filename, role: "reader", readOnly: true });
619 const scope = yield* Effect.scope;
620 const context = yield* Effect.context<never>();
621
622 const recover = (delay: Duration.Duration): Effect.Effect<void> =>
623 Effect.sleep(delay).pipe(
624 Effect.andThen(acquire),
625 Effect.matchEffect({
626 onSuccess: () =>
627 Effect.suspend(() => {
628 pool.unavailable = false;
629 return Effect.logInfo(
630 "SQLite reader worker available again; reads use the reader workers",
631 );
632 }),
633 onFailure: (error) => {
634 const { reason, permanent } = startFailure(error);
635 return permanent
636 ? Effect.logInfo(
637 "SQLite reader worker retries stopped permanently; reads use the writer",
638 { reason },
639 )
640 : recover(Duration.min(Duration.times(delay, 2), READER_RETRY_MAX_DELAY));
641 },
642 }),
643 );
644
645 return Effect.suspend((): Effect.Effect<Connection | undefined> =>
646 pool.unavailable
647 ? Effect.undefined
648 : acquire.pipe(
649 Effect.map((connection) => (pool.unavailable ? undefined : connection)),
650 Effect.catch((error) => {
651 if (pool.unavailable) return Effect.undefined;
652 pool.unavailable = true;
653 const { reason, permanent } = startFailure(error);
654 // Pool state belongs to the client: never log or retry with the failed read's services.
655 return Effect.logWarning("SQLite reader worker unavailable; reads use the writer", {
656 reason,
657 }).pipe(
658 Effect.andThen(
659 permanent ? Effect.void : Effect.forkIn(recover(READER_RETRY_DELAY), scope),
660 ),
661 Effect.updateContext((_: Context.Context<never>) => context),
662 Effect.as(undefined),
663 );
664 }),
665 ),
666 );
667});
668
669// A checkpoint copies WAL pages into the database and syncs it. On the writer's thread every
670// write would wait for that sync, so a second connection checkpoints beside the writes.
671const CHECKPOINT_FRAMES = 1000;
672const CHECKPOINT_IDLE_MS = 100;
673// If checkpoints fall behind constant writes, the writer checkpoints itself, delaying writes only.
674const WRITER_BACKSTOP_FRAMES = 10_000;
675
676const checkpointWorkerSource = `
677const { parentPort, workerData } = require("node:worker_threads");
678const { DatabaseSync } = require("node:sqlite");
679let db;
680let frames;
681let passive;
682let idle;
683const check = (force) => {
684 if (db === undefined) {
685 db = new DatabaseSync(workerData.filename);
686 db.exec("PRAGMA busy_timeout = 5000;");
687 // macOS requires F_FULLFSYNC to flush the drive cache.
688 db.exec("PRAGMA checkpoint_fullfsync = ON;");
689 frames = db.prepare("PRAGMA wal_checkpoint(NOOP)");
690 passive = db.prepare("PRAGMA wal_checkpoint(PASSIVE)");
691 }
692 const before = frames.get();
693 let state = before;
694 if (state.log - state.checkpointed >= workerData.frames || (force && state.log > state.checkpointed)) {
695 passive.get();
696 state = frames.get();
697 }
698 // The WAL restarts only once every frame is checkpointed, so catch up when writes pause.
699 // A reader pinning the WAL stops progress; the next write retries instead of a timer loop.
700 const progressed = !force || state.checkpointed > before.checkpointed;
701 if (state.log > state.checkpointed && progressed) {
702 idle = setTimeout(() => run(true), workerData.idleMs);
703 }
704 parentPort.postMessage({ type: "checked", log: state.log, checkpointed: state.checkpointed });
705};
706const run = (force) => {
707 clearTimeout(idle);
708 try {
709 check(force);
710 } catch (error) {
711 parentPort.postMessage({ type: "failed", message: String(error && error.message ? error.message : error) });
712 }
713};
714parentPort.on("message", () => run(false));
715`;
716
717const sqliteVersion = () => {
718 const db = new NodeSqlite.DatabaseSync(":memory:");
719 try {
720 return String(db.prepare("SELECT sqlite_version() AS version").get()?.version);
721 } finally {
722 db.close();
723 }
724};
725
726// Returns the writer's per-statement notification, or undefined when the writer checkpoints alone.
727const startCheckpointWorker = Effect.fnUntraced(function* (filename: string) {
728 const warn = (reason: string) =>
729 Effect.logWarning("SQLite checkpoint worker unavailable; the writer checkpoints its own WAL", {
730 reason,
731 });
732 const version = sqliteVersion();
733 const [major = 0, minor = 0] = version.split(".").map(Number);
734 // Older SQLite treats NOOP as PASSIVE, so counting frames would checkpoint on every write.
735 if (major < 3 || (major === 3 && minor < 51)) {
736 yield* warn(`SQLite ${version} has no NOOP checkpoint`);
737 return undefined;
738 }
739 const started = Result.try(
740 () =>
741 new NodeWorkerThreads.Worker(checkpointWorkerSource, {
742 eval: true,
743 workerData: { filename, frames: CHECKPOINT_FRAMES, idleMs: CHECKPOINT_IDLE_MS },
744 }),
745 );
746 if (Result.isFailure(started)) {
747 yield* warn(String(started.failure));
748 return undefined;
749 }
750 const worker = started.success;
751 worker.unref();
752 const runFork = Effect.runForkWith(yield* Effect.context<never>());
753 let stopped = false;
754 const stop = (reason: string) => {
755 if (stopped) return;
756 stopped = true;
757 void worker.terminate();
758 runFork(warn(reason));
759 };
760 worker.on("message", (message: { readonly type?: unknown; readonly message?: unknown }) => {
761 if (message?.type === "failed") stop(String(message.message));
762 });
763 worker.on("error", (cause) => stop(cause.message));
764 worker.on("exit", (code) => stop(`exited with code ${code}`));
765 yield* Effect.addFinalizer(() =>
766 Effect.promise(() => {
767 stopped = true;
768 return worker.terminate();
769 }),
770 );
771 let scheduled = false;
772 return () => {
773 if (stopped || scheduled) return;
774 scheduled = true;
775 // One check per event-loop turn is enough, however many statements finished in it.
776 setImmediate(() => {
777 scheduled = false;
778 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
779 if (!stopped) worker.postMessage(0);
780 });
781 };
782});
783
784const make = Effect.fn("makeWithDatabase")(function* (
785 options: SqliteClientConfig,
786): Effect.fn.Return<Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity> {
787 yield* checkNodeSqliteCompat();
788
789 const compiler = Statement.makeCompilerSqlite();
790 const isFileDatabase = options.filename !== ":memory:" && options.filename !== "";
791
792 const makeConnection = Effect.gen(function* () {
793 const scope = yield* Effect.scope;
794 const db = yield* Effect.try({
795 try: () =>
796 new NodeSqlite.DatabaseSync(options.filename, {
797 readOnly: options.readonly ?? false,
798 allowExtension: false,
799 }),
800 catch: (cause) =>
801 new SqlError({
802 reason: classifyError(cause, "Failed to open database", "open"),
803 }),
804 });
805 yield* Scope.addFinalizer(
806 scope,
807 Effect.try({
808 try: () => db.close(),
809 catch: (cause) =>
810 new SqlError({
811 reason: classifyError(cause, "Failed to close database", "close"),
812 }),
813 }).pipe(Effect.orDie),
814 );
815 const statementReaderCache = new WeakMap<NodeSqlite.StatementSync, boolean>();
816 const hasRows = (statement: NodeSqlite.StatementSync): boolean => {
817 const cached = statementReaderCache.get(statement);
818 if (cached !== undefined) {
819 return cached;
820 }
821 const value = statement.columns().length > 0;
822 statementReaderCache.set(statement, value);
823 return value;
824 };
825
826 const prepare = (sql: string) =>
827 Effect.try({
828 try: () => db.prepare(sql),
829 catch: (cause) =>
830 new SqlError({
831 reason: classifyError(cause, "Failed to prepare statement", "prepare"),
832 }),
833 });
834
835 const prepareCache = yield* Cache.makeWith(prepare, {
836 capacity: 200,
837 // A transient prepare failure must not outlive the lock or missing schema.
838 timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.minutes(10) : Duration.zero),
839 });
840
841 const statementFor = (sql: string, params: ReadonlyArray<unknown>) =>
842 hasLargeBinding(params) ? prepare(sql) : Cache.get(prepareCache, sql);
843
844 const runStatement = (
845 statement: NodeSqlite.StatementSync,
846 params: ReadonlyArray<unknown>,
847 mode: "rows" | "raw" | "values" = "rows",
848 ) =>
849 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
850 let arrays = false;
851 let result: Exit.Exit<ReadonlyArray<unknown>, SqlError>;
852 try {
853 statement.setReadBigInts(Boolean(Context.get(fiber.context, Client.SafeIntegers)));
854 if (hasRows(statement)) {
855 arrays = mode === "values";
856 if (arrays) statement.setReturnArrays(true);
857 result = Exit.succeed(statement.all(...(params as any)));
858 } else {
859 // `run` reports the connection's last insert rowid even for BEGIN. One above 2^53
860 // throws on conversion after the statement already took effect, so a discarded
861 // result is read as BigInt.
862 if (mode !== "raw") statement.setReadBigInts(true);
863 const value = statement.run(...(params as any));
864 result = Exit.succeed(
865 mode === "raw" ? (value as unknown as ReadonlyArray<unknown>) : [],
866 );
867 }
868 } catch (cause) {
869 result = Exit.fail(
870 new SqlError({
871 reason: classifyError(cause, "Failed to execute statement", "execute"),
872 }),
873 );
874 }
875 if (arrays) {
876 try {
877 statement.setReturnArrays(false);
878 } catch (cause) {
879 return Exit.die(
880 new SqlError({
881 reason: classifyError(
882 cause,
883 "Failed to reset statement result mode",
884 "resetResultMode",
885 ),
886 }),
887 );
888 }
889 }
890 return result;
891 });
892
893 const run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
894 Effect.flatMap(statementFor(sql, params), (statement) =>
895 runStatement(statement, params, raw ? "raw" : "rows"),
896 );
897 const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
898 Effect.flatMap(statementFor(sql, params), (statement) =>
899 runStatement(statement, params, "values"),
900 );
901
902 return identity<Connection>({
903 execute(sql, params, rowTransform) {
904 return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params);
905 },
906 executeRaw(sql, params) {
907 return run(sql, params, true);
908 },
909 executeValues(sql, params) {
910 return runValues(sql, params);
911 },
912 executeValuesUnprepared(sql, params) {
913 return Effect.flatMap(prepare(sql), (statement) =>
914 runStatement(statement, params ?? [], "values"),
915 );
916 },
917 executeUnprepared(sql, params, rowTransform) {
918 const effect = prepare(sql).pipe(
919 Effect.flatMap((statement) => runStatement(statement, params ?? [])),
920 );
921 return rowTransform ? Effect.map(effect, rowTransform) : effect;
922 },
923 executeStream(_sql, _params) {
924 return Stream.die(new UnsupportedNodeSqliteOperationError());
925 },
926 });
927 });
928
929 const semaphore = yield* Semaphore.make(1);
930 const writerWorker = options.writerWorker === true && isFileDatabase;
931 let checkpointAfterWrite: (() => void) | undefined;
932 const writerConnection: Effect.Effect<Connection, SqlError> = writerWorker
933 ? yield* makeWorkerConnection({
934 filename: options.filename,
935 role: "writer",
936 readOnly: options.readonly ?? false,
937 onReply: () => checkpointAfterWrite?.(),
938 })
939 : Effect.succeed(yield* makeConnection);
940 // Opening now fails the layer for a file that is not a database, not its first query.
941 const opened = yield* writerConnection;
942 // Started after the writer, so it stops first and the writer's close can checkpoint.
943 if (writerWorker && options.readonly !== true) {
944 checkpointAfterWrite = yield* startCheckpointWorker(options.filename);
945 if (checkpointAfterWrite !== undefined) {
946 yield* opened.executeUnprepared(
947 `PRAGMA wal_autocheckpoint = ${WRITER_BACKSTOP_FRAMES}`,
948 [],
949 undefined,
950 );
951 }
952 }
953 const readerPool = { unavailable: false };
954 const readers =
955 options.readerWorker && isFileDatabase
956 ? yield* Effect.forEach(Array.from({ length: READER_POOL_SIZE }), () =>
957 Effect.map(
958 Effect.all([makeReader(options.filename, readerPool), Semaphore.make(1)]),
959 ([acquire, lock]) => ({
960 acquire,
961 lock,
962 claimed: false,
963 }),
964 ),
965 )
966 : [];
967 // One permit per slot, so a queued read waits for any reader, not one it picked while all were busy.
968 const readerAdmission = yield* Semaphore.make(readers.length);
969
970 interface Target {
971 readonly name: Acquired["connection"];
972 readonly lock: Semaphore.Semaphore;
973 readonly connection: Connection;
974 }
975 const writer = Effect.map(writerConnection, (connection): Target => ({
976 name: "writer",
977 lock: semaphore,
978 connection,
979 }));
980 let activeWriter: ConnectionOwner | undefined;
981 // Callers must run route uninterruptibly and pass `claimed` a finalizer that runs `release` once.
982 // Waits use the caller's `restore`, not readOnly's, which may have been captured outside a mask.
983 const route = (
984 claimed: (release: Effect.Effect<void>) => Effect.Effect<void>,
985 restore: typeof Effect.interruptible,
986 ) =>
987 Effect.withFiber((fiber): Effect.Effect<Target, SqlError> => {
988 if (readers.length === 0 || readerPool.unavailable || !Context.get(fiber.context, ReadOnly)) {
989 return writer;
990 }
991 const claim = Effect.andThen(
992 restore(readerAdmission.take(1)),
993 Effect.suspend(() => {
994 // Holding a permit leaves a slot idle; the lowest wins, so idle slots never start a worker.
995 const reader = readers.find((slot) => !slot.claimed)!;
996 reader.claimed = true;
997 const release = Effect.andThen(
998 Effect.sync(() => {
999 reader.claimed = false;
1000 }),
1001 readerAdmission.release(1),
1002 );
1003 return Effect.as(claimed(release), reader);
1004 }),
1005 );
1006 return Effect.flatMap(
1007 // A scheduler yield after taking the permit must not precede its release finalizer.
1008 Effect.provideService(claim, Scheduler.PreventSchedulerYield, true),
1009 (reader) =>
1010 Effect.flatMap(
1011 Effect.provideService(reader.acquire, ReadOnly, restore),
1012 (readerConnection) =>
1013 readerConnection === undefined
1014 ? writer
1015 : Effect.succeed<Target>({
1016 name: "reader",
1017 lock: reader.lock,
1018 connection: readerConnection,
1019 }),
1020 ),
1021 );
1022 });
1023
1024 const acquired = (
1025 target: { readonly name: Acquired["connection"] },
1026 clock: Clock.Clock,
1027 start: bigint,
1028 ): Acquired => ({
1029 connection: target.name,
1030 lockWaitMs: Number((clock.monotonicTimeNanosUnsafe() - start) / 1000n) / 1000,
1031 });
1032
1033 const borrower: Borrower = (use) =>
1034 Effect.uninterruptibleMask((restore) => {
1035 let release: Effect.Effect<void> = Effect.void;
1036 const claimed = (next: Effect.Effect<void>) =>
1037 Effect.sync(() => {
1038 release = next;
1039 });
1040 // Started before routing, so lock wait includes waiting for reader admission.
1041 return Effect.withFiber((fiber) => {
1042 const start = fiber.getRef(Clock.Clock).monotonicTimeNanosUnsafe();
1043 return Effect.flatMap(route(claimed, restore), (target) =>
1044 restore(borrowTarget(target, use, start)),
1045 );
1046 }).pipe(Effect.ensuring(Effect.suspend(() => release)));
1047 });
1048 const borrowTarget = <A, E, R>(
1049 target: Target,
1050 use: (connection: Connection) => Effect.Effect<A, E, R>,
1051 start: bigint,
1052 ): Effect.Effect<A, E, R> =>
1053 Effect.withFiber((fiber) => {
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 useConnection = Effect.suspend(() => {
1058 if (target.name === "writer") activeWriter = owner;
1059 if (
1060 fiber.getRef(References.TracerEnabled) &&
1061 fiber.getRef(Statement.SpanPropagationEnabled)
1062 ) {
1063 annotateAcquired(fiber, acquired(target, clock, start), ownerAtWaitStart);
1064 }
1065 return use(target.connection);
1066 });
1067 const useOwnedConnection =
1068 target.name === "writer"
1069 ? Effect.onExit(useConnection, () =>
1070 Effect.sync(() => {
1071 if (activeWriter === owner) activeWriter = undefined;
1072 }),
1073 )
1074 : useConnection;
1075 return target.lock.withPermits(1)(useOwnedConnection);
1076 });
1077 const claimedUntilScopeCloses = (release: Effect.Effect<void>) =>
1078 Effect.withFiber((fiber) =>
1079 Scope.addFinalizer(Context.getUnsafe(fiber.context, Scope.Scope), release),
1080 );
1081 // Started before routing, so lock wait includes waiting for reader admission.
1082 const transactionAcquirer = Effect.uninterruptibleMask((maskRestore) =>
1083 Effect.withFiber((fiber) => {
1084 const start = fiber.getRef(Clock.Clock).monotonicTimeNanosUnsafe();
1085 const pending = fiber.getRef(TransactionAcquire);
1086 const restore = pending?.restore ?? maskRestore;
1087 return Effect.flatMap(route(claimedUntilScopeCloses, restore), (target) => {
1088 const scope = Context.getUnsafe(fiber.context, Scope.Scope);
1089 const clock = fiber.getRef(Clock.Clock);
1090 const ownerAtWaitStart = target.name === "writer" ? activeWriter : undefined;
1091 const owner = target.name === "writer" ? connectionOwner(fiber) : undefined;
1092 const acquire = Effect.tap(restore(target.lock.take(1)), () => {
1093 if (target.name === "writer") activeWriter = owner;
1094 if (pending !== undefined) {
1095 pending.acquired = acquired(target, clock, start);
1096 pending.ownerAtWaitStart = ownerAtWaitStart;
1097 }
1098 return Scope.addFinalizer(
1099 scope,
1100 Effect.sync(() => {
1101 if (target.name === "writer" && activeWriter === owner) activeWriter = undefined;
1102 }).pipe(Effect.andThen(target.lock.release(1))),
1103 );
1104 });
1105 return Effect.as(
1106 // A scheduler yield after taking the permit must not precede its release finalizer.
1107 Effect.provideService(acquire, Scheduler.PreventSchedulerYield, true),
1108 target.connection,
1109 );
1110 });
1111 }),
1112 );
1113
1114 const client = yield* Client.make({
1115 driver: "node:sqlite",
1116 acquirer: transactionAcquirer,
1117 borrower,
1118 compiler,
1119 transactionAcquirer,
1120 // BEGIN IMMEDIATE avoids read-then-write SQLITE_BUSY_SNAPSHOT, which busy_timeout cannot resolve.
1121 beginTransaction: options.readonly === true ? "BEGIN" : "BEGIN IMMEDIATE",
1122 spanAttributes: [
1123 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
1124 [ATTR_DB_SYSTEM_NAME, "sqlite"],
1125 ],
1126 });
1127 const withTransaction = client.withTransaction;
1128 return Object.assign(client, {
1129 withTransaction: <A, E, R>(effect: Effect.Effect<A, E, R>) =>
1130 Effect.uninterruptibleMask((restore) => {
1131 // SqlClient masks setup; acquisition must preserve the caller's interruptibility.
1132 const pending: {
1133 acquired?: Acquired;
1134 ownerAtWaitStart: ConnectionOwner | undefined;
1135 restore: typeof Effect.interruptible | undefined;
1136 } = {
1137 ownerAtWaitStart: undefined,
1138 restore,
1139 };
1140 const body = Effect.withFiber<A, E, R>((fiber) => {
1141 annotateAcquired(fiber, pending.acquired, pending.ownerAtWaitStart);
1142 pending.restore = undefined;
1143 return effect;
1144 });
1145 return restore(
1146 withTransaction(body).pipe(Effect.provideService(TransactionAcquire, pending)),
1147 );
1148 }),
1149 });
1150});
1151
1152export const layer = (config: SqliteClientConfig): Layer.Layer<Client.SqlClient, SqlError> =>
1153 Layer.effect(Client.SqlClient, make(config)).pipe(Layer.provide(Reactivity.layer));