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