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

nodeSqliteClient.test.ts

424 lines17.1 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 Effect from "effect/Effect";
7import * as Fiber from "effect/Fiber";
8import * as FileSystem from "effect/FileSystem";
9import * as Path from "effect/Path";
10import * as SqlClient from "effect/sql/SqlClient";
11import * as Statement from "effect/sql/Statement";
12import type * as Tracer from "effect/Tracer";
13import { vi } from "vite-plus/test";
14​
15import * as SqliteClient from "./nodeSqliteClient.ts";
16​
17const startedWorkers = vi.hoisted((): Array<NodeWorkerThreads.Worker> => []);
18const silentWorkers = vi.hoisted(() => ({ on: false, readyOnTerminate: false }));
19const failingWorkers = vi.hoisted(() => ({ message: undefined as string | undefined }));
20​
21vi.mock("node:worker_threads", async (importOriginal) => {
22 const actual = await importOriginal<typeof NodeWorkerThreads>();
23 class RecordedWorker extends actual.Worker {
24 constructor(...args: ConstructorParameters<typeof actual.Worker>) {
25 super(
26 ...((silentWorkers.on
27 ? ["setInterval(() => {}, 1 << 30);", { eval: true }]
28 : failingWorkers.message !== undefined
29 ? [`throw new Error(${JSON.stringify(failingWorkers.message)});`, { eval: true }]
30 : args) as ConstructorParameters<typeof actual.Worker>),
31 );
32 startedWorkers.push(this);
33 }
34 override terminate() {
35 // A "ready" already queued when termination starts reaches the parent before "exit".
36 if (silentWorkers.readyOnTerminate) this.emit("message", { type: "ready" });
37 return super.terminate();
38 }
39 }
40 return { ...actual, Worker: RecordedWorker };
41});
42​
43const withReaderClient = <A, E>(
44 use: (sql: SqlClient.SqlClient) => Effect.Effect<A, E, SqlClient.SqlClient>,
45) =>
46 Effect.gen(function* () {
47 const fs = yield* FileSystem.FileSystem;
48 const path = yield* Path.Path;
49 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-reader-" });
50 const filename = path.join(directory, "state.sqlite");
51 return yield* Effect.gen(function* () {
52 const sql = yield* SqlClient.SqlClient;
53 yield* sql`PRAGMA journal_mode = WAL`;
54 yield* sql`CREATE TABLE entries(name TEXT NOT NULL)`;
55 yield* sql`INSERT INTO entries VALUES ('first')`;
56 return yield* use(sql);
57 }).pipe(Effect.provide(SqliteClient.layer({ filename, readerWorker: true })));
58 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
59​
60const countEntries = (sql: SqlClient.SqlClient) =>
61 Effect.map(
62 sql<{ count: number }>`SELECT COUNT(*) AS count FROM entries`,
63 (rows) => rows[0]?.count,
64 );
65​
66const layer = it.layer(SqliteClient.layer({ filename: ":memory:" }));
67​
68layer("NodeSqliteClient", (it) => {
69 it.effect("records the writer connection owner on a waiting query", () =>
70 Effect.gen(function* () {
71 const sql = yield* SqlClient.SqlClient;
72 const held = yield* Deferred.make<void>();
73 const release = yield* Deferred.make<void>();
74 const holder = yield* sql
75 .withTransaction(
76 sql`SELECT 1`.pipe(
77 Effect.andThen(Deferred.succeed(held, undefined)),
78 Effect.andThen(Deferred.await(release)),
79 ),
80 )
81 .pipe(Effect.withSpan("test.writerHolder"), Effect.forkChild);
82 yield* Deferred.await(held);
83​
84 const waitingSpan = yield* Deferred.make<Tracer.Span>();
85 const observeWaiter: Statement.Transformer = (statement, _sql, _fiber, span) =>
86 Deferred.succeed(waitingSpan, span).pipe(Effect.as(statement));
87 const waiter = yield* sql`SELECT 1`.pipe(
88 Effect.provideService(Statement.CurrentTransformer, observeWaiter),
89 Effect.provideService(Statement.SpanPropagationEnabled, true),
90 (effect) => Effect.forkChild(effect, { startImmediately: true }),
91 );
92 const span = yield* Deferred.await(waitingSpan);
93 yield* Deferred.succeed(release, undefined);
94 yield* Fiber.join(holder);
95 yield* Fiber.join(waiter);
96​
97 assert.equal(span.attributes.get("db.lock_owner_at_start.name"), "test.writerHolder");
98 assert.typeOf(span.attributes.get("db.lock_owner_at_start.fiber_id"), "number");
99 assert.typeOf(span.attributes.get("db.lock_owner_at_start.trace_id"), "string");
100 assert.typeOf(span.attributes.get("db.lock_owner_at_start.span_id"), "string");
101 }),
102 );
103​
104 it.effect("retries preparing a query after the missing schema becomes available", () =>
105 Effect.gen(function* () {
106 const sql = yield* SqlClient.SqlClient;
107 const select = sql<{ name: string }>`SELECT name FROM created_after_prepare_failure`;
108 const error = yield* select.pipe(Effect.flip);
109 assert.equal(error._tag, "SqlError");
110 assert.equal(error.reason.operation, "prepare");
111​
112 yield* sql`CREATE TABLE created_after_prepare_failure(name TEXT NOT NULL)`;
113 yield* sql`INSERT INTO created_after_prepare_failure VALUES ('recovered')`;
114 assert.deepEqual(yield* select, [{ name: "recovered" }]);
115 assert.deepEqual(yield* select.values, [["recovered"]]);
116 }),
117 );
118​
119 it.effect("classifies constraint failures by their SQLite result code", () =>
120 Effect.gen(function* () {
121 const sql = yield* SqlClient.SqlClient;
122 yield* sql`CREATE TABLE constrained(name TEXT NOT NULL UNIQUE)`;
123 yield* sql`INSERT INTO constrained VALUES ('taken')`;
124​
125 const duplicate = yield* sql`INSERT INTO constrained VALUES ('taken')`.pipe(Effect.flip);
126 assert(duplicate.reason._tag === "UniqueViolation");
127 assert.equal(duplicate.reason.constraint, "constrained.name");
128​
129 const missing = yield* sql`INSERT INTO constrained VALUES (NULL)`.pipe(Effect.flip);
130 assert.equal(missing.reason._tag, "ConstraintError");
131 }),
132 );
133});
134​
135const largeText = "x".repeat(64 * 1024 + 1);
136​
137it.effect("reads integers on the values path as the caller asked, cached or not", () =>
138 Effect.gen(function* () {
139 const sql = yield* SqlClient.SqlClient;
140 for (const value of ["small", largeText]) {
141 const values = sql`SELECT 1 AS id, length(${value}) AS size`.values;
142 assert.deepEqual(yield* values.pipe(Effect.provideService(SqlClient.SafeIntegers, true)), [
143 [1n, BigInt(value.length)],
144 ]);
145 assert.deepEqual(yield* values, [[1, value.length]]);
146 }
147 }).pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:" }))),
148);
149​
150const makeTempDatabase = Effect.gen(function* () {
151 const fs = yield* FileSystem.FileSystem;
152 const path = yield* Path.Path;
153 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-transaction-" });
154 const filename = path.join(directory, "state.sqlite");
155 const other = yield* Effect.acquireRelease(
156 Effect.sync(() => new NodeSqlite.DatabaseSync(filename)),
157 (database) => Effect.sync(() => database.close()),
158 );
159 yield* Effect.sync(() => {
160 other.exec(`
161 PRAGMA journal_mode = WAL;
162 CREATE TABLE counters(id INTEGER PRIMARY KEY, value INTEGER NOT NULL);
163 INSERT INTO counters VALUES (1, 0);
164 `);
165 });
166 return { filename, other };
167});
168​
169it.effect("keeps another connection from committing between a transaction's read and write", () =>
170 Effect.gen(function* () {
171 const { filename, other } = yield* makeTempDatabase;
172 yield* Effect.gen(function* () {
173 const sql = yield* SqlClient.SqlClient;
174 yield* sql.withTransaction(
175 Effect.gen(function* () {
176 const [row] = yield* sql<{ readonly value: number }>`
177 SELECT value FROM counters WHERE id = 1
178 `;
179 // With a deferred BEGIN this commit lands and the write below fails
180 // with SQLITE_BUSY_SNAPSHOT, which no busy timeout can wait out.
181 yield* Effect.sync(() =>
182 assert.throws(
183 () => other.exec("UPDATE counters SET value = value + 1 WHERE id = 1"),
184 /database is locked/,
185 ),
186 );
187 yield* sql`UPDATE counters SET value = ${(row?.value ?? 0) + 10} WHERE id = 1`;
188 }),
189 );
190 yield* Effect.sync(() => other.exec("UPDATE counters SET value = value + 1 WHERE id = 1"));
191 assert.deepEqual(yield* sql`SELECT value FROM counters WHERE id = 1`.values, [[11]]);
192 }).pipe(Effect.provide(SqliteClient.layer({ filename })));
193 }).pipe(Effect.provide(NodeServices.layer)),
194);
195​
196it.effect("reports a transaction blocked by another writer as a lock timeout", () =>
197 Effect.gen(function* () {
198 const { filename, other } = yield* makeTempDatabase;
199 yield* Effect.gen(function* () {
200 const sql = yield* SqlClient.SqlClient;
201 yield* sql`PRAGMA busy_timeout = 0`;
202 const read = sql.withTransaction(sql`SELECT value FROM counters WHERE id = 1`.values);
203​
204 yield* Effect.sync(() => other.exec("BEGIN IMMEDIATE"));
205 const error = yield* read.pipe(Effect.flip);
206 assert.equal(error.reason._tag, "LockTimeoutError");
207​
208 yield* Effect.sync(() => other.exec("COMMIT"));
209 assert.deepEqual(yield* read, [[0]]);
210 }).pipe(Effect.provide(SqliteClient.layer({ filename })));
211 }).pipe(Effect.provide(NodeServices.layer)),
212);
213​
214it.effect("lets the writer commit while a read-only transaction is open", () =>
215 withReaderClient((sql) =>
216 Effect.gen(function* () {
217 const snapshotTaken = yield* Deferred.make<void>();
218 const writer = yield* Effect.forkChild(
219 Deferred.await(snapshotTaken).pipe(
220 Effect.andThen(sql`INSERT INTO entries VALUES ('second')`),
221 ),
222 );
223 const counts = yield* sql
224 .withTransaction(
225 Effect.gen(function* () {
226 const before = yield* countEntries(sql);
227 yield* Deferred.succeed(snapshotTaken, undefined);
228 // Holding the writer lock here would deadlock this join.
229 yield* Fiber.join(writer);
230 const after = yield* countEntries(sql);
231 return { before, after };
232 }),
233 )
234 .pipe(SqliteClient.readOnly);
235​
236 assert.deepEqual(counts, { before: 1, after: 1 });
237 assert.equal(yield* countEntries(sql).pipe(SqliteClient.readOnly), 2);
238 }),
239 ),
240);
241​
242// regression: #19226 read-only transactions run on the separate reader connection
243it.effect("rejects a write in a read-only transaction", () =>
244 withReaderClient((sql) =>
245 Effect.gen(function* () {
246 const error = yield* sql
247 .withTransaction(sql`INSERT INTO entries VALUES ('blocked')`)
248 .pipe(SqliteClient.readOnly, Effect.flip);
249​
250 assert.equal(error._tag, "SqlError");
251 assert.include(String(error.reason.cause), "readonly database");
252 assert.equal(yield* countEntries(sql), 1);
253 }),
254 ),
255);
256​
257it.effect("keeps the reader read-only even if a statement turns query_only off", () =>
258 withReaderClient((sql) =>
259 Effect.gen(function* () {
260 const error = yield* sql
261 .withTransaction(
262 Effect.gen(function* () {
263 yield* sql`PRAGMA query_only = OFF`;
264 yield* sql`INSERT INTO entries VALUES ('blocked')`;
265 }),
266 )
267 .pipe(SqliteClient.readOnly, Effect.flip);
268​
269 assert.equal(error._tag, "SqlError");
270 assert.include(String(error.reason.cause), "readonly database");
271 assert.equal(yield* countEntries(sql), 1);
272 }),
273 ),
274);
275​
276it.effect("keeps read-only work inside a write transaction on the writer", () =>
277 withReaderClient((sql) =>
278 sql.withTransaction(
279 Effect.gen(function* () {
280 yield* sql`INSERT INTO entries VALUES ('uncommitted')`;
281 const count = yield* sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly);
282 assert.equal(count, 2);
283 }),
284 ),
285 ),
286);
287​
288it.effect("fails a read-only transaction whose reader stops, then starts a new reader", () =>
289 withReaderClient((sql) =>
290 Effect.gen(function* () {
291 const startedBefore = startedWorkers.length;
292 const error = yield* sql
293 .withTransaction(
294 Effect.gen(function* () {
295 yield* countEntries(sql);
296 yield* Effect.promise(() => startedWorkers.at(-1)!.terminate());
297 return yield* countEntries(sql);
298 }),
299 )
300 .pipe(SqliteClient.readOnly, Effect.flip);
301​
302 assert.equal(error._tag, "SqlError");
303 assert.include(String(error.reason.cause), "Database reader exited");
304 assert.equal(yield* countEntries(sql).pipe(SqliteClient.readOnly), 1);
305 assert.equal(startedWorkers.length, startedBefore + 2);
306 }),
307 ),
308);
309​
310const withFileClient = <A, E>(
311 setup: (
312 sql: SqlClient.SqlClient,
313 filename: string,
314 ) => Effect.Effect<A, E, SqlClient.SqlClient | FileSystem.FileSystem>,
315) =>
316 Effect.gen(function* () {
317 const fs = yield* FileSystem.FileSystem;
318 const path = yield* Path.Path;
319 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-reader-off-" });
320 const filename = path.join(directory, "state.sqlite");
321 return yield* Effect.gen(function* () {
322 return yield* setup(yield* SqlClient.SqlClient, filename);
323 }).pipe(Effect.provide(SqliteClient.layer({ filename, readerWorker: true })));
324 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
325​
326it.effect("uses the writer when the reader cannot open the database", () =>
327 withFileClient((sql, filename) =>
328 Effect.gen(function* () {
329 yield* sql`PRAGMA journal_mode = WAL`;
330 yield* sql`CREATE TABLE entries(name TEXT NOT NULL)`;
331 yield* sql`INSERT INTO entries VALUES ('kept')`;
332 yield* (yield* FileSystem.FileSystem).remove(filename);
333 const startedBefore = startedWorkers.length;
334​
335 assert.equal(yield* sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly), 1);
336 assert.equal(yield* sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly), 1);
337 assert.equal(startedWorkers.length, startedBefore + 1);
338 }),
339 ),
340);
341​
342it.effect("finishes masked database cleanup after its caller is interrupted", () =>
343 Effect.gen(function* () {
344 const sql = yield* SqlClient.SqlClient;
345 yield* sql`CREATE TABLE cleanup_writes(value INTEGER PRIMARY KEY)`;
346 const entered = yield* Deferred.make<void>();
347 const work = yield* Effect.forkChild(
348 Deferred.succeed(entered, undefined).pipe(
349 Effect.andThen(Effect.never),
350 Effect.onInterrupt(() =>
351 Effect.gen(function* () {
352 yield* sql`INSERT INTO cleanup_writes VALUES (1)`;
353 yield* sql.withTransaction(sql`INSERT INTO cleanup_writes VALUES (2)`);
354 }),
355 ),
356 ),
357 { startImmediately: true },
358 );
359 yield* Deferred.await(entered);
360 yield* Fiber.interrupt(work);
361 assert.deepEqual(yield* sql`SELECT value FROM cleanup_writes ORDER BY value`.values, [
362 [1],
363 [2],
364 ]);
365 }).pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:" }))),
366);
367​
368// 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
369const eventLoopTurn = Effect.promise(() => new Promise<void>((resolve) => setImmediate(resolve)));
370​
371it.effect.each([
372 { reservation: false, masked: false },
373 { reservation: false, masked: true },
374 { reservation: true, masked: false },
375 { reservation: true, masked: true },
376])(
377 "preserves caller cancellation while waiting (reservation=$reservation, masked=$masked)",
378 ({ reservation, masked }) =>
379 Effect.gen(function* () {
380 const sql = yield* SqlClient.SqlClient;
381 yield* sql`CREATE TABLE entries(value INTEGER)`;
382 const held = yield* Deferred.make<void>();
383 const release = yield* Deferred.make<void>();
384 const holder = yield* Effect.forkChild(
385 sql.withTransaction(
386 Deferred.succeed(held, undefined).pipe(Effect.andThen(Deferred.await(release))),
387 ),
388 { startImmediately: true },
389 );
390 yield* Deferred.await(held);
391 const entered = yield* Deferred.make<void>();
392 const body = sql`INSERT INTO entries VALUES (1)`.pipe(
393 Effect.andThen(Deferred.succeed(entered, undefined)),
394 );
395 const acquire = reservation
396 ? Effect.scoped(
397 Effect.gen(function* () {
398 const connection = yield* sql.reserve;
399 yield* connection.executeUnprepared("INSERT INTO entries VALUES (1)", [], undefined);
400 yield* Deferred.succeed(entered, undefined);
401 }),
402 )
403 : sql.withTransaction(body);
404 const waiter = yield* Effect.forkChild(masked ? Effect.uninterruptible(acquire) : acquire, {
405 startImmediately: true,
406 });
407 const cancelled = yield* Effect.forkChild(Fiber.interrupt(waiter), {
408 startImmediately: true,
409 });
410 yield* Effect.gen(function* () {
411 yield* eventLoopTurn;
412 assert.equal(cancelled.pollUnsafe() !== undefined, !masked);
413 assert.isFalse(yield* Deferred.isDone(entered));
414 }).pipe(Effect.ensuring(Deferred.succeed(release, undefined)));
415 yield* Fiber.join(holder);
416 yield* Fiber.join(cancelled);
417 assert.equal(yield* Deferred.isDone(entered), masked);
418 yield* sql.withTransaction(sql`INSERT INTO entries VALUES (2)`);
419 assert.deepEqual(
420 yield* sql`SELECT value FROM entries ORDER BY value`.values,
421 masked ? [[1], [2]] : [[2]],
422 );
423 }).pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:" }))),
424);