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

nodeSqliteClient.ts

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