Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

nodeSqliteClient.test.ts

978 lines40.3 KB

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