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

Sqlite.test.ts

317 lines12.4 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3import * as NodeOS from "node:os";
4import * as NodePath from "node:path";
5import * as NodeSqlite from "node:sqlite";
6import type * as NodeWorkerThreads from "node:worker_threads";
7​
8import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
9import * as NodeServices from "@effect/platform-node/NodeServices";
10import { assert, it } from "@effect/vitest";
11import * as HostProcess from "@t3tools/shared/HostProcess";
12import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
13import * as Effect from "effect/Effect";
14import * as FileSystem from "effect/FileSystem";
15import * as Layer from "effect/Layer";
16import * as SqlClient from "effect/sql/SqlClient";
17import * as SqlError from "effect/sql/SqlError";
18import { vi } from "vite-plus/test";
19​
20import * as ServerConfig from "../config.ts";
21import * as ProcessRunner from "../processRunner.ts";
22import * as ServerOwnership from "../serverOwnership.ts";
23import { migrationManifest, runMigrations } from "./Migrations.ts";
24import * as SqlitePersistence from "./Sqlite.ts";
25​
26const workers = vi.hoisted((): Array<NodeWorkerThreads.Worker> => []);
27const workerData = vi.hoisted((): Array<unknown> => []);
28​
29vi.mock("node:worker_threads", async (importOriginal) => {
30 const actual = await importOriginal<typeof NodeWorkerThreads>();
31 class RecordedWorker extends actual.Worker {
32 constructor(...args: ConstructorParameters<typeof actual.Worker>) {
33 super(...args);
34 workers.push(this);
35 workerData.push(args[1]?.workerData);
36 }
37 }
38 return { ...actual, Worker: RecordedWorker };
39});
40​
41it.effect("keeps writes moving past a 48 MiB WAL while a reader retains its snapshot", () => {
42 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-sqlite-burst-"));
43 const dbPath = NodePath.join(tempDir, "state.sqlite");
44 const persistence = SqlitePersistence.layerFromPath(dbPath).pipe(
45 Layer.provide(NodeServices.layer),
46 );
47​
48 return Effect.gen(function* () {
49 const sql = yield* SqlClient.SqlClient;
50 const checkpointWorker = workers.at(-1)!;
51 yield* sql`CREATE TABLE burst_probe(id INTEGER PRIMARY KEY, payload BLOB)`;
52 yield* sql`INSERT INTO burst_probe VALUES (1, NULL)`;
53 yield* sql`PRAGMA wal_checkpoint(TRUNCATE)`;
54 const reader = yield* Effect.acquireRelease(
55 Effect.sync(() => new NodeSqlite.DatabaseSync(dbPath, { readOnly: true })),
56 (database) => Effect.sync(() => database.close()),
57 );
58 reader.exec("BEGIN");
59 assert.equal(reader.prepare("SELECT COUNT(*) AS count FROM burst_probe").get()?.count, 1);
60​
61 yield* sql.withTransaction(
62 sql`INSERT INTO burst_probe VALUES (2, zeroblob(${48 * 1024 * 1024}))`,
63 );
64 const state = yield* Effect.callback<{
65 readonly log: number;
66 readonly checkpointed: number;
67 readonly blocked: boolean;
68 }>((resume) => {
69 const onMessage = (message: {
70 readonly type?: string;
71 readonly log?: number;
72 readonly checkpointed?: number;
73 readonly blocked?: boolean;
74 }) => {
75 if (
76 message.type === "checkpoint" &&
77 typeof message.log === "number" &&
78 message.log > 10_000 &&
79 typeof message.checkpointed === "number" &&
80 typeof message.blocked === "boolean"
81 ) {
82 checkpointWorker.off("message", onMessage);
83 resume(
84 Effect.succeed({
85 log: message.log,
86 checkpointed: message.checkpointed,
87 blocked: message.blocked,
88 }),
89 );
90 }
91 };
92 checkpointWorker.on("message", onMessage);
93 checkpointWorker.ref();
94 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
95 checkpointWorker.postMessage("barrier");
96 return Effect.sync(() => checkpointWorker.off("message", onMessage));
97 });
98 assert.isBelow(state.checkpointed, state.log);
99 assert.isFalse(state.blocked);
100​
101 yield* sql.withTransaction(sql`INSERT INTO burst_probe VALUES (3, NULL)`);
102 assert.equal(reader.prepare("SELECT COUNT(*) AS count FROM burst_probe").get()?.count, 1);
103 reader.exec("COMMIT");
104 assert.equal(reader.prepare("SELECT COUNT(*) AS count FROM burst_probe").get()?.count, 3);
105 }).pipe(
106 Effect.scoped,
107 Effect.provide(persistence),
108 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))),
109 );
110});
111​
112// Linux names an open, already-deleted file "<path> (deleted)" in /proc/self/fd.
113// SQLite names its temp files "etilqs_*" and, without TMPDIR, puts them in
114// /var/tmp while os.tmpdir() is /tmp, so match the name, not the directory.
115const openDeletedTempFiles = () =>
116 NodeFS.readdirSync("/proc/self/fd").flatMap((fd) => {
117 try {
118 const target = NodeFS.readlinkSync(`/proc/self/fd/${fd}`);
119 return target.includes("/etilqs_") && target.endsWith(" (deleted)") ? [target] : [];
120 } catch {
121 return [];
122 }
123 });
124​
125it.effect.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
126 "keeps a write transaction's statement journal off the temp directory",
127 () => {
128 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-sqlite-temp-"));
129 const persistence = SqlitePersistence.layerFromPath(
130 NodePath.join(tempDir, "state.sqlite"),
131 ).pipe(Layer.provide(NodeServices.layer));
132​
133 return Effect.gen(function* () {
134 const sql = yield* SqlClient.SqlClient;
135 yield* sql`CREATE TABLE journal_probe(id INTEGER PRIMARY KEY, payload TEXT NOT NULL)`;
136 for (let id = 0; id < 64; id++) {
137 yield* sql`INSERT INTO journal_probe VALUES (${id}, ${"x".repeat(4096)})`;
138 }
139 const before = new Set(openDeletedTempFiles());
140 const opened = yield* sql.withTransaction(
141 Effect.gen(function* () {
142 // A multi-row update can fail halfway, so SQLite journals every page
143 // it changes, here well past the 64 KiB it holds in memory by default.
144 yield* sql`UPDATE journal_probe SET payload = payload || 'y'`;
145 return openDeletedTempFiles().filter((target) => !before.has(target));
146 }),
147 );
148 assert.deepEqual(opened, []);
149 }).pipe(
150 Effect.provide(persistence),
151 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))),
152 );
153 },
154);
155​
156it.effect("drops planner statistics a database already has", () => {
157 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-sqlite-stats-"));
158 const dbPath = NodePath.join(tempDir, "state.sqlite");
159 const persistence = () =>
160 SqlitePersistence.layerFromPath(dbPath).pipe(Layer.provide(NodeServices.layer));
161​
162 return Effect.gen(function* () {
163 yield* Effect.gen(function* () {
164 const sql = yield* SqlClient.SqlClient;
165 yield* sql`CREATE TABLE walk_probe(node_id TEXT PRIMARY KEY, parent_node_id TEXT)`;
166 yield* sql`INSERT INTO walk_probe VALUES ('node-1', NULL), ('node-2', 'node-1')`;
167 yield* sql`ANALYZE walk_probe`;
168 }).pipe(Effect.provide(persistence()));
169​
170 yield* Effect.gen(function* () {
171 const sql = yield* SqlClient.SqlClient;
172 const stats = yield* sql<{ readonly count: number }>`
173 SELECT COUNT(*) AS count FROM sqlite_stat1
174 `;
175 assert.equal(stats[0]?.count, 0);
176 // A connection still using the old stats scans the table at each step.
177 const plan = yield* sql<{ readonly detail: string }>`
178 EXPLAIN QUERY PLAN
179 WITH RECURSIVE retained(node_id) AS (
180 SELECT 'node-2'
181 UNION
182 SELECT parent.parent_node_id FROM walk_probe AS parent
183 INNER JOIN retained ON parent.node_id = retained.node_id
184 )
185 SELECT node_id FROM retained
186 `;
187 assert.include(
188 plan.map((row) => row.detail),
189 "SEARCH parent USING INDEX sqlite_autoindex_walk_probe_1 (node_id=?)",
190 );
191 }).pipe(Effect.provide(persistence()));
192 }).pipe(
193 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))),
194 );
195});
196​
197it.effect("upgrades an existing database on a read-write worker connection", () => {
198 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-sqlite-upgrade-"));
199 const dbPath = NodePath.join(tempDir, "state.sqlite");
200​
201 return Effect.gen(function* () {
202 yield* Effect.gen(function* () {
203 const sql = yield* SqlClient.SqlClient;
204 yield* sql`PRAGMA journal_mode = WAL;`;
205 yield* runMigrations({ toMigrationInclusive: 81 });
206 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dbPath })));
207 const startedBefore = workerData.length;
208​
209 yield* Effect.gen(function* () {
210 const sql = yield* SqlClient.SqlClient;
211 const rows = yield* sql<{ readonly migration_id: number; readonly name: string }>`
212 SELECT migration_id, name FROM effect_sql_migrations ORDER BY migration_id
213 `;
214 assert.deepStrictEqual(
215 rows.map((row) => [row.migration_id, row.name] as const),
216 migrationManifest,
217 );
218 }).pipe(
219 Effect.provide(
220 SqlitePersistence.layerFromPath(dbPath).pipe(Layer.provide(NodeServices.layer)),
221 ),
222 );
223 assert.deepInclude(workerData.slice(startedBefore), {
224 filename: dbPath,
225 readOnly: false,
226 allowExtension: false,
227 prepareCacheSize: 200,
228 });
229 }).pipe(
230 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))),
231 );
232});
233​
234it.effect("names a database file that is not SQLite", () => {
235 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-sqlite-notadb-"));
236 const dbPath = NodePath.join(tempDir, "state.sqlite");
237 NodeFS.writeFileSync(dbPath, "not a db\n");
238​
239 return Effect.gen(function* () {
240 const opened = yield* Effect.void.pipe(
241 Effect.provide(
242 SqlitePersistence.layerFromPath(dbPath).pipe(Layer.provide(NodeServices.layer)),
243 ),
244 Effect.result,
245 );
246​
247 assert.equal(opened._tag, "Failure");
248 if (opened._tag === "Failure") {
249 assert.isTrue(SqlError.isSqlError(opened.failure));
250 assert.include(opened.failure.message, dbPath);
251 }
252 }).pipe(
253 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))),
254 );
255});
256​
257const ownT3Home = Effect.fn(function* () {
258 const { serverRuntimeStatePath } = yield* ServerConfig.ServerConfig;
259 // An empty home, so no boot service installed on this machine is read.
260 const home = yield* (yield* FileSystem.FileSystem).makeTempDirectoryScoped();
261 yield* ServerOwnership.acquireServerOwnership(serverRuntimeStatePath).pipe(
262 Effect.provide(ProcessRunner.layer),
263 Effect.provideService(HostProcess.HomeDirectory, home),
264 Effect.provideService(HostProcess.Environment, {}),
265 );
266});
267​
268const migrateTo = (toMigrationInclusive?: number) =>
269 Effect.gen(function* () {
270 const { dbPath } = yield* ServerConfig.ServerConfig;
271 yield* runMigrations({ toMigrationInclusive }).pipe(
272 Effect.provide(NodeSqliteClient.layer({ filename: dbPath })),
273 );
274 });
275​
276const latestRecordedMigrationId = Effect.gen(function* () {
277 const { dbPath } = yield* ServerConfig.ServerConfig;
278 const rows = yield* Effect.gen(function* () {
279 const sql = yield* SqlClient.SqlClient;
280 return yield* sql<{ readonly id: number }>`
281 SELECT MAX(migration_id) AS id FROM effect_sql_migrations
282 `;
283 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dbPath })));
284 return rows[0]?.id;
285});
286​
287const layerT3Home = ServerConfig.layerTest(process.cwd(), { prefix: "t3-sqlite-cli-" });
288​
289it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("layerCliConfig", (it) => {
290 it.effect("does not migrate a T3 home a running server owns", () =>
291 Effect.gen(function* () {
292 const recorded = Math.max(...migrationManifest.map(([id]) => id)) - 1;
293 yield* migrateTo(recorded);
294 yield* ownT3Home();
295​
296 const opened = yield* Effect.void.pipe(
297 Effect.provide(SqlitePersistence.layerCliConfig),
298 Effect.result,
299 );
300​
301 assert.equal(yield* latestRecordedMigrationId, recorded);
302 assert.equal(opened._tag, "Failure");
303 if (opened._tag === "Failure") {
304 assert.instanceOf(opened.failure, SqlitePersistence.ServerOwnsDatabaseError);
305 }
306 }).pipe(Effect.scoped, Effect.provide(layerT3Home)),
307 );
308​
309 it.effect("opens a current T3 home while a running server owns it", () =>
310 Effect.gen(function* () {
311 yield* migrateTo();
312 yield* ownT3Home();
313​
314 yield* Effect.void.pipe(Effect.provide(SqlitePersistence.layerCliConfig));
315 }).pipe(Effect.scoped, Effect.provide(layerT3Home)),
316 );
317});