Open History to see the last commit
1import * as NodeSqlite from "node:sqlite";
2import type * as NodeWorkerThreads from "node:worker_threads";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { assert, it } from "@effect/vitest";
5import * as Deferred from "effect/Deferred";
6import * as Cause from "effect/Cause";
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 * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Logger from "effect/Logger";
14import * as Path from "effect/Path";
15import * as Queue from "effect/Queue";
16import * as SqlClient from "effect/sql/SqlClient";
17import * as SqlError from "effect/sql/SqlError";
18import * as Statement from "effect/sql/Statement";
19import { ChildProcess, ChildProcessSpawner } from "effect/process";
20import * as Stream from "effect/Stream";
21import * as TestClock from "effect/testing/TestClock";
22import type * as Tracer from "effect/Tracer";
23import { vi } from "vite-plus/test";
24
25import * as SqliteClient from "./nodeSqliteClient.ts";
26
27const startedWorkers = vi.hoisted((): Array<NodeWorkerThreads.Worker> => []);
28const workerExits = vi.hoisted(() => new WeakMap<NodeWorkerThreads.Worker, Promise<void>>());
29const silentWorkers = vi.hoisted(() => ({ on: false, readyOnTerminate: false }));
30const failingWorkers = vi.hoisted(() => ({ message: undefined as string | undefined }));
31const checkpointWorkers = vi.hoisted((): Array<NodeWorkerThreads.Worker> => []);
32
33vi.mock("node:worker_threads", async (importOriginal) => {
34 const actual = await importOriginal<typeof NodeWorkerThreads>();
35 class RecordedWorker extends actual.Worker {
36 constructor(...args: ConstructorParameters<typeof actual.Worker>) {
37 super(
38 ...((silentWorkers.on
39 ? ["setInterval(() => {}, 1 << 30);", { eval: true }]
40 : failingWorkers.message !== undefined
41 ? [`throw new Error(${JSON.stringify(failingWorkers.message)});`, { eval: true }]
42 : args) as ConstructorParameters<typeof actual.Worker>),
43 );
44 startedWorkers.push(this);
45 workerExits.set(this, new Promise((resolve) => this.once("exit", () => resolve())));
46 if (args[1]?.workerData?.frames !== undefined) checkpointWorkers.push(this);
47 }
48 override terminate() {
49 // A "ready" already queued when termination starts reaches the parent before "exit".
50 if (silentWorkers.readyOnTerminate) this.emit("message", { type: "ready" });
51 return super.terminate();
52 }
53 }
54 return { ...actual, Worker: RecordedWorker };
55});
56
57const withReaderClient = <A, E>(
58 use: (sql: SqlClient.SqlClient) => Effect.Effect<A, E, SqlClient.SqlClient>,
59) =>
60 Effect.gen(function* () {
61 const fs = yield* FileSystem.FileSystem;
62 const path = yield* Path.Path;
63 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-reader-" });
64 const filename = path.join(directory, "state.sqlite");
65 return yield* Effect.gen(function* () {
66 const sql = yield* SqlClient.SqlClient;
67 yield* sql`PRAGMA journal_mode = WAL`;
68 yield* sql`CREATE TABLE entries(name TEXT NOT NULL)`;
69 yield* sql`INSERT INTO entries VALUES ('first')`;
70 return yield* use(sql);
71 }).pipe(Effect.provide(SqliteClient.layer({ filename, readerWorker: true })));
72 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
73
74const countEntries = (sql: SqlClient.SqlClient) =>
75 Effect.map(
76 sql<{ count: number }>`SELECT COUNT(*) AS count FROM entries`,
77 (rows) => rows[0]?.count,
78 );
79
80const layer = it.layer(SqliteClient.layer({ filename: ":memory:" }));
81
82layer("NodeSqliteClient", (it) => {
83 it.effect("records the writer connection owner on a waiting query", () =>
84 Effect.gen(function* () {
85 const sql = yield* SqlClient.SqlClient;
86 const held = yield* Deferred.make<void>();
87 const release = yield* Deferred.make<void>();
88 const holder = yield* sql
89 .withTransaction(
90 sql`SELECT 1`.pipe(
91 Effect.andThen(Deferred.succeed(held, undefined)),
92 Effect.andThen(Deferred.await(release)),
93 ),
94 )
95 .pipe(Effect.withSpan("test.writerHolder"), Effect.forkChild);
96 yield* Deferred.await(held);
97
98 const waitingSpan = yield* Deferred.make<Tracer.Span>();
99 const observeWaiter: Statement.Transformer = (statement, _sql, _fiber, span) =>
100 Deferred.succeed(waitingSpan, span).pipe(Effect.as(statement));
101 const waiter = yield* sql`SELECT 1`.pipe(
102 Effect.provideService(Statement.CurrentTransformer, observeWaiter),
103 Effect.provideService(Statement.SpanPropagationEnabled, true),
104 (effect) => Effect.forkChild(effect, { startImmediately: true }),
105 );
106 const span = yield* Deferred.await(waitingSpan);
107 yield* Deferred.succeed(release, undefined);
108 yield* Fiber.join(holder);
109 yield* Fiber.join(waiter);
110
111 assert.equal(span.attributes.get("db.lock_owner_at_start.name"), "test.writerHolder");
112 assert.typeOf(span.attributes.get("db.lock_owner_at_start.fiber_id"), "number");
113 assert.typeOf(span.attributes.get("db.lock_owner_at_start.trace_id"), "string");
114 assert.typeOf(span.attributes.get("db.lock_owner_at_start.span_id"), "string");
115 }),
116 );
117
118 it.effect("retries preparing a query after the missing schema becomes available", () =>
119 Effect.gen(function* () {
120 const sql = yield* SqlClient.SqlClient;
121 const select = sql<{ name: string }>`SELECT name FROM created_after_prepare_failure`;
122 const error = yield* select.pipe(Effect.flip);
123 assert.equal(error._tag, "SqlError");
124 assert.equal(error.reason.operation, "prepare");
125
126 yield* sql`CREATE TABLE created_after_prepare_failure(name TEXT NOT NULL)`;
127 yield* sql`INSERT INTO created_after_prepare_failure VALUES ('recovered')`;
128 assert.deepEqual(yield* select, [{ name: "recovered" }]);
129 assert.deepEqual(yield* select.values, [["recovered"]]);
130 }),
131 );
132
133 it.effect("classifies constraint failures by their SQLite result code", () =>
134 Effect.gen(function* () {
135 const sql = yield* SqlClient.SqlClient;
136 yield* sql`CREATE TABLE constrained(name TEXT NOT NULL UNIQUE)`;
137 yield* sql`INSERT INTO constrained VALUES ('taken')`;
138
139 const duplicate = yield* sql`INSERT INTO constrained VALUES ('taken')`.pipe(Effect.flip);
140 assert(duplicate.reason._tag === "UniqueViolation");
141 assert.equal(duplicate.reason.constraint, "constrained.name");
142
143 const missing = yield* sql`INSERT INTO constrained VALUES (NULL)`.pipe(Effect.flip);
144 assert.equal(missing.reason._tag, "ConstraintError");
145 }),
146 );
147});
148
149const largeText = "x".repeat(64 * 1024 + 1);
150
151it.effect("a rowid above 2^53 does not leave a transaction open", () =>
152 Effect.gen(function* () {
153 const sql = yield* SqlClient.SqlClient;
154 yield* sql`CREATE TABLE big (id INTEGER PRIMARY KEY, name TEXT)`;
155 yield* sql`INSERT INTO big (id, name) VALUES (246166233861328896, 'first')`;
156 // BEGIN reports the connection's last insert rowid; a failure to convert it must not
157 // read as a failed BEGIN, or the open transaction is never rolled back.
158 yield* sql.withTransaction(sql`INSERT INTO big (name) VALUES ('second')`);
159 yield* sql.withTransaction(sql`UPDATE big SET name = 'third' WHERE name = 'second'`);
160 const rows = yield* sql<{ name: string }>`SELECT name FROM big ORDER BY id`;
161 assert.deepStrictEqual(
162 rows.map((row) => row.name),
163 ["first", "third"],
164 );
165 }).pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:" }))),
166);
167
168it.effect("reads integers on the values path as the caller asked, cached or not", () =>
169 Effect.gen(function* () {
170 const sql = yield* SqlClient.SqlClient;
171 for (const value of ["small", largeText]) {
172 const values = sql`SELECT 1 AS id, length(${value}) AS size`.values;
173 assert.deepEqual(yield* values.pipe(Effect.provideService(SqlClient.SafeIntegers, true)), [
174 [1n, BigInt(value.length)],
175 ]);
176 assert.deepEqual(yield* values, [[1, value.length]]);
177 }
178 }).pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:" }))),
179);
180
181const makeTempDatabase = Effect.gen(function* () {
182 const fs = yield* FileSystem.FileSystem;
183 const path = yield* Path.Path;
184 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-transaction-" });
185 const filename = path.join(directory, "state.sqlite");
186 const other = yield* Effect.acquireRelease(
187 Effect.sync(() => new NodeSqlite.DatabaseSync(filename)),
188 (database) => Effect.sync(() => database.close()),
189 );
190 yield* Effect.sync(() => {
191 other.exec(`
192 PRAGMA journal_mode = WAL;
193 CREATE TABLE counters(id INTEGER PRIMARY KEY, value INTEGER NOT NULL);
194 INSERT INTO counters VALUES (1, 0);
195 `);
196 });
197 return { filename, other };
198});
199
200it.effect.each([false, true])("batches worker results without losing rows (reader=%s)", (reader) =>
201 Effect.gen(function* () {
202 const { filename } = yield* makeTempDatabase;
203 yield* Effect.gen(function* () {
204 const sql = yield* SqlClient.SqlClient;
205 const route = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
206 reader ? effect.pipe(SqliteClient.readOnly) : effect;
207 yield* route(sql`SELECT 1`);
208 const worker = startedWorkers
209 .filter((candidate) => !checkpointWorkers.includes(candidate))
210 .at(-1)!;
211 const batches: Array<ReadonlyArray<unknown>> = [];
212 const record = (reply: { rows?: ReadonlyArray<unknown> }) => {
213 if (Array.isArray(reply.rows) && reply.rows.length > 0) batches.push(reply.rows);
214 };
215 worker.prependListener("message", record);
216 yield* Effect.gen(function* () {
217 const text = "x".repeat(16 * 1024);
218 const query = sql<{ n: number; text: string }>`
219 WITH RECURSIVE sequence(n) AS (
220 SELECT 1 UNION ALL SELECT n + 1 FROM sequence WHERE n < 300
221 ) SELECT n, ${text} AS text FROM sequence
222 `;
223 const rows = yield* reader ? route(query.values) : query;
224 assert.equal(rows.length, 300);
225 for (const [index, row] of rows.entries()) {
226 assert.deepEqual(row, reader ? [index + 1, text] : { n: index + 1, text });
227 }
228 assert.isAbove(batches.length, 1);
229 for (const batch of batches) {
230 assert.isAtMost(batch.length, 16_384);
231 assert.isAtMost(batch.length * text.length * 2, 8 * 1024 * 1024);
232 }
233 batches.length = 0;
234 const narrow = sql<{ n: number }>`
235 WITH RECURSIVE sequence(n) AS (
236 SELECT 1 UNION ALL SELECT n + 1 FROM sequence WHERE n < 10000
237 ) SELECT n FROM sequence
238 `;
239 const narrowRows = yield* reader ? route(narrow.values) : narrow;
240 assert.equal(narrowRows.length, 10_000);
241 assert.deepEqual(narrowRows.at(-1), reader ? [10_000] : { n: 10_000 });
242 assert.equal(batches.length, 1);
243 }).pipe(Effect.ensuring(Effect.sync(() => worker.off("message", record))));
244 }).pipe(
245 Effect.provide(SqliteClient.layer({ filename, writerWorker: true, readerWorker: true })),
246 );
247 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
248);
249
250it.effect("coalesces savepoints with queries and preserves nested rollback", () =>
251 Effect.gen(function* () {
252 const { filename } = yield* makeTempDatabase;
253 yield* Effect.gen(function* () {
254 const sql = yield* SqlClient.SqlClient;
255 const worker = startedWorkers.filter((entry) => !checkpointWorkers.includes(entry)).at(-1)!;
256 using messages = vi.spyOn(worker, "postMessage");
257 yield* sql.withTransaction(
258 Effect.forEach(Array.from({ length: 53 }), () => sql.withTransaction(Effect.void)),
259 );
260 assert.equal(messages.mock.calls.length, 2);
261
262 yield* sql.withTransaction(
263 Effect.gen(function* () {
264 yield* sql`UPDATE counters SET value = 1 WHERE id = 1`;
265 const failure = yield* sql
266 .withTransaction(
267 sql`UPDATE counters SET value = 2 WHERE id = 1`.pipe(
268 Effect.andThen(Effect.fail("bad update")),
269 ),
270 )
271 .pipe(Effect.flip);
272 assert.equal(failure, "bad update");
273 const sent = messages.mock.calls.length;
274 assert.equal(
275 yield* sql.withTransaction(Effect.fail("empty update")).pipe(Effect.flip),
276 "empty update",
277 );
278 assert.equal(messages.mock.calls.length, sent);
279 assert.deepEqual(yield* sql`SELECT value FROM counters WHERE id = 1`, [{ value: 1 }]);
280 assert.deepEqual(messages.mock.calls.at(-1)?.[0].savepoints, []);
281 yield* sql.withTransaction(
282 sql
283 .withTransaction(
284 sql`UPDATE counters SET value = 3 WHERE id = 1`.pipe(
285 Effect.andThen(Effect.fail("nested update")),
286 ),
287 )
288 .pipe(Effect.flip),
289 );
290 assert.deepEqual(yield* sql`SELECT value FROM counters WHERE id = 1`, [{ value: 1 }]);
291
292 yield* sql.withTransaction(sql`UPDATE counters SET value = 4 WHERE id = 1`);
293 yield* sql`UPDATE counters SET value = 5 WHERE id = 1`;
294 const unsent = yield* sql
295 .withTransaction(sql.unsafe("SELECT ?", [Symbol("uncloneable")]))
296 .pipe(Effect.exit);
297 assert.isTrue(Exit.isFailure(unsent));
298 }),
299 );
300 assert.deepEqual(yield* sql`SELECT value FROM counters WHERE id = 1`, [{ value: 5 }]);
301 }).pipe(Effect.provide(SqliteClient.layer({ filename, writerWorker: true })));
302 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
303);
304
305it.effect("reuses a worker query after an iterator constraint failure", () =>
306 Effect.gen(function* () {
307 const { filename } = yield* makeTempDatabase;
308 yield* Effect.gen(function* () {
309 const sql = yield* SqlClient.SqlClient;
310 yield* sql`CREATE TABLE unique_entries(name TEXT UNIQUE)`;
311 const insert = (name: string) =>
312 sql<{ name: string }>`INSERT INTO unique_entries VALUES (${name}) RETURNING name`;
313 yield* insert("first");
314 const error = yield* insert("first").pipe(Effect.flip);
315 assert.equal(error.reason._tag, "UniqueViolation");
316 assert.deepEqual(yield* insert("second"), [{ name: "second" }]);
317 }).pipe(Effect.provide(SqliteClient.layer({ filename, writerWorker: true })));
318 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
319);
320
321it.effect("commits on the worker writer after a returning write timed out on a lock", () =>
322 Effect.gen(function* () {
323 const { filename, other } = yield* makeTempDatabase;
324 yield* Effect.gen(function* () {
325 const sql = yield* SqlClient.SqlClient;
326 yield* sql`PRAGMA busy_timeout = 0`;
327 yield* Effect.sync(() => other.exec("BEGIN IMMEDIATE"));
328 const error = yield* sql`UPDATE counters SET value = 1 WHERE id = 1 RETURNING value`.pipe(
329 Effect.flip,
330 );
331 assert.equal(error.reason._tag, "LockTimeoutError");
332 yield* Effect.sync(() => other.exec("COMMIT"));
333
334 yield* sql.withTransaction(sql`UPDATE counters SET value = 2 WHERE id = 1`);
335 assert.deepEqual(yield* sql`SELECT value FROM counters WHERE id = 1`.values, [[2]]);
336 }).pipe(Effect.provide(SqliteClient.layer({ filename, writerWorker: true })));
337 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
338);
339
340it.effect("keeps another connection from committing between a transaction's read and write", () =>
341 Effect.gen(function* () {
342 const { filename, other } = yield* makeTempDatabase;
343 yield* Effect.gen(function* () {
344 const sql = yield* SqlClient.SqlClient;
345 yield* sql.withTransaction(
346 Effect.gen(function* () {
347 const [row] = yield* sql<{ readonly value: number }>`
348 SELECT value FROM counters WHERE id = 1
349 `;
350 // Deferred BEGIN permits a competing commit, causing SQLITE_BUSY_SNAPSHOT that no timeout can resolve.
351 yield* Effect.sync(() =>
352 assert.throws(
353 () => other.exec("UPDATE counters SET value = value + 1 WHERE id = 1"),
354 /database is locked/,
355 ),
356 );
357 yield* sql`UPDATE counters SET value = ${(row?.value ?? 0) + 10} WHERE id = 1`;
358 }),
359 );
360 yield* Effect.sync(() => other.exec("UPDATE counters SET value = value + 1 WHERE id = 1"));
361 assert.deepEqual(yield* sql`SELECT value FROM counters WHERE id = 1`.values, [[11]]);
362 }).pipe(Effect.provide(SqliteClient.layer({ filename })));
363 }).pipe(Effect.provide(NodeServices.layer)),
364);
365
366it.effect("waits for another process's lock while the database opens", () =>
367 Effect.gen(function* () {
368 const fs = yield* FileSystem.FileSystem;
369 const path = yield* Path.Path;
370 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-open-" });
371 const filename = path.join(directory, "state.sqlite");
372 const seed = new NodeSqlite.DatabaseSync(filename);
373 seed.exec("PRAGMA journal_mode = WAL; CREATE TABLE entries(name TEXT NOT NULL)");
374 seed.close();
375 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
376 const holder = yield* spawner.spawn(
377 ChildProcess.make(process.execPath, [
378 "-e",
379 `const db = new (require("node:sqlite").DatabaseSync)(process.argv[1]);
380 db.exec("PRAGMA locking_mode = EXCLUSIVE; BEGIN EXCLUSIVE");
381 console.log("held");
382 setTimeout(() => db.close(), 300);`,
383 filename,
384 ]),
385 );
386 yield* Stream.runHead(holder.stdout);
387 yield* Effect.gen(function* () {
388 const sql = yield* SqlClient.SqlClient;
389 assert.deepEqual(yield* sql`SELECT COUNT(*) FROM entries`.values, [[0]]);
390 }).pipe(Effect.provide(SqliteClient.layer({ filename, writerWorker: true })));
391 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
392);
393
394it.effect("reports a transaction blocked by another writer as a lock timeout", () =>
395 Effect.gen(function* () {
396 const { filename, other } = yield* makeTempDatabase;
397 yield* Effect.gen(function* () {
398 const sql = yield* SqlClient.SqlClient;
399 yield* sql`PRAGMA busy_timeout = 0`;
400 const read = sql.withTransaction(sql`SELECT value FROM counters WHERE id = 1`.values);
401
402 yield* Effect.sync(() => other.exec("BEGIN IMMEDIATE"));
403 const error = yield* read.pipe(Effect.flip);
404 assert.equal(error.reason._tag, "LockTimeoutError");
405
406 yield* Effect.sync(() => other.exec("COMMIT"));
407 assert.deepEqual(yield* read, [[0]]);
408 }).pipe(Effect.provide(SqliteClient.layer({ filename })));
409 }).pipe(Effect.provide(NodeServices.layer)),
410);
411
412it.effect("lets the event loop run while a write waits for another connection's lock", () =>
413 Effect.gen(function* () {
414 const { filename, other } = yield* makeTempDatabase;
415 yield* Effect.gen(function* () {
416 const sql = yield* SqlClient.SqlClient;
417 yield* sql`PRAGMA busy_timeout = 5000`;
418 yield* Effect.sync(() => other.exec("BEGIN IMMEDIATE"));
419 const write = yield* Effect.forkChild(
420 sql`UPDATE counters SET value = value + 1 WHERE id = 1`,
421 { startImmediately: true },
422 );
423 // A writer on the event loop sleeps in SQLite's busy handler here, so this commit
424 // cannot run until that write has already timed out.
425 yield* eventLoopTurn;
426 yield* Effect.sync(() => other.exec("UPDATE counters SET value = 10 WHERE id = 1; COMMIT"));
427 yield* Fiber.join(write);
428 assert.deepEqual(yield* sql`SELECT value FROM counters WHERE id = 1`.values, [[11]]);
429 }).pipe(Effect.provide(SqliteClient.layer({ filename, writerWorker: true })));
430 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
431);
432
433it.effect("finishes a write already sent to the writer before its caller is interrupted", () =>
434 Effect.gen(function* () {
435 const { filename, other } = yield* makeTempDatabase;
436 yield* Effect.gen(function* () {
437 const sql = yield* SqlClient.SqlClient;
438 yield* sql`PRAGMA busy_timeout = 5000`;
439 yield* Effect.sync(() => other.exec("BEGIN IMMEDIATE"));
440 const write = yield* Effect.forkChild(
441 sql`UPDATE counters SET value = value + 1 WHERE id = 1`,
442 { startImmediately: true },
443 );
444 yield* eventLoopTurn;
445 const interrupted = yield* Effect.forkChild(Fiber.interrupt(write), {
446 startImmediately: true,
447 });
448 yield* eventLoopTurn;
449 // The write is waiting in the worker for the lock, so the interrupt has to wait too.
450 assert.isUndefined(interrupted.pollUnsafe());
451 yield* Effect.sync(() => other.exec("COMMIT"));
452 yield* Fiber.join(interrupted);
453 assert.deepEqual(yield* sql`SELECT value FROM counters WHERE id = 1`.values, [[1]]);
454 }).pipe(Effect.provide(SqliteClient.layer({ filename, writerWorker: true })));
455 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
456);
457
458it.effect("lets the writer commit while a read-only transaction is open", () =>
459 withReaderClient((sql) =>
460 Effect.gen(function* () {
461 const snapshotTaken = yield* Deferred.make<void>();
462 const writer = yield* Effect.forkChild(
463 Deferred.await(snapshotTaken).pipe(
464 Effect.andThen(sql`INSERT INTO entries VALUES ('second')`),
465 ),
466 );
467 const counts = yield* sql
468 .withTransaction(
469 Effect.gen(function* () {
470 const before = yield* countEntries(sql);
471 yield* Deferred.succeed(snapshotTaken, undefined);
472 // Holding the writer lock here would deadlock this join.
473 yield* Fiber.join(writer);
474 const after = yield* countEntries(sql);
475 return { before, after };
476 }),
477 )
478 .pipe(SqliteClient.readOnly);
479
480 assert.deepEqual(counts, { before: 1, after: 1 });
481 assert.equal(yield* countEntries(sql).pipe(SqliteClient.readOnly), 2);
482 }),
483 ),
484);
485
486it.effect("serves another read while a read-only transaction is open", () =>
487 withReaderClient((sql) =>
488 Effect.gen(function* () {
489 const opened = yield* Deferred.make<void>();
490 const other = yield* Effect.forkChild(
491 Deferred.await(opened).pipe(Effect.andThen(countEntries(sql).pipe(SqliteClient.readOnly))),
492 );
493 yield* sql
494 .withTransaction(
495 Effect.gen(function* () {
496 yield* countEntries(sql);
497 yield* Deferred.succeed(opened, undefined);
498 // One shared reader would make this join wait on the transaction forever.
499 assert.equal(yield* Fiber.join(other), 1);
500 }),
501 )
502 .pipe(SqliteClient.readOnly);
503 }),
504 ),
505);
506
507it.effect("gives a queued read the first reader that frees up", () =>
508 withReaderClient((sql) =>
509 Effect.gen(function* () {
510 const holders = yield* Effect.forEach([0, 1, 2, 3], () =>
511 Effect.gen(function* () {
512 const held = yield* Deferred.make<void>();
513 const release = yield* Deferred.make<void>();
514 const fiber = yield* sql
515 .withTransaction(
516 countEntries(sql).pipe(
517 Effect.andThen(Deferred.succeed(held, undefined)),
518 Effect.andThen(Deferred.await(release)),
519 ),
520 )
521 .pipe(SqliteClient.readOnly, Effect.forkChild);
522 yield* Deferred.await(held);
523 return { fiber, release };
524 }),
525 );
526 const cancelled = yield* Effect.uninterruptibleMask((restore) =>
527 SqliteClient.readOnly(restore(sql.withTransaction(countEntries(sql)))),
528 ).pipe((effect) => Effect.forkChild(effect, { startImmediately: true }));
529 yield* Fiber.interrupt(cancelled);
530 const cancelledRead = yield* Effect.uninterruptibleMask((restore) =>
531 SqliteClient.readOnly(restore(countEntries(sql))),
532 ).pipe((effect) => Effect.forkChild(effect, { startImmediately: true }));
533 yield* Fiber.interrupt(cancelledRead);
534 const queuedSpan = yield* Deferred.make<Tracer.Span>();
535 const observeQueued: Statement.Transformer = (statement, _sql, _fiber, span) =>
536 Deferred.succeed(queuedSpan, span).pipe(Effect.as(statement));
537 const queued = yield* countEntries(sql).pipe(
538 Effect.provideService(Statement.CurrentTransformer, observeQueued),
539 Effect.provideService(Statement.SpanPropagationEnabled, true),
540 SqliteClient.readOnly,
541 (effect) => Effect.forkChild(effect, { startImmediately: true }),
542 );
543 // Masked read-only work keeps its cancellation pending and still runs once a reader frees up.
544 let maskedRan = 0;
545 const maskedRuns = yield* Effect.forEach(
546 [
547 Effect.scoped(
548 Effect.flatMap(sql.reserve, (connection) =>
549 connection.executeUnprepared("SELECT 1", [], undefined),
550 ),
551 ).pipe(Effect.asVoid),
552 sql.withTransaction(countEntries(sql)).pipe(Effect.asVoid),
553 ],
554 (effect) =>
555 effect.pipe(
556 Effect.andThen(Effect.sync(() => maskedRan++)),
557 Effect.uninterruptible,
558 SqliteClient.readOnly,
559 (masked) => Effect.forkChild(masked, { startImmediately: true }),
560 ),
561 );
562 const interrupting = yield* Effect.forEach(maskedRuns, (fiber) =>
563 Effect.forkChild(Fiber.interrupt(fiber), { startImmediately: true }),
564 );
565 yield* TestClock.adjust("1 second");
566 yield* Deferred.succeed(holders[1]!.release, undefined);
567 yield* Fiber.join(holders[1]!.fiber);
568 // Pinned to the first reader it saw, this read would wait for that reader's transaction.
569 assert.equal(yield* Fiber.join(queued), 1);
570 assert.equal((yield* Deferred.await(queuedSpan)).attributes.get("db.lock_wait_ms"), 1000);
571 for (const { fiber, release } of [holders[0]!, holders[2]!, holders[3]!]) {
572 yield* Deferred.succeed(release, undefined);
573 yield* Fiber.join(fiber);
574 }
575 yield* Effect.forEach(interrupting, Fiber.join);
576 assert.equal(maskedRan, 2);
577 }),
578 ),
579);
580
581// regression: #19226 read-only transactions run on the separate reader connection
582it.effect("rejects a write in a read-only transaction", () =>
583 withReaderClient((sql) =>
584 Effect.gen(function* () {
585 const error = yield* sql
586 .withTransaction(sql`INSERT INTO entries VALUES ('blocked')`)
587 .pipe(SqliteClient.readOnly, Effect.flip);
588
589 assert.equal(error._tag, "SqlError");
590 assert.include(String(error.reason.cause), "readonly database");
591 assert.equal(yield* countEntries(sql), 1);
592 }),
593 ),
594);
595
596it.effect("keeps the reader read-only even if a statement turns query_only off", () =>
597 withReaderClient((sql) =>
598 Effect.gen(function* () {
599 const error = yield* sql
600 .withTransaction(
601 Effect.gen(function* () {
602 yield* sql`PRAGMA query_only = OFF`;
603 yield* sql`INSERT INTO entries VALUES ('blocked')`;
604 }),
605 )
606 .pipe(SqliteClient.readOnly, Effect.flip);
607
608 assert.equal(error._tag, "SqlError");
609 assert.include(String(error.reason.cause), "readonly database");
610 assert.equal(yield* countEntries(sql), 1);
611 }),
612 ),
613);
614
615it.effect("keeps read-only work inside a write transaction on the writer", () =>
616 withReaderClient((sql) =>
617 sql.withTransaction(
618 Effect.gen(function* () {
619 yield* sql`INSERT INTO entries VALUES ('uncommitted')`;
620 const count = yield* sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly);
621 assert.equal(count, 2);
622 }),
623 ),
624 ),
625);
626
627it.effect("fails a read-only transaction whose reader stops, then starts a new reader", () =>
628 withReaderClient((sql) =>
629 Effect.gen(function* () {
630 const startedBefore = startedWorkers.length;
631 const error = yield* sql
632 .withTransaction(
633 Effect.gen(function* () {
634 yield* countEntries(sql);
635 yield* Effect.promise(() => startedWorkers.at(-1)!.terminate());
636 return yield* countEntries(sql);
637 }),
638 )
639 .pipe(SqliteClient.readOnly, Effect.flip);
640
641 assert.equal(error._tag, "SqlError");
642 assert.include(String(error.reason.cause), "Database reader exited");
643 assert.equal(yield* countEntries(sql).pipe(SqliteClient.readOnly), 1);
644 assert.equal(startedWorkers.length, startedBefore + 2);
645 }),
646 ),
647);
648
649const withFileClient = <A, E>(
650 setup: (
651 sql: SqlClient.SqlClient,
652 filename: string,
653 ) => Effect.Effect<A, E, SqlClient.SqlClient | FileSystem.FileSystem>,
654) =>
655 Effect.gen(function* () {
656 const fs = yield* FileSystem.FileSystem;
657 const path = yield* Path.Path;
658 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-reader-off-" });
659 const filename = path.join(directory, "state.sqlite");
660 return yield* Effect.gen(function* () {
661 return yield* setup(yield* SqlClient.SqlClient, filename);
662 }).pipe(Effect.provide(SqliteClient.layer({ filename, readerWorker: true })));
663 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
664
665it.effect("uses the writer when the reader cannot open the database", () =>
666 withFileClient((sql, filename) =>
667 Effect.gen(function* () {
668 yield* sql`PRAGMA journal_mode = WAL`;
669 yield* sql`CREATE TABLE entries(name TEXT NOT NULL)`;
670 yield* sql`INSERT INTO entries VALUES ('kept')`;
671 yield* (yield* FileSystem.FileSystem).remove(filename);
672 const startedBefore = startedWorkers.length;
673
674 assert.equal(yield* sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly), 1);
675 assert.equal(yield* sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly), 1);
676
677 // A read beside an open read transaction must not start a worker on the next slot.
678 const held = yield* Deferred.make<void>();
679 const release = yield* Deferred.make<void>();
680 const holder = yield* sql
681 .withTransaction(
682 countEntries(sql).pipe(
683 Effect.andThen(Deferred.succeed(held, undefined)),
684 Effect.andThen(Deferred.await(release)),
685 ),
686 )
687 .pipe(SqliteClient.readOnly, Effect.forkChild);
688 yield* Deferred.await(held);
689 const other = yield* countEntries(sql).pipe(SqliteClient.readOnly, (effect) =>
690 Effect.forkChild(effect, { startImmediately: true }),
691 );
692 yield* Deferred.succeed(release, undefined);
693 yield* Fiber.join(holder);
694 assert.equal(yield* Fiber.join(other), 1);
695 assert.equal(startedWorkers.length, startedBefore + 1);
696 }),
697 ),
698);
699
700const withLogLines = <A, E, R>(
701 use: (lines: Queue.Queue<ReadonlyArray<unknown>>) => Effect.Effect<A, E, R>,
702) =>
703 Effect.gen(function* () {
704 const lines = yield* Queue.unbounded<ReadonlyArray<unknown>>();
705 const logger = Logger.make(({ logLevel, message }) => {
706 Queue.offerUnsafe(lines, [logLevel, ...(message as ReadonlyArray<unknown>)]);
707 });
708 return yield* use(lines).pipe(
709 Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
710 );
711 });
712
713const readConnection = (sql: SqlClient.SqlClient) =>
714 Effect.gen(function* () {
715 const spans: Array<Tracer.Span> = [];
716 const observe: Statement.Transformer = (statement, _sql, _fiber, span) =>
717 Effect.sync(() => {
718 spans.push(span);
719 return statement;
720 });
721 const count = yield* countEntries(sql).pipe(
722 SqliteClient.readOnly,
723 Effect.provideService(Statement.CurrentTransformer, observe),
724 Effect.provideService(Statement.SpanPropagationEnabled, true),
725 );
726 return { count, connection: spans.map((span) => span.attributes.get("db.connection")) };
727 });
728
729const withWorkers = <A, E, R>(
730 mode: { readonly failWith?: string; readonly silent?: boolean },
731 effect: Effect.Effect<A, E, R>,
732) =>
733 Effect.acquireUseRelease(
734 Effect.sync(() => {
735 failingWorkers.message = mode.failWith;
736 silentWorkers.on = mode.silent ?? false;
737 }),
738 () => effect,
739 () =>
740 Effect.sync(() => {
741 failingWorkers.message = undefined;
742 silentWorkers.on = false;
743 }),
744 );
745
746const unavailableWarning = "SQLite reader worker unavailable; reads use the writer";
747
748const notWal = "database uses journal_mode delete, not wal";
749
750it.effect.each([
751 {
752 failure: "a crash",
753 workers: { failWith: "reader start failed" },
754 startup: Duration.zero,
755 reason: "Database reader failed: reader start failed",
756 },
757 {
758 failure: "a startup timeout",
759 workers: { silent: true },
760 startup: Duration.seconds(10),
761 reason: "Database reader did not open the database within 10000 ms",
762 },
763])(
764 "reads on the writer after $failure until a retry starts the reader again",
765 ({ workers, startup, reason }) =>
766 withLogLines((lines) =>
767 withReaderClient((sql) =>
768 Effect.gen(function* () {
769 const failed = yield* withWorkers(
770 workers,
771 Effect.gen(function* () {
772 const read = yield* Effect.forkChild(readConnection(sql), {
773 startImmediately: true,
774 });
775 yield* TestClock.adjust(startup);
776 return yield* Fiber.join(read);
777 }),
778 );
779 assert.deepEqual(failed, { count: 1, connection: ["writer"] });
780 const startedBefore = startedWorkers.length;
781 assert.deepEqual(yield* readConnection(sql), { count: 1, connection: ["writer"] });
782 assert.equal(startedWorkers.length, startedBefore);
783 assert.deepEqual(yield* Queue.take(lines), ["Warn", unavailableWarning, { reason }]);
784
785 yield* TestClock.adjust("1 second");
786 assert.equal(startedWorkers.length, startedBefore + 1);
787 assert.deepEqual(yield* Queue.take(lines), [
788 "Info",
789 "SQLite reader worker available again; reads use the reader workers",
790 ]);
791 assert.deepEqual(yield* readConnection(sql), { count: 1, connection: ["reader"] });
792 assert.equal(Queue.sizeUnsafe(lines), 0);
793 }),
794 ),
795 ),
796);
797
798it.effect("backs off a reader that never starts without logging each retry", () =>
799 withLogLines((lines) =>
800 withReaderClient((sql) =>
801 withWorkers(
802 { silent: true },
803 Effect.gen(function* () {
804 const read = yield* Effect.forkChild(readConnection(sql), { startImmediately: true });
805 yield* TestClock.adjust("10 seconds");
806 assert.deepEqual(yield* Fiber.join(read), { count: 1, connection: ["writer"] });
807
808 const startedBefore = startedWorkers.length;
809 // Each retry waits 10 s for startup; the gaps between them double from 1 s up to a minute.
810 yield* TestClock.adjust("10 minutes");
811 assert.equal(startedWorkers.length - startedBefore, 12);
812 assert.equal(Queue.sizeUnsafe(lines), 1);
813 }),
814 ),
815 ),
816 ),
817);
818
819it.effect.each([
820 { phase: "the retry waits", beforeClose: Duration.zero, retries: 0 },
821 { phase: "a retried reader starts", beforeClose: Duration.seconds(1), retries: 1 },
822])("stops retrying the reader when the client closes while $phase", ({ beforeClose, retries }) =>
823 withWorkers(
824 { silent: true },
825 Effect.gen(function* () {
826 const startedAtClose = yield* withReaderClient((sql) =>
827 Effect.gen(function* () {
828 const read = yield* Effect.forkChild(readConnection(sql), { startImmediately: true });
829 yield* TestClock.adjust("10 seconds");
830 assert.deepEqual(yield* Fiber.join(read), { count: 1, connection: ["writer"] });
831
832 const startedBefore = startedWorkers.length;
833 yield* TestClock.adjust(beforeClose);
834 assert.equal(startedWorkers.length - startedBefore, retries);
835 return startedWorkers.length;
836 }),
837 );
838 yield* TestClock.adjust("10 minutes");
839 assert.equal(startedWorkers.length, startedAtClose);
840 }),
841 ),
842);
843
844it.effect.each([
845 {
846 when: "the database is not in WAL mode",
847 journalMode: "DELETE",
848 workers: {},
849 starts: 1,
850 logged: [["Warn", unavailableWarning, { reason: notWal }]],
851 },
852 {
853 when: "a retry finds the database out of WAL mode",
854 journalMode: "WAL",
855 workers: { failWith: "reader start failed" },
856 starts: 2,
857 logged: [
858 ["Warn", unavailableWarning, { reason: "Database reader failed: reader start failed" }],
859 [
860 "Info",
861 "SQLite reader worker retries stopped permanently; reads use the writer",
862 { reason: notWal },
863 ],
864 ],
865 },
866])(
867 "keeps readers off without further retries when $when",
868 ({ journalMode, workers, starts, logged }) =>
869 withLogLines((lines) =>
870 withFileClient((sql) =>
871 Effect.gen(function* () {
872 yield* sql.unsafe(`PRAGMA journal_mode = ${journalMode}`);
873 yield* sql`CREATE TABLE entries(name TEXT NOT NULL)`;
874 yield* sql`INSERT INTO entries VALUES ('kept')`;
875 const startedBefore = startedWorkers.length;
876
877 const failed = yield* withWorkers(workers, readConnection(sql));
878 assert.deepEqual(failed, { count: 1, connection: ["writer"] });
879 yield* sql`PRAGMA journal_mode = DELETE`;
880 yield* TestClock.adjust("1 second");
881 yield* Effect.promise(() => workerExits.get(startedWorkers.at(-1)!)!);
882 yield* TestClock.adjust("1 hour");
883 assert.deepEqual(yield* readConnection(sql), { count: 1, connection: ["writer"] });
884 assert.equal(startedWorkers.length, startedBefore + starts);
885 assert.deepEqual(yield* Queue.clear(lines), logged);
886 }),
887 ),
888 ),
889);
890
891it.effect("fails with a typed SqlError when the database file is not SQLite", () =>
892 Effect.gen(function* () {
893 const fs = yield* FileSystem.FileSystem;
894 const path = yield* Path.Path;
895 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-notadb-" });
896 const filename = path.join(directory, "state.sqlite");
897 yield* fs.writeFileString(filename, "not a db\n");
898
899 const exit = yield* Layer.build(SqliteClient.layer({ filename, writerWorker: true })).pipe(
900 Effect.exit,
901 );
902
903 assert.isTrue(Exit.isFailure(exit));
904 if (Exit.isFailure(exit)) assert.isTrue(SqlError.isSqlError(Cause.squash(exit.cause)));
905 if (Exit.isFailure(exit)) assert.isFalse(Cause.hasDies(exit.cause));
906 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
907);
908
909it.effect("finishes masked database cleanup after its caller is interrupted", () =>
910 Effect.gen(function* () {
911 const sql = yield* SqlClient.SqlClient;
912 yield* sql`CREATE TABLE cleanup_writes(value INTEGER PRIMARY KEY)`;
913 const entered = yield* Deferred.make<void>();
914 const work = yield* Effect.forkChild(
915 Deferred.succeed(entered, undefined).pipe(
916 Effect.andThen(Effect.never),
917 Effect.onInterrupt(() =>
918 Effect.gen(function* () {
919 yield* sql`INSERT INTO cleanup_writes VALUES (1)`;
920 yield* sql.withTransaction(sql`INSERT INTO cleanup_writes VALUES (2)`);
921 }),
922 ),
923 ),
924 { startImmediately: true },
925 );
926 yield* Deferred.await(entered);
927 yield* Fiber.interrupt(work);
928 assert.deepEqual(yield* sql`SELECT value FROM cleanup_writes ORDER BY value`.values, [
929 [1],
930 [2],
931 ]);
932 }).pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:" }))),
933);
934
935// oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- a zero-delay macrotask boundary that lets the worker's queued messages land, not a wait for time
936const eventLoopTurn = Effect.promise(() => new Promise<void>((resolve) => setImmediate(resolve)));
937
938it.effect.each([
939 { reservation: false, masked: false },
940 { reservation: false, masked: true },
941 { reservation: true, masked: false },
942 { reservation: true, masked: true },
943])(
944 "preserves caller cancellation while waiting (reservation=$reservation, masked=$masked)",
945 ({ reservation, masked }) =>
946 Effect.gen(function* () {
947 const sql = yield* SqlClient.SqlClient;
948 yield* sql`CREATE TABLE entries(value INTEGER)`;
949 const held = yield* Deferred.make<void>();
950 const release = yield* Deferred.make<void>();
951 const holder = yield* Effect.forkChild(
952 sql.withTransaction(
953 Deferred.succeed(held, undefined).pipe(Effect.andThen(Deferred.await(release))),
954 ),
955 { startImmediately: true },
956 );
957 yield* Deferred.await(held);
958 const entered = yield* Deferred.make<void>();
959 const body = sql`INSERT INTO entries VALUES (1)`.pipe(
960 Effect.andThen(Deferred.succeed(entered, undefined)),
961 );
962 const acquire = reservation
963 ? Effect.scoped(
964 Effect.gen(function* () {
965 const connection = yield* sql.reserve;
966 yield* connection.executeUnprepared("INSERT INTO entries VALUES (1)", [], undefined);
967 yield* Deferred.succeed(entered, undefined);
968 }),
969 )
970 : sql.withTransaction(body);
971 const waiter = yield* Effect.forkChild(masked ? Effect.uninterruptible(acquire) : acquire, {
972 startImmediately: true,
973 });
974 const cancelled = yield* Effect.forkChild(Fiber.interrupt(waiter), {
975 startImmediately: true,
976 });
977 yield* Effect.gen(function* () {
978 yield* eventLoopTurn;
979 assert.equal(cancelled.pollUnsafe() !== undefined, !masked);
980 assert.isFalse(yield* Deferred.isDone(entered));
981 }).pipe(Effect.ensuring(Deferred.succeed(release, undefined)));
982 yield* Fiber.join(holder);
983 yield* Fiber.join(cancelled);
984 assert.equal(yield* Deferred.isDone(entered), masked);
985 yield* sql.withTransaction(sql`INSERT INTO entries VALUES (2)`);
986 assert.deepEqual(
987 yield* sql`SELECT value FROM entries ORDER BY value`.values,
988 masked ? [[1], [2]] : [[2]],
989 );
990 }).pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:" }))),
991);
992
993it.effect("keeps writes moving while an outside reader pins the WAL, then trims the WAL", () =>
994 Effect.gen(function* () {
995 const fs = yield* FileSystem.FileSystem;
996 const path = yield* Path.Path;
997 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-pinned-wal-" });
998 const filename = path.join(directory, "state.sqlite");
999 // Stands in for `sqlite3 statev2.sqlite` or a backup script reading the database.
1000 const outside = yield* Effect.acquireRelease(
1001 Effect.sync(() => new NodeSqlite.DatabaseSync(filename)),
1002 (db) =>
1003 Effect.sync(() => {
1004 if (db.isTransaction) db.exec("COMMIT");
1005 db.close();
1006 }),
1007 );
1008 outside.exec("PRAGMA journal_mode = WAL; CREATE TABLE blobs(data BLOB NOT NULL)");
1009 const walSize = fs.stat(`${filename}-wal`).pipe(
1010 Effect.map((info) => Number(info.size)),
1011 Effect.orDie,
1012 );
1013 const limit = 8 * 1024 * 1024;
1014 const payload = new Uint8Array(1024 * 1024).fill(7);
1015 yield* Effect.gen(function* () {
1016 const sql = yield* SqlClient.SqlClient;
1017 yield* sql.unsafe(`PRAGMA journal_size_limit = ${limit}`);
1018 yield* sql`INSERT INTO blobs VALUES (${payload})`;
1019 outside.exec("BEGIN");
1020 outside.prepare("SELECT COUNT(*) FROM blobs").get();
1021 for (let write = 0; write < 24; write++) yield* sql`INSERT INTO blobs VALUES (${payload})`;
1022 assert.isAbove(yield* walSize, limit);
1023 outside.exec("COMMIT");
1024 const checkpointer = checkpointWorkers.at(-1)!;
1025 const caughtUp = Effect.callback<void>((resume) => {
1026 const onMessage = (message: { type?: unknown; log?: unknown; checkpointed?: unknown }) => {
1027 if (
1028 message?.type === "checked" &&
1029 typeof message.log === "number" &&
1030 message.log > 0 &&
1031 message.log === message.checkpointed
1032 ) {
1033 resume(Effect.void);
1034 }
1035 };
1036 checkpointer.on("message", onMessage);
1037 checkpointer.ref();
1038 return Effect.sync(() => {
1039 checkpointer.off("message", onMessage);
1040 checkpointer.unref();
1041 });
1042 });
1043 // The worker checkpoints the released frames; the next write restarts the WAL at the limit.
1044 yield* Effect.all([caughtUp, sql`DELETE FROM blobs WHERE rowid = 1`], { concurrency: 2 });
1045 yield* sql`DELETE FROM blobs WHERE rowid = 2`;
1046 assert.isAtMost(yield* walSize, limit);
1047 assert.deepEqual(yield* sql`SELECT COUNT(*) FROM blobs`.values, [[23]]);
1048 }).pipe(Effect.provide(SqliteClient.layer({ filename, writerWorker: true })));
1049 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1050);