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