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// Bind transactions to one worker; fail after its exit instead of resuming outside the transaction on a replacement.
297const makeReader = Effect.fnUntraced(function* (options: SqliteClientConfig) {
298 let current:
299 | {
300 readonly worker: NodeWorkerThreads.Worker;
301 readonly connection: Connection;
302 readonly started: Promise<ReaderStartup>;
303 }
304 | undefined;
305 let unavailable = false;
306 let nextRequestId = 0;
307
308 const start = () => {
309 const worker = new NodeWorkerThreads.Worker(readerWorkerSource, {
310 eval: true,
311 workerData: {
312 filename: options.filename,
313 allowExtension: false,
314 prepareCacheSize: 200,
315 },
316 });
317 let announce: (startup: ReaderStartup) => void = () => {};
318 const started = new Promise<ReaderStartup>((resolve) => {
319 announce = resolve;
320 });
321 let stoppedMessage: string | undefined;
322 const pending = new Map<
323 number,
324 { readonly endsTransaction: boolean; readonly resume: (reply: ReaderReply) => void }
325 >();
326 const stop = (message: string) => {
327 stoppedMessage = message;
328 announce({ type: "unavailable", message });
329 if (current?.worker === worker) current = undefined;
330 for (const [id, request] of pending) {
331 request.resume(
332 request.endsTransaction
333 ? { id, rows: [] }
334 : { id, error: { operation: "execute", message } },
335 );
336 }
337 pending.clear();
338 };
339 worker.on("message", (reply: ReaderReply | ReaderStartup) => {
340 if ("type" in reply) {
341 announce(reply);
342 if (pending.size === 0) worker.unref();
343 return;
344 }
345 const request = pending.get(reply.id);
346 if (request === undefined) return;
347 pending.delete(reply.id);
348 if (pending.size === 0) worker.unref();
349 request.resume(reply);
350 });
351 worker.on("error", (cause) => stop(`Database reader failed: ${cause.message}`));
352 worker.on("exit", (code) => stop(`Database reader exited with code ${code}`));
353
354 const request = (input: ReaderRequest) =>
355 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
356 const endsTransaction = endsReadTransaction(input.sql);
357 if (stoppedMessage !== undefined) {
358 return endsTransaction
359 ? Effect.succeed([])
360 : Effect.fail(
361 failed(new Error(stoppedMessage), readerFailureMessages.execute, "execute"),
362 );
363 }
364 const safeIntegers = Boolean(Context.get(fiber.context, Client.SafeIntegers));
365 return Effect.callback<ReadonlyArray<any>, SqlError>((resume) => {
366 const id = nextRequestId++;
367 pending.set(id, {
368 endsTransaction,
369 resume: (reply) => {
370 if ("rows" in reply) {
371 resume(Effect.succeed(reply.rows));
372 return;
373 }
374 const { operation, message, ...codes } = reply.error;
375 resume(
376 Effect.fail(
377 failed(
378 Object.assign(new Error(message), codes),
379 readerFailureMessages[operation],
380 operation,
381 ),
382 ),
383 );
384 },
385 });
386 if (pending.size === 1) worker.ref();
387 const cached = input.cached && !hasLargeBinding(input.params);
388 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
389 worker.postMessage({ id, safeIntegers, ...input, cached });
390 });
391 });
392
393 const connection = identity<Connection>({
394 execute(sql, params, rowTransform) {
395 const effect = request({ sql, params, cached: true, values: false, raw: false });
396 return rowTransform ? Effect.map(effect, rowTransform) : effect;
397 },
398 executeRaw(sql, params) {
399 return request({ sql, params, cached: true, values: false, raw: true });
400 },
401 executeValues(sql, params) {
402 return request({ sql, params, cached: true, values: true, raw: false });
403 },
404 executeValuesUnprepared(sql, params) {
405 return request({ sql, params: params ?? [], cached: false, values: true, raw: false });
406 },
407 executeUnprepared(sql, params, rowTransform) {
408 // Read snapshots need deferred BEGIN; readonly connections reject IMMEDIATE and EXCLUSIVE.
409 const statement = /^\s*BEGIN\b/i.test(sql) ? "BEGIN" : sql;
410 const effect = request({
411 sql: statement,
412 params: params ?? [],
413 cached: false,
414 values: false,
415 raw: false,
416 });
417 return rowTransform ? Effect.map(effect, rowTransform) : effect;
418 },
419 executeStream(_sql, _params) {
420 return Stream.die(new UnsupportedNodeSqliteOperationError());
421 },
422 });
423 current = { worker, connection, started };
424 return current;
425 };
426
427 yield* Effect.addFinalizer(() =>
428 Effect.promise(async () => {
429 await current?.worker.terminate();
430 }),
431 );
432
433 const startupTimeout = Duration.seconds(10);
434
435 const turnOff = (reader: typeof current, reason: string) =>
436 Effect.suspend(() => {
437 if (reader !== undefined) {
438 if (current === reader) current = undefined;
439 void reader.worker.terminate();
440 }
441 // @effect-diagnostics-next-line effectSucceedWithVoid:off - The connection result distinguishes undefined from void.
442 if (unavailable) return Effect.succeed(undefined);
443 unavailable = true;
444 return Effect.logWarning("SQLite reader worker unavailable; reads use the main connection", {
445 reason,
446 }).pipe(Effect.as(undefined));
447 });
448
449 return Effect.suspend((): Effect.Effect<Connection | undefined> => {
450 // @effect-diagnostics-next-line effectSucceedWithVoid:off - The connection result distinguishes undefined from void.
451 if (unavailable) return Effect.succeed(undefined);
452 let reader: NonNullable<typeof current>;
453 try {
454 reader = current ?? start();
455 } catch (cause) {
456 return turnOff(undefined, String(cause));
457 }
458 return Effect.flatMap(
459 Effect.withFiber((fiber) => {
460 const restore = Context.get(fiber.context, ReadOnly) ?? identity;
461 return restore(
462 Effect.timeoutOption(
463 Effect.promise(() => reader.started),
464 startupTimeout,
465 ),
466 );
467 }),
468 (startup): Effect.Effect<Connection | undefined> =>
469 // A late ready event must not hand out a worker retired by another acquire timeout.
470 unavailable || current !== reader
471 ? // @effect-diagnostics-next-line effectSucceedWithVoid:off - The connection result distinguishes undefined from void.
472 Effect.succeed(undefined)
473 : Option.isSome(startup) && startup.value.type === "ready"
474 ? Effect.succeed(reader.connection)
475 : turnOff(
476 reader,
477 Option.isSome(startup) && startup.value.type === "unavailable"
478 ? startup.value.message
479 : `worker did not open the database within ${Duration.toMillis(startupTimeout)} ms`,
480 ),
481 );
482 });
483});
484
485const CHECKPOINT_FRAMES = 1000;
486const CHECKPOINT_IDLE_MS = 100;
487const CHECKPOINT_BACKPRESSURE_FRAMES = 10 * CHECKPOINT_FRAMES;
488
489const readSafeSqliteInteger = (value: unknown) => {
490 const number = typeof value === "bigint" ? Number(value) : value;
491 return typeof number === "number" && Number.isSafeInteger(number) ? number : undefined;
492};
493
494// Evaluated source also works in bundles and single-executable builds.
495const checkpointWorkerSource = `
496const { parentPort, workerData } = require("node:worker_threads");
497const { DatabaseSync } = require("node:sqlite");
498const { statSync } = require("node:fs");
499let db;
500let frames;
501let checkpoint;
502let truncate;
503let journalSizeLimit = -1;
504let generation = 0;
505let nextTruncateId = 0;
506let pendingTruncate;
507let pendingBarriers = 0;
508let idle;
509const initialize = () => {
510 if (db !== undefined) return;
511 // The writer switches to WAL after constructing the client.
512 db = new DatabaseSync(workerData.filename);
513 db.exec("PRAGMA busy_timeout = 5000;");
514 const mode = String(db.prepare("PRAGMA journal_mode").get().journal_mode).toLowerCase();
515 if (mode !== "wal") throw new Error("database uses journal_mode " + mode + ", not wal");
516 // macOS requires F_FULLFSYNC to flush the drive cache.
517 db.exec("PRAGMA checkpoint_fullfsync = ON;");
518 frames = db.prepare("PRAGMA wal_checkpoint(NOOP)");
519 checkpoint = db.prepare("PRAGMA wal_checkpoint(PASSIVE)");
520 truncate = db.prepare("PRAGMA wal_checkpoint(TRUNCATE)");
521};
522const atCeiling = (state) => state.log >= workerData.backpressureFrames;
523const exceedsSizeLimit = () =>
524 journalSizeLimit >= 0 && statSync(workerData.filename + "-wal").size > journalSizeLimit;
525const schedule = (state, blocked) => {
526 if (blocked || state.log - state.checkpointed >= workerData.frames) {
527 idle = setTimeout(() => check(undefined, undefined, true), workerData.idleMs);
528 }
529};
530const check = (id, nextJournalSizeLimit, force, nextGeneration = generation) => {
531 initialize();
532 if (Number.isSafeInteger(nextGeneration)) generation = Math.max(generation, nextGeneration);
533 if (Number.isSafeInteger(nextJournalSizeLimit)) journalSizeLimit = nextJournalSizeLimit;
534 let state = frames.get();
535 const oversized = exceedsSizeLimit();
536 if (force || state.log - state.checkpointed >= workerData.frames || oversized) {
537 checkpoint.get();
538 state = frames.get();
539 }
540 if (state.checkpointed === state.log && (atCeiling(state) || oversized)) {
541 pendingTruncate = { truncateId: ++nextTruncateId, checkId: id, generation, state };
542 parentPort.postMessage({
543 type: "truncate-request",
544 truncateId: pendingTruncate.truncateId,
545 checkId: id,
546 generation,
547 ...state,
548 });
549 return;
550 }
551 const blocked = (atCeiling(state) || oversized) && state.checkpointed < state.log;
552 parentPort.postMessage({ type: "checkpoint", id, generation, ...state, blocked });
553 schedule(state, blocked);
554};
555const finishTruncate = (truncateId) => {
556 if (pendingTruncate === undefined || pendingTruncate.truncateId !== truncateId) return;
557 const pending = pendingTruncate;
558 parentPort.postMessage({ type: "truncate-start", truncateId });
559 let busy;
560 // Admission is paused here; a pinned reader must not make truncation wait.
561 db.exec("PRAGMA busy_timeout = 0;");
562 try {
563 busy = truncate.get().busy !== 0;
564 } finally {
565 db.exec("PRAGMA busy_timeout = 5000;");
566 }
567 const state = frames.get();
568 const blocked = (atCeiling(state) && (busy || state.checkpointed < state.log)) || exceedsSizeLimit();
569 pendingTruncate = undefined;
570 parentPort.postMessage({
571 type: "checkpoint",
572 id: pending.checkId,
573 generation: pending.generation,
574 truncateId,
575 ...state,
576 blocked,
577 });
578 while (pendingBarriers > 0) {
579 pendingBarriers--;
580 parentPort.postMessage("barrier");
581 }
582 schedule(state, blocked);
583};
584parentPort.on("message", (request) => {
585 clearTimeout(idle);
586 if (request && request.type === "truncate") {
587 finishTruncate(request.truncateId);
588 return;
589 }
590 const isBarrier = request === "barrier";
591 if (pendingTruncate !== undefined) {
592 if (isBarrier) pendingBarriers++;
593 else if (request && request.type === "check") {
594 // Retire the request without labeling the pending snapshot with a newer generation.
595 parentPort.postMessage({
596 type: "checkpoint",
597 id: request.id,
598 generation: pendingTruncate.generation,
599 ...pendingTruncate.state,
600 blocked: true,
601 });
602 }
603 return;
604 }
605 const input = request && typeof request === "object" ? request : {};
606 check(input.id, input.journalSizeLimit, input.force, input.generation);
607 if (isBarrier) {
608 if (pendingTruncate !== undefined) pendingBarriers++;
609 else parentPort.postMessage("barrier");
610 }
611});
612`;
613
614const startCheckpointWorker = Effect.fnUntraced(function* (
615 filename: string,
616 writer: NodeSqlite.DatabaseSync,
617) {
618 const warn = (reason: string) =>
619 Effect.logWarning(
620 "SQLite checkpoint worker unavailable; checkpoints run on the main connection",
621 { reason },
622 );
623 if (typeof writer.isTransaction !== "boolean" || typeof writer.setAuthorizer !== "function") {
624 yield* warn("Node SQLite lacks transaction-state or statement-authorizer support");
625 return undefined;
626 }
627 const version = String(writer.prepare("SELECT sqlite_version() AS version").get()?.version);
628 const [major = 0, minor = 0] = version.split(".").map(Number);
629 // Older SQLite treats NOOP as PASSIVE, which would checkpoint on the writer.
630 if (major < 3 || (major === 3 && minor < 51)) {
631 yield* warn(`SQLite ${version} has no NOOP checkpoint`);
632 return undefined;
633 }
634 const frames = writer.prepare("PRAGMA wal_checkpoint(NOOP)");
635 const sizeLimit = writer.prepare("PRAGMA journal_size_limit");
636 const started = yield* Effect.try(
637 () =>
638 new NodeWorkerThreads.Worker(checkpointWorkerSource, {
639 eval: true,
640 workerData: {
641 filename,
642 frames: CHECKPOINT_FRAMES,
643 backpressureFrames: CHECKPOINT_BACKPRESSURE_FRAMES,
644 idleMs: CHECKPOINT_IDLE_MS,
645 },
646 }),
647 ).pipe(Effect.result);
648 if (Result.isFailure(started)) {
649 yield* warn(String(started.failure.cause));
650 return undefined;
651 }
652 const worker = started.success;
653 const runFork = Effect.runForkWith(yield* Effect.context<never>());
654 let stopped = false;
655 let generation = 0;
656 let nextId = 0;
657 let inFlight: number | undefined;
658 let checkAgain = false;
659 let blocked = false;
660 let log = 0;
661 let checkpointed = 0;
662 let unknown = false;
663 let truncate: { id: number; acknowledged: boolean } | undefined;
664 type Waiter = { resume: () => void; cancelled: boolean };
665 const waiters: Array<Waiter> = [];
666 let elected: Waiter | undefined;
667 const gated = () =>
668 !stopped &&
669 !writer.isTransaction &&
670 (unknown || blocked || truncate !== undefined || log >= CHECKPOINT_BACKPRESSURE_FRAMES);
671 const wake = () => {
672 if (!gated() && elected === undefined) {
673 elected = waiters.shift();
674 elected?.resume();
675 }
676 if (waiters.length === 0 && elected === undefined) worker.unref();
677 };
678 const release = (waiter: Waiter) => {
679 waiter.cancelled = true;
680 const index = waiters.indexOf(waiter);
681 if (index !== -1) waiters.splice(index, 1);
682 if (elected === waiter) elected = undefined;
683 wake();
684 };
685 const handBack = (reason: string) => {
686 if (stopped) return;
687 stopped = true;
688 truncate = undefined;
689 try {
690 writer.exec(`PRAGMA wal_autocheckpoint = ${CHECKPOINT_FRAMES};`);
691 } catch {}
692 wake();
693 runFork(warn(reason));
694 };
695 const send = (message: unknown) => {
696 try {
697 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
698 worker.postMessage(message);
699 } catch (cause) {
700 handBack(String(cause));
701 }
702 };
703 const acknowledge = () => {
704 if (truncate === undefined || truncate.acknowledged || stopped || writer.isTransaction) return;
705 truncate.acknowledged = true;
706 send({ type: "truncate", truncateId: truncate.id });
707 };
708 const observe = () => {
709 try {
710 const state = frames.get();
711 const nextLog = readSafeSqliteInteger(state?.log);
712 const nextCheckpointed = readSafeSqliteInteger(state?.checkpointed);
713 if (nextLog === undefined || nextCheckpointed === undefined)
714 throw new Error("Invalid WAL frame counts");
715 log = nextLog;
716 checkpointed = nextCheckpointed;
717 unknown = false;
718 } catch {
719 unknown = true;
720 }
721 };
722 const request = (force = false) => {
723 if (stopped || writer.isTransaction) return;
724 if (truncate !== undefined) {
725 acknowledge();
726 return;
727 }
728 if (inFlight !== undefined) {
729 checkAgain = true;
730 return;
731 }
732 if (!force && !gated() && log - checkpointed < CHECKPOINT_FRAMES) return;
733 inFlight = ++nextId;
734 try {
735 send({
736 type: "check",
737 id: inFlight,
738 generation,
739 journalSizeLimit: readSafeSqliteInteger(sizeLimit.get()?.journal_size_limit),
740 force: force || gated(),
741 });
742 } catch (cause) {
743 handBack(String(cause));
744 }
745 };
746 const check = () => {
747 if (stopped || writer.isTransaction) return;
748 generation++;
749 observe();
750 request();
751 wake();
752 };
753 worker.on("error", (cause) => handBack(cause.message));
754 worker.on("exit", (code) => handBack(`exited with code ${code}`));
755 worker.on("message", (message: unknown) => {
756 if (stopped || typeof message !== "object" || message === null || !("type" in message)) return;
757 if (
758 message.type === "truncate-request" &&
759 "truncateId" in message &&
760 typeof message.truncateId === "number"
761 ) {
762 truncate = { id: message.truncateId, acknowledged: false };
763 blocked = true;
764 acknowledge();
765 return;
766 }
767 if (message.type !== "checkpoint") return;
768 const completedTruncate =
769 truncate !== undefined && "truncateId" in message && message.truncateId === truncate.id;
770 if (completedTruncate) truncate = undefined;
771 // An acknowledged truncate excludes new writer mutations, so its result is current.
772 if (
773 (completedTruncate || ("generation" in message && message.generation === generation)) &&
774 "log" in message &&
775 typeof message.log === "number" &&
776 "checkpointed" in message &&
777 typeof message.checkpointed === "number" &&
778 "blocked" in message &&
779 typeof message.blocked === "boolean"
780 ) {
781 log = message.log;
782 checkpointed = message.checkpointed;
783 blocked = message.blocked;
784 unknown = false;
785 }
786 // Even a stale snapshot must retire its request so a newer check can run.
787 if ("id" in message && message.id === inFlight) inFlight = undefined;
788 if (checkAgain && inFlight === undefined) {
789 checkAgain = false;
790 request(true);
791 }
792 wake();
793 });
794 yield* Effect.addFinalizer(() =>
795 Effect.promise(() => {
796 stopped = true;
797 truncate = undefined;
798 wake();
799 return worker.terminate();
800 }),
801 );
802 writer.exec("PRAGMA wal_autocheckpoint = 0;");
803 observe();
804 worker.unref();
805
806 const runWithAdmission = <A, E>(
807 execute: () => Exit.Exit<A, E>,
808 admitted?: Waiter,
809 ): Effect.Effect<A, E> =>
810 Effect.suspend(() => {
811 if (!gated()) {
812 // Release the election after executing; its successor must see the new WAL state.
813 try {
814 return execute();
815 } finally {
816 if (admitted !== undefined) release(admitted);
817 }
818 }
819 if (admitted !== undefined) release(admitted);
820 const waiter: Waiter = { resume: () => {}, cancelled: false };
821 const wait = Effect.uninterruptibleMask((restore) =>
822 Effect.withFiber((fiber) =>
823 (fiber.getRef(TransactionAcquire)?.restore ?? restore)(
824 Effect.callback<void>(function (this: Scheduler.Scheduler, resume) {
825 const dispatcher = this.makeDispatcher();
826 waiter.resume = () => {
827 dispatcher.scheduleTask(() => {
828 if (!waiter.cancelled) resume(Effect.void);
829 }, 0);
830 };
831 waiters.push(waiter);
832 worker.ref();
833 request(true);
834 wake();
835 return Effect.sync(() => release(waiter));
836 }),
837 ),
838 ),
839 );
840 return wait.pipe(
841 Effect.flatMap(() => runWithAdmission(execute, waiter)),
842 Effect.onInterrupt(() => Effect.sync(() => release(waiter))),
843 );
844 });
845 return { check, runWithAdmission };
846});
847
848const make = Effect.fn("makeWithDatabase")(function* (
849 options: SqliteClientConfig,
850): Effect.fn.Return<Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity> {
851 yield* checkNodeSqliteCompat();
852
853 const compiler = Statement.makeCompilerSqlite();
854 const isFileDatabase = options.filename !== ":memory:" && options.filename !== "";
855
856 const makeConnection = Effect.gen(function* () {
857 const scope = yield* Effect.scope;
858 const db = yield* Effect.try({
859 try: () =>
860 new NodeSqlite.DatabaseSync(options.filename, {
861 readOnly: options.readonly ?? false,
862 allowExtension: false,
863 }),
864 catch: (cause) =>
865 new SqlError({
866 reason: classifyError(cause, "Failed to open database", "open"),
867 }),
868 });
869 yield* Scope.addFinalizer(
870 scope,
871 Effect.try({
872 try: () => db.close(),
873 catch: (cause) =>
874 new SqlError({
875 reason: classifyError(cause, "Failed to close database", "close"),
876 }),
877 }).pipe(Effect.orDie),
878 );
879 // Started after the close finalizer, so the worker stops before the writer closes.
880 const checkpoint =
881 options.checkpointWorker && isFileDatabase
882 ? yield* startCheckpointWorker(options.filename, db)
883 : undefined;
884
885 const statementReaderCache = new WeakMap<NodeSqlite.StatementSync, boolean>();
886 interface CheckpointClassification {
887 backpressure: boolean;
888 check: boolean;
889 }
890 const checkpointClassifications = new WeakMap<
891 NodeSqlite.StatementSync,
892 CheckpointClassification
893 >();
894 const mutatingPragmasWithValues = new Set([
895 "application_id",
896 "auto_vacuum",
897 "journal_mode",
898 "schema_version",
899 "user_version",
900 ]);
901 const mutatesPragma = (name: string | null, value: string | null) => {
902 const pragma = name?.toLowerCase();
903 if (pragma === undefined) return false;
904 if (pragma === "incremental_vacuum" || pragma === "optimize") return true;
905 if (pragma === "wal_checkpoint") return value?.toLowerCase() !== "noop";
906 return value !== null && mutatingPragmasWithValues.has(pragma);
907 };
908 let activeClassification: CheckpointClassification | undefined;
909 const withClassification = <A>(
910 classification: CheckpointClassification | undefined,
911 f: () => A,
912 ): A => {
913 if (classification === undefined) return f();
914 const previous = activeClassification;
915 activeClassification = classification;
916 try {
917 return f();
918 } finally {
919 activeClassification = previous;
920 }
921 };
922 if (checkpoint !== undefined) {
923 // SQLite may reprepare an expired statement while it executes. Keep this
924 // callback installed and collect only around that statement's prepare/run.
925 db.setAuthorizer((actionCode, action, argument) => {
926 const classification = activeClassification;
927 if (classification === undefined) return NodeSqlite.constants.SQLITE_OK;
928 const constants = NodeSqlite.constants;
929 if (actionCode === constants.SQLITE_TRANSACTION) {
930 classification.backpressure ||= action === "BEGIN";
931 classification.check ||= action === "COMMIT" || action === "ROLLBACK";
932 } else if (actionCode === constants.SQLITE_SAVEPOINT) {
933 classification.backpressure ||= action === "BEGIN";
934 classification.check = true;
935 } else if (actionCode === constants.SQLITE_PRAGMA && mutatesPragma(action, argument)) {
936 classification.backpressure = true;
937 classification.check = true;
938 } else if (
939 actionCode !== constants.SQLITE_READ &&
940 actionCode !== constants.SQLITE_SELECT &&
941 actionCode !== constants.SQLITE_FUNCTION &&
942 actionCode !== constants.SQLITE_RECURSIVE &&
943 actionCode !== constants.SQLITE_PRAGMA
944 ) {
945 classification.backpressure = true;
946 classification.check = true;
947 }
948 return constants.SQLITE_OK;
949 });
950 }
951 const hasRows = (statement: NodeSqlite.StatementSync): boolean => {
952 const cached = statementReaderCache.get(statement);
953 if (cached !== undefined) {
954 return cached;
955 }
956 const value = statement.columns().length > 0;
957 statementReaderCache.set(statement, value);
958 return value;
959 };
960
961 const prepare = (sql: string) =>
962 Effect.try({
963 try: () => {
964 const classification = { backpressure: false, check: false };
965 const statement = withClassification(classification, () => db.prepare(sql));
966 if (checkpoint !== undefined) checkpointClassifications.set(statement, classification);
967 return statement;
968 },
969 catch: (cause) =>
970 new SqlError({
971 reason: classifyError(cause, "Failed to prepare statement", "prepare"),
972 }),
973 });
974
975 const prepareCache = yield* Cache.makeWith(prepare, {
976 capacity: 200,
977 // A transient prepare failure must not outlive the lock or missing schema.
978 timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.minutes(10) : Duration.zero),
979 });
980
981 const statementFor = (sql: string, params: ReadonlyArray<unknown>) =>
982 hasLargeBinding(params) ? prepare(sql) : Cache.get(prepareCache, sql);
983
984 const runStatement = (
985 statement: NodeSqlite.StatementSync,
986 params: ReadonlyArray<unknown>,
987 mode: "rows" | "raw" | "values" = "rows",
988 ) =>
989 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
990 const classification = checkpointClassifications.get(statement);
991 const execute = () => {
992 let arrays = false;
993 let result: Exit.Exit<ReadonlyArray<unknown>, SqlError>;
994 try {
995 const value = withClassification(classification, () => {
996 statement.setReadBigInts(Boolean(Context.get(fiber.context, Client.SafeIntegers)));
997 if (hasRows(statement)) {
998 arrays = mode === "values";
999 if (arrays) statement.setReturnArrays(true);
1000 return statement.all(...(params as any));
1001 }
1002 const result = statement.run(...(params as any));
1003 return mode === "raw" ? (result as unknown as ReadonlyArray<unknown>) : [];
1004 });
1005 result = Exit.succeed(value);
1006 } catch (cause) {
1007 result = Exit.fail(
1008 new SqlError({
1009 reason: classifyError(cause, "Failed to execute statement", "execute"),
1010 }),
1011 );
1012 } finally {
1013 // OR FAIL may have committed earlier rows even when execution throws.
1014 if (classification?.check) checkpoint?.check();
1015 }
1016 if (arrays) {
1017 try {
1018 statement.setReturnArrays(false);
1019 } catch (cause) {
1020 return Exit.die(
1021 new SqlError({
1022 reason: classifyError(
1023 cause,
1024 "Failed to reset statement result mode",
1025 "resetResultMode",
1026 ),
1027 }),
1028 );
1029 }
1030 }
1031 return result;
1032 };
1033 return checkpoint !== undefined && classification?.backpressure
1034 ? checkpoint.runWithAdmission(execute)
1035 : execute();
1036 });
1037
1038 const run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
1039 Effect.flatMap(statementFor(sql, params), (statement) =>
1040 runStatement(statement, params, raw ? "raw" : "rows"),
1041 );
1042 const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
1043 Effect.flatMap(statementFor(sql, params), (statement) =>
1044 runStatement(statement, params, "values"),
1045 );
1046
1047 return identity<Connection>({
1048 execute(sql, params, rowTransform) {
1049 return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params);
1050 },
1051 executeRaw(sql, params) {
1052 return run(sql, params, true);
1053 },
1054 executeValues(sql, params) {
1055 return runValues(sql, params);
1056 },
1057 executeValuesUnprepared(sql, params) {
1058 return Effect.flatMap(prepare(sql), (statement) =>
1059 runStatement(statement, params ?? [], "values"),
1060 );
1061 },
1062 executeUnprepared(sql, params, rowTransform) {
1063 const effect = prepare(sql).pipe(
1064 Effect.flatMap((statement) => runStatement(statement, params ?? [])),
1065 );
1066 return rowTransform ? Effect.map(effect, rowTransform) : effect;
1067 },
1068 executeStream(_sql, _params) {
1069 return Stream.die(new UnsupportedNodeSqliteOperationError());
1070 },
1071 });
1072 });
1073
1074 const semaphore = yield* Semaphore.make(1);
1075 const connection = yield* makeConnection;
1076 const acquireReader =
1077 options.readerWorker && isFileDatabase ? yield* makeReader(options) : undefined;
1078 const readerSemaphore = yield* Semaphore.make(1);
1079
1080 const writer = { name: "writer" as const, lock: semaphore, connection };
1081 let activeWriter: ConnectionOwner | undefined;
1082 const route = Effect.withFiber((fiber) =>
1083 acquireReader !== undefined && Context.get(fiber.context, ReadOnly)
1084 ? Effect.map(acquireReader, (readerConnection) =>
1085 readerConnection === undefined
1086 ? writer
1087 : { name: "reader" as const, lock: readerSemaphore, connection: readerConnection },
1088 )
1089 : Effect.succeed(writer),
1090 );
1091
1092 const acquired = (
1093 target: { readonly name: Acquired["connection"] },
1094 clock: Clock.Clock,
1095 start: bigint,
1096 ): Acquired => ({
1097 connection: target.name,
1098 lockWaitMs: Number((clock.monotonicTimeNanosUnsafe() - start) / 1000n) / 1000,
1099 });
1100
1101 const writerBorrowBatchSize = 16;
1102 let writerBorrowsSinceYield = 0;
1103 const borrower: Borrower = (use) =>
1104 Effect.flatMap(route, (target) =>
1105 Effect.withFiber((fiber) => {
1106 const clock = fiber.getRef(Clock.Clock);
1107 const start = clock.monotonicTimeNanosUnsafe();
1108 const ownerAtWaitStart = target.name === "writer" ? activeWriter : undefined;
1109 const owner = target.name === "writer" ? connectionOwner(fiber) : undefined;
1110 const useConnection = Effect.suspend(() => {
1111 if (target.name === "writer") activeWriter = owner;
1112 if (
1113 fiber.getRef(References.TracerEnabled) &&
1114 fiber.getRef(Statement.SpanPropagationEnabled)
1115 ) {
1116 annotateAcquired(fiber, acquired(target, clock, start), ownerAtWaitStart);
1117 }
1118 return use(target.connection);
1119 });
1120 const useOwnedConnection =
1121 target.name === "writer"
1122 ? Effect.onExit(useConnection, () =>
1123 Effect.sync(() => {
1124 if (activeWriter === owner) activeWriter = undefined;
1125 }),
1126 )
1127 : useConnection;
1128 if (!options.checkpointWorker || target.name !== "writer") {
1129 return target.lock.withPermits(1)(useOwnedConnection);
1130 }
1131 const writerUse = Effect.onExit(useOwnedConnection, (exit) =>
1132 Effect.sync(() => {
1133 writerBorrowsSinceYield = Exit.hasInterrupts(exit)
1134 ? 0
1135 : Math.min(writerBorrowsSinceYield + 1, writerBorrowBatchSize);
1136 }),
1137 );
1138 return Effect.flatMap(target.lock.withPermitsIfAvailable(1)(writerUse), (result) =>
1139 Option.isSome(result)
1140 ? Effect.succeed(result.value)
1141 : target.lock.withPermits(1)(
1142 Effect.andThen(
1143 // Failed SQL also consumes the batch; cancellation hands off immediately.
1144 Effect.suspend(() => {
1145 if (writerBorrowsSinceYield < writerBorrowBatchSize) return Effect.void;
1146 writerBorrowsSinceYield = 0;
1147 return Effect.callback<void>((resume) => {
1148 const immediate = setImmediate(() => resume(Effect.void));
1149 return Effect.sync(() => clearImmediate(immediate));
1150 });
1151 }),
1152 writerUse,
1153 ),
1154 ),
1155 );
1156 }),
1157 );
1158 const transactionAcquirer = Effect.flatMap(route, (target) =>
1159 Effect.uninterruptibleMask((restore) => {
1160 const fiber = Fiber.getCurrent()!;
1161 const scope = Context.getUnsafe(fiber.context, Scope.Scope);
1162 const clock = fiber.getRef(Clock.Clock);
1163 const start = clock.monotonicTimeNanosUnsafe();
1164 const pending = fiber.getRef(TransactionAcquire);
1165 const ownerAtWaitStart = target.name === "writer" ? activeWriter : undefined;
1166 const owner = target.name === "writer" ? connectionOwner(fiber) : undefined;
1167 const acquire = Effect.tap((pending?.restore ?? restore)(target.lock.take(1)), () => {
1168 if (target.name === "writer") activeWriter = owner;
1169 if (pending !== undefined) {
1170 pending.acquired = acquired(target, clock, start);
1171 pending.ownerAtWaitStart = ownerAtWaitStart;
1172 }
1173 return Scope.addFinalizer(
1174 scope,
1175 Effect.sync(() => {
1176 if (target.name === "writer" && activeWriter === owner) activeWriter = undefined;
1177 }).pipe(Effect.andThen(target.lock.release(1))),
1178 );
1179 });
1180 return Effect.as(
1181 // A scheduler yield after taking the permit must not precede its release finalizer.
1182 Effect.provideService(acquire, Scheduler.PreventSchedulerYield, true),
1183 target.connection,
1184 );
1185 }),
1186 );
1187
1188 const client = yield* Client.make({
1189 acquirer: transactionAcquirer,
1190 borrower,
1191 compiler,
1192 transactionAcquirer,
1193 // BEGIN IMMEDIATE avoids read-then-write SQLITE_BUSY_SNAPSHOT, which busy_timeout cannot resolve.
1194 beginTransaction: options.readonly === true ? "BEGIN" : "BEGIN IMMEDIATE",
1195 spanAttributes: [
1196 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
1197 [ATTR_DB_SYSTEM_NAME, "sqlite"],
1198 ],
1199 });
1200 const withTransaction = client.withTransaction;
1201 return Object.assign(client, {
1202 withTransaction: <A, E, R>(effect: Effect.Effect<A, E, R>) =>
1203 Effect.uninterruptibleMask((restore) => {
1204 // SqlClient masks setup; acquisition must preserve the caller's interruptibility.
1205 const pending: {
1206 acquired?: Acquired;
1207 ownerAtWaitStart: ConnectionOwner | undefined;
1208 restore: typeof Effect.interruptible | undefined;
1209 } = {
1210 ownerAtWaitStart: undefined,
1211 restore,
1212 };
1213 const body = Effect.withFiber<A, E, R>((fiber) => {
1214 annotateAcquired(fiber, pending.acquired, pending.ownerAtWaitStart);
1215 pending.restore = undefined;
1216 return effect;
1217 });
1218 return restore(
1219 withTransaction(body).pipe(Effect.provideService(TransactionAcquire, pending)),
1220 );
1221 }),
1222 });
1223});
1224
1225export const layer = (config: SqliteClientConfig): Layer.Layer<Client.SqlClient, SqlError> =>
1226 Layer.effect(Client.SqlClient, make(config)).pipe(Layer.provide(Reactivity.layer));