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 Effect from "effect/Effect";
7import * as Fiber from "effect/Fiber";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Logger from "effect/Logger";
11import * as Path from "effect/Path";
12import * as SqlClient from "effect/sql/SqlClient";
13import * as TestClock from "effect/testing/TestClock";
14import { vi } from "vite-plus/test";
15
16import * as SqliteClient from "./nodeSqliteClient.ts";
17
18const startedWorkers = vi.hoisted((): Array<NodeWorkerThreads.Worker> => []);
19// When on, workers run a script that never announces, like a worker stuck opening the file.
20const silentWorkers = vi.hoisted(() => ({ on: false, readyOnTerminate: false }));
21
22vi.mock("node:worker_threads", async (importOriginal) => {
23 const actual = await importOriginal<typeof NodeWorkerThreads>();
24 class RecordedWorker extends actual.Worker {
25 constructor(...args: ConstructorParameters<typeof actual.Worker>) {
26 super(
27 ...((silentWorkers.on
28 ? ["setInterval(() => {}, 1 << 30);", { eval: true }]
29 : args) as ConstructorParameters<typeof actual.Worker>),
30 );
31 startedWorkers.push(this);
32 }
33 override terminate() {
34 // A "ready" already queued when termination starts reaches the parent before "exit".
35 if (silentWorkers.readyOnTerminate) this.emit("message", { type: "ready" });
36 return super.terminate();
37 }
38 }
39 return { ...actual, Worker: RecordedWorker };
40});
41
42const withReaderClient = <A, E>(
43 use: (sql: SqlClient.SqlClient) => Effect.Effect<A, E, SqlClient.SqlClient>,
44) =>
45 Effect.gen(function* () {
46 const fs = yield* FileSystem.FileSystem;
47 const path = yield* Path.Path;
48 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-reader-" });
49 const filename = path.join(directory, "state.sqlite");
50 return yield* Effect.gen(function* () {
51 const sql = yield* SqlClient.SqlClient;
52 yield* sql`PRAGMA journal_mode = WAL`;
53 yield* sql`CREATE TABLE entries(name TEXT NOT NULL)`;
54 yield* sql`INSERT INTO entries VALUES ('first')`;
55 return yield* use(sql);
56 }).pipe(Effect.provide(SqliteClient.layer({ filename, readerWorker: true })));
57 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
58
59const countEntries = (sql: SqlClient.SqlClient) =>
60 Effect.map(
61 sql<{ count: number }>`SELECT COUNT(*) AS count FROM entries`,
62 (rows) => rows[0]?.count,
63 );
64
65const layer = it.layer(SqliteClient.layer({ filename: ":memory:" }));
66
67layer("NodeSqliteClient", (it) => {
68 it.effect("retries preparing a query after the missing schema becomes available", () =>
69 Effect.gen(function* () {
70 const sql = yield* SqlClient.SqlClient;
71 const select = sql<{ name: string }>`SELECT name FROM created_after_prepare_failure`;
72 const error = yield* select.pipe(Effect.flip);
73 assert.equal(error._tag, "SqlError");
74 assert.equal(error.reason.operation, "prepare");
75
76 yield* sql`CREATE TABLE created_after_prepare_failure(name TEXT NOT NULL)`;
77 yield* sql`INSERT INTO created_after_prepare_failure VALUES ('recovered')`;
78 assert.deepEqual(yield* select, [{ name: "recovered" }]);
79 assert.deepEqual(yield* select.values, [["recovered"]]);
80 }),
81 );
82
83 it.effect("runs prepared queries and returns positional values", () =>
84 Effect.gen(function* () {
85 const sql = yield* SqlClient.SqlClient;
86
87 yield* sql`CREATE TABLE entries(id INTEGER PRIMARY KEY, name TEXT NOT NULL)`;
88 yield* sql`INSERT INTO entries(name) VALUES (${"alpha"}), (${"beta"})`;
89
90 const rows = yield* sql<{ readonly id: number; readonly name: string }>`
91 SELECT id, name FROM entries ORDER BY id
92 `;
93 assert.equal(rows.length, 2);
94 assert.equal(rows[0]?.name, "alpha");
95 assert.equal(rows[1]?.name, "beta");
96
97 const values = yield* sql`SELECT id, name FROM entries ORDER BY id`.values;
98 assert.equal(values.length, 2);
99 assert.equal(values[0]?.[1], "alpha");
100 assert.equal(values[1]?.[1], "beta");
101
102 const unpreparedValues = yield* sql`SELECT id, name FROM entries ORDER BY id`
103 .valuesUnprepared;
104 assert.deepEqual(unpreparedValues, values);
105 }),
106 );
107
108 it.effect("returns a typed failure when an unprepared statement cannot be prepared", () =>
109 Effect.gen(function* () {
110 const sql = yield* SqlClient.SqlClient;
111 const error = yield* Effect.flip(sql.unsafe("SELECT FROM").unprepared);
112
113 assert.equal(error._tag, "SqlError");
114 assert.equal(error.reason.operation, "prepare");
115 }),
116 );
117
118 it.effect("classifies constraint failures by their SQLite result code", () =>
119 Effect.gen(function* () {
120 const sql = yield* SqlClient.SqlClient;
121 yield* sql`CREATE TABLE constrained(name TEXT NOT NULL UNIQUE)`;
122 yield* sql`INSERT INTO constrained VALUES ('taken')`;
123
124 const duplicate = yield* sql`INSERT INTO constrained VALUES ('taken')`.pipe(Effect.flip);
125 assert(duplicate.reason._tag === "UniqueViolation");
126 assert.equal(duplicate.reason.constraint, "constrained.name");
127
128 const missing = yield* sql`INSERT INTO constrained VALUES (NULL)`.pipe(Effect.flip);
129 assert.equal(missing.reason._tag, "ConstraintError");
130 }),
131 );
132});
133
134const largeText = "x".repeat(64 * 1024 + 1);
135
136it.effect("keeps large text and blob parameters off cached statements", () =>
137 Effect.gen(function* () {
138 const sql = yield* SqlClient.SqlClient;
139 const statements: Array<NodeSqlite.StatementSync> = [];
140 const all = NodeSqlite.StatementSync.prototype.all;
141 yield* Effect.acquireRelease(
142 Effect.sync(() =>
143 vi.spyOn(NodeSqlite.StatementSync.prototype, "all").mockImplementation(function (
144 this: NodeSqlite.StatementSync,
145 ...params
146 ) {
147 statements.push(this);
148 return all.apply(this, params);
149 }),
150 ),
151 (spy) => Effect.sync(() => spy.mockRestore()),
152 );
153
154 const small = "small";
155 const queries = [
156 (value: string | Uint8Array | ArrayBuffer) => sql`SELECT length(${value}) AS size`,
157 (value: string | Uint8Array | ArrayBuffer) =>
158 sql.unsafe("SELECT length($value) AS size", [{ $value: value }]),
159 (value: string | Uint8Array | ArrayBuffer) =>
160 sql.unsafe("SELECT length($value) AS callable", [
161 Object.assign(() => {}, { $value: value }),
162 ]),
163 ];
164 const cached = new Set<NodeSqlite.StatementSync>();
165 const large = new Set<NodeSqlite.StatementSync>();
166 const largeBlobs = [new Uint8Array(64 * 1024 + 1), new ArrayBuffer(64 * 1024 + 1)];
167 for (const value of [small, largeText, ...largeBlobs, small]) {
168 const expected = typeof value === "string" ? value.length : value.byteLength;
169 for (const query of queries) {
170 assert.deepEqual((yield* query(value)).map(Object.values), [[expected]]);
171 assert.deepEqual(yield* query(value).values, [[expected]]);
172 for (const statement of statements.splice(0)) {
173 (value === small ? cached : large).add(statement);
174 }
175 }
176 }
177
178 // Small parameters keep reusing the one cached statement for each query.
179 assert.equal(cached.size, queries.length);
180 // Each large execution gets a statement that nothing holds on to afterwards.
181 assert.equal(large.size, queries.length * 6);
182 assert.isTrue(cached.isDisjointFrom(large));
183 }).pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:" }))),
184);
185
186it.effect("reads integers on the values path as the caller asked, cached or not", () =>
187 Effect.gen(function* () {
188 const sql = yield* SqlClient.SqlClient;
189 for (const value of ["small", largeText]) {
190 const values = sql`SELECT 1 AS id, length(${value}) AS size`.values;
191 assert.deepEqual(yield* values.pipe(Effect.provideService(SqlClient.SafeIntegers, true)), [
192 [1n, BigInt(value.length)],
193 ]);
194 assert.deepEqual(yield* values, [[1, value.length]]);
195 }
196 }).pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:" }))),
197);
198
199it.effect("leaves a parameter it cannot measure for the statement to handle", () =>
200 Effect.gen(function* () {
201 const sql = yield* SqlClient.SqlClient;
202 const detached = new DataView(new ArrayBuffer(8));
203 structuredClone(detached.buffer, { transfer: [detached.buffer] });
204 // What a detached view binds as varies by Node version; match the statement itself.
205 const native = new NodeSqlite.DatabaseSync(":memory:");
206 const expected = native.prepare("SELECT length(?) AS size").all(detached);
207 native.close();
208 assert.deepEqual(yield* sql`SELECT length(${detached}) AS size`, expected);
209
210 const throwing = {
211 get $value(): string {
212 throw new Error("unreadable");
213 },
214 };
215 const error = yield* sql.unsafe("SELECT length($value) AS size", [throwing]).pipe(Effect.flip);
216 assert.equal(error.reason.operation, "execute");
217
218 // Only the statement reads a getter, so it runs once as it would natively.
219 let reads = 0;
220 const counting = {
221 get $value(): number {
222 return ++reads;
223 },
224 };
225 assert.deepEqual(yield* sql.unsafe("SELECT $value AS value", [counting]), [{ value: 1 }]);
226 assert.equal(reads, 1);
227 }).pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:" }))),
228);
229
230const makeTempDatabase = Effect.gen(function* () {
231 const fs = yield* FileSystem.FileSystem;
232 const path = yield* Path.Path;
233 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-transaction-" });
234 const filename = path.join(directory, "state.sqlite");
235 // node:sqlite connections fail a busy statement at once unless given a timeout.
236 const other = yield* Effect.acquireRelease(
237 Effect.sync(() => new NodeSqlite.DatabaseSync(filename)),
238 (database) => Effect.sync(() => database.close()),
239 );
240 yield* Effect.sync(() => {
241 other.exec(`
242 PRAGMA journal_mode = WAL;
243 CREATE TABLE counters(id INTEGER PRIMARY KEY, value INTEGER NOT NULL);
244 INSERT INTO counters VALUES (1, 0);
245 `);
246 });
247 return { filename, other };
248});
249
250it.effect("keeps another connection from committing between a transaction's read and write", () =>
251 Effect.gen(function* () {
252 const { filename, other } = yield* makeTempDatabase;
253 yield* Effect.gen(function* () {
254 const sql = yield* SqlClient.SqlClient;
255 yield* sql.withTransaction(
256 Effect.gen(function* () {
257 const [row] = yield* sql<{ readonly value: number }>`
258 SELECT value FROM counters WHERE id = 1
259 `;
260 // With a deferred BEGIN this commit lands and the write below fails
261 // with SQLITE_BUSY_SNAPSHOT, which no busy timeout can wait out.
262 yield* Effect.sync(() =>
263 assert.throws(
264 () => other.exec("UPDATE counters SET value = value + 1 WHERE id = 1"),
265 /database is locked/,
266 ),
267 );
268 yield* sql`UPDATE counters SET value = ${(row?.value ?? 0) + 10} WHERE id = 1`;
269 }),
270 );
271 yield* Effect.sync(() => other.exec("UPDATE counters SET value = value + 1 WHERE id = 1"));
272 assert.deepEqual(yield* sql`SELECT value FROM counters WHERE id = 1`.values, [[11]]);
273 }).pipe(Effect.provide(SqliteClient.layer({ filename })));
274 }).pipe(Effect.provide(NodeServices.layer)),
275);
276
277it.effect("reports a transaction blocked by another writer as a lock timeout", () =>
278 Effect.gen(function* () {
279 const { filename, other } = yield* makeTempDatabase;
280 yield* Effect.gen(function* () {
281 const sql = yield* SqlClient.SqlClient;
282 yield* sql`PRAGMA busy_timeout = 0`;
283 const read = sql.withTransaction(sql`SELECT value FROM counters WHERE id = 1`.values);
284
285 yield* Effect.sync(() => other.exec("BEGIN IMMEDIATE"));
286 const error = yield* read.pipe(Effect.flip);
287 assert.equal(error.reason._tag, "LockTimeoutError");
288
289 yield* Effect.sync(() => other.exec("COMMIT"));
290 assert.deepEqual(yield* read, [[0]]);
291 }).pipe(Effect.provide(SqliteClient.layer({ filename })));
292 }).pipe(Effect.provide(NodeServices.layer)),
293);
294
295it.effect("returns a typed failure when the database cannot be opened", () =>
296 Effect.gen(function* () {
297 const error = yield* Effect.flip(
298 Layer.build(SqliteClient.layer({ filename: "\0" })).pipe(Effect.scoped),
299 );
300
301 assert.equal(error._tag, "SqlError");
302 assert.equal(error.reason.operation, "open");
303 }),
304);
305
306it.effect(
307 "recovers a prepared query immediately after an exclusive database lock is released",
308 () =>
309 Effect.gen(function* () {
310 const fs = yield* FileSystem.FileSystem;
311 const path = yield* Path.Path;
312 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-prepare-" });
313 const filename = path.join(directory, "state.sqlite");
314 const blocker = yield* Effect.acquireRelease(
315 Effect.sync(() => new NodeSqlite.DatabaseSync(filename)),
316 (database) => Effect.sync(() => database.close()),
317 );
318 yield* Effect.sync(() => {
319 blocker.exec("CREATE TABLE entries(value TEXT); INSERT INTO entries VALUES ('retained')");
320 });
321 yield* Effect.gen(function* () {
322 const sql = yield* SqlClient.SqlClient;
323 yield* Effect.sync(() => blocker.exec("BEGIN EXCLUSIVE"));
324 const select = sql`SELECT value FROM entries`;
325 const error = yield* select.values.pipe(Effect.flip);
326 assert.equal(error._tag, "SqlError");
327 assert.equal(error.reason.operation, "prepare");
328 yield* Effect.sync(() => blocker.exec("ROLLBACK"));
329 assert.deepEqual(yield* select.values, [["retained"]]);
330 assert.deepEqual(yield* select, [{ value: "retained" }]);
331 }).pipe(Effect.provide(SqliteClient.layer({ filename })));
332 }).pipe(Effect.provide(NodeServices.layer)),
333);
334
335it.effect("lets the writer commit while a read-only transaction is open", () =>
336 withReaderClient((sql) =>
337 Effect.gen(function* () {
338 const snapshotTaken = yield* Deferred.make<void>();
339 const writer = yield* Effect.forkChild(
340 Deferred.await(snapshotTaken).pipe(
341 Effect.andThen(sql`INSERT INTO entries VALUES ('second')`),
342 ),
343 );
344 const counts = yield* sql
345 .withTransaction(
346 Effect.gen(function* () {
347 const before = yield* countEntries(sql);
348 yield* Deferred.succeed(snapshotTaken, undefined);
349 // Holding the writer lock here would deadlock this join.
350 yield* Fiber.join(writer);
351 const after = yield* countEntries(sql);
352 return { before, after };
353 }),
354 )
355 .pipe(SqliteClient.readOnly);
356
357 // The reader keeps the snapshot it began with, and later reads see the commit.
358 assert.deepEqual(counts, { before: 1, after: 1 });
359 assert.equal(yield* countEntries(sql).pipe(SqliteClient.readOnly), 2);
360 }),
361 ),
362);
363
364it.effect("rejects a write in a read-only transaction", () =>
365 withReaderClient((sql) =>
366 Effect.gen(function* () {
367 const error = yield* sql
368 .withTransaction(sql`INSERT INTO entries VALUES ('blocked')`)
369 .pipe(SqliteClient.readOnly, Effect.flip);
370
371 assert.equal(error._tag, "SqlError");
372 assert.include(String(error.reason.cause), "readonly database");
373 assert.equal(yield* countEntries(sql), 1);
374 }),
375 ),
376);
377
378it.effect("keeps the reader read-only even if a statement turns query_only off", () =>
379 withReaderClient((sql) =>
380 Effect.gen(function* () {
381 const error = yield* sql
382 .withTransaction(
383 Effect.gen(function* () {
384 yield* sql`PRAGMA query_only = OFF`;
385 yield* sql`INSERT INTO entries VALUES ('blocked')`;
386 }),
387 )
388 .pipe(SqliteClient.readOnly, Effect.flip);
389
390 assert.equal(error._tag, "SqlError");
391 assert.include(String(error.reason.cause), "readonly database");
392 assert.equal(yield* countEntries(sql), 1);
393 }),
394 ),
395);
396
397it.effect("keeps read-only work inside a write transaction on the writer", () =>
398 withReaderClient((sql) =>
399 sql.withTransaction(
400 Effect.gen(function* () {
401 yield* sql`INSERT INTO entries VALUES ('uncommitted')`;
402 // Only the writer can see its own uncommitted row.
403 const count = yield* sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly);
404 assert.equal(count, 2);
405 }),
406 ),
407 ),
408);
409
410it.effect("keeps large parameters off the reader worker's cached statements", () =>
411 withReaderClient((sql) =>
412 Effect.gen(function* () {
413 const read = (value: string) =>
414 sql<{ size: number }>`SELECT length(${value}) AS size`.pipe(
415 Effect.map((rows) => rows[0]?.size),
416 );
417 // Start the worker so its requests can be recorded.
418 yield* countEntries(sql).pipe(SqliteClient.readOnly);
419 const worker = startedWorkers.at(-1)!;
420 const cached: Array<boolean> = [];
421 const postMessage = worker.postMessage;
422 yield* Effect.acquireRelease(
423 Effect.sync(() =>
424 vi.spyOn(worker, "postMessage").mockImplementation(function (
425 this: NodeWorkerThreads.Worker,
426 message: { readonly cached: boolean },
427 ) {
428 cached.push(message.cached);
429 return postMessage.call(this, message);
430 }),
431 ),
432 (spy) => Effect.sync(() => spy.mockRestore()),
433 );
434
435 assert.equal(yield* read("small").pipe(SqliteClient.readOnly), 5);
436 assert.equal(yield* read(largeText).pipe(SqliteClient.readOnly), largeText.length);
437 assert.deepEqual(cached, [true, false]);
438 }).pipe(Effect.scoped),
439 ),
440);
441
442it.effect("fails a read-only transaction whose reader stops, then starts a new reader", () =>
443 withReaderClient((sql) =>
444 Effect.gen(function* () {
445 const startedBefore = startedWorkers.length;
446 const error = yield* sql
447 .withTransaction(
448 Effect.gen(function* () {
449 yield* countEntries(sql);
450 yield* Effect.promise(() => startedWorkers.at(-1)!.terminate());
451 return yield* countEntries(sql);
452 }),
453 )
454 .pipe(SqliteClient.readOnly, Effect.flip);
455
456 assert.equal(error._tag, "SqlError");
457 assert.include(String(error.reason.cause), "Database reader exited");
458 assert.equal(yield* countEntries(sql).pipe(SqliteClient.readOnly), 1);
459 assert.equal(startedWorkers.length, startedBefore + 2);
460 }),
461 ),
462);
463
464it.effect("uses the writer for read-only work on an in-memory database", () =>
465 Effect.gen(function* () {
466 const startedBefore = startedWorkers.length;
467 const sql = yield* SqlClient.SqlClient;
468 yield* sql`CREATE TABLE memory_entries(name TEXT NOT NULL)`;
469 yield* sql`INSERT INTO memory_entries VALUES ('kept')`;
470
471 const rows = yield* sql
472 .withTransaction(sql<{ name: string }>`SELECT name FROM memory_entries`)
473 .pipe(SqliteClient.readOnly);
474
475 assert.deepEqual(rows, [{ name: "kept" }]);
476 assert.equal(startedWorkers.length, startedBefore);
477 }).pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:", readerWorker: true }))),
478);
479
480it.effect("keeps a nested transaction inside a read-only transaction on the reader", () =>
481 withReaderClient((sql) =>
482 Effect.gen(function* () {
483 const snapshotTaken = yield* Deferred.make<void>();
484 const writer = yield* Effect.forkChild(
485 Deferred.await(snapshotTaken).pipe(
486 Effect.andThen(sql`INSERT INTO entries VALUES ('second')`),
487 ),
488 );
489 // Callers wrap a store read that opens its own transaction, as the
490 // shell snapshot routes do around getShellSnapshot.
491 const counts = yield* sql
492 .withTransaction(
493 Effect.gen(function* () {
494 const outer = yield* countEntries(sql);
495 yield* Deferred.succeed(snapshotTaken, undefined);
496 yield* Fiber.join(writer);
497 const nested = yield* sql.withTransaction(countEntries(sql));
498 return { outer, nested };
499 }),
500 )
501 .pipe(SqliteClient.readOnly);
502
503 assert.deepEqual(counts, { outer: 1, nested: 1 });
504 }),
505 ),
506);
507
508const withFileClient = <A, E>(
509 setup: (
510 sql: SqlClient.SqlClient,
511 filename: string,
512 ) => Effect.Effect<A, E, SqlClient.SqlClient | FileSystem.FileSystem>,
513) =>
514 Effect.gen(function* () {
515 const fs = yield* FileSystem.FileSystem;
516 const path = yield* Path.Path;
517 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-reader-off-" });
518 const filename = path.join(directory, "state.sqlite");
519 return yield* Effect.gen(function* () {
520 return yield* setup(yield* SqlClient.SqlClient, filename);
521 }).pipe(Effect.provide(SqliteClient.layer({ filename, readerWorker: true })));
522 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
523
524it.effect("uses the writer when the reader cannot open the database", () =>
525 withFileClient((sql, filename) =>
526 Effect.gen(function* () {
527 yield* sql`PRAGMA journal_mode = WAL`;
528 yield* sql`CREATE TABLE entries(name TEXT NOT NULL)`;
529 yield* sql`INSERT INTO entries VALUES ('kept')`;
530 // The writer keeps its open file; a read-only open of the path now fails.
531 yield* (yield* FileSystem.FileSystem).remove(filename);
532 const startedBefore = startedWorkers.length;
533
534 assert.equal(yield* sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly), 1);
535 assert.equal(yield* sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly), 1);
536 assert.equal(startedWorkers.length, startedBefore + 1);
537 }),
538 ),
539);
540
541it.effect("uses the writer for a database that is not in WAL mode", () =>
542 withFileClient((sql) =>
543 Effect.gen(function* () {
544 yield* sql`CREATE TABLE entries(name TEXT NOT NULL)`;
545 const startedBefore = startedWorkers.length;
546
547 // A write inside readOnly only succeeds on the writer: the reader is read-only.
548 yield* sql
549 .withTransaction(sql`INSERT INTO entries VALUES ('on the writer')`)
550 .pipe(SqliteClient.readOnly);
551 assert.equal(yield* sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly), 1);
552 assert.equal(startedWorkers.length, startedBefore + 1);
553 }),
554 ),
555);
556
557const captureWarnings = () => {
558 const warnings: Array<unknown> = [];
559 const logger = Logger.make(({ logLevel, message }) => {
560 if (logLevel === "Warn") warnings.push(message);
561 });
562 return { warnings, layer: Logger.layer([logger], { mergeWithExisting: false }) };
563};
564
565const silently = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
566 Effect.acquireUseRelease(
567 Effect.sync(() => {
568 silentWorkers.on = true;
569 }),
570 () => effect,
571 () =>
572 Effect.sync(() => {
573 silentWorkers.on = false;
574 silentWorkers.readyOnTerminate = false;
575 }),
576 );
577
578it.effect("turns the reader off when its worker never opens the database", () => {
579 const { warnings, layer: logs } = captureWarnings();
580 return withFileClient((sql) =>
581 Effect.gen(function* () {
582 yield* sql`PRAGMA journal_mode = WAL`;
583 yield* sql`CREATE TABLE entries(name TEXT NOT NULL)`;
584 yield* sql`INSERT INTO entries VALUES ('kept')`;
585 const read = yield* silently(
586 Effect.gen(function* () {
587 const fiber = yield* Effect.forkChild(
588 sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly),
589 );
590 yield* Effect.yieldNow;
591 yield* TestClock.adjust("10 seconds");
592 return yield* Fiber.join(fiber);
593 }),
594 );
595
596 assert.equal(read, 1);
597 assert.equal(yield* sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly), 1);
598 assert.lengthOf(warnings, 1);
599 }),
600 ).pipe(Effect.provide(logs));
601});
602
603it.effect("lets a read be cancelled while its worker is still starting", () =>
604 withFileClient((sql) =>
605 Effect.gen(function* () {
606 yield* sql`PRAGMA journal_mode = WAL`;
607 yield* sql`CREATE TABLE entries(name TEXT NOT NULL)`;
608 yield* silently(
609 Effect.gen(function* () {
610 const fiber = yield* Effect.forkChild(
611 sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly),
612 );
613 yield* Effect.yieldNow;
614 // Never returns if the wait for the worker were uninterruptible: the
615 // test clock has not moved, so the startup deadline cannot fire.
616 yield* Fiber.interrupt(fiber);
617 }),
618 );
619
620 // The client stays usable: the next read waits out the deadline, then uses the writer.
621 const next = yield* Effect.forkChild(
622 sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly),
623 );
624 yield* Effect.yieldNow;
625 yield* TestClock.adjust("10 seconds");
626 assert.equal(yield* Fiber.join(next), 0);
627 }),
628 ),
629);
630
631it.effect("logs one warning when concurrent first reads find the reader unavailable", () => {
632 const { warnings, layer: logs } = captureWarnings();
633 return withFileClient((sql, filename) =>
634 Effect.gen(function* () {
635 yield* sql`PRAGMA journal_mode = WAL`;
636 yield* sql`CREATE TABLE entries(name TEXT NOT NULL)`;
637 yield* (yield* FileSystem.FileSystem).remove(filename);
638 const startedBefore = startedWorkers.length;
639
640 const counts = yield* Effect.all(
641 [
642 sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly),
643 sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly),
644 ],
645 { concurrency: "unbounded" },
646 );
647
648 assert.deepEqual(counts, [0, 0]);
649 assert.equal(startedWorkers.length, startedBefore + 1);
650 assert.lengthOf(warnings, 1);
651 }),
652 ).pipe(Effect.provide(logs));
653});
654
655it.effect("does not hand out a worker that reports ready after another read timed it out", () =>
656 withFileClient((sql) =>
657 Effect.gen(function* () {
658 yield* sql`PRAGMA journal_mode = WAL`;
659 yield* sql`CREATE TABLE entries(name TEXT NOT NULL)`;
660 yield* sql`INSERT INTO entries VALUES ('kept')`;
661 const read = () => sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly);
662 const counts = yield* silently(
663 Effect.gen(function* () {
664 const first = yield* Effect.forkChild(read());
665 yield* Effect.yieldNow;
666 yield* TestClock.adjust("5 seconds");
667 const second = yield* Effect.forkChild(read());
668 yield* Effect.yieldNow;
669 // The first read reaches its deadline and retires the worker; the second
670 // is still waiting when the worker's "ready" arrives, before it exits.
671 silentWorkers.readyOnTerminate = true;
672 yield* TestClock.adjust("5 seconds");
673 return [yield* Fiber.join(first), yield* Fiber.join(second)];
674 }),
675 );
676
677 assert.deepEqual(counts, [1, 1]);
678 }),
679 ),
680);
681
682const withCheckpointClient = <A, E>(
683 use: (
684 sql: SqlClient.SqlClient,
685 filename: string,
686 ) => Effect.Effect<A, E, SqlClient.SqlClient | FileSystem.FileSystem>,
687) =>
688 Effect.gen(function* () {
689 const fs = yield* FileSystem.FileSystem;
690 const path = yield* Path.Path;
691 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-checkpoint-" });
692 const filename = path.join(directory, "state.sqlite");
693 return yield* Effect.gen(function* () {
694 const sql = yield* SqlClient.SqlClient;
695 yield* sql`PRAGMA journal_mode = WAL`;
696 return yield* use(sql, filename);
697 }).pipe(Effect.provide(SqliteClient.layer({ filename, checkpointWorker: true })));
698 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
699
700// Resolves once the worker has handled a request sent now, after every
701// statement so far. Earlier requests from the writer reply with null.
702const checkpointWorkerReply = (worker: NodeWorkerThreads.Worker) =>
703 Effect.promise(
704 () =>
705 new Promise<void>((resolve) => {
706 const onReply = (reply: unknown) => {
707 if (reply !== "barrier") return;
708 worker.off("message", onReply);
709 resolve();
710 };
711 worker.on("message", onReply);
712 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
713 worker.postMessage("barrier");
714 }),
715 );
716
717it.effect("checkpoints the WAL on the worker instead of the writer", () =>
718 withCheckpointClient((sql, filename) =>
719 Effect.gen(function* () {
720 const fs = yield* FileSystem.FileSystem;
721 const walSize = Effect.map(fs.stat(`${filename}-wal`), (info) => Number(info.size));
722 const worker = startedWorkers.at(-1)!;
723 const limit = 1024 * 1024;
724 yield* sql.unsafe(`PRAGMA journal_size_limit = ${limit}`);
725 const autocheckpoint = yield* sql<{
726 readonly wal_autocheckpoint: number;
727 }>`PRAGMA wal_autocheckpoint`;
728 // The writer leaves a WAL of this size to the worker.
729 assert.equal(autocheckpoint[0]?.wal_autocheckpoint, 10_000);
730
731 // About 1200 frames, past the 1000 that start a checkpoint.
732 yield* sql`CREATE TABLE pages(payload BLOB)`;
733 yield* sql`
734 WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 1200)
735 INSERT INTO pages(payload) SELECT randomblob(4000) FROM n
736 `;
737 yield* checkpointWorkerReply(worker);
738 const wal = yield* sql<{
739 readonly log: number;
740 readonly checkpointed: number;
741 }>`PRAGMA wal_checkpoint(NOOP)`;
742 assert.isAbove(wal[0]!.log, 1000);
743 assert.equal(wal[0]!.checkpointed, wal[0]!.log);
744
745 // Every frame is in the database, so the next commit restarts the WAL and
746 // cuts the file back to the size limit.
747 assert.isAbove(yield* walSize, limit);
748 yield* sql`INSERT INTO pages(payload) VALUES (x'00')`;
749 assert.isAtMost(yield* walSize, limit);
750 }),
751 ),
752);
753
754it.effect("hands checkpoints back to the writer when the worker stops", () =>
755 withCheckpointClient((sql) =>
756 Effect.gen(function* () {
757 yield* Effect.promise(() => startedWorkers.at(-1)!.terminate());
758 const autocheckpoint = yield* sql<{
759 readonly wal_autocheckpoint: number;
760 }>`PRAGMA wal_autocheckpoint`;
761 assert.equal(autocheckpoint[0]?.wal_autocheckpoint, 1000);
762 }),
763 ),
764);