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 /** Ignored for in-memory databases. */
39 readonly checkpointWorker?: 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// Inline worker source also runs in bundles and single-executable builds without module files.
197const readerWorkerSource = `
198const { parentPort, workerData } = require("node:worker_threads");
199const { DatabaseSync } = require("node:sqlite");
200let db;
201try {
202 // A read-only open cannot be undone by SQL, unlike PRAGMA query_only.
203 const next = new DatabaseSync(workerData.filename, {
204 readOnly: true,
205 allowExtension: workerData.allowExtension,
206 });
207 next.exec("PRAGMA busy_timeout = 5000;");
208 // Without WAL a reader's shared lock blocks the writer's commits, so refuse.
209 const mode = String(next.prepare("PRAGMA journal_mode").get().journal_mode).toLowerCase();
210 if (mode !== "wal") throw new Error("database uses journal_mode " + mode + ", not wal");
211 db = next;
212 parentPort.postMessage({ type: "ready" });
213} catch (error) {
214 parentPort.postMessage({ type: "unavailable", message: String(error && error.message ? error.message : error) });
215}
216const statements = new Map();
217const prepare = (sql, cached) => {
218 if (!cached) return db.prepare(sql);
219 let statement = statements.get(sql);
220 if (statement === undefined) {
221 statement = db.prepare(sql);
222 if (statements.size >= workerData.prepareCacheSize) statements.delete(statements.keys().next().value);
223 } else {
224 statements.delete(sql);
225 }
226 statements.set(sql, statement);
227 return statement;
228};
229parentPort.on("message", ({ id, sql, params, cached, values, raw, safeIntegers }) => {
230 let operation = "open";
231 try {
232 if (db === undefined) throw new Error("database reader is unavailable");
233 operation = "prepare";
234 const statement = prepare(sql, cached);
235 operation = "execute";
236 statement.setReadBigInts(safeIntegers);
237 if (statement.columns().length > 0) {
238 statement.setReturnArrays(values);
239 parentPort.postMessage({ id, rows: statement.all(...params) });
240 } else {
241 const result = statement.run(...params);
242 parentPort.postMessage({ id, rows: raw ? result : [] });
243 }
244 } catch (error) {
245 parentPort.postMessage({
246 id,
247 error: {
248 operation,
249 message: String(error && error.message ? error.message : error),
250 code: error && error.code,
251 errcode: error && error.errcode,
252 errstr: error && error.errstr,
253 },
254 });
255 }
256});
257`;
258
259interface ReaderRequest {
260 readonly sql: string;
261 readonly params: ReadonlyArray<unknown>;
262 readonly cached: boolean;
263 readonly values: boolean;
264 readonly raw: boolean;
265}
266
267type ReaderStartup =
268 | { readonly type: "ready" }
269 | { readonly type: "unavailable"; readonly message: string };
270
271type ReaderReply =
272 | { readonly id: number; readonly rows: ReadonlyArray<any> }
273 | {
274 readonly id: number;
275 readonly error: {
276 readonly operation: "open" | "prepare" | "execute";
277 readonly message: string;
278 readonly code?: unknown;
279 readonly errcode?: unknown;
280 readonly errstr?: unknown;
281 };
282 };
283
284const readerFailureMessages = {
285 open: "Failed to open database",
286 prepare: "Failed to prepare statement",
287 execute: "Failed to execute statement",
288} as const;
289
290const failed = (cause: unknown, message: string, operation: string) =>
291 new SqlError({ reason: classifyError(cause, message, operation) });
292
293// Read-transaction cleanup succeeds after worker exit because it can no longer change anything.
294const endsReadTransaction = (sql: string) => /^\s*ROLLBACK\b|^\s*COMMIT\b/i.test(sql);
295
296// WAL readers run concurrently; one worker serialized every read behind the slowest transaction.
297const READER_POOL_SIZE = 4;
298
299// Bind transactions to one worker; fail after its exit instead of resuming outside the transaction on a replacement.
300const makeReader = Effect.fnUntraced(function* (
301 options: SqliteClientConfig,
302 pool: { unavailable: boolean },
303) {
304 let current:
305 | {
306 readonly worker: NodeWorkerThreads.Worker;
307 readonly connection: Connection;
308 readonly started: Promise<ReaderStartup>;
309 }
310 | undefined;
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: false,
319 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.seconds(10);
439
440 const turnOff = (reader: typeof current, reason: string) =>
441 Effect.suspend(() => {
442 if (reader !== undefined) {
443 if (current === reader) current = undefined;
444 void reader.worker.terminate();
445 }
446 // @effect-diagnostics-next-line effectSucceedWithVoid:off - The connection result distinguishes undefined from void.
447 if (pool.unavailable) return Effect.succeed(undefined);
448 pool.unavailable = true;
449 return Effect.logWarning("SQLite reader worker unavailable; reads use the main connection", {
450 reason,
451 }).pipe(Effect.as(undefined));
452 });
453
454 return Effect.suspend((): Effect.Effect<Connection | undefined> => {
455 // @effect-diagnostics-next-line effectSucceedWithVoid:off - The connection result distinguishes undefined from void.
456 if (pool.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 pool.unavailable || current !== reader
476 ? // @effect-diagnostics-next-line effectSucceedWithVoid:off - The connection result distinguishes undefined from void.
477 Effect.succeed(undefined)
478 : Option.isSome(startup) && startup.value.type === "ready"
479 ? Effect.succeed(reader.connection)
480 : turnOff(
481 reader,
482 Option.isSome(startup) && startup.value.type === "unavailable"
483 ? startup.value.message
484 : `worker did not open the database within ${Duration.toMillis(startupTimeout)} ms`,
485 ),
486 );
487 });
488});
489
490const CHECKPOINT_FRAMES = 1000;
491const CHECKPOINT_IDLE_MS = 100;
492const CHECKPOINT_BACKPRESSURE_FRAMES = 10 * CHECKPOINT_FRAMES;
493
494const readSafeSqliteInteger = (value: unknown) => {
495 const number = typeof value === "bigint" ? Number(value) : value;
496 return typeof number === "number" && Number.isSafeInteger(number) ? number : undefined;
497};
498
499// Evaluated source also works in bundles and single-executable builds.
500const checkpointWorkerSource = `
501const { parentPort, workerData } = require("node:worker_threads");
502const { DatabaseSync } = require("node:sqlite");
503const { statSync } = require("node:fs");
504let db;
505let frames;
506let checkpoint;
507let truncate;
508let journalSizeLimit = -1;
509let generation = 0;
510let nextTruncateId = 0;
511let pendingTruncate;
512let pendingBarriers = 0;
513let idle;
514const initialize = () => {
515 if (db !== undefined) return;
516 // The writer switches to WAL after constructing the client.
517 db = new DatabaseSync(workerData.filename);
518 db.exec("PRAGMA busy_timeout = 5000;");
519 const mode = String(db.prepare("PRAGMA journal_mode").get().journal_mode).toLowerCase();
520 if (mode !== "wal") throw new Error("database uses journal_mode " + mode + ", not wal");
521 // macOS requires F_FULLFSYNC to flush the drive cache.
522 db.exec("PRAGMA checkpoint_fullfsync = ON;");
523 frames = db.prepare("PRAGMA wal_checkpoint(NOOP)");
524 checkpoint = db.prepare("PRAGMA wal_checkpoint(PASSIVE)");
525 truncate = db.prepare("PRAGMA wal_checkpoint(TRUNCATE)");
526};
527const atCeiling = (state) => state.log >= workerData.backpressureFrames;
528const exceedsSizeLimit = () =>
529 journalSizeLimit >= 0 && statSync(workerData.filename + "-wal").size > journalSizeLimit;
530const schedule = (state, blocked) => {
531 if (blocked || state.log - state.checkpointed >= workerData.frames) {
532 idle = setTimeout(() => check(undefined, undefined, true), workerData.idleMs);
533 }
534};
535const check = (id, nextJournalSizeLimit, force, nextGeneration = generation) => {
536 initialize();
537 if (Number.isSafeInteger(nextGeneration)) generation = Math.max(generation, nextGeneration);
538 if (Number.isSafeInteger(nextJournalSizeLimit)) journalSizeLimit = nextJournalSizeLimit;
539 let state = frames.get();
540 const oversized = exceedsSizeLimit();
541 if (force || state.log - state.checkpointed >= workerData.frames || oversized) {
542 checkpoint.get();
543 state = frames.get();
544 }
545 if (state.checkpointed === state.log && (atCeiling(state) || oversized)) {
546 pendingTruncate = { truncateId: ++nextTruncateId, checkId: id, generation, state };
547 parentPort.postMessage({
548 type: "truncate-request",
549 truncateId: pendingTruncate.truncateId,
550 checkId: id,
551 generation,
552 ...state,
553 });
554 return;
555 }
556 const blocked = (atCeiling(state) || oversized) && state.checkpointed < state.log;
557 parentPort.postMessage({ type: "checkpoint", id, generation, ...state, blocked });
558 schedule(state, blocked);
559};
560const finishTruncate = (truncateId) => {
561 if (pendingTruncate === undefined || pendingTruncate.truncateId !== truncateId) return;
562 const pending = pendingTruncate;
563 parentPort.postMessage({ type: "truncate-start", truncateId });
564 let busy;
565 // Admission is paused here; a pinned reader must not make truncation wait.
566 db.exec("PRAGMA busy_timeout = 0;");
567 try {
568 busy = truncate.get().busy !== 0;
569 } finally {
570 db.exec("PRAGMA busy_timeout = 5000;");
571 }
572 const state = frames.get();
573 const blocked = (atCeiling(state) && (busy || state.checkpointed < state.log)) || exceedsSizeLimit();
574 pendingTruncate = undefined;
575 parentPort.postMessage({
576 type: "checkpoint",
577 id: pending.checkId,
578 generation: pending.generation,
579 truncateId,
580 ...state,
581 blocked,
582 });
583 while (pendingBarriers > 0) {
584 pendingBarriers--;
585 parentPort.postMessage("barrier");
586 }
587 schedule(state, blocked);
588};
589parentPort.on("message", (request) => {
590 clearTimeout(idle);
591 if (request && request.type === "truncate") {
592 finishTruncate(request.truncateId);
593 return;
594 }
595 const isBarrier = request === "barrier";
596 if (pendingTruncate !== undefined) {
597 if (isBarrier) pendingBarriers++;
598 else if (request && request.type === "check") {
599 // Retire the request without labeling the pending snapshot with a newer generation.
600 parentPort.postMessage({
601 type: "checkpoint",
602 id: request.id,
603 generation: pendingTruncate.generation,
604 ...pendingTruncate.state,
605 blocked: true,
606 });
607 }
608 return;
609 }
610 const input = request && typeof request === "object" ? request : {};
611 check(input.id, input.journalSizeLimit, input.force, input.generation);
612 if (isBarrier) {
613 if (pendingTruncate !== undefined) pendingBarriers++;
614 else parentPort.postMessage("barrier");
615 }
616});
617`;
618
619const startCheckpointWorker = Effect.fnUntraced(function* (
620 filename: string,
621 writer: NodeSqlite.DatabaseSync,
622) {
623 const warn = (reason: string) =>
624 Effect.logWarning(
625 "SQLite checkpoint worker unavailable; checkpoints run on the main connection",
626 { reason },
627 );
628 if (typeof writer.isTransaction !== "boolean" || typeof writer.setAuthorizer !== "function") {
629 yield* warn("Node SQLite lacks transaction-state or statement-authorizer support");
630 return undefined;
631 }
632 // These are the writer's first statements, before callers set their own wait.
633 writer.exec("PRAGMA busy_timeout = 5000;");
634 const version = String(writer.prepare("SELECT sqlite_version() AS version").get()?.version);
635 const [major = 0, minor = 0] = version.split(".").map(Number);
636 // Older SQLite treats NOOP as PASSIVE, which would checkpoint on the writer.
637 if (major < 3 || (major === 3 && minor < 51)) {
638 yield* warn(`SQLite ${version} has no NOOP checkpoint`);
639 return undefined;
640 }
641 const frames = writer.prepare("PRAGMA wal_checkpoint(NOOP)");
642 const sizeLimit = writer.prepare("PRAGMA journal_size_limit");
643 const started = yield* Effect.try(
644 () =>
645 new NodeWorkerThreads.Worker(checkpointWorkerSource, {
646 eval: true,
647 workerData: {
648 filename,
649 frames: CHECKPOINT_FRAMES,
650 backpressureFrames: CHECKPOINT_BACKPRESSURE_FRAMES,
651 idleMs: CHECKPOINT_IDLE_MS,
652 },
653 }),
654 ).pipe(Effect.result);
655 if (Result.isFailure(started)) {
656 yield* warn(String(started.failure.cause));
657 return undefined;
658 }
659 const worker = started.success;
660 const runFork = Effect.runForkWith(yield* Effect.context<never>());
661 let stopped = false;
662 let generation = 0;
663 let nextId = 0;
664 let inFlight: number | undefined;
665 let checkAgain = false;
666 let blocked = false;
667 let log = 0;
668 let checkpointed = 0;
669 let unknown = false;
670 let truncate: { id: number; acknowledged: boolean } | undefined;
671 type Waiter = { resume: () => void; cancelled: boolean };
672 const waiters: Array<Waiter> = [];
673 let elected: Waiter | undefined;
674 const gated = () =>
675 !stopped &&
676 !writer.isTransaction &&
677 (unknown || blocked || truncate !== undefined || log >= CHECKPOINT_BACKPRESSURE_FRAMES);
678 const wake = () => {
679 if (!gated() && elected === undefined) {
680 elected = waiters.shift();
681 elected?.resume();
682 }
683 if (waiters.length === 0 && elected === undefined) worker.unref();
684 };
685 const release = (waiter: Waiter) => {
686 waiter.cancelled = true;
687 const index = waiters.indexOf(waiter);
688 if (index !== -1) waiters.splice(index, 1);
689 if (elected === waiter) elected = undefined;
690 wake();
691 };
692 const handBack = (reason: string) => {
693 if (stopped) return;
694 stopped = true;
695 truncate = undefined;
696 try {
697 writer.exec(`PRAGMA wal_autocheckpoint = ${CHECKPOINT_FRAMES};`);
698 } catch {}
699 wake();
700 runFork(warn(reason));
701 };
702 const send = (message: unknown) => {
703 try {
704 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
705 worker.postMessage(message);
706 } catch (cause) {
707 handBack(String(cause));
708 }
709 };
710 const acknowledge = () => {
711 if (truncate === undefined || truncate.acknowledged || stopped || writer.isTransaction) return;
712 truncate.acknowledged = true;
713 send({ type: "truncate", truncateId: truncate.id });
714 };
715 const observe = () => {
716 try {
717 const state = frames.get();
718 const nextLog = readSafeSqliteInteger(state?.log);
719 const nextCheckpointed = readSafeSqliteInteger(state?.checkpointed);
720 if (nextLog === undefined || nextCheckpointed === undefined)
721 throw new Error("Invalid WAL frame counts");
722 log = nextLog;
723 checkpointed = nextCheckpointed;
724 unknown = false;
725 } catch {
726 unknown = true;
727 }
728 };
729 const request = (force = false) => {
730 if (stopped || writer.isTransaction) return;
731 if (truncate !== undefined) {
732 acknowledge();
733 return;
734 }
735 if (inFlight !== undefined) {
736 checkAgain = true;
737 return;
738 }
739 if (!force && !gated() && log - checkpointed < CHECKPOINT_FRAMES) return;
740 inFlight = ++nextId;
741 try {
742 send({
743 type: "check",
744 id: inFlight,
745 generation,
746 journalSizeLimit: readSafeSqliteInteger(sizeLimit.get()?.journal_size_limit),
747 force: force || gated(),
748 });
749 } catch (cause) {
750 handBack(String(cause));
751 }
752 };
753 const check = () => {
754 if (stopped || writer.isTransaction) return;
755 generation++;
756 observe();
757 request();
758 wake();
759 };
760 worker.on("error", (cause) => handBack(cause.message));
761 worker.on("exit", (code) => handBack(`exited with code ${code}`));
762 worker.on("message", (message: unknown) => {
763 if (stopped || typeof message !== "object" || message === null || !("type" in message)) return;
764 if (
765 message.type === "truncate-request" &&
766 "truncateId" in message &&
767 typeof message.truncateId === "number"
768 ) {
769 truncate = { id: message.truncateId, acknowledged: false };
770 blocked = true;
771 acknowledge();
772 return;
773 }
774 if (message.type !== "checkpoint") return;
775 const completedTruncate =
776 truncate !== undefined && "truncateId" in message && message.truncateId === truncate.id;
777 if (completedTruncate) truncate = undefined;
778 // An acknowledged truncate excludes new writer mutations, so its result is current.
779 if (
780 (completedTruncate || ("generation" in message && message.generation === generation)) &&
781 "log" in message &&
782 typeof message.log === "number" &&
783 "checkpointed" in message &&
784 typeof message.checkpointed === "number" &&
785 "blocked" in message &&
786 typeof message.blocked === "boolean"
787 ) {
788 log = message.log;
789 checkpointed = message.checkpointed;
790 blocked = message.blocked;
791 unknown = false;
792 }
793 // Even a stale snapshot must retire its request so a newer check can run.
794 if ("id" in message && message.id === inFlight) inFlight = undefined;
795 if (checkAgain && inFlight === undefined) {
796 checkAgain = false;
797 request(true);
798 }
799 wake();
800 });
801 yield* Effect.addFinalizer(() =>
802 Effect.promise(() => {
803 stopped = true;
804 truncate = undefined;
805 wake();
806 return worker.terminate();
807 }),
808 );
809 writer.exec("PRAGMA wal_autocheckpoint = 0;");
810 observe();
811 worker.unref();
812
813 const runWithAdmission = <A, E>(
814 execute: () => Exit.Exit<A, E>,
815 admitted?: Waiter,
816 ): Effect.Effect<A, E> =>
817 Effect.suspend(() => {
818 if (!gated()) {
819 // Release the election after executing; its successor must see the new WAL state.
820 try {
821 return execute();
822 } finally {
823 if (admitted !== undefined) release(admitted);
824 }
825 }
826 if (admitted !== undefined) release(admitted);
827 const waiter: Waiter = { resume: () => {}, cancelled: false };
828 const wait = Effect.uninterruptibleMask((restore) =>
829 Effect.withFiber((fiber) =>
830 (fiber.getRef(TransactionAcquire)?.restore ?? restore)(
831 Effect.callback<void>(function (this: Scheduler.Scheduler, resume) {
832 const dispatcher = this.makeDispatcher();
833 waiter.resume = () => {
834 dispatcher.scheduleTask(() => {
835 if (!waiter.cancelled) resume(Effect.void);
836 }, 0);
837 };
838 waiters.push(waiter);
839 worker.ref();
840 request(true);
841 wake();
842 return Effect.sync(() => release(waiter));
843 }),
844 ),
845 ),
846 );
847 return wait.pipe(
848 Effect.flatMap(() => runWithAdmission(execute, waiter)),
849 Effect.onInterrupt(() => Effect.sync(() => release(waiter))),
850 );
851 });
852 return { check, runWithAdmission };
853});
854
855const make = Effect.fn("makeWithDatabase")(function* (
856 options: SqliteClientConfig,
857): Effect.fn.Return<Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity> {
858 yield* checkNodeSqliteCompat();
859
860 const compiler = Statement.makeCompilerSqlite();
861 const isFileDatabase = options.filename !== ":memory:" && options.filename !== "";
862
863 const makeConnection = Effect.gen(function* () {
864 const scope = yield* Effect.scope;
865 const db = yield* Effect.try({
866 try: () =>
867 new NodeSqlite.DatabaseSync(options.filename, {
868 readOnly: options.readonly ?? false,
869 allowExtension: false,
870 }),
871 catch: (cause) =>
872 new SqlError({
873 reason: classifyError(cause, "Failed to open database", "open"),
874 }),
875 });
876 yield* Scope.addFinalizer(
877 scope,
878 Effect.try({
879 try: () => db.close(),
880 catch: (cause) =>
881 new SqlError({
882 reason: classifyError(cause, "Failed to close database", "close"),
883 }),
884 }).pipe(Effect.orDie),
885 );
886 // Started after the close finalizer, so the worker stops before the writer closes.
887 const checkpoint =
888 options.checkpointWorker && isFileDatabase
889 ? yield* startCheckpointWorker(options.filename, db)
890 : undefined;
891
892 const statementReaderCache = new WeakMap<NodeSqlite.StatementSync, boolean>();
893 interface CheckpointClassification {
894 backpressure: boolean;
895 check: boolean;
896 }
897 const checkpointClassifications = new WeakMap<
898 NodeSqlite.StatementSync,
899 CheckpointClassification
900 >();
901 const mutatingPragmasWithValues = new Set([
902 "application_id",
903 "auto_vacuum",
904 "journal_mode",
905 "schema_version",
906 "user_version",
907 ]);
908 const mutatesPragma = (name: string | null, value: string | null) => {
909 const pragma = name?.toLowerCase();
910 if (pragma === undefined) return false;
911 if (pragma === "incremental_vacuum" || pragma === "optimize") return true;
912 if (pragma === "wal_checkpoint") return value?.toLowerCase() !== "noop";
913 return value !== null && mutatingPragmasWithValues.has(pragma);
914 };
915 let activeClassification: CheckpointClassification | undefined;
916 const withClassification = <A>(
917 classification: CheckpointClassification | undefined,
918 f: () => A,
919 ): A => {
920 if (classification === undefined) return f();
921 const previous = activeClassification;
922 activeClassification = classification;
923 try {
924 return f();
925 } finally {
926 activeClassification = previous;
927 }
928 };
929 if (checkpoint !== undefined) {
930 // SQLite may reprepare an expired statement while it executes. Keep this
931 // callback installed and collect only around that statement's prepare/run.
932 db.setAuthorizer((actionCode, action, argument) => {
933 const classification = activeClassification;
934 if (classification === undefined) return NodeSqlite.constants.SQLITE_OK;
935 const constants = NodeSqlite.constants;
936 if (actionCode === constants.SQLITE_TRANSACTION) {
937 classification.backpressure ||= action === "BEGIN";
938 classification.check ||= action === "COMMIT" || action === "ROLLBACK";
939 } else if (actionCode === constants.SQLITE_SAVEPOINT) {
940 classification.backpressure ||= action === "BEGIN";
941 classification.check = true;
942 } else if (actionCode === constants.SQLITE_PRAGMA && mutatesPragma(action, argument)) {
943 classification.backpressure = true;
944 classification.check = true;
945 } else if (
946 actionCode !== constants.SQLITE_READ &&
947 actionCode !== constants.SQLITE_SELECT &&
948 actionCode !== constants.SQLITE_FUNCTION &&
949 actionCode !== constants.SQLITE_RECURSIVE &&
950 actionCode !== constants.SQLITE_PRAGMA
951 ) {
952 classification.backpressure = true;
953 classification.check = true;
954 }
955 return constants.SQLITE_OK;
956 });
957 }
958 const hasRows = (statement: NodeSqlite.StatementSync): boolean => {
959 const cached = statementReaderCache.get(statement);
960 if (cached !== undefined) {
961 return cached;
962 }
963 const value = statement.columns().length > 0;
964 statementReaderCache.set(statement, value);
965 return value;
966 };
967
968 const prepare = (sql: string) =>
969 Effect.try({
970 try: () => {
971 const classification = { backpressure: false, check: false };
972 const statement = withClassification(classification, () => db.prepare(sql));
973 if (checkpoint !== undefined) checkpointClassifications.set(statement, classification);
974 return statement;
975 },
976 catch: (cause) =>
977 new SqlError({
978 reason: classifyError(cause, "Failed to prepare statement", "prepare"),
979 }),
980 });
981
982 const prepareCache = yield* Cache.makeWith(prepare, {
983 capacity: 200,
984 // A transient prepare failure must not outlive the lock or missing schema.
985 timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.minutes(10) : Duration.zero),
986 });
987
988 const statementFor = (sql: string, params: ReadonlyArray<unknown>) =>
989 hasLargeBinding(params) ? prepare(sql) : Cache.get(prepareCache, sql);
990
991 const runStatement = (
992 statement: NodeSqlite.StatementSync,
993 params: ReadonlyArray<unknown>,
994 mode: "rows" | "raw" | "values" = "rows",
995 ) =>
996 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
997 const classification = checkpointClassifications.get(statement);
998 const execute = () => {
999 let arrays = false;
1000 let result: Exit.Exit<ReadonlyArray<unknown>, SqlError>;
1001 try {
1002 const value = withClassification(classification, () => {
1003 statement.setReadBigInts(Boolean(Context.get(fiber.context, Client.SafeIntegers)));
1004 if (hasRows(statement)) {
1005 arrays = mode === "values";
1006 if (arrays) statement.setReturnArrays(true);
1007 return statement.all(...(params as any));
1008 }
1009 const result = statement.run(...(params as any));
1010 return mode === "raw" ? (result as unknown as ReadonlyArray<unknown>) : [];
1011 });
1012 result = Exit.succeed(value);
1013 } catch (cause) {
1014 result = Exit.fail(
1015 new SqlError({
1016 reason: classifyError(cause, "Failed to execute statement", "execute"),
1017 }),
1018 );
1019 } finally {
1020 // OR FAIL may have committed earlier rows even when execution throws.
1021 if (classification?.check) checkpoint?.check();
1022 }
1023 if (arrays) {
1024 try {
1025 statement.setReturnArrays(false);
1026 } catch (cause) {
1027 return Exit.die(
1028 new SqlError({
1029 reason: classifyError(
1030 cause,
1031 "Failed to reset statement result mode",
1032 "resetResultMode",
1033 ),
1034 }),
1035 );
1036 }
1037 }
1038 return result;
1039 };
1040 return checkpoint !== undefined && classification?.backpressure
1041 ? checkpoint.runWithAdmission(execute)
1042 : execute();
1043 });
1044
1045 const run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
1046 Effect.flatMap(statementFor(sql, params), (statement) =>
1047 runStatement(statement, params, raw ? "raw" : "rows"),
1048 );
1049 const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
1050 Effect.flatMap(statementFor(sql, params), (statement) =>
1051 runStatement(statement, params, "values"),
1052 );
1053
1054 return identity<Connection>({
1055 execute(sql, params, rowTransform) {
1056 return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params);
1057 },
1058 executeRaw(sql, params) {
1059 return run(sql, params, true);
1060 },
1061 executeValues(sql, params) {
1062 return runValues(sql, params);
1063 },
1064 executeValuesUnprepared(sql, params) {
1065 return Effect.flatMap(prepare(sql), (statement) =>
1066 runStatement(statement, params ?? [], "values"),
1067 );
1068 },
1069 executeUnprepared(sql, params, rowTransform) {
1070 const effect = prepare(sql).pipe(
1071 Effect.flatMap((statement) => runStatement(statement, params ?? [])),
1072 );
1073 return rowTransform ? Effect.map(effect, rowTransform) : effect;
1074 },
1075 executeStream(_sql, _params) {
1076 return Stream.die(new UnsupportedNodeSqliteOperationError());
1077 },
1078 });
1079 });
1080
1081 const semaphore = yield* Semaphore.make(1);
1082 const connection = yield* makeConnection;
1083 // A reader that cannot start turns off the whole pool, so routing never picks a dead slot.
1084 const readerPool = { unavailable: false };
1085 const readers =
1086 options.readerWorker && isFileDatabase
1087 ? yield* Effect.forEach(Array.from({ length: READER_POOL_SIZE }), () =>
1088 Effect.map(
1089 Effect.all([makeReader(options, readerPool), Semaphore.make(1)]),
1090 ([acquire, lock]) => ({
1091 acquire,
1092 lock,
1093 claims: 0,
1094 }),
1095 ),
1096 )
1097 : [];
1098
1099 const writer = { name: "writer" as const, lock: semaphore, connection };
1100 let activeWriter: ConnectionOwner | undefined;
1101 // Callers must run route uninterruptibly and pass `claimed` a finalizer that runs `release` once.
1102 const route = (claimed: (release: Effect.Effect<void>) => Effect.Effect<void>) =>
1103 Effect.withFiber((fiber) => {
1104 if (readers.length === 0 || readerPool.unavailable || !Context.get(fiber.context, ReadOnly)) {
1105 return Effect.succeed(writer);
1106 }
1107 // Least claimed wins and ties go to the lowest slot, so idle slots never start a worker.
1108 let slot = readers[0]!;
1109 for (const candidate of readers) if (candidate.claims < slot.claims) slot = candidate;
1110 slot.claims++;
1111 const reader = slot;
1112 return Effect.andThen(
1113 claimed(
1114 Effect.sync(() => {
1115 reader.claims--;
1116 }),
1117 ),
1118 Effect.map(reader.acquire, (readerConnection) =>
1119 readerConnection === undefined
1120 ? writer
1121 : { name: "reader" as const, lock: reader.lock, connection: readerConnection },
1122 ),
1123 );
1124 });
1125
1126 const acquired = (
1127 target: { readonly name: Acquired["connection"] },
1128 clock: Clock.Clock,
1129 start: bigint,
1130 ): Acquired => ({
1131 connection: target.name,
1132 lockWaitMs: Number((clock.monotonicTimeNanosUnsafe() - start) / 1000n) / 1000,
1133 });
1134
1135 const writerBorrowBatchSize = 16;
1136 let writerBorrowsSinceYield = 0;
1137 const borrower: Borrower = (use) =>
1138 Effect.uninterruptibleMask((restore) => {
1139 let release: Effect.Effect<void> = Effect.void;
1140 const claimed = (next: Effect.Effect<void>) =>
1141 Effect.sync(() => {
1142 release = next;
1143 });
1144 return Effect.flatMap(route(claimed), (target) => restore(borrowTarget(target, use))).pipe(
1145 Effect.ensuring(Effect.suspend(() => release)),
1146 );
1147 });
1148 const borrowTarget = <A, E, R>(
1149 target: {
1150 readonly name: Acquired["connection"];
1151 readonly lock: Semaphore.Semaphore;
1152 readonly connection: Connection;
1153 },
1154 use: (connection: Connection) => Effect.Effect<A, E, R>,
1155 ): Effect.Effect<A, E, R> =>
1156 Effect.withFiber((fiber) => {
1157 const clock = fiber.getRef(Clock.Clock);
1158 const start = clock.monotonicTimeNanosUnsafe();
1159 const ownerAtWaitStart = target.name === "writer" ? activeWriter : undefined;
1160 const owner = target.name === "writer" ? connectionOwner(fiber) : undefined;
1161 const useConnection = Effect.suspend(() => {
1162 if (target.name === "writer") activeWriter = owner;
1163 if (
1164 fiber.getRef(References.TracerEnabled) &&
1165 fiber.getRef(Statement.SpanPropagationEnabled)
1166 ) {
1167 annotateAcquired(fiber, acquired(target, clock, start), ownerAtWaitStart);
1168 }
1169 return use(target.connection);
1170 });
1171 const useOwnedConnection =
1172 target.name === "writer"
1173 ? Effect.onExit(useConnection, () =>
1174 Effect.sync(() => {
1175 if (activeWriter === owner) activeWriter = undefined;
1176 }),
1177 )
1178 : useConnection;
1179 if (!options.checkpointWorker || target.name !== "writer") {
1180 return target.lock.withPermits(1)(useOwnedConnection);
1181 }
1182 const writerUse = Effect.onExit(useOwnedConnection, (exit) =>
1183 Effect.sync(() => {
1184 writerBorrowsSinceYield = Exit.hasInterrupts(exit)
1185 ? 0
1186 : Math.min(writerBorrowsSinceYield + 1, writerBorrowBatchSize);
1187 }),
1188 );
1189 return Effect.flatMap(target.lock.withPermitsIfAvailable(1)(writerUse), (result) =>
1190 Option.isSome(result)
1191 ? Effect.succeed(result.value)
1192 : target.lock.withPermits(1)(
1193 Effect.andThen(
1194 // Failed SQL also consumes the batch; cancellation hands off immediately.
1195 Effect.suspend(() => {
1196 if (writerBorrowsSinceYield < writerBorrowBatchSize) return Effect.void;
1197 writerBorrowsSinceYield = 0;
1198 return Effect.callback<void>((resume) => {
1199 const immediate = setImmediate(() => resume(Effect.void));
1200 return Effect.sync(() => clearImmediate(immediate));
1201 });
1202 }),
1203 writerUse,
1204 ),
1205 ),
1206 );
1207 });
1208 const claimedUntilScopeCloses = (release: Effect.Effect<void>) =>
1209 Effect.withFiber((fiber) =>
1210 Scope.addFinalizer(Context.getUnsafe(fiber.context, Scope.Scope), release),
1211 );
1212 const transactionAcquirer = Effect.uninterruptible(route(claimedUntilScopeCloses)).pipe(
1213 Effect.flatMap((target) =>
1214 Effect.uninterruptibleMask((restore) => {
1215 const fiber = Fiber.getCurrent()!;
1216 const scope = Context.getUnsafe(fiber.context, Scope.Scope);
1217 const clock = fiber.getRef(Clock.Clock);
1218 const start = clock.monotonicTimeNanosUnsafe();
1219 const pending = fiber.getRef(TransactionAcquire);
1220 const ownerAtWaitStart = target.name === "writer" ? activeWriter : undefined;
1221 const owner = target.name === "writer" ? connectionOwner(fiber) : undefined;
1222 const acquire = Effect.tap((pending?.restore ?? restore)(target.lock.take(1)), () => {
1223 if (target.name === "writer") activeWriter = owner;
1224 if (pending !== undefined) {
1225 pending.acquired = acquired(target, clock, start);
1226 pending.ownerAtWaitStart = ownerAtWaitStart;
1227 }
1228 return Scope.addFinalizer(
1229 scope,
1230 Effect.sync(() => {
1231 if (target.name === "writer" && activeWriter === owner) activeWriter = undefined;
1232 }).pipe(Effect.andThen(target.lock.release(1))),
1233 );
1234 });
1235 return Effect.as(
1236 // A scheduler yield after taking the permit must not precede its release finalizer.
1237 Effect.provideService(acquire, Scheduler.PreventSchedulerYield, true),
1238 target.connection,
1239 );
1240 }),
1241 ),
1242 );
1243
1244 const client = yield* Client.make({
1245 driver: "node:sqlite",
1246 acquirer: transactionAcquirer,
1247 borrower,
1248 compiler,
1249 transactionAcquirer,
1250 // BEGIN IMMEDIATE avoids read-then-write SQLITE_BUSY_SNAPSHOT, which busy_timeout cannot resolve.
1251 beginTransaction: options.readonly === true ? "BEGIN" : "BEGIN IMMEDIATE",
1252 spanAttributes: [
1253 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
1254 [ATTR_DB_SYSTEM_NAME, "sqlite"],
1255 ],
1256 });
1257 const withTransaction = client.withTransaction;
1258 return Object.assign(client, {
1259 withTransaction: <A, E, R>(effect: Effect.Effect<A, E, R>) =>
1260 Effect.uninterruptibleMask((restore) => {
1261 // SqlClient masks setup; acquisition must preserve the caller's interruptibility.
1262 const pending: {
1263 acquired?: Acquired;
1264 ownerAtWaitStart: ConnectionOwner | undefined;
1265 restore: typeof Effect.interruptible | undefined;
1266 } = {
1267 ownerAtWaitStart: undefined,
1268 restore,
1269 };
1270 const body = Effect.withFiber<A, E, R>((fiber) => {
1271 annotateAcquired(fiber, pending.acquired, pending.ownerAtWaitStart);
1272 pending.restore = undefined;
1273 return effect;
1274 });
1275 return restore(
1276 withTransaction(body).pipe(Effect.provideService(TransactionAcquire, pending)),
1277 );
1278 }),
1279 });
1280});
1281
1282export const layer = (config: SqliteClientConfig): Layer.Layer<Client.SqlClient, SqlError> =>
1283 Layer.effect(Client.SqlClient, make(config)).pipe(Layer.provide(Reactivity.layer));