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 const version = String(writer.prepare("SELECT sqlite_version() AS version").get()?.version);
633 const [major = 0, minor = 0] = version.split(".").map(Number);
634 // Older SQLite treats NOOP as PASSIVE, which would checkpoint on the writer.
635 if (major < 3 || (major === 3 && minor < 51)) {
636 yield* warn(`SQLite ${version} has no NOOP checkpoint`);
637 return undefined;
638 }
639 const frames = writer.prepare("PRAGMA wal_checkpoint(NOOP)");
640 const sizeLimit = writer.prepare("PRAGMA journal_size_limit");
641 const started = yield* Effect.try(
642 () =>
643 new NodeWorkerThreads.Worker(checkpointWorkerSource, {
644 eval: true,
645 workerData: {
646 filename,
647 frames: CHECKPOINT_FRAMES,
648 backpressureFrames: CHECKPOINT_BACKPRESSURE_FRAMES,
649 idleMs: CHECKPOINT_IDLE_MS,
650 },
651 }),
652 ).pipe(Effect.result);
653 if (Result.isFailure(started)) {
654 yield* warn(String(started.failure.cause));
655 return undefined;
656 }
657 const worker = started.success;
658 const runFork = Effect.runForkWith(yield* Effect.context<never>());
659 let stopped = false;
660 let generation = 0;
661 let nextId = 0;
662 let inFlight: number | undefined;
663 let checkAgain = false;
664 let blocked = false;
665 let log = 0;
666 let checkpointed = 0;
667 let unknown = false;
668 let truncate: { id: number; acknowledged: boolean } | undefined;
669 type Waiter = { resume: () => void; cancelled: boolean };
670 const waiters: Array<Waiter> = [];
671 let elected: Waiter | undefined;
672 const gated = () =>
673 !stopped &&
674 !writer.isTransaction &&
675 (unknown || blocked || truncate !== undefined || log >= CHECKPOINT_BACKPRESSURE_FRAMES);
676 const wake = () => {
677 if (!gated() && elected === undefined) {
678 elected = waiters.shift();
679 elected?.resume();
680 }
681 if (waiters.length === 0 && elected === undefined) worker.unref();
682 };
683 const release = (waiter: Waiter) => {
684 waiter.cancelled = true;
685 const index = waiters.indexOf(waiter);
686 if (index !== -1) waiters.splice(index, 1);
687 if (elected === waiter) elected = undefined;
688 wake();
689 };
690 const handBack = (reason: string) => {
691 if (stopped) return;
692 stopped = true;
693 truncate = undefined;
694 try {
695 writer.exec(`PRAGMA wal_autocheckpoint = ${CHECKPOINT_FRAMES};`);
696 } catch {}
697 wake();
698 runFork(warn(reason));
699 };
700 const send = (message: unknown) => {
701 try {
702 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
703 worker.postMessage(message);
704 } catch (cause) {
705 handBack(String(cause));
706 }
707 };
708 const acknowledge = () => {
709 if (truncate === undefined || truncate.acknowledged || stopped || writer.isTransaction) return;
710 truncate.acknowledged = true;
711 send({ type: "truncate", truncateId: truncate.id });
712 };
713 const observe = () => {
714 try {
715 const state = frames.get();
716 const nextLog = readSafeSqliteInteger(state?.log);
717 const nextCheckpointed = readSafeSqliteInteger(state?.checkpointed);
718 if (nextLog === undefined || nextCheckpointed === undefined)
719 throw new Error("Invalid WAL frame counts");
720 log = nextLog;
721 checkpointed = nextCheckpointed;
722 unknown = false;
723 } catch {
724 unknown = true;
725 }
726 };
727 const request = (force = false) => {
728 if (stopped || writer.isTransaction) return;
729 if (truncate !== undefined) {
730 acknowledge();
731 return;
732 }
733 if (inFlight !== undefined) {
734 checkAgain = true;
735 return;
736 }
737 if (!force && !gated() && log - checkpointed < CHECKPOINT_FRAMES) return;
738 inFlight = ++nextId;
739 try {
740 send({
741 type: "check",
742 id: inFlight,
743 generation,
744 journalSizeLimit: readSafeSqliteInteger(sizeLimit.get()?.journal_size_limit),
745 force: force || gated(),
746 });
747 } catch (cause) {
748 handBack(String(cause));
749 }
750 };
751 const check = () => {
752 if (stopped || writer.isTransaction) return;
753 generation++;
754 observe();
755 request();
756 wake();
757 };
758 worker.on("error", (cause) => handBack(cause.message));
759 worker.on("exit", (code) => handBack(`exited with code ${code}`));
760 worker.on("message", (message: unknown) => {
761 if (stopped || typeof message !== "object" || message === null || !("type" in message)) return;
762 if (
763 message.type === "truncate-request" &&
764 "truncateId" in message &&
765 typeof message.truncateId === "number"
766 ) {
767 truncate = { id: message.truncateId, acknowledged: false };
768 blocked = true;
769 acknowledge();
770 return;
771 }
772 if (message.type !== "checkpoint") return;
773 const completedTruncate =
774 truncate !== undefined && "truncateId" in message && message.truncateId === truncate.id;
775 if (completedTruncate) truncate = undefined;
776 // An acknowledged truncate excludes new writer mutations, so its result is current.
777 if (
778 (completedTruncate || ("generation" in message && message.generation === generation)) &&
779 "log" in message &&
780 typeof message.log === "number" &&
781 "checkpointed" in message &&
782 typeof message.checkpointed === "number" &&
783 "blocked" in message &&
784 typeof message.blocked === "boolean"
785 ) {
786 log = message.log;
787 checkpointed = message.checkpointed;
788 blocked = message.blocked;
789 unknown = false;
790 }
791 // Even a stale snapshot must retire its request so a newer check can run.
792 if ("id" in message && message.id === inFlight) inFlight = undefined;
793 if (checkAgain && inFlight === undefined) {
794 checkAgain = false;
795 request(true);
796 }
797 wake();
798 });
799 yield* Effect.addFinalizer(() =>
800 Effect.promise(() => {
801 stopped = true;
802 truncate = undefined;
803 wake();
804 return worker.terminate();
805 }),
806 );
807 writer.exec("PRAGMA wal_autocheckpoint = 0;");
808 observe();
809 worker.unref();
810
811 const runWithAdmission = <A, E>(
812 execute: () => Exit.Exit<A, E>,
813 admitted?: Waiter,
814 ): Effect.Effect<A, E> =>
815 Effect.suspend(() => {
816 if (!gated()) {
817 // Release the election after executing; its successor must see the new WAL state.
818 try {
819 return execute();
820 } finally {
821 if (admitted !== undefined) release(admitted);
822 }
823 }
824 if (admitted !== undefined) release(admitted);
825 const waiter: Waiter = { resume: () => {}, cancelled: false };
826 const wait = Effect.uninterruptibleMask((restore) =>
827 Effect.withFiber((fiber) =>
828 (fiber.getRef(TransactionAcquire)?.restore ?? restore)(
829 Effect.callback<void>(function (this: Scheduler.Scheduler, resume) {
830 const dispatcher = this.makeDispatcher();
831 waiter.resume = () => {
832 dispatcher.scheduleTask(() => {
833 if (!waiter.cancelled) resume(Effect.void);
834 }, 0);
835 };
836 waiters.push(waiter);
837 worker.ref();
838 request(true);
839 wake();
840 return Effect.sync(() => release(waiter));
841 }),
842 ),
843 ),
844 );
845 return wait.pipe(
846 Effect.flatMap(() => runWithAdmission(execute, waiter)),
847 Effect.onInterrupt(() => Effect.sync(() => release(waiter))),
848 );
849 });
850 return { check, runWithAdmission };
851});
852
853const make = Effect.fn("makeWithDatabase")(function* (
854 options: SqliteClientConfig,
855): Effect.fn.Return<Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity> {
856 yield* checkNodeSqliteCompat();
857
858 const compiler = Statement.makeCompilerSqlite();
859 const isFileDatabase = options.filename !== ":memory:" && options.filename !== "";
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: 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: 200,
982 // A transient prepare failure must not outlive the lock or missing schema.
983 timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.minutes(10) : Duration.zero),
984 });
985
986 const statementFor = (sql: string, params: ReadonlyArray<unknown>) =>
987 hasLargeBinding(params) ? prepare(sql) : Cache.get(prepareCache, sql);
988
989 const runStatement = (
990 statement: NodeSqlite.StatementSync,
991 params: ReadonlyArray<unknown>,
992 mode: "rows" | "raw" | "values" = "rows",
993 ) =>
994 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
995 const classification = checkpointClassifications.get(statement);
996 const execute = () => {
997 let arrays = false;
998 let result: Exit.Exit<ReadonlyArray<unknown>, SqlError>;
999 try {
1000 const value = withClassification(classification, () => {
1001 statement.setReadBigInts(Boolean(Context.get(fiber.context, Client.SafeIntegers)));
1002 if (hasRows(statement)) {
1003 arrays = mode === "values";
1004 if (arrays) statement.setReturnArrays(true);
1005 return statement.all(...(params as any));
1006 }
1007 const result = statement.run(...(params as any));
1008 return mode === "raw" ? (result as unknown as ReadonlyArray<unknown>) : [];
1009 });
1010 result = Exit.succeed(value);
1011 } catch (cause) {
1012 result = Exit.fail(
1013 new SqlError({
1014 reason: classifyError(cause, "Failed to execute statement", "execute"),
1015 }),
1016 );
1017 } finally {
1018 // OR FAIL may have committed earlier rows even when execution throws.
1019 if (classification?.check) checkpoint?.check();
1020 }
1021 if (arrays) {
1022 try {
1023 statement.setReturnArrays(false);
1024 } catch (cause) {
1025 return Exit.die(
1026 new SqlError({
1027 reason: classifyError(
1028 cause,
1029 "Failed to reset statement result mode",
1030 "resetResultMode",
1031 ),
1032 }),
1033 );
1034 }
1035 }
1036 return result;
1037 };
1038 return checkpoint !== undefined && classification?.backpressure
1039 ? checkpoint.runWithAdmission(execute)
1040 : execute();
1041 });
1042
1043 const run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
1044 Effect.flatMap(statementFor(sql, params), (statement) =>
1045 runStatement(statement, params, raw ? "raw" : "rows"),
1046 );
1047 const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
1048 Effect.flatMap(statementFor(sql, params), (statement) =>
1049 runStatement(statement, params, "values"),
1050 );
1051
1052 return identity<Connection>({
1053 execute(sql, params, rowTransform) {
1054 return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params);
1055 },
1056 executeRaw(sql, params) {
1057 return run(sql, params, true);
1058 },
1059 executeValues(sql, params) {
1060 return runValues(sql, params);
1061 },
1062 executeValuesUnprepared(sql, params) {
1063 return Effect.flatMap(prepare(sql), (statement) =>
1064 runStatement(statement, params ?? [], "values"),
1065 );
1066 },
1067 executeUnprepared(sql, params, rowTransform) {
1068 const effect = prepare(sql).pipe(
1069 Effect.flatMap((statement) => runStatement(statement, params ?? [])),
1070 );
1071 return rowTransform ? Effect.map(effect, rowTransform) : effect;
1072 },
1073 executeStream(_sql, _params) {
1074 return Stream.die(new UnsupportedNodeSqliteOperationError());
1075 },
1076 });
1077 });
1078
1079 const semaphore = yield* Semaphore.make(1);
1080 const connection = yield* makeConnection;
1081 // A reader that cannot start turns off the whole pool, so routing never picks a dead slot.
1082 const readerPool = { unavailable: false };
1083 const readers =
1084 options.readerWorker && isFileDatabase
1085 ? yield* Effect.forEach(Array.from({ length: READER_POOL_SIZE }), () =>
1086 Effect.map(
1087 Effect.all([makeReader(options, readerPool), Semaphore.make(1)]),
1088 ([acquire, lock]) => ({
1089 acquire,
1090 lock,
1091 claims: 0,
1092 }),
1093 ),
1094 )
1095 : [];
1096
1097 const writer = { name: "writer" as const, lock: semaphore, connection };
1098 let activeWriter: ConnectionOwner | undefined;
1099 // Callers must run route uninterruptibly and pass `claimed` a finalizer that runs `release` once.
1100 const route = (claimed: (release: Effect.Effect<void>) => Effect.Effect<void>) =>
1101 Effect.withFiber((fiber) => {
1102 if (readers.length === 0 || readerPool.unavailable || !Context.get(fiber.context, ReadOnly)) {
1103 return Effect.succeed(writer);
1104 }
1105 // Least claimed wins and ties go to the lowest slot, so idle slots never start a worker.
1106 let slot = readers[0]!;
1107 for (const candidate of readers) if (candidate.claims < slot.claims) slot = candidate;
1108 slot.claims++;
1109 const reader = slot;
1110 return Effect.andThen(
1111 claimed(
1112 Effect.sync(() => {
1113 reader.claims--;
1114 }),
1115 ),
1116 Effect.map(reader.acquire, (readerConnection) =>
1117 readerConnection === undefined
1118 ? writer
1119 : { name: "reader" as const, lock: reader.lock, connection: readerConnection },
1120 ),
1121 );
1122 });
1123
1124 const acquired = (
1125 target: { readonly name: Acquired["connection"] },
1126 clock: Clock.Clock,
1127 start: bigint,
1128 ): Acquired => ({
1129 connection: target.name,
1130 lockWaitMs: Number((clock.monotonicTimeNanosUnsafe() - start) / 1000n) / 1000,
1131 });
1132
1133 const writerBorrowBatchSize = 16;
1134 let writerBorrowsSinceYield = 0;
1135 const borrower: Borrower = (use) =>
1136 Effect.uninterruptibleMask((restore) => {
1137 let release: Effect.Effect<void> = Effect.void;
1138 const claimed = (next: Effect.Effect<void>) =>
1139 Effect.sync(() => {
1140 release = next;
1141 });
1142 return Effect.flatMap(route(claimed), (target) => restore(borrowTarget(target, use))).pipe(
1143 Effect.ensuring(Effect.suspend(() => release)),
1144 );
1145 });
1146 const borrowTarget = <A, E, R>(
1147 target: {
1148 readonly name: Acquired["connection"];
1149 readonly lock: Semaphore.Semaphore;
1150 readonly connection: Connection;
1151 },
1152 use: (connection: Connection) => Effect.Effect<A, E, R>,
1153 ): Effect.Effect<A, E, R> =>
1154 Effect.withFiber((fiber) => {
1155 const clock = fiber.getRef(Clock.Clock);
1156 const start = clock.monotonicTimeNanosUnsafe();
1157 const ownerAtWaitStart = target.name === "writer" ? activeWriter : undefined;
1158 const owner = target.name === "writer" ? connectionOwner(fiber) : undefined;
1159 const useConnection = Effect.suspend(() => {
1160 if (target.name === "writer") activeWriter = owner;
1161 if (
1162 fiber.getRef(References.TracerEnabled) &&
1163 fiber.getRef(Statement.SpanPropagationEnabled)
1164 ) {
1165 annotateAcquired(fiber, acquired(target, clock, start), ownerAtWaitStart);
1166 }
1167 return use(target.connection);
1168 });
1169 const useOwnedConnection =
1170 target.name === "writer"
1171 ? Effect.onExit(useConnection, () =>
1172 Effect.sync(() => {
1173 if (activeWriter === owner) activeWriter = undefined;
1174 }),
1175 )
1176 : useConnection;
1177 if (!options.checkpointWorker || target.name !== "writer") {
1178 return target.lock.withPermits(1)(useOwnedConnection);
1179 }
1180 const writerUse = Effect.onExit(useOwnedConnection, (exit) =>
1181 Effect.sync(() => {
1182 writerBorrowsSinceYield = Exit.hasInterrupts(exit)
1183 ? 0
1184 : Math.min(writerBorrowsSinceYield + 1, writerBorrowBatchSize);
1185 }),
1186 );
1187 return Effect.flatMap(target.lock.withPermitsIfAvailable(1)(writerUse), (result) =>
1188 Option.isSome(result)
1189 ? Effect.succeed(result.value)
1190 : target.lock.withPermits(1)(
1191 Effect.andThen(
1192 // Failed SQL also consumes the batch; cancellation hands off immediately.
1193 Effect.suspend(() => {
1194 if (writerBorrowsSinceYield < writerBorrowBatchSize) return Effect.void;
1195 writerBorrowsSinceYield = 0;
1196 return Effect.callback<void>((resume) => {
1197 const immediate = setImmediate(() => resume(Effect.void));
1198 return Effect.sync(() => clearImmediate(immediate));
1199 });
1200 }),
1201 writerUse,
1202 ),
1203 ),
1204 );
1205 });
1206 const claimedUntilScopeCloses = (release: Effect.Effect<void>) =>
1207 Effect.withFiber((fiber) =>
1208 Scope.addFinalizer(Context.getUnsafe(fiber.context, Scope.Scope), release),
1209 );
1210 const transactionAcquirer = Effect.uninterruptible(route(claimedUntilScopeCloses)).pipe(
1211 Effect.flatMap((target) =>
1212 Effect.uninterruptibleMask((restore) => {
1213 const fiber = Fiber.getCurrent()!;
1214 const scope = Context.getUnsafe(fiber.context, Scope.Scope);
1215 const clock = fiber.getRef(Clock.Clock);
1216 const start = clock.monotonicTimeNanosUnsafe();
1217 const pending = fiber.getRef(TransactionAcquire);
1218 const ownerAtWaitStart = target.name === "writer" ? activeWriter : undefined;
1219 const owner = target.name === "writer" ? connectionOwner(fiber) : undefined;
1220 const acquire = Effect.tap((pending?.restore ?? restore)(target.lock.take(1)), () => {
1221 if (target.name === "writer") activeWriter = owner;
1222 if (pending !== undefined) {
1223 pending.acquired = acquired(target, clock, start);
1224 pending.ownerAtWaitStart = ownerAtWaitStart;
1225 }
1226 return Scope.addFinalizer(
1227 scope,
1228 Effect.sync(() => {
1229 if (target.name === "writer" && activeWriter === owner) activeWriter = undefined;
1230 }).pipe(Effect.andThen(target.lock.release(1))),
1231 );
1232 });
1233 return Effect.as(
1234 // A scheduler yield after taking the permit must not precede its release finalizer.
1235 Effect.provideService(acquire, Scheduler.PreventSchedulerYield, true),
1236 target.connection,
1237 );
1238 }),
1239 ),
1240 );
1241
1242 const client = yield* Client.make({
1243 acquirer: transactionAcquirer,
1244 borrower,
1245 compiler,
1246 transactionAcquirer,
1247 // BEGIN IMMEDIATE avoids read-then-write SQLITE_BUSY_SNAPSHOT, which busy_timeout cannot resolve.
1248 beginTransaction: options.readonly === true ? "BEGIN" : "BEGIN IMMEDIATE",
1249 spanAttributes: [
1250 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
1251 [ATTR_DB_SYSTEM_NAME, "sqlite"],
1252 ],
1253 });
1254 const withTransaction = client.withTransaction;
1255 return Object.assign(client, {
1256 withTransaction: <A, E, R>(effect: Effect.Effect<A, E, R>) =>
1257 Effect.uninterruptibleMask((restore) => {
1258 // SqlClient masks setup; acquisition must preserve the caller's interruptibility.
1259 const pending: {
1260 acquired?: Acquired;
1261 ownerAtWaitStart: ConnectionOwner | undefined;
1262 restore: typeof Effect.interruptible | undefined;
1263 } = {
1264 ownerAtWaitStart: undefined,
1265 restore,
1266 };
1267 const body = Effect.withFiber<A, E, R>((fiber) => {
1268 annotateAcquired(fiber, pending.acquired, pending.ownerAtWaitStart);
1269 pending.restore = undefined;
1270 return effect;
1271 });
1272 return restore(
1273 withTransaction(body).pipe(Effect.provideService(TransactionAcquire, pending)),
1274 );
1275 }),
1276 });
1277});
1278
1279export const layer = (config: SqliteClientConfig): Layer.Layer<Client.SqlClient, SqlError> =>
1280 Layer.effect(Client.SqlClient, make(config)).pipe(Layer.provide(Reactivity.layer));