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