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