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 makeTempDatabase = Effect.gen(function* () {
135 const fs = yield* FileSystem.FileSystem;
136 const path = yield* Path.Path;
137 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-transaction-" });
138 const filename = path.join(directory, "state.sqlite");
139 // node:sqlite connections fail a busy statement at once unless given a timeout.
140 const other = yield* Effect.acquireRelease(
141 Effect.sync(() => new NodeSqlite.DatabaseSync(filename)),
142 (database) => Effect.sync(() => database.close()),
143 );
144 yield* Effect.sync(() => {
145 other.exec(`
146 PRAGMA journal_mode = WAL;
147 CREATE TABLE counters(id INTEGER PRIMARY KEY, value INTEGER NOT NULL);
148 INSERT INTO counters VALUES (1, 0);
149 `);
150 });
151 return { filename, other };
152});
153
154it.effect("keeps another connection from committing between a transaction's read and write", () =>
155 Effect.gen(function* () {
156 const { filename, other } = yield* makeTempDatabase;
157 yield* Effect.gen(function* () {
158 const sql = yield* SqlClient.SqlClient;
159 yield* sql.withTransaction(
160 Effect.gen(function* () {
161 const [row] = yield* sql<{ readonly value: number }>`
162 SELECT value FROM counters WHERE id = 1
163 `;
164 // With a deferred BEGIN this commit lands and the write below fails
165 // with SQLITE_BUSY_SNAPSHOT, which no busy timeout can wait out.
166 yield* Effect.sync(() =>
167 assert.throws(
168 () => other.exec("UPDATE counters SET value = value + 1 WHERE id = 1"),
169 /database is locked/,
170 ),
171 );
172 yield* sql`UPDATE counters SET value = ${(row?.value ?? 0) + 10} WHERE id = 1`;
173 }),
174 );
175 yield* Effect.sync(() => other.exec("UPDATE counters SET value = value + 1 WHERE id = 1"));
176 assert.deepEqual(yield* sql`SELECT value FROM counters WHERE id = 1`.values, [[11]]);
177 }).pipe(Effect.provide(SqliteClient.layer({ filename })));
178 }).pipe(Effect.provide(NodeServices.layer)),
179);
180
181it.effect("reports a transaction blocked by another writer as a lock timeout", () =>
182 Effect.gen(function* () {
183 const { filename, other } = yield* makeTempDatabase;
184 yield* Effect.gen(function* () {
185 const sql = yield* SqlClient.SqlClient;
186 yield* sql`PRAGMA busy_timeout = 0`;
187 const read = sql.withTransaction(sql`SELECT value FROM counters WHERE id = 1`.values);
188
189 yield* Effect.sync(() => other.exec("BEGIN IMMEDIATE"));
190 const error = yield* read.pipe(Effect.flip);
191 assert.equal(error.reason._tag, "LockTimeoutError");
192
193 yield* Effect.sync(() => other.exec("COMMIT"));
194 assert.deepEqual(yield* read, [[0]]);
195 }).pipe(Effect.provide(SqliteClient.layer({ filename })));
196 }).pipe(Effect.provide(NodeServices.layer)),
197);
198
199it.effect("returns a typed failure when the database cannot be opened", () =>
200 Effect.gen(function* () {
201 const error = yield* Effect.flip(
202 Layer.build(SqliteClient.layer({ filename: "\0" })).pipe(Effect.scoped),
203 );
204
205 assert.equal(error._tag, "SqlError");
206 assert.equal(error.reason.operation, "open");
207 }),
208);
209
210it.effect(
211 "recovers a prepared query immediately after an exclusive database lock is released",
212 () =>
213 Effect.gen(function* () {
214 const fs = yield* FileSystem.FileSystem;
215 const path = yield* Path.Path;
216 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-prepare-" });
217 const filename = path.join(directory, "state.sqlite");
218 const blocker = yield* Effect.acquireRelease(
219 Effect.sync(() => new NodeSqlite.DatabaseSync(filename)),
220 (database) => Effect.sync(() => database.close()),
221 );
222 yield* Effect.sync(() => {
223 blocker.exec("CREATE TABLE entries(value TEXT); INSERT INTO entries VALUES ('retained')");
224 });
225 yield* Effect.gen(function* () {
226 const sql = yield* SqlClient.SqlClient;
227 yield* Effect.sync(() => blocker.exec("BEGIN EXCLUSIVE"));
228 const select = sql`SELECT value FROM entries`;
229 const error = yield* select.values.pipe(Effect.flip);
230 assert.equal(error._tag, "SqlError");
231 assert.equal(error.reason.operation, "prepare");
232 yield* Effect.sync(() => blocker.exec("ROLLBACK"));
233 assert.deepEqual(yield* select.values, [["retained"]]);
234 assert.deepEqual(yield* select, [{ value: "retained" }]);
235 }).pipe(Effect.provide(SqliteClient.layer({ filename })));
236 }).pipe(Effect.provide(NodeServices.layer)),
237);
238
239it.effect("lets the writer commit while a read-only transaction is open", () =>
240 withReaderClient((sql) =>
241 Effect.gen(function* () {
242 const snapshotTaken = yield* Deferred.make<void>();
243 const writer = yield* Effect.forkChild(
244 Deferred.await(snapshotTaken).pipe(
245 Effect.andThen(sql`INSERT INTO entries VALUES ('second')`),
246 ),
247 );
248 const counts = yield* sql
249 .withTransaction(
250 Effect.gen(function* () {
251 const before = yield* countEntries(sql);
252 yield* Deferred.succeed(snapshotTaken, undefined);
253 // Holding the writer lock here would deadlock this join.
254 yield* Fiber.join(writer);
255 const after = yield* countEntries(sql);
256 return { before, after };
257 }),
258 )
259 .pipe(SqliteClient.readOnly);
260
261 // The reader keeps the snapshot it began with, and later reads see the commit.
262 assert.deepEqual(counts, { before: 1, after: 1 });
263 assert.equal(yield* countEntries(sql).pipe(SqliteClient.readOnly), 2);
264 }),
265 ),
266);
267
268it.effect("rejects a write in a read-only transaction", () =>
269 withReaderClient((sql) =>
270 Effect.gen(function* () {
271 const error = yield* sql
272 .withTransaction(sql`INSERT INTO entries VALUES ('blocked')`)
273 .pipe(SqliteClient.readOnly, Effect.flip);
274
275 assert.equal(error._tag, "SqlError");
276 assert.include(String(error.reason.cause), "readonly database");
277 assert.equal(yield* countEntries(sql), 1);
278 }),
279 ),
280);
281
282it.effect("keeps the reader read-only even if a statement turns query_only off", () =>
283 withReaderClient((sql) =>
284 Effect.gen(function* () {
285 const error = yield* sql
286 .withTransaction(
287 Effect.gen(function* () {
288 yield* sql`PRAGMA query_only = OFF`;
289 yield* sql`INSERT INTO entries VALUES ('blocked')`;
290 }),
291 )
292 .pipe(SqliteClient.readOnly, Effect.flip);
293
294 assert.equal(error._tag, "SqlError");
295 assert.include(String(error.reason.cause), "readonly database");
296 assert.equal(yield* countEntries(sql), 1);
297 }),
298 ),
299);
300
301it.effect("keeps read-only work inside a write transaction on the writer", () =>
302 withReaderClient((sql) =>
303 sql.withTransaction(
304 Effect.gen(function* () {
305 yield* sql`INSERT INTO entries VALUES ('uncommitted')`;
306 // Only the writer can see its own uncommitted row.
307 const count = yield* sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly);
308 assert.equal(count, 2);
309 }),
310 ),
311 ),
312);
313
314it.effect("fails a read-only transaction whose reader stops, then starts a new reader", () =>
315 withReaderClient((sql) =>
316 Effect.gen(function* () {
317 const startedBefore = startedWorkers.length;
318 const error = yield* sql
319 .withTransaction(
320 Effect.gen(function* () {
321 yield* countEntries(sql);
322 yield* Effect.promise(() => startedWorkers.at(-1)!.terminate());
323 return yield* countEntries(sql);
324 }),
325 )
326 .pipe(SqliteClient.readOnly, Effect.flip);
327
328 assert.equal(error._tag, "SqlError");
329 assert.include(String(error.reason.cause), "Database reader exited");
330 assert.equal(yield* countEntries(sql).pipe(SqliteClient.readOnly), 1);
331 assert.equal(startedWorkers.length, startedBefore + 2);
332 }),
333 ),
334);
335
336it.effect("uses the writer for read-only work on an in-memory database", () =>
337 Effect.gen(function* () {
338 const startedBefore = startedWorkers.length;
339 const sql = yield* SqlClient.SqlClient;
340 yield* sql`CREATE TABLE memory_entries(name TEXT NOT NULL)`;
341 yield* sql`INSERT INTO memory_entries VALUES ('kept')`;
342
343 const rows = yield* sql
344 .withTransaction(sql<{ name: string }>`SELECT name FROM memory_entries`)
345 .pipe(SqliteClient.readOnly);
346
347 assert.deepEqual(rows, [{ name: "kept" }]);
348 assert.equal(startedWorkers.length, startedBefore);
349 }).pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:", readerWorker: true }))),
350);
351
352it.effect("keeps a nested transaction inside a read-only transaction on the reader", () =>
353 withReaderClient((sql) =>
354 Effect.gen(function* () {
355 const snapshotTaken = yield* Deferred.make<void>();
356 const writer = yield* Effect.forkChild(
357 Deferred.await(snapshotTaken).pipe(
358 Effect.andThen(sql`INSERT INTO entries VALUES ('second')`),
359 ),
360 );
361 // Callers wrap a store read that opens its own transaction, as the
362 // shell snapshot routes do around getShellSnapshot.
363 const counts = yield* sql
364 .withTransaction(
365 Effect.gen(function* () {
366 const outer = yield* countEntries(sql);
367 yield* Deferred.succeed(snapshotTaken, undefined);
368 yield* Fiber.join(writer);
369 const nested = yield* sql.withTransaction(countEntries(sql));
370 return { outer, nested };
371 }),
372 )
373 .pipe(SqliteClient.readOnly);
374
375 assert.deepEqual(counts, { outer: 1, nested: 1 });
376 }),
377 ),
378);
379
380const withFileClient = <A, E>(
381 setup: (
382 sql: SqlClient.SqlClient,
383 filename: string,
384 ) => Effect.Effect<A, E, SqlClient.SqlClient | FileSystem.FileSystem>,
385) =>
386 Effect.gen(function* () {
387 const fs = yield* FileSystem.FileSystem;
388 const path = yield* Path.Path;
389 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-reader-off-" });
390 const filename = path.join(directory, "state.sqlite");
391 return yield* Effect.gen(function* () {
392 return yield* setup(yield* SqlClient.SqlClient, filename);
393 }).pipe(Effect.provide(SqliteClient.layer({ filename, readerWorker: true })));
394 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
395
396it.effect("uses the writer when the reader cannot open the database", () =>
397 withFileClient((sql, filename) =>
398 Effect.gen(function* () {
399 yield* sql`PRAGMA journal_mode = WAL`;
400 yield* sql`CREATE TABLE entries(name TEXT NOT NULL)`;
401 yield* sql`INSERT INTO entries VALUES ('kept')`;
402 // The writer keeps its open file; a read-only open of the path now fails.
403 yield* (yield* FileSystem.FileSystem).remove(filename);
404 const startedBefore = startedWorkers.length;
405
406 assert.equal(yield* sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly), 1);
407 assert.equal(yield* sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly), 1);
408 assert.equal(startedWorkers.length, startedBefore + 1);
409 }),
410 ),
411);
412
413it.effect("uses the writer for a database that is not in WAL mode", () =>
414 withFileClient((sql) =>
415 Effect.gen(function* () {
416 yield* sql`CREATE TABLE entries(name TEXT NOT NULL)`;
417 const startedBefore = startedWorkers.length;
418
419 // A write inside readOnly only succeeds on the writer: the reader is read-only.
420 yield* sql
421 .withTransaction(sql`INSERT INTO entries VALUES ('on the writer')`)
422 .pipe(SqliteClient.readOnly);
423 assert.equal(yield* sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly), 1);
424 assert.equal(startedWorkers.length, startedBefore + 1);
425 }),
426 ),
427);
428
429const captureWarnings = () => {
430 const warnings: Array<unknown> = [];
431 const logger = Logger.make(({ logLevel, message }) => {
432 if (logLevel === "Warn") warnings.push(message);
433 });
434 return { warnings, layer: Logger.layer([logger], { mergeWithExisting: false }) };
435};
436
437const silently = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
438 Effect.acquireUseRelease(
439 Effect.sync(() => {
440 silentWorkers.on = true;
441 }),
442 () => effect,
443 () =>
444 Effect.sync(() => {
445 silentWorkers.on = false;
446 silentWorkers.readyOnTerminate = false;
447 }),
448 );
449
450it.effect("turns the reader off when its worker never opens the database", () => {
451 const { warnings, layer: logs } = captureWarnings();
452 return withFileClient((sql) =>
453 Effect.gen(function* () {
454 yield* sql`PRAGMA journal_mode = WAL`;
455 yield* sql`CREATE TABLE entries(name TEXT NOT NULL)`;
456 yield* sql`INSERT INTO entries VALUES ('kept')`;
457 const read = yield* silently(
458 Effect.gen(function* () {
459 const fiber = yield* Effect.forkChild(
460 sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly),
461 );
462 yield* Effect.yieldNow;
463 yield* TestClock.adjust("10 seconds");
464 return yield* Fiber.join(fiber);
465 }),
466 );
467
468 assert.equal(read, 1);
469 assert.equal(yield* sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly), 1);
470 assert.lengthOf(warnings, 1);
471 }),
472 ).pipe(Effect.provide(logs));
473});
474
475it.effect("lets a read be cancelled while its worker is still starting", () =>
476 withFileClient((sql) =>
477 Effect.gen(function* () {
478 yield* sql`PRAGMA journal_mode = WAL`;
479 yield* sql`CREATE TABLE entries(name TEXT NOT NULL)`;
480 yield* silently(
481 Effect.gen(function* () {
482 const fiber = yield* Effect.forkChild(
483 sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly),
484 );
485 yield* Effect.yieldNow;
486 // Never returns if the wait for the worker were uninterruptible: the
487 // test clock has not moved, so the startup deadline cannot fire.
488 yield* Fiber.interrupt(fiber);
489 }),
490 );
491
492 // The client stays usable: the next read waits out the deadline, then uses the writer.
493 const next = yield* Effect.forkChild(
494 sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly),
495 );
496 yield* Effect.yieldNow;
497 yield* TestClock.adjust("10 seconds");
498 assert.equal(yield* Fiber.join(next), 0);
499 }),
500 ),
501);
502
503it.effect("logs one warning when concurrent first reads find the reader unavailable", () => {
504 const { warnings, layer: logs } = captureWarnings();
505 return withFileClient((sql, filename) =>
506 Effect.gen(function* () {
507 yield* sql`PRAGMA journal_mode = WAL`;
508 yield* sql`CREATE TABLE entries(name TEXT NOT NULL)`;
509 yield* (yield* FileSystem.FileSystem).remove(filename);
510 const startedBefore = startedWorkers.length;
511
512 const counts = yield* Effect.all(
513 [
514 sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly),
515 sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly),
516 ],
517 { concurrency: "unbounded" },
518 );
519
520 assert.deepEqual(counts, [0, 0]);
521 assert.equal(startedWorkers.length, startedBefore + 1);
522 assert.lengthOf(warnings, 1);
523 }),
524 ).pipe(Effect.provide(logs));
525});
526
527it.effect("does not hand out a worker that reports ready after another read timed it out", () =>
528 withFileClient((sql) =>
529 Effect.gen(function* () {
530 yield* sql`PRAGMA journal_mode = WAL`;
531 yield* sql`CREATE TABLE entries(name TEXT NOT NULL)`;
532 yield* sql`INSERT INTO entries VALUES ('kept')`;
533 const read = () => sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly);
534 const counts = yield* silently(
535 Effect.gen(function* () {
536 const first = yield* Effect.forkChild(read());
537 yield* Effect.yieldNow;
538 yield* TestClock.adjust("5 seconds");
539 const second = yield* Effect.forkChild(read());
540 yield* Effect.yieldNow;
541 // The first read reaches its deadline and retires the worker; the second
542 // is still waiting when the worker's "ready" arrives, before it exits.
543 silentWorkers.readyOnTerminate = true;
544 yield* TestClock.adjust("5 seconds");
545 return [yield* Fiber.join(first), yield* Fiber.join(second)];
546 }),
547 );
548
549 assert.deepEqual(counts, [1, 1]);
550 }),
551 ),
552);