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 } = 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;
308}
309
310interface WorkerFailure {
311 readonly message: string;
312 readonly code?: unknown;
313 readonly errcode?: unknown;
314 readonly errstr?: unknown;
315}
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 after a checkpoint leaves frames
668 // behind, catch up when writes pause. Before any checkpoint, wait for the frame threshold.
669 // A reader pinning the WAL stops progress; the next write retries instead of a timer loop.
670 const progressed = !force || state.checkpointed > before.checkpointed;
671 if (state.checkpointed > 0 && state.log > state.checkpointed && progressed) {
672 idle = setTimeout(() => run(true), workerData.idleMs);
673 }
674 parentPort.postMessage({ type: "checked", log: state.log, checkpointed: state.checkpointed });
675};
676const run = (force) => {
677 clearTimeout(idle);
678 try {
679 check(force);
680 } catch (error) {
681 parentPort.postMessage({ type: "failed", message: String(error && error.message ? error.message : error) });
682 }
683};
684parentPort.on("message", () => run(false));
685`;
686
687const sqliteVersion = () => {
688 const db = new NodeSqlite.DatabaseSync(":memory:");
689 try {
690 return String(db.prepare("SELECT sqlite_version() AS version").get()?.version);
691 } finally {
692 db.close();
693 }
694};
695
696// Returns the writer's per-statement notification, or undefined when the writer checkpoints alone.
697const startCheckpointWorker = Effect.fnUntraced(function* (filename: string) {
698 const warn = (reason: string) =>
699 Effect.logWarning("SQLite checkpoint worker unavailable; the writer checkpoints its own WAL", {
700 reason,
701 });
702 const version = sqliteVersion();
703 const [major = 0, minor = 0] = version.split(".").map(Number);
704 // Older SQLite treats NOOP as PASSIVE, so counting frames would checkpoint on every write.
705 if (major < 3 || (major === 3 && minor < 51)) {
706 yield* warn(`SQLite ${version} has no NOOP checkpoint`);
707 return undefined;
708 }
709 const started = Result.try(
710 () =>
711 new NodeWorkerThreads.Worker(checkpointWorkerSource, {
712 eval: true,
713 workerData: { filename, frames: CHECKPOINT_FRAMES, idleMs: CHECKPOINT_IDLE_MS },
714 }),
715 );
716 if (Result.isFailure(started)) {
717 yield* warn(String(started.failure));
718 return undefined;
719 }
720 const worker = started.success;
721 worker.unref();
722 const runFork = Effect.runForkWith(yield* Effect.context<never>());
723 let stopped = false;
724 const stop = (reason: string) => {
725 if (stopped) return;
726 stopped = true;
727 void worker.terminate();
728 runFork(warn(reason));
729 };
730 worker.on("message", (message: { readonly type?: unknown; readonly message?: unknown }) => {
731 if (message?.type === "failed") stop(String(message.message));
732 });
733 worker.on("error", (cause) => stop(cause.message));
734 worker.on("exit", (code) => stop(`exited with code ${code}`));
735 yield* Effect.addFinalizer(() =>
736 Effect.promise(() => {
737 stopped = true;
738 return worker.terminate();
739 }),
740 );
741 let scheduled = false;
742 return () => {
743 if (stopped || scheduled) return;
744 scheduled = true;
745 // One check per event-loop turn is enough, however many statements finished in it.
746 setImmediate(() => {
747 scheduled = false;
748 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
749 if (!stopped) worker.postMessage(0);
750 });
751 };
752});
753
754const make = Effect.fn("makeWithDatabase")(function* (
755 options: SqliteClientConfig,
756): Effect.fn.Return<Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity> {
757 yield* checkNodeSqliteCompat();
758
759 const compiler = Statement.makeCompilerSqlite();
760 const isFileDatabase = options.filename !== ":memory:" && options.filename !== "";
761
762 const makeConnection = Effect.gen(function* () {
763 const scope = yield* Effect.scope;
764 const db = yield* Effect.try({
765 try: () =>
766 new NodeSqlite.DatabaseSync(options.filename, {
767 readOnly: options.readonly ?? false,
768 allowExtension: false,
769 }),
770 catch: (cause) =>
771 new SqlError({
772 reason: classifyError(cause, "Failed to open database", "open"),
773 }),
774 });
775 yield* Scope.addFinalizer(
776 scope,
777 Effect.try({
778 try: () => db.close(),
779 catch: (cause) =>
780 new SqlError({
781 reason: classifyError(cause, "Failed to close database", "close"),
782 }),
783 }).pipe(Effect.orDie),
784 );
785 const statementReaderCache = new WeakMap<NodeSqlite.StatementSync, boolean>();
786 const hasRows = (statement: NodeSqlite.StatementSync): boolean => {
787 const cached = statementReaderCache.get(statement);
788 if (cached !== undefined) {
789 return cached;
790 }
791 const value = statement.columns().length > 0;
792 statementReaderCache.set(statement, value);
793 return value;
794 };
795
796 const prepare = (sql: string) =>
797 Effect.try({
798 try: () => db.prepare(sql),
799 catch: (cause) =>
800 new SqlError({
801 reason: classifyError(cause, "Failed to prepare statement", "prepare"),
802 }),
803 });
804
805 const prepareCache = yield* Cache.makeWith(prepare, {
806 capacity: 200,
807 // A transient prepare failure must not outlive the lock or missing schema.
808 timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.minutes(10) : Duration.zero),
809 });
810
811 const statementFor = (sql: string, params: ReadonlyArray<unknown>) =>
812 hasLargeBinding(params) ? prepare(sql) : Cache.get(prepareCache, sql);
813
814 const runStatement = (
815 statement: NodeSqlite.StatementSync,
816 params: ReadonlyArray<unknown>,
817 mode: "rows" | "raw" | "values" = "rows",
818 ) =>
819 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
820 let arrays = false;
821 let result: Exit.Exit<ReadonlyArray<unknown>, SqlError>;
822 try {
823 statement.setReadBigInts(Boolean(Context.get(fiber.context, Client.SafeIntegers)));
824 if (hasRows(statement)) {
825 arrays = mode === "values";
826 if (arrays) statement.setReturnArrays(true);
827 result = Exit.succeed(statement.all(...(params as any)));
828 } else {
829 const value = statement.run(...(params as any));
830 result = Exit.succeed(
831 mode === "raw" ? (value as unknown as ReadonlyArray<unknown>) : [],
832 );
833 }
834 } catch (cause) {
835 result = Exit.fail(
836 new SqlError({
837 reason: classifyError(cause, "Failed to execute statement", "execute"),
838 }),
839 );
840 }
841 if (arrays) {
842 try {
843 statement.setReturnArrays(false);
844 } catch (cause) {
845 return Exit.die(
846 new SqlError({
847 reason: classifyError(
848 cause,
849 "Failed to reset statement result mode",
850 "resetResultMode",
851 ),
852 }),
853 );
854 }
855 }
856 return result;
857 });
858
859 const run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
860 Effect.flatMap(statementFor(sql, params), (statement) =>
861 runStatement(statement, params, raw ? "raw" : "rows"),
862 );
863 const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
864 Effect.flatMap(statementFor(sql, params), (statement) =>
865 runStatement(statement, params, "values"),
866 );
867
868 return identity<Connection>({
869 execute(sql, params, rowTransform) {
870 return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params);
871 },
872 executeRaw(sql, params) {
873 return run(sql, params, true);
874 },
875 executeValues(sql, params) {
876 return runValues(sql, params);
877 },
878 executeValuesUnprepared(sql, params) {
879 return Effect.flatMap(prepare(sql), (statement) =>
880 runStatement(statement, params ?? [], "values"),
881 );
882 },
883 executeUnprepared(sql, params, rowTransform) {
884 const effect = prepare(sql).pipe(
885 Effect.flatMap((statement) => runStatement(statement, params ?? [])),
886 );
887 return rowTransform ? Effect.map(effect, rowTransform) : effect;
888 },
889 executeStream(_sql, _params) {
890 return Stream.die(new UnsupportedNodeSqliteOperationError());
891 },
892 });
893 });
894
895 const semaphore = yield* Semaphore.make(1);
896 const writerWorker = options.writerWorker === true && isFileDatabase;
897 let checkpointAfterWrite: (() => void) | undefined;
898 const writerConnection: Effect.Effect<Connection, SqlError> = writerWorker
899 ? yield* makeWorkerConnection({
900 filename: options.filename,
901 role: "writer",
902 readOnly: options.readonly ?? false,
903 onReply: () => checkpointAfterWrite?.(),
904 })
905 : Effect.succeed(yield* makeConnection);
906 // Opening now fails the layer for a file that is not a database, not its first query.
907 const opened = yield* writerConnection;
908 // Started after the writer, so it stops first and the writer's close can checkpoint.
909 if (writerWorker && options.readonly !== true) {
910 checkpointAfterWrite = yield* startCheckpointWorker(options.filename);
911 if (checkpointAfterWrite !== undefined) {
912 yield* opened.executeUnprepared(
913 `PRAGMA wal_autocheckpoint = ${WRITER_BACKSTOP_FRAMES}`,
914 [],
915 undefined,
916 );
917 }
918 }
919 const readerPool = { unavailable: false };
920 const readers =
921 options.readerWorker && isFileDatabase
922 ? yield* Effect.forEach(Array.from({ length: READER_POOL_SIZE }), () =>
923 Effect.map(
924 Effect.all([makeReader(options.filename, readerPool), Semaphore.make(1)]),
925 ([acquire, lock]) => ({
926 acquire,
927 lock,
928 claimed: false,
929 }),
930 ),
931 )
932 : [];
933 // One permit per slot, so a queued read waits for any reader, not one it picked while all were busy.
934 const readerAdmission = yield* Semaphore.make(readers.length);
935
936 interface Target {
937 readonly name: Acquired["connection"];
938 readonly lock: Semaphore.Semaphore;
939 readonly connection: Connection;
940 }
941 const writer = Effect.map(writerConnection, (connection): Target => ({
942 name: "writer",
943 lock: semaphore,
944 connection,
945 }));
946 let activeWriter: ConnectionOwner | undefined;
947 // Callers must run route uninterruptibly and pass `claimed` a finalizer that runs `release` once.
948 // Waits use the caller's `restore`, not readOnly's, which may have been captured outside a mask.
949 const route = (
950 claimed: (release: Effect.Effect<void>) => Effect.Effect<void>,
951 restore: typeof Effect.interruptible,
952 ) =>
953 Effect.withFiber((fiber): Effect.Effect<Target, SqlError> => {
954 if (readers.length === 0 || readerPool.unavailable || !Context.get(fiber.context, ReadOnly)) {
955 return writer;
956 }
957 const claim = Effect.andThen(
958 restore(readerAdmission.take(1)),
959 Effect.suspend(() => {
960 // Holding a permit leaves a slot idle; the lowest wins, so idle slots never start a worker.
961 const reader = readers.find((slot) => !slot.claimed)!;
962 reader.claimed = true;
963 const release = Effect.andThen(
964 Effect.sync(() => {
965 reader.claimed = false;
966 }),
967 readerAdmission.release(1),
968 );
969 return Effect.as(claimed(release), reader);
970 }),
971 );
972 return Effect.flatMap(
973 // A scheduler yield after taking the permit must not precede its release finalizer.
974 Effect.provideService(claim, Scheduler.PreventSchedulerYield, true),
975 (reader) =>
976 Effect.flatMap(
977 Effect.provideService(reader.acquire, ReadOnly, restore),
978 (readerConnection) =>
979 readerConnection === undefined
980 ? writer
981 : Effect.succeed<Target>({
982 name: "reader",
983 lock: reader.lock,
984 connection: readerConnection,
985 }),
986 ),
987 );
988 });
989
990 const acquired = (
991 target: { readonly name: Acquired["connection"] },
992 clock: Clock.Clock,
993 start: bigint,
994 ): Acquired => ({
995 connection: target.name,
996 lockWaitMs: Number((clock.monotonicTimeNanosUnsafe() - start) / 1000n) / 1000,
997 });
998
999 const borrower: Borrower = (use) =>
1000 Effect.uninterruptibleMask((restore) => {
1001 let release: Effect.Effect<void> = Effect.void;
1002 const claimed = (next: Effect.Effect<void>) =>
1003 Effect.sync(() => {
1004 release = next;
1005 });
1006 // Started before routing, so lock wait includes waiting for reader admission.
1007 return Effect.withFiber((fiber) => {
1008 const start = fiber.getRef(Clock.Clock).monotonicTimeNanosUnsafe();
1009 return Effect.flatMap(route(claimed, restore), (target) =>
1010 restore(borrowTarget(target, use, start)),
1011 );
1012 }).pipe(Effect.ensuring(Effect.suspend(() => release)));
1013 });
1014 const borrowTarget = <A, E, R>(
1015 target: Target,
1016 use: (connection: Connection) => Effect.Effect<A, E, R>,
1017 start: bigint,
1018 ): Effect.Effect<A, E, R> =>
1019 Effect.withFiber((fiber) => {
1020 const clock = fiber.getRef(Clock.Clock);
1021 const ownerAtWaitStart = target.name === "writer" ? activeWriter : undefined;
1022 const owner = target.name === "writer" ? connectionOwner(fiber) : undefined;
1023 const useConnection = Effect.suspend(() => {
1024 if (target.name === "writer") activeWriter = owner;
1025 if (
1026 fiber.getRef(References.TracerEnabled) &&
1027 fiber.getRef(Statement.SpanPropagationEnabled)
1028 ) {
1029 annotateAcquired(fiber, acquired(target, clock, start), ownerAtWaitStart);
1030 }
1031 return use(target.connection);
1032 });
1033 const useOwnedConnection =
1034 target.name === "writer"
1035 ? Effect.onExit(useConnection, () =>
1036 Effect.sync(() => {
1037 if (activeWriter === owner) activeWriter = undefined;
1038 }),
1039 )
1040 : useConnection;
1041 return target.lock.withPermits(1)(useOwnedConnection);
1042 });
1043 const claimedUntilScopeCloses = (release: Effect.Effect<void>) =>
1044 Effect.withFiber((fiber) =>
1045 Scope.addFinalizer(Context.getUnsafe(fiber.context, Scope.Scope), release),
1046 );
1047 // Started before routing, so lock wait includes waiting for reader admission.
1048 const transactionAcquirer = Effect.uninterruptibleMask((maskRestore) =>
1049 Effect.withFiber((fiber) => {
1050 const start = fiber.getRef(Clock.Clock).monotonicTimeNanosUnsafe();
1051 const pending = fiber.getRef(TransactionAcquire);
1052 const restore = pending?.restore ?? maskRestore;
1053 return Effect.flatMap(route(claimedUntilScopeCloses, restore), (target) => {
1054 const scope = Context.getUnsafe(fiber.context, Scope.Scope);
1055 const clock = fiber.getRef(Clock.Clock);
1056 const ownerAtWaitStart = target.name === "writer" ? activeWriter : undefined;
1057 const owner = target.name === "writer" ? connectionOwner(fiber) : undefined;
1058 const acquire = Effect.tap(restore(target.lock.take(1)), () => {
1059 if (target.name === "writer") activeWriter = owner;
1060 if (pending !== undefined) {
1061 pending.acquired = acquired(target, clock, start);
1062 pending.ownerAtWaitStart = ownerAtWaitStart;
1063 }
1064 return Scope.addFinalizer(
1065 scope,
1066 Effect.sync(() => {
1067 if (target.name === "writer" && activeWriter === owner) activeWriter = undefined;
1068 }).pipe(Effect.andThen(target.lock.release(1))),
1069 );
1070 });
1071 return Effect.as(
1072 // A scheduler yield after taking the permit must not precede its release finalizer.
1073 Effect.provideService(acquire, Scheduler.PreventSchedulerYield, true),
1074 target.connection,
1075 );
1076 });
1077 }),
1078 );
1079
1080 const client = yield* Client.make({
1081 driver: "node:sqlite",
1082 acquirer: transactionAcquirer,
1083 borrower,
1084 compiler,
1085 transactionAcquirer,
1086 // BEGIN IMMEDIATE avoids read-then-write SQLITE_BUSY_SNAPSHOT, which busy_timeout cannot resolve.
1087 beginTransaction: options.readonly === true ? "BEGIN" : "BEGIN IMMEDIATE",
1088 spanAttributes: [
1089 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
1090 [ATTR_DB_SYSTEM_NAME, "sqlite"],
1091 ],
1092 });
1093 const withTransaction = client.withTransaction;
1094 return Object.assign(client, {
1095 withTransaction: <A, E, R>(effect: Effect.Effect<A, E, R>) =>
1096 Effect.uninterruptibleMask((restore) => {
1097 // SqlClient masks setup; acquisition must preserve the caller's interruptibility.
1098 const pending: {
1099 acquired?: Acquired;
1100 ownerAtWaitStart: ConnectionOwner | undefined;
1101 restore: typeof Effect.interruptible | undefined;
1102 } = {
1103 ownerAtWaitStart: undefined,
1104 restore,
1105 };
1106 const body = Effect.withFiber<A, E, R>((fiber) => {
1107 annotateAcquired(fiber, pending.acquired, pending.ownerAtWaitStart);
1108 pending.restore = undefined;
1109 return effect;
1110 });
1111 return restore(
1112 withTransaction(body).pipe(Effect.provideService(TransactionAcquire, pending)),
1113 );
1114 }),
1115 });
1116});
1117
1118export const layer = (config: SqliteClientConfig): Layer.Layer<Client.SqlClient, SqlError> =>
1119 Layer.effect(Client.SqlClient, make(config)).pipe(Layer.provide(Reactivity.layer));