Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import * as Clock from "effect/Clock";
4import * as Deferred from "effect/Deferred";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Option from "effect/Option";
9import * as Path from "effect/Path";
10import * as Queue from "effect/Queue";
11import * as Stream from "effect/Stream";
12import * as TestClock from "effect/testing/TestClock";
13import * as SqlClient from "effect/sql/SqlClient";
14
15import * as ServerConfig from "../config.ts";
16import * as EventStore from "../orchestration-v2/EventStore.ts";
17import * as ProjectionMaintenance from "../orchestration-v2/ProjectionMaintenance.ts";
18import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
19import * as DatabaseStorage from "./DatabaseStorage.ts";
20import * as Sqlite from "./Sqlite.ts";
21
22const freePages = Effect.map(
23 Effect.flatMap(
24 SqlClient.SqlClient,
25 (sql) => sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`,
26 ),
27 (rows) => rows[0]?.freelist_count ?? 0,
28);
29
30const storageLayer = <E>(
31 config: Layer.Layer<ServerConfig.ServerConfig, E, FileSystem.FileSystem | Path.Path>,
32) =>
33 DatabaseStorage.layer.pipe(
34 Layer.provide(ProjectionMaintenance.layer),
35 Layer.provide(Layer.merge(EventStore.layer, ProjectionStore.layer)),
36 Layer.provideMerge(Sqlite.layerMemory),
37 Layer.provideMerge(config),
38 Layer.provide(NodeServices.layer),
39 );
40
41const testConfig = ServerConfig.layerTest(process.cwd(), { prefix: "database-storage-" });
42
43const currentStatus = Effect.flatMap(DatabaseStorage.DatabaseStorage, (storage) =>
44 storage.status.pipe(Stream.take(1), Stream.runHead),
45);
46
47it.effect("a new database returns freed pages online without losing data", () =>
48 Effect.gen(function* () {
49 const sql = yield* SqlClient.SqlClient;
50 const storage = yield* DatabaseStorage.DatabaseStorage;
51 assert.deepEqual(yield* sql`PRAGMA auto_vacuum`, [{ auto_vacuum: 2 }]);
52 yield* sql`CREATE TABLE retained (value TEXT)`;
53 yield* sql`INSERT INTO retained VALUES ('keep')`;
54 yield* sql`CREATE TABLE discarded (value BLOB)`;
55 yield* sql`INSERT INTO discarded VALUES (zeroblob(1048576))`;
56 yield* sql`DROP TABLE discarded`;
57 assert.isAbove(yield* freePages, 0);
58 yield* storage.reclaim;
59 assert.equal(yield* freePages, 0);
60 assert.deepEqual(yield* sql`SELECT value FROM retained`, [{ value: "keep" }]);
61 }).pipe(Effect.provide(storageLayer(testConfig))),
62);
63
64it.effect("publishes file accounting and the doctor command after each pass", () =>
65 Effect.gen(function* () {
66 const sql = yield* SqlClient.SqlClient;
67 const config = yield* ServerConfig.ServerConfig;
68 yield* sql`CREATE TABLE discarded (value BLOB)`;
69 yield* sql`INSERT INTO discarded VALUES (zeroblob(1048576))`;
70 yield* TestClock.adjust("1 minute");
71 const before = (yield* currentStatus).pipe(Option.getOrThrow);
72 assert.isNotNull(before);
73 assert.isAbove(before!.databaseBytes, 1048576);
74 assert.isTrue(before!.incrementalVacuumEnabled);
75 // Quoting follows the host shell, so check each word on its own.
76 assert.include(before!.compactCommand, "doctor");
77 assert.include(before!.compactCommand, "--base-dir");
78 assert.include(before!.compactCommand, config.baseDir);
79
80 // The next reclaim pass frees the dropped table and republishes.
81 yield* sql`DROP TABLE discarded`;
82 yield* TestClock.adjust("1 minute");
83 const storage = yield* DatabaseStorage.DatabaseStorage;
84 const after = yield* storage.status.pipe(
85 Stream.filter((status) => status !== null && status.databaseBytes < before!.databaseBytes),
86 Stream.runHead,
87 Effect.map(Option.getOrThrow),
88 );
89 assert.isAtMost(after!.databaseBytes, before!.databaseBytes - 1048576);
90 assert.equal(after!.reclaimableBytes, 0);
91 }).pipe(Effect.provide(storageLayer(testConfig))),
92);
93
94it.effect("publishes nothing when doctor would repair a different database", () =>
95 Effect.gen(function* () {
96 yield* TestClock.adjust("1 minute");
97 assert.deepEqual(yield* currentStatus, Option.some(null));
98 }).pipe(
99 Effect.provide(
100 storageLayer(
101 // A dev server without an explicit home keeps state in <baseDir>/dev,
102 // while `doctor --base-dir` targets <baseDir>/userdata.
103 Layer.effect(
104 ServerConfig.ServerConfig,
105 Effect.gen(function* () {
106 const config = yield* ServerConfig.ServerConfig;
107 return { ...config, dbPath: `${config.baseDir}/dev/statev2.sqlite` };
108 }),
109 ).pipe(Layer.provide(testConfig)),
110 ),
111 ),
112 ),
113);
114
115const compactionLayer = (
116 compactEventStore: ProjectionMaintenance.ProjectionMaintenanceV2["Service"]["compactEventStore"],
117) =>
118 DatabaseStorage.layer.pipe(
119 Layer.provide(
120 Layer.succeed(ProjectionMaintenance.ProjectionMaintenanceV2, {
121 compactEventStore,
122 verify: Effect.die("unexpected verification"),
123 rebuild: Effect.die("unexpected rebuild"),
124 }),
125 ),
126 Layer.provide(Sqlite.layerMemory),
127 );
128
129const minute = 60_000;
130const hour = 60 * minute;
131const startupTime = Date.UTC(2026, 9, 19);
132const emptyCompaction = { deletedEventCount: 0, deletedReceiptCount: 0, reclaimableBytes: 0 };
133
134it.effect.each([
135 { name: "recent success", saved: String(startupTime - 2 * hour), delay: 4 * hour },
136 { name: "overdue success", saved: String(startupTime - 7 * hour), delay: minute },
137 { name: "nearly due success", saved: String(startupTime - 6 * hour + 1), delay: minute },
138 { name: "future timestamp", saved: String(startupTime + hour), delay: 6 * hour },
139 { name: "missing timestamp", saved: undefined, delay: minute },
140 { name: "invalid timestamp", saved: "not a timestamp", delay: minute },
141 { name: "unreadable timestamp", saved: undefined, delay: minute },
142])("schedules startup compaction after $name", ({ name, saved, delay }) =>
143 Effect.gen(function* () {
144 yield* TestClock.setTime(startupTime);
145 const fs = yield* FileSystem.FileSystem;
146 const path = yield* Path.Path;
147 const config = yield* ServerConfig.ServerConfig;
148 const timestampPath = path.join(path.dirname(config.dbPath), "compacted-at");
149 if (name === "unreadable timestamp") yield* fs.makeDirectory(timestampPath);
150 else if (saved !== undefined) yield* fs.writeFileString(timestampPath, saved);
151 const started = yield* Deferred.make<number>();
152 const compact = Clock.currentTimeMillis.pipe(
153 Effect.flatMap((now) => Deferred.succeed(started, now)),
154 Effect.as(emptyCompaction),
155 );
156 yield* Effect.gen(function* () {
157 yield* TestClock.adjust(delay - 1);
158 assert.isFalse(yield* Deferred.isDone(started));
159 yield* TestClock.adjust(1);
160 assert.equal(yield* Deferred.await(started), startupTime + delay);
161 }).pipe(Effect.provide(compactionLayer(compact)));
162 }).pipe(Effect.provide(testConfig.pipe(Layer.provideMerge(NodeServices.layer)))),
163);
164
165it.effect.each(["success", "compaction failure", "timestamp write failure"] as const)(
166 "keeps the six-hour cadence after %s and remembers only successful completion",
167 (outcome) =>
168 Effect.gen(function* () {
169 yield* TestClock.setTime(startupTime);
170 const fs = yield* FileSystem.FileSystem;
171 const path = yield* Path.Path;
172 const config = yield* ServerConfig.ServerConfig;
173 const timestampPath = path.join(path.dirname(config.dbPath), "compacted-at");
174 const previous = String(startupTime - 7 * hour);
175 if (outcome === "timestamp write failure") yield* fs.makeDirectory(timestampPath);
176 else yield* fs.writeFileString(timestampPath, previous);
177 const starts = yield* Queue.unbounded<number>();
178 const finish = yield* Queue.unbounded<void>();
179 const writeFinished = yield* Deferred.make<void>();
180 const compact = Effect.gen(function* () {
181 yield* Queue.offer(starts, yield* Clock.currentTimeMillis);
182 yield* Queue.take(finish);
183 if (outcome === "compaction failure") {
184 return yield* new ProjectionMaintenance.ProjectionMaintenanceError({ operation: "test" });
185 }
186 return emptyCompaction;
187 });
188 yield* Effect.gen(function* () {
189 yield* TestClock.adjust(minute);
190 assert.equal(yield* Queue.take(starts), startupTime + minute);
191 yield* TestClock.adjust(2 * minute);
192 if (outcome !== "timestamp write failure") {
193 assert.equal(yield* fs.readFileString(timestampPath), previous);
194 }
195 yield* Queue.offer(finish, undefined);
196 if (outcome !== "compaction failure") yield* Deferred.await(writeFinished);
197 yield* TestClock.adjust(6 * hour - 1);
198 assert.equal(yield* Queue.size(starts), 0);
199 yield* TestClock.adjust(1);
200 assert.equal(yield* Queue.take(starts), startupTime + 3 * minute + 6 * hour);
201 }).pipe(
202 Effect.provide(compactionLayer(compact)),
203 Effect.provideService(FileSystem.FileSystem, {
204 ...fs,
205 writeFileString: (file, content, options) =>
206 fs
207 .writeFileString(file, content, options)
208 .pipe(Effect.ensuring(Deferred.succeed(writeFinished, undefined))),
209 }),
210 );
211 if (outcome !== "timestamp write failure") {
212 const saved = Number(yield* fs.readFileString(timestampPath));
213 assert.equal(saved, outcome === "success" ? startupTime + 3 * minute : Number(previous));
214 }
215 }).pipe(Effect.provide(testConfig.pipe(Layer.provideMerge(NodeServices.layer)))),
216);