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 Exit from "effect/Exit";
10import * as Fiber from "effect/Fiber";
11import { identity } from "effect/Function";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Predicate from "effect/Predicate";
15import * as References from "effect/References";
16import * as Schema from "effect/Schema";
17import * as Scheduler from "effect/Scheduler";
18import * as Scope from "effect/Scope";
19import * as Semaphore from "effect/Semaphore";
20import * as Context from "effect/Context";
21import * as Stream from "effect/Stream";
22import * as Tracer from "effect/Tracer";
23import * as Reactivity from "effect/reactivity/Reactivity";
24import * as Client from "effect/sql/SqlClient";
25import type { Borrower, Connection } from "effect/sql/SqlConnection";
26import { SqlError, classifySqliteError } from "effect/sql/SqlError";
27import * as Statement from "effect/sql/Statement";
28
29const ATTR_DB_SYSTEM_NAME = "db.system.name";
30
31export interface SqliteClientConfig {
32 readonly filename: string;
33 readonly readonly?: boolean | undefined;
34 readonly allowExtension?: boolean | undefined;
35 readonly prepareCacheSize?: number | undefined;
36 readonly prepareCacheTTL?: Duration.Input | undefined;
37 readonly spanAttributes?: Record<string, unknown> | undefined;
38 readonly transformResultNames?: ((str: string) => string) | undefined;
39 readonly transformQueryNames?: ((str: string) => string) | undefined;
40 /** Ignored for in-memory databases, which cannot share a second connection. */
41 readonly readerWorker?: boolean | undefined;
42 readonly readerStartupTimeout?: Duration.Input | undefined;
43 /** Ignored for in-memory databases. */
44 readonly checkpointWorker?: boolean | undefined;
45}
46
47// SqlClient masks transaction acquisition, so readOnly carries the caller's interruption policy.
48const ReadOnly = Context.Reference<typeof Effect.interruptible | undefined>(
49 "@t3tools/shared/nodeSqliteClient/ReadOnly",
50 { defaultValue: () => undefined },
51);
52
53/** Wrap the whole transaction; existing write transactions retain the writer, and writes on the reader fail as readonly. */
54export const readOnly = <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
55 Effect.uninterruptibleMask((restore) =>
56 restore(Effect.provideService(effect, ReadOnly, restore)),
57 );
58
59interface Acquired {
60 readonly connection: "writer" | "reader";
61 readonly lockWaitMs: number;
62}
63
64interface ConnectionOwner {
65 readonly fiberId: number;
66 readonly name: string;
67 readonly traceId?: string;
68 readonly spanId?: string;
69}
70
71const connectionOwner = (fiber: Fiber.Fiber<unknown, unknown>): ConnectionOwner => {
72 const current = Context.getOrUndefined(fiber.context, Tracer.ParentSpan);
73 if (current?._tag !== "Span") return { fiberId: fiber.id, name: "untraced" };
74 let span: Tracer.Span = current;
75 while (span.name === "sqlite" || span.name === "sql.transaction") {
76 const parent: Tracer.AnySpan | undefined = Option.getOrUndefined(span.parent);
77 if (parent?._tag !== "Span") break;
78 span = parent;
79 }
80 return { fiberId: fiber.id, name: span.name, traceId: span.traceId, spanId: span.spanId };
81};
82
83const annotateAcquired = (
84 fiber: Fiber.Fiber<unknown, unknown>,
85 acquired: Acquired | undefined,
86 ownerAtWaitStart?: ConnectionOwner,
87) => {
88 const span = Context.getOrUndefined(fiber.context, Tracer.ParentSpan);
89 if (span?._tag !== "Span" || acquired === undefined) return;
90 span.attribute("db.connection", acquired.connection);
91 span.attribute("db.lock_wait_ms", acquired.lockWaitMs);
92 if (ownerAtWaitStart !== undefined) {
93 span.attribute("db.lock_owner_at_start.fiber_id", ownerAtWaitStart.fiberId);
94 span.attribute("db.lock_owner_at_start.name", ownerAtWaitStart.name);
95 if (ownerAtWaitStart.traceId !== undefined) {
96 span.attribute("db.lock_owner_at_start.trace_id", ownerAtWaitStart.traceId);
97 }
98 if (ownerAtWaitStart.spanId !== undefined) {
99 span.attribute("db.lock_owner_at_start.span_id", ownerAtWaitStart.spanId);
100 }
101 }
102};
103
104const TransactionAcquire = Context.Reference<
105 | {
106 acquired?: Acquired;
107 ownerAtWaitStart: ConnectionOwner | undefined;
108 restore: typeof Effect.interruptible | undefined;
109 }
110 | undefined
111>("@t3tools/shared/nodeSqliteClient/TransactionAcquire", { defaultValue: () => undefined });
112
113export class UnsupportedNodeSqliteVersionError extends Schema.TaggedError<UnsupportedNodeSqliteVersionError>()(
114 "UnsupportedNodeSqliteVersionError",
115 {
116 nodeVersion: Schema.String,
117 requirement: Schema.String,
118 },
119) {
120 override get message(): string {
121 return `Node.js ${this.nodeVersion} is missing required node:sqlite APIs. Upgrade to ${this.requirement}.`;
122 }
123}
124
125export class UnsupportedNodeSqliteOperationError extends Schema.TaggedError<UnsupportedNodeSqliteOperationError>()(
126 "UnsupportedNodeSqliteOperationError",
127 {},
128) {
129 override get message(): string {
130 return "Node SQLite does not support executeStream.";
131 }
132}
133
134const checkNodeSqliteCompat = () => {
135 const parts = process.versions.node.split(".").map(Number);
136 const major = parts[0] ?? 0;
137 const minor = parts[1] ?? 0;
138 const supported = (major === 22 && minor >= 16) || (major === 23 && minor >= 11) || major >= 24;
139
140 if (!supported) {
141 return Effect.die(
142 new UnsupportedNodeSqliteVersionError({
143 nodeVersion: process.versions.node,
144 requirement: "Node.js >=22.16, >=23.11, or >=24",
145 }),
146 );
147 }
148 return Effect.void;
149};
150
151// node:sqlite supplies errcode; classifySqliteError expects errno.
152const classifyError = (cause: unknown, message: string, operation: string) => {
153 if (
154 Predicate.hasProperty(cause, "errcode") &&
155 typeof cause.errcode === "number" &&
156 !Predicate.hasProperty(cause, "errno")
157 ) {
158 Object.assign(cause, { errno: cause.errcode });
159 }
160 return classifySqliteError(cause, { message, operation });
161};
162
163// SQLite retains text/blob bindings until rebind or finalization; node:sqlite cannot clear them.
164const LARGE_BINDING_SIZE = 64 * 1024;
165
166const isBlob = (value: unknown): value is ArrayBufferView | ArrayBufferLike =>
167 ArrayBuffer.isView(value) || NodeUtil.types.isAnyArrayBuffer(value);
168
169const bindingSize = (value: unknown): number => {
170 if (typeof value === "string") {
171 return value.length;
172 }
173 return isBlob(value) ? value.byteLength : 0;
174};
175
176const hasLargeBinding = (params: ReadonlyArray<unknown>): boolean => {
177 try {
178 let size = 0;
179 for (const param of params) {
180 if (
181 (typeof param === "object" || typeof param === "function") &&
182 param !== null &&
183 !isBlob(param)
184 ) {
185 // Named parameters may be callable objects; read data properties only to avoid invoking getters twice.
186 for (const property of Object.values(Object.getOwnPropertyDescriptors(param))) {
187 if (!property.enumerable) continue;
188 if (!("value" in property)) return true;
189 size += bindingSize(property.value);
190 }
191 } else {
192 size += bindingSize(param);
193 }
194 }
195 return size > LARGE_BINDING_SIZE;
196 } catch {
197 return true;
198 }
199};
200
201// Inline worker source also runs in bundles and single-executable builds without module files.
202const readerWorkerSource = `
203const { parentPort, workerData } = require("node:worker_threads");
204const { DatabaseSync } = require("node:sqlite");
205let db;
206try {
207 // A read-only open cannot be undone by SQL, unlike PRAGMA query_only.
208 const next = new DatabaseSync(workerData.filename, {
209 readOnly: true,
210 allowExtension: workerData.allowExtension,
211 });
212 next.exec("PRAGMA busy_timeout = 5000;");
213 // Without WAL a reader's shared lock blocks the writer's commits, so refuse.
214 const mode = String(next.prepare("PRAGMA journal_mode").get().journal_mode).toLowerCase();
215 if (mode !== "wal") throw new Error("database uses journal_mode " + mode + ", not wal");
216 db = next;
217 parentPort.postMessage({ type: "ready" });
218} catch (error) {
219 parentPort.postMessage({ type: "unavailable", message: String(error && error.message ? error.message : error) });
220}
221const statements = new Map();
222const prepare = (sql, cached) => {
223 if (!cached) return db.prepare(sql);
224 let statement = statements.get(sql);
225 if (statement === undefined) {
226 statement = db.prepare(sql);
227 if (statements.size >= workerData.prepareCacheSize) statements.delete(statements.keys().next().value);
228 } else {
229 statements.delete(sql);
230 }
231 statements.set(sql, statement);
232 return statement;
233};
234parentPort.on("message", ({ id, sql, params, cached, values, raw, safeIntegers }) => {
235 let operation = "open";
236 try {
237 if (db === undefined) throw new Error("database reader is unavailable");
238 operation = "prepare";
239 const statement = prepare(sql, cached);
240 operation = "execute";
241 statement.setReadBigInts(safeIntegers);
242 if (statement.columns().length > 0) {
243 statement.setReturnArrays(values);
244 parentPort.postMessage({ id, rows: statement.all(...params) });
245 } else {
246 const result = statement.run(...params);
247 parentPort.postMessage({ id, rows: raw ? result : [] });
248 }
249 } catch (error) {
250 parentPort.postMessage({
251 id,
252 error: {
253 operation,
254 message: String(error && error.message ? error.message : error),
255 code: error && error.code,
256 errcode: error && error.errcode,
257 errstr: error && error.errstr,
258 },
259 });
260 }
261});
262`;
263
264interface ReaderRequest {
265 readonly sql: string;
266 readonly params: ReadonlyArray<unknown>;
267 readonly cached: boolean;
268 readonly values: boolean;
269 readonly raw: boolean;
270}
271
272type ReaderStartup =
273 | { readonly type: "ready" }
274 | { readonly type: "unavailable"; readonly message: string };
275
276type ReaderReply =
277 | { readonly id: number; readonly rows: ReadonlyArray<any> }
278 | {
279 readonly id: number;
280 readonly error: {
281 readonly operation: "open" | "prepare" | "execute";
282 readonly message: string;
283 readonly code?: unknown;
284 readonly errcode?: unknown;
285 readonly errstr?: unknown;
286 };
287 };
288
289const readerFailureMessages = {
290 open: "Failed to open database",
291 prepare: "Failed to prepare statement",
292 execute: "Failed to execute statement",
293} as const;
294
295const failed = (cause: unknown, message: string, operation: string) =>
296 new SqlError({ reason: classifyError(cause, message, operation) });
297
298// Read-transaction cleanup succeeds after worker exit because it can no longer change anything.
299const endsReadTransaction = (sql: string) => /^\s*ROLLBACK\b|^\s*COMMIT\b/i.test(sql);
300
301// Bind transactions to one worker; fail after its exit instead of resuming outside the transaction on a replacement.
302const makeReader = Effect.fnUntraced(function* (options: SqliteClientConfig) {
303 let current:
304 | {
305 readonly worker: NodeWorkerThreads.Worker;
306 readonly connection: Connection;
307 readonly started: Promise<ReaderStartup>;
308 }
309 | undefined;
310 let unavailable = false;
311 let nextRequestId = 0;
312
313 const start = () => {
314 const worker = new NodeWorkerThreads.Worker(readerWorkerSource, {
315 eval: true,
316 workerData: {
317 filename: options.filename,
318 allowExtension: options.allowExtension ?? false,
319 prepareCacheSize: options.prepareCacheSize ?? 200,
320 },
321 });
322 let announce: (startup: ReaderStartup) => void = () => {};
323 const started = new Promise<ReaderStartup>((resolve) => {
324 announce = resolve;
325 });
326 let stoppedMessage: string | undefined;
327 const pending = new Map<
328 number,
329 { readonly endsTransaction: boolean; readonly resume: (reply: ReaderReply) => void }
330 >();
331 const stop = (message: string) => {
332 stoppedMessage = message;
333 announce({ type: "unavailable", message });
334 if (current?.worker === worker) current = undefined;
335 for (const [id, request] of pending) {
336 request.resume(
337 request.endsTransaction
338 ? { id, rows: [] }
339 : { id, error: { operation: "execute", message } },
340 );
341 }
342 pending.clear();
343 };
344 worker.on("message", (reply: ReaderReply | ReaderStartup) => {
345 if ("type" in reply) {
346 announce(reply);
347 if (pending.size === 0) worker.unref();
348 return;
349 }
350 const request = pending.get(reply.id);
351 if (request === undefined) return;
352 pending.delete(reply.id);
353 if (pending.size === 0) worker.unref();
354 request.resume(reply);
355 });
356 worker.on("error", (cause) => stop(`Database reader failed: ${cause.message}`));
357 worker.on("exit", (code) => stop(`Database reader exited with code ${code}`));
358
359 const request = (input: ReaderRequest) =>
360 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
361 const endsTransaction = endsReadTransaction(input.sql);
362 if (stoppedMessage !== undefined) {
363 return endsTransaction
364 ? Effect.succeed([])
365 : Effect.fail(
366 failed(new Error(stoppedMessage), readerFailureMessages.execute, "execute"),
367 );
368 }
369 const safeIntegers = Boolean(Context.get(fiber.context, Client.SafeIntegers));
370 return Effect.callback<ReadonlyArray<any>, SqlError>((resume) => {
371 const id = nextRequestId++;
372 pending.set(id, {
373 endsTransaction,
374 resume: (reply) => {
375 if ("rows" in reply) {
376 resume(Effect.succeed(reply.rows));
377 return;
378 }
379 const { operation, message, ...codes } = reply.error;
380 resume(
381 Effect.fail(
382 failed(
383 Object.assign(new Error(message), codes),
384 readerFailureMessages[operation],
385 operation,
386 ),
387 ),
388 );
389 },
390 });
391 if (pending.size === 1) worker.ref();
392 const cached = input.cached && !hasLargeBinding(input.params);
393 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
394 worker.postMessage({ id, safeIntegers, ...input, cached });
395 });
396 });
397
398 const connection = identity<Connection>({
399 execute(sql, params, rowTransform) {
400 const effect = request({ sql, params, cached: true, values: false, raw: false });
401 return rowTransform ? Effect.map(effect, rowTransform) : effect;
402 },
403 executeRaw(sql, params) {
404 return request({ sql, params, cached: true, values: false, raw: true });
405 },
406 executeValues(sql, params) {
407 return request({ sql, params, cached: true, values: true, raw: false });
408 },
409 executeValuesUnprepared(sql, params) {
410 return request({ sql, params: params ?? [], cached: false, values: true, raw: false });
411 },
412 executeUnprepared(sql, params, rowTransform) {
413 // Read snapshots need deferred BEGIN; readonly connections reject IMMEDIATE and EXCLUSIVE.
414 const statement = /^\s*BEGIN\b/i.test(sql) ? "BEGIN" : sql;
415 const effect = request({
416 sql: statement,
417 params: params ?? [],
418 cached: false,
419 values: false,
420 raw: false,
421 });
422 return rowTransform ? Effect.map(effect, rowTransform) : effect;
423 },
424 executeStream(_sql, _params) {
425 return Stream.die(new UnsupportedNodeSqliteOperationError());
426 },
427 });
428 current = { worker, connection, started };
429 return current;
430 };
431
432 yield* Effect.addFinalizer(() =>
433 Effect.promise(async () => {
434 await current?.worker.terminate();
435 }),
436 );
437
438 const startupTimeout = Duration.fromInputUnsafe(
439 options.readerStartupTimeout ?? Duration.seconds(10),
440 );
441
442 const turnOff = (reader: typeof current, reason: string) =>
443 Effect.suspend(() => {
444 if (reader !== undefined) {
445 if (current === reader) current = undefined;
446 void reader.worker.terminate();
447 }
448 if (unavailable) return Effect.succeed(undefined);
449 unavailable = true;
450 return Effect.logWarning("SQLite reader worker unavailable; reads use the main connection", {
451 reason,
452 }).pipe(Effect.as(undefined));
453 });
454
455 return Effect.suspend((): Effect.Effect<Connection | undefined> => {
456 if (unavailable) return Effect.succeed(undefined);
457 let reader: NonNullable<typeof current>;
458 try {
459 reader = current ?? start();
460 } catch (cause) {
461 return turnOff(undefined, String(cause));
462 }
463 return Effect.flatMap(
464 Effect.withFiber((fiber) => {
465 const restore = Context.get(fiber.context, ReadOnly) ?? identity;
466 return restore(
467 Effect.timeoutOption(
468 Effect.promise(() => reader.started),
469 startupTimeout,
470 ),
471 );
472 }),
473 (startup): Effect.Effect<Connection | undefined> =>
474 // A late ready event must not hand out a worker retired by another acquire timeout.
475 unavailable || current !== reader
476 ? Effect.succeed(undefined)
477 : Option.isSome(startup) && startup.value.type === "ready"
478 ? Effect.succeed(reader.connection)
479 : turnOff(
480 reader,
481 Option.isSome(startup) && startup.value.type === "unavailable"
482 ? startup.value.message
483 : `worker did not open the database within ${Duration.toMillis(startupTimeout)} ms`,
484 ),
485 );
486 });
487});
488
489const CHECKPOINT_FRAMES = 1000;
490const CHECKPOINT_IDLE_MS = 100;
491const CHECKPOINT_BACKPRESSURE_FRAMES = 10 * CHECKPOINT_FRAMES;
492
493const readSafeSqliteInteger = (value: unknown) => {
494 const number = typeof value === "bigint" ? Number(value) : value;
495 return typeof number === "number" && Number.isSafeInteger(number) ? number : undefined;
496};
497
498// Evaluated source also works in bundles and single-executable builds.
499const checkpointWorkerSource = `
500const { parentPort, workerData } = require("node:worker_threads");
501const { DatabaseSync } = require("node:sqlite");
502const { statSync } = require("node:fs");
503let db;
504let frames;
505let checkpoint;
506let truncate;
507let journalSizeLimit = -1;
508let generation = 0;
509let nextTruncateId = 0;
510let pendingTruncate;
511let pendingBarriers = 0;
512let idle;
513const initialize = () => {
514 if (db !== undefined) return;
515 // The writer switches to WAL after constructing the client.
516 db = new DatabaseSync(workerData.filename);
517 db.exec("PRAGMA busy_timeout = 5000;");
518 const mode = String(db.prepare("PRAGMA journal_mode").get().journal_mode).toLowerCase();
519 if (mode !== "wal") throw new Error("database uses journal_mode " + mode + ", not wal");
520 // macOS requires F_FULLFSYNC to flush the drive cache.
521 db.exec("PRAGMA checkpoint_fullfsync = ON;");
522 frames = db.prepare("PRAGMA wal_checkpoint(NOOP)");
523 checkpoint = db.prepare("PRAGMA wal_checkpoint(PASSIVE)");
524 truncate = db.prepare("PRAGMA wal_checkpoint(TRUNCATE)");
525};
526const atCeiling = (state) => state.log >= workerData.backpressureFrames;
527const exceedsSizeLimit = () =>
528 journalSizeLimit >= 0 && statSync(workerData.filename + "-wal").size > journalSizeLimit;
529const schedule = (state, blocked) => {
530 if (blocked || state.log - state.checkpointed >= workerData.frames) {
531 idle = setTimeout(() => check(undefined, undefined, true), workerData.idleMs);
532 }
533};
534const check = (id, nextJournalSizeLimit, force, nextGeneration = generation) => {
535 initialize();
536 if (Number.isSafeInteger(nextGeneration)) generation = Math.max(generation, nextGeneration);
537 if (Number.isSafeInteger(nextJournalSizeLimit)) journalSizeLimit = nextJournalSizeLimit;
538 let state = frames.get();
539 const oversized = exceedsSizeLimit();
540 if (force || state.log - state.checkpointed >= workerData.frames || oversized) {
541 checkpoint.get();
542 state = frames.get();
543 }
544 if (state.checkpointed === state.log && (atCeiling(state) || oversized)) {
545 pendingTruncate = { truncateId: ++nextTruncateId, checkId: id, generation, state };
546 parentPort.postMessage({
547 type: "truncate-request",
548 truncateId: pendingTruncate.truncateId,
549 checkId: id,
550 generation,
551 ...state,
552 });
553 return;
554 }
555 const blocked = (atCeiling(state) || oversized) && state.checkpointed < state.log;
556 parentPort.postMessage({ type: "checkpoint", id, generation, ...state, blocked });
557 schedule(state, blocked);
558};
559const finishTruncate = (truncateId) => {
560 if (pendingTruncate === undefined || pendingTruncate.truncateId !== truncateId) return;
561 const pending = pendingTruncate;
562 parentPort.postMessage({ type: "truncate-start", truncateId });
563 let busy;
564 // Admission is paused here; a pinned reader must not make truncation wait.
565 db.exec("PRAGMA busy_timeout = 0;");
566 try {
567 busy = truncate.get().busy !== 0;
568 } finally {
569 db.exec("PRAGMA busy_timeout = 5000;");
570 }
571 const state = frames.get();
572 const blocked = (atCeiling(state) && (busy || state.checkpointed < state.log)) || exceedsSizeLimit();
573 pendingTruncate = undefined;
574 parentPort.postMessage({
575 type: "checkpoint",
576 id: pending.checkId,
577 generation: pending.generation,
578 truncateId,
579 ...state,
580 blocked,
581 });
582 while (pendingBarriers > 0) {
583 pendingBarriers--;
584 parentPort.postMessage("barrier");
585 }
586 schedule(state, blocked);
587};
588parentPort.on("message", (request) => {
589 clearTimeout(idle);
590 if (request && request.type === "truncate") {
591 finishTruncate(request.truncateId);
592 return;
593 }
594 const isBarrier = request === "barrier";
595 if (pendingTruncate !== undefined) {
596 if (isBarrier) pendingBarriers++;
597 else if (request && request.type === "check") {
598 // Retire the request without labeling the pending snapshot with a newer generation.
599 parentPort.postMessage({
600 type: "checkpoint",
601 id: request.id,
602 generation: pendingTruncate.generation,
603 ...pendingTruncate.state,
604 blocked: true,
605 });
606 }
607 return;
608 }
609 const input = request && typeof request === "object" ? request : {};
610 check(input.id, input.journalSizeLimit, input.force, input.generation);
611 if (isBarrier) {
612 if (pendingTruncate !== undefined) pendingBarriers++;
613 else parentPort.postMessage("barrier");
614 }
615});
616`;
617
618const startCheckpointWorker = Effect.fnUntraced(function* (
619 filename: string,
620 writer: NodeSqlite.DatabaseSync,
621) {
622 const warn = (reason: string) =>
623 Effect.logWarning(
624 "SQLite checkpoint worker unavailable; checkpoints run on the main connection",
625 { reason },
626 );
627 if (typeof writer.isTransaction !== "boolean" || typeof writer.setAuthorizer !== "function") {
628 yield* warn("Node SQLite lacks transaction-state or statement-authorizer support");
629 return undefined;
630 }
631 const version = String(writer.prepare("SELECT sqlite_version() AS version").get()?.version);
632 const [major = 0, minor = 0] = version.split(".").map(Number);
633 // Older SQLite treats NOOP as PASSIVE, which would checkpoint on the writer.
634 if (major < 3 || (major === 3 && minor < 51)) {
635 yield* warn(`SQLite ${version} has no NOOP checkpoint`);
636 return undefined;
637 }
638 const frames = writer.prepare("PRAGMA wal_checkpoint(NOOP)");
639 const sizeLimit = writer.prepare("PRAGMA journal_size_limit");
640 let worker: NodeWorkerThreads.Worker;
641 try {
642 worker = new NodeWorkerThreads.Worker(checkpointWorkerSource, {
643 eval: true,
644 workerData: {
645 filename,
646 frames: CHECKPOINT_FRAMES,
647 backpressureFrames: CHECKPOINT_BACKPRESSURE_FRAMES,
648 idleMs: CHECKPOINT_IDLE_MS,
649 },
650 });
651 } catch (cause) {
652 yield* warn(String(cause));
653 return undefined;
654 }
655 const runFork = Effect.runForkWith(yield* Effect.context<never>());
656 let stopped = false;
657 let generation = 0;
658 let nextId = 0;
659 let inFlight: number | undefined;
660 let checkAgain = false;
661 let blocked = false;
662 let log = 0;
663 let checkpointed = 0;
664 let unknown = false;
665 let truncate: { id: number; acknowledged: boolean } | undefined;
666 type Waiter = { resume: () => void; cancelled: boolean };
667 const waiters: Array<Waiter> = [];
668 let elected: Waiter | undefined;
669 const gated = () =>
670 !stopped &&
671 !writer.isTransaction &&
672 (unknown || blocked || truncate !== undefined || log >= CHECKPOINT_BACKPRESSURE_FRAMES);
673 const wake = () => {
674 if (!gated() && elected === undefined) {
675 elected = waiters.shift();
676 elected?.resume();
677 }
678 if (waiters.length === 0 && elected === undefined) worker.unref();
679 };
680 const release = (waiter: Waiter) => {
681 waiter.cancelled = true;
682 const index = waiters.indexOf(waiter);
683 if (index !== -1) waiters.splice(index, 1);
684 if (elected === waiter) elected = undefined;
685 wake();
686 };
687 const handBack = (reason: string) => {
688 if (stopped) return;
689 stopped = true;
690 truncate = undefined;
691 try {
692 writer.exec(`PRAGMA wal_autocheckpoint = ${CHECKPOINT_FRAMES};`);
693 } catch {}
694 wake();
695 runFork(warn(reason));
696 };
697 const send = (message: unknown) => {
698 try {
699 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
700 worker.postMessage(message);
701 } catch (cause) {
702 handBack(String(cause));
703 }
704 };
705 const acknowledge = () => {
706 if (truncate === undefined || truncate.acknowledged || stopped || writer.isTransaction) return;
707 truncate.acknowledged = true;
708 send({ type: "truncate", truncateId: truncate.id });
709 };
710 const observe = () => {
711 try {
712 const state = frames.get();
713 const nextLog = readSafeSqliteInteger(state?.log);
714 const nextCheckpointed = readSafeSqliteInteger(state?.checkpointed);
715 if (nextLog === undefined || nextCheckpointed === undefined)
716 throw new Error("Invalid WAL frame counts");
717 log = nextLog;
718 checkpointed = nextCheckpointed;
719 unknown = false;
720 } catch {
721 unknown = true;
722 }
723 };
724 const request = (force = false) => {
725 if (stopped || writer.isTransaction) return;
726 if (truncate !== undefined) {
727 acknowledge();
728 return;
729 }
730 if (inFlight !== undefined) {
731 checkAgain = true;
732 return;
733 }
734 if (!force && !gated() && log - checkpointed < CHECKPOINT_FRAMES) return;
735 inFlight = ++nextId;
736 try {
737 send({
738 type: "check",
739 id: inFlight,
740 generation,
741 journalSizeLimit: readSafeSqliteInteger(sizeLimit.get()?.journal_size_limit),
742 force: force || gated(),
743 });
744 } catch (cause) {
745 handBack(String(cause));
746 }
747 };
748 const check = () => {
749 if (stopped || writer.isTransaction) return;
750 generation++;
751 observe();
752 request();
753 wake();
754 };
755 worker.on("error", (cause) => handBack(cause.message));
756 worker.on("exit", (code) => handBack(`exited with code ${code}`));
757 worker.on("message", (message: unknown) => {
758 if (stopped || typeof message !== "object" || message === null || !("type" in message)) return;
759 if (
760 message.type === "truncate-request" &&
761 "truncateId" in message &&
762 typeof message.truncateId === "number"
763 ) {
764 truncate = { id: message.truncateId, acknowledged: false };
765 blocked = true;
766 acknowledge();
767 return;
768 }
769 if (message.type !== "checkpoint") return;
770 const completedTruncate =
771 truncate !== undefined && "truncateId" in message && message.truncateId === truncate.id;
772 if (completedTruncate) truncate = undefined;
773 // An acknowledged truncate excludes new writer mutations, so its result is current.
774 if (
775 (completedTruncate || ("generation" in message && message.generation === generation)) &&
776 "log" in message &&
777 typeof message.log === "number" &&
778 "checkpointed" in message &&
779 typeof message.checkpointed === "number" &&
780 "blocked" in message &&
781 typeof message.blocked === "boolean"
782 ) {
783 log = message.log;
784 checkpointed = message.checkpointed;
785 blocked = message.blocked;
786 unknown = false;
787 }
788 // Even a stale snapshot must retire its request so a newer check can run.
789 if ("id" in message && message.id === inFlight) inFlight = undefined;
790 if (checkAgain && inFlight === undefined) {
791 checkAgain = false;
792 request(true);
793 }
794 wake();
795 });
796 yield* Effect.addFinalizer(() =>
797 Effect.promise(() => {
798 stopped = true;
799 truncate = undefined;
800 wake();
801 return worker.terminate();
802 }),
803 );
804 writer.exec("PRAGMA wal_autocheckpoint = 0;");
805 observe();
806 worker.unref();
807
808 const runWithAdmission = <A, E>(
809 execute: () => Exit.Exit<A, E>,
810 admitted?: Waiter,
811 ): Effect.Effect<A, E> =>
812 Effect.suspend(() => {
813 if (!gated()) {
814 // Release the election after executing; its successor must see the new WAL state.
815 try {
816 return execute();
817 } finally {
818 if (admitted !== undefined) release(admitted);
819 }
820 }
821 if (admitted !== undefined) release(admitted);
822 const waiter: Waiter = { resume: () => {}, cancelled: false };
823 const wait = Effect.uninterruptibleMask((restore) =>
824 Effect.withFiber((fiber) =>
825 (fiber.getRef(TransactionAcquire)?.restore ?? restore)(
826 Effect.callback<void>(function (this: Scheduler.Scheduler, resume) {
827 const dispatcher = this.makeDispatcher();
828 waiter.resume = () => {
829 dispatcher.scheduleTask(() => {
830 if (!waiter.cancelled) resume(Effect.void);
831 }, 0);
832 };
833 waiters.push(waiter);
834 worker.ref();
835 request(true);
836 wake();
837 return Effect.sync(() => release(waiter));
838 }),
839 ),
840 ),
841 );
842 return wait.pipe(
843 Effect.flatMap(() => runWithAdmission(execute, waiter)),
844 Effect.onInterrupt(() => Effect.sync(() => release(waiter))),
845 );
846 });
847 return { check, runWithAdmission };
848});
849
850const make = Effect.fn("makeWithDatabase")(function* (
851 options: SqliteClientConfig,
852): Effect.fn.Return<Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity> {
853 yield* checkNodeSqliteCompat();
854
855 const compiler = Statement.makeCompilerSqlite(options.transformQueryNames);
856 const isFileDatabase = options.filename !== ":memory:" && options.filename !== "";
857 const transformRows = options.transformResultNames
858 ? Statement.defaultTransforms(options.transformResultNames).array
859 : undefined;
860
861 const makeConnection = Effect.gen(function* () {
862 const scope = yield* Effect.scope;
863 const db = yield* Effect.try({
864 try: () =>
865 new NodeSqlite.DatabaseSync(options.filename, {
866 readOnly: options.readonly ?? false,
867 allowExtension: options.allowExtension ?? false,
868 }),
869 catch: (cause) =>
870 new SqlError({
871 reason: classifyError(cause, "Failed to open database", "open"),
872 }),
873 });
874 yield* Scope.addFinalizer(
875 scope,
876 Effect.try({
877 try: () => db.close(),
878 catch: (cause) =>
879 new SqlError({
880 reason: classifyError(cause, "Failed to close database", "close"),
881 }),
882 }).pipe(Effect.orDie),
883 );
884 // Started after the close finalizer, so the worker stops before the writer closes.
885 const checkpoint =
886 options.checkpointWorker && isFileDatabase
887 ? yield* startCheckpointWorker(options.filename, db)
888 : undefined;
889
890 const statementReaderCache = new WeakMap<NodeSqlite.StatementSync, boolean>();
891 interface CheckpointClassification {
892 backpressure: boolean;
893 check: boolean;
894 }
895 const checkpointClassifications = new WeakMap<
896 NodeSqlite.StatementSync,
897 CheckpointClassification
898 >();
899 const mutatingPragmasWithValues = new Set([
900 "application_id",
901 "auto_vacuum",
902 "journal_mode",
903 "schema_version",
904 "user_version",
905 ]);
906 const mutatesPragma = (name: string | null, value: string | null) => {
907 const pragma = name?.toLowerCase();
908 if (pragma === undefined) return false;
909 if (pragma === "incremental_vacuum" || pragma === "optimize") return true;
910 if (pragma === "wal_checkpoint") return value?.toLowerCase() !== "noop";
911 return value !== null && mutatingPragmasWithValues.has(pragma);
912 };
913 let activeClassification: CheckpointClassification | undefined;
914 const withClassification = <A>(
915 classification: CheckpointClassification | undefined,
916 f: () => A,
917 ): A => {
918 if (classification === undefined) return f();
919 const previous = activeClassification;
920 activeClassification = classification;
921 try {
922 return f();
923 } finally {
924 activeClassification = previous;
925 }
926 };
927 if (checkpoint !== undefined) {
928 // SQLite may reprepare an expired statement while it executes. Keep this
929 // callback installed and collect only around that statement's prepare/run.
930 db.setAuthorizer((actionCode, action, argument) => {
931 const classification = activeClassification;
932 if (classification === undefined) return NodeSqlite.constants.SQLITE_OK;
933 const constants = NodeSqlite.constants;
934 if (actionCode === constants.SQLITE_TRANSACTION) {
935 classification.backpressure ||= action === "BEGIN";
936 classification.check ||= action === "COMMIT" || action === "ROLLBACK";
937 } else if (actionCode === constants.SQLITE_SAVEPOINT) {
938 classification.backpressure ||= action === "BEGIN";
939 classification.check = true;
940 } else if (actionCode === constants.SQLITE_PRAGMA && mutatesPragma(action, argument)) {
941 classification.backpressure = true;
942 classification.check = true;
943 } else if (
944 actionCode !== constants.SQLITE_READ &&
945 actionCode !== constants.SQLITE_SELECT &&
946 actionCode !== constants.SQLITE_FUNCTION &&
947 actionCode !== constants.SQLITE_RECURSIVE &&
948 actionCode !== constants.SQLITE_PRAGMA
949 ) {
950 classification.backpressure = true;
951 classification.check = true;
952 }
953 return constants.SQLITE_OK;
954 });
955 }
956 const hasRows = (statement: NodeSqlite.StatementSync): boolean => {
957 const cached = statementReaderCache.get(statement);
958 if (cached !== undefined) {
959 return cached;
960 }
961 const value = statement.columns().length > 0;
962 statementReaderCache.set(statement, value);
963 return value;
964 };
965
966 const prepare = (sql: string) =>
967 Effect.try({
968 try: () => {
969 const classification = { backpressure: false, check: false };
970 const statement = withClassification(classification, () => db.prepare(sql));
971 if (checkpoint !== undefined) checkpointClassifications.set(statement, classification);
972 return statement;
973 },
974 catch: (cause) =>
975 new SqlError({
976 reason: classifyError(cause, "Failed to prepare statement", "prepare"),
977 }),
978 });
979
980 const prepareCache = yield* Cache.makeWith(prepare, {
981 capacity: options.prepareCacheSize ?? 200,
982 // A transient prepare failure must not outlive the lock or missing schema.
983 timeToLive: (exit) =>
984 Exit.isSuccess(exit) ? (options.prepareCacheTTL ?? Duration.minutes(10)) : Duration.zero,
985 });
986
987 const statementFor = (sql: string, params: ReadonlyArray<unknown>) =>
988 hasLargeBinding(params) ? prepare(sql) : Cache.get(prepareCache, sql);
989
990 const runStatement = (
991 statement: NodeSqlite.StatementSync,
992 params: ReadonlyArray<unknown>,
993 mode: "rows" | "raw" | "values" = "rows",
994 ) =>
995 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
996 const classification = checkpointClassifications.get(statement);
997 const execute = () => {
998 let arrays = false;
999 let result: Exit.Exit<ReadonlyArray<unknown>, SqlError>;
1000 try {
1001 const value = withClassification(classification, () => {
1002 statement.setReadBigInts(Boolean(Context.get(fiber.context, Client.SafeIntegers)));
1003 if (hasRows(statement)) {
1004 arrays = mode === "values";
1005 if (arrays) statement.setReturnArrays(true);
1006 return statement.all(...(params as any));
1007 }
1008 const result = statement.run(...(params as any));
1009 return mode === "raw" ? (result as unknown as ReadonlyArray<unknown>) : [];
1010 });
1011 result = Exit.succeed(value);
1012 } catch (cause) {
1013 result = Exit.fail(
1014 new SqlError({
1015 reason: classifyError(cause, "Failed to execute statement", "execute"),
1016 }),
1017 );
1018 } finally {
1019 // OR FAIL may have committed earlier rows even when execution throws.
1020 if (classification?.check) checkpoint?.check();
1021 }
1022 if (arrays) {
1023 try {
1024 statement.setReturnArrays(false);
1025 } catch (cause) {
1026 return Exit.die(
1027 new SqlError({
1028 reason: classifyError(
1029 cause,
1030 "Failed to reset statement result mode",
1031 "resetResultMode",
1032 ),
1033 }),
1034 );
1035 }
1036 }
1037 return result;
1038 };
1039 return checkpoint !== undefined && classification?.backpressure
1040 ? checkpoint.runWithAdmission(execute)
1041 : execute();
1042 });
1043
1044 const run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
1045 Effect.flatMap(statementFor(sql, params), (statement) =>
1046 runStatement(statement, params, raw ? "raw" : "rows"),
1047 );
1048 const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
1049 Effect.flatMap(statementFor(sql, params), (statement) =>
1050 runStatement(statement, params, "values"),
1051 );
1052
1053 return identity<Connection>({
1054 execute(sql, params, rowTransform) {
1055 return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params);
1056 },
1057 executeRaw(sql, params) {
1058 return run(sql, params, true);
1059 },
1060 executeValues(sql, params) {
1061 return runValues(sql, params);
1062 },
1063 executeValuesUnprepared(sql, params) {
1064 return Effect.flatMap(prepare(sql), (statement) =>
1065 runStatement(statement, params ?? [], "values"),
1066 );
1067 },
1068 executeUnprepared(sql, params, rowTransform) {
1069 const effect = prepare(sql).pipe(
1070 Effect.flatMap((statement) => runStatement(statement, params ?? [])),
1071 );
1072 return rowTransform ? Effect.map(effect, rowTransform) : effect;
1073 },
1074 executeStream(_sql, _params) {
1075 return Stream.die(new UnsupportedNodeSqliteOperationError());
1076 },
1077 });
1078 });
1079
1080 const semaphore = yield* Semaphore.make(1);
1081 const connection = yield* makeConnection;
1082 const acquireReader =
1083 options.readerWorker && isFileDatabase ? yield* makeReader(options) : undefined;
1084 const readerSemaphore = yield* Semaphore.make(1);
1085
1086 const writer = { name: "writer" as const, lock: semaphore, connection };
1087 let activeWriter: ConnectionOwner | undefined;
1088 const route = Effect.withFiber((fiber) =>
1089 acquireReader !== undefined && Context.get(fiber.context, ReadOnly)
1090 ? Effect.map(acquireReader, (readerConnection) =>
1091 readerConnection === undefined
1092 ? writer
1093 : { name: "reader" as const, lock: readerSemaphore, connection: readerConnection },
1094 )
1095 : Effect.succeed(writer),
1096 );
1097
1098 const acquired = (
1099 target: { readonly name: Acquired["connection"] },
1100 clock: Clock.Clock,
1101 start: bigint,
1102 ): Acquired => ({
1103 connection: target.name,
1104 lockWaitMs: Number((clock.monotonicTimeNanosUnsafe() - start) / 1000n) / 1000,
1105 });
1106
1107 const writerBorrowBatchSize = 16;
1108 let writerBorrowsSinceYield = 0;
1109 const borrower: Borrower = (use) =>
1110 Effect.flatMap(route, (target) =>
1111 Effect.withFiber((fiber) => {
1112 const clock = fiber.getRef(Clock.Clock);
1113 const start = clock.monotonicTimeNanosUnsafe();
1114 const ownerAtWaitStart = target.name === "writer" ? activeWriter : undefined;
1115 const owner = target.name === "writer" ? connectionOwner(fiber) : undefined;
1116 const useConnection = Effect.suspend(() => {
1117 if (target.name === "writer") activeWriter = owner;
1118 if (
1119 fiber.getRef(References.TracerEnabled) &&
1120 fiber.getRef(Statement.SpanPropagationEnabled)
1121 ) {
1122 annotateAcquired(fiber, acquired(target, clock, start), ownerAtWaitStart);
1123 }
1124 return use(target.connection);
1125 });
1126 const useOwnedConnection =
1127 target.name === "writer"
1128 ? Effect.onExit(useConnection, () =>
1129 Effect.sync(() => {
1130 if (activeWriter === owner) activeWriter = undefined;
1131 }),
1132 )
1133 : useConnection;
1134 if (!options.checkpointWorker || target.name !== "writer") {
1135 return target.lock.withPermits(1)(useOwnedConnection);
1136 }
1137 const writerUse = Effect.onExit(useOwnedConnection, (exit) =>
1138 Effect.sync(() => {
1139 writerBorrowsSinceYield = Exit.hasInterrupts(exit)
1140 ? 0
1141 : Math.min(writerBorrowsSinceYield + 1, writerBorrowBatchSize);
1142 }),
1143 );
1144 return Effect.flatMap(target.lock.withPermitsIfAvailable(1)(writerUse), (result) =>
1145 Option.isSome(result)
1146 ? Effect.succeed(result.value)
1147 : target.lock.withPermits(1)(
1148 Effect.andThen(
1149 // Failed SQL also consumes the batch; cancellation hands off immediately.
1150 Effect.suspend(() => {
1151 if (writerBorrowsSinceYield < writerBorrowBatchSize) return Effect.void;
1152 writerBorrowsSinceYield = 0;
1153 return Effect.callback<void>((resume) => {
1154 const immediate = setImmediate(() => resume(Effect.void));
1155 return Effect.sync(() => clearImmediate(immediate));
1156 });
1157 }),
1158 writerUse,
1159 ),
1160 ),
1161 );
1162 }),
1163 );
1164 const transactionAcquirer = Effect.flatMap(route, (target) =>
1165 Effect.uninterruptibleMask((restore) => {
1166 const fiber = Fiber.getCurrent()!;
1167 const scope = Context.getUnsafe(fiber.context, Scope.Scope);
1168 const clock = fiber.getRef(Clock.Clock);
1169 const start = clock.monotonicTimeNanosUnsafe();
1170 const pending = fiber.getRef(TransactionAcquire);
1171 const ownerAtWaitStart = target.name === "writer" ? activeWriter : undefined;
1172 const owner = target.name === "writer" ? connectionOwner(fiber) : undefined;
1173 const acquire = Effect.tap((pending?.restore ?? restore)(target.lock.take(1)), () => {
1174 if (target.name === "writer") activeWriter = owner;
1175 if (pending !== undefined) {
1176 pending.acquired = acquired(target, clock, start);
1177 pending.ownerAtWaitStart = ownerAtWaitStart;
1178 }
1179 return Scope.addFinalizer(
1180 scope,
1181 Effect.sync(() => {
1182 if (target.name === "writer" && activeWriter === owner) activeWriter = undefined;
1183 }).pipe(Effect.andThen(target.lock.release(1))),
1184 );
1185 });
1186 return Effect.as(
1187 // A scheduler yield after taking the permit must not precede its release finalizer.
1188 Effect.provideService(acquire, Scheduler.PreventSchedulerYield, true),
1189 target.connection,
1190 );
1191 }),
1192 );
1193
1194 const client = yield* Client.make({
1195 acquirer: transactionAcquirer,
1196 borrower,
1197 compiler,
1198 transactionAcquirer,
1199 // BEGIN IMMEDIATE avoids read-then-write SQLITE_BUSY_SNAPSHOT, which busy_timeout cannot resolve.
1200 beginTransaction: options.readonly === true ? "BEGIN" : "BEGIN IMMEDIATE",
1201 spanAttributes: [
1202 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
1203 [ATTR_DB_SYSTEM_NAME, "sqlite"],
1204 ],
1205 transformRows,
1206 });
1207 const withTransaction = client.withTransaction;
1208 return Object.assign(client, {
1209 withTransaction: <A, E, R>(effect: Effect.Effect<A, E, R>) =>
1210 Effect.uninterruptibleMask((restore) => {
1211 // SqlClient masks setup; acquisition must preserve the caller's interruptibility.
1212 const pending: {
1213 acquired?: Acquired;
1214 ownerAtWaitStart: ConnectionOwner | undefined;
1215 restore: typeof Effect.interruptible | undefined;
1216 } = {
1217 ownerAtWaitStart: undefined,
1218 restore,
1219 };
1220 const body = Effect.withFiber<A, E, R>((fiber) => {
1221 annotateAcquired(fiber, pending.acquired, pending.ownerAtWaitStart);
1222 pending.restore = undefined;
1223 return effect;
1224 });
1225 return restore(
1226 withTransaction(body).pipe(Effect.provideService(TransactionAcquire, pending)),
1227 );
1228 }),
1229 });
1230});
1231
1232export const layer = (config: SqliteClientConfig): Layer.Layer<Client.SqlClient, SqlError> =>
1233 Layer.effect(Client.SqlClient, make(config)).pipe(Layer.provide(Reactivity.layer));