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

DatabaseMaintenance.ts

346 lines13.6 KB

1import * as HostProcess from "@t3tools/shared/HostProcess";
2import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
3import * as Context from "effect/Context";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Path from "effect/Path";
9import * as Schedule from "effect/Schedule";
10import * as Schema from "effect/Schema";
11// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect has no free-space query.
12import * as NodeFSP from "node:fs/promises";
13import * as NodeOS from "node:os";
14import * as SqlClient from "effect/sql/SqlClient";
15import { isSqlError } from "effect/sql/SqlError";
16​
17import * as ProjectionMaintenance from "../orchestration-v2/ProjectionMaintenance.ts";
18import { rebuildMessageSearch } from "../orchestration-v2/messageSearchIndex.ts";
19​
20export class DatabaseMissingError extends Schema.TaggedError<DatabaseMissingError>()(
21 "DatabaseMissingError",
22 { path: Schema.String },
23) {
24 override get message() {
25 return "No existing T3 Code database was found in this data directory.";
26 }
28​
29export class DatabaseInUseError extends Schema.TaggedError<DatabaseInUseError>()(
30 "DatabaseInUseError",
31 { path: Schema.String, cause: Schema.Defect() },
32) {
33 override get message() {
34 return "Stop the T3 Code server and desktop app, including any version before 0.1.0, before repairing the database.";
35 }
37​
38export class DatabaseInspectError extends Schema.TaggedError<DatabaseInspectError>()(
39 "DatabaseInspectError",
40 { path: Schema.String, cause: Schema.Defect() },
41) {
42 override get message() {
43 return "Could not read the database. Check that this user can open it.";
44 }
46​
47export class DatabaseCompactError extends Schema.TaggedError<DatabaseCompactError>()(
48 "DatabaseCompactError",
49 { path: Schema.String, cause: Schema.Defect() },
50) {
51 override get message() {
52 return "Database compaction failed. Check that no other process has the database open and enough disk space is available.";
53 }
55​
56export class LegacyDatabaseRemoveError extends Schema.TaggedError<LegacyDatabaseRemoveError>()(
57 "LegacyDatabaseRemoveError",
58 { path: Schema.String, cause: Schema.Defect() },
59) {
60 override get message() {
61 return "Could not delete the database from before 0.1.0. Check that this user can write to the data directory.";
62 }
64​
65export class DiskSpaceCheckError extends Schema.TaggedError<DiskSpaceCheckError>()(
66 "DiskSpaceCheckError",
67 { path: Schema.String, cause: Schema.Defect() },
68) {
69 override get message() {
70 return "Could not check free disk space.";
71 }
73​
74export class DatabaseMaintenance extends Context.Service<
75 DatabaseMaintenance,
76 {
77 readonly inspect: (databasePath: string) => Effect.Effect<
78 {
79 readonly databaseBytes: number;
80 readonly reclaimableBytes: number;
81 readonly incrementalVacuumEnabled: boolean;
82 /** Size of the database from before 0.1.0 still kept beside it, or null. */
83 readonly legacyDatabaseBytes: number | null;
84 },
85 DatabaseMissingError | DatabaseInspectError
86 >;
87 /** Compacts history, then VACUUMs into incremental auto_vacuum. Refuses while a server has it open. */
88 readonly compact: (databasePath: string) => Effect.Effect<
89 {
90 readonly beforeBytes: number;
91 readonly afterBytes: number;
92 readonly deletedEventCount: number;
93 readonly deletedReceiptCount: number;
94 },
95 DatabaseMissingError | DatabaseInUseError | DatabaseCompactError
96 >;
97 /** Deletes only the pre-0.1.0 database; earlier versions still use it. */
98 readonly removeLegacyDatabase: (
99 databasePath: string,
100 ) => Effect.Effect<void, DatabaseInUseError | LegacyDatabaseRemoveError>;
101 }
102>()("t3/persistence/DatabaseMaintenance") {}
103​
104const isDomainError = Schema.is(Schema.Union([DatabaseMissingError, DatabaseInUseError]));
105​
106const readStorage = Effect.gen(function* () {
107 const sql = yield* SqlClient.SqlClient;
108 const pages = yield* sql<{ readonly page_count: number }>`PRAGMA page_count`;
109 const free = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
110 const size = yield* sql<{ readonly page_size: number }>`PRAGMA page_size`;
111 const mode = yield* sql<{ readonly auto_vacuum: number }>`PRAGMA auto_vacuum`;
112 const pageSize = size[0]?.page_size ?? 0;
113 return {
114 databaseBytes: (pages[0]?.page_count ?? 0) * pageSize,
115 reclaimableBytes: (free[0]?.freelist_count ?? 0) * pageSize,
116 incrementalVacuumEnabled: mode[0]?.auto_vacuum === 2,
117 };
118});
119​
120/**
121 * Holds an exclusive lock on the connection's database. In WAL mode this is
122 * refused while any other connection has the file open, even an idle one,
123 * which is how a running server or desktop app is detected.
124 */
125const lockExclusively = Effect.fn("DatabaseMaintenance.lockExclusively")(function* (
126 databasePath: string,
127) {
128 const sql = yield* SqlClient.SqlClient;
129 yield* sql`PRAGMA busy_timeout = 0`;
130 yield* sql`PRAGMA locking_mode = EXCLUSIVE`;
131 yield* sql`BEGIN EXCLUSIVE`.pipe(
132 Effect.mapError((cause) =>
133 isSqlError(cause) && cause.reason._tag === "LockTimeoutError"
134 ? new DatabaseInUseError({ path: databasePath, cause })
135 : cause,
136 ),
137 );
138 yield* sql`COMMIT`;
139});
140​
141const make = Effect.gen(function* () {
142 const fs = yield* FileSystem.FileSystem;
143 const path = yield* Path.Path;
144 const legacyPath = (databasePath: string) =>
145 path.join(path.dirname(databasePath), "state.sqlite");
146​
147 const locate = Effect.fn("DatabaseMaintenance.locate")(function* (databasePath: string) {
148 if (!(yield* fs.exists(databasePath))) {
149 return yield* new DatabaseMissingError({ path: databasePath });
150 }
151 });
152​
153 const inspect = Effect.fn("DatabaseMaintenance.inspect")(
154 function* (databasePath: string) {
155 yield* locate(databasePath);
156 const storage = yield* readStorage.pipe(
157 Effect.provide(NodeSqliteClient.layer({ filename: databasePath, readonly: true })),
158 );
159 const legacy = legacyPath(databasePath);
160 const legacyDatabaseBytes = (yield* fs.exists(legacy))
161 ? Number((yield* fs.stat(legacy)).size)
162 : null;
163 return { ...storage, legacyDatabaseBytes };
164 },
165 (effect, databasePath) =>
166 effect.pipe(
167 Effect.mapError((cause) =>
168 isDomainError(cause) ? cause : new DatabaseInspectError({ path: databasePath, cause }),
169 ),
170 ),
171 );
172​
173 const compact = Effect.fn("DatabaseMaintenance.compact")(
174 function* (databasePath: string) {
175 yield* locate(databasePath);
176 const beforeBytes = Number((yield* fs.stat(databasePath)).size);
177 const result = yield* Effect.gen(function* () {
178 const sql = yield* SqlClient.SqlClient;
179 yield* lockExclusively(databasePath);
180 const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
181 const summary = yield* maintenance.pruneEventStore();
182 // VACUUM is required to enable incremental auto_vacuum on existing databases.
183 yield* sql`PRAGMA auto_vacuum = INCREMENTAL`;
184 yield* sql`VACUUM`;
185 yield* rebuildMessageSearch(sql);
186 yield* sql`PRAGMA wal_checkpoint(TRUNCATE)`;
187 return summary;
188 }).pipe(
189 Effect.provide(
190 ProjectionMaintenance.layer.pipe(
191 Layer.provideMerge(NodeSqliteClient.layer({ filename: databasePath })),
192 ),
193 ),
194 );
195 const afterBytes = Number((yield* fs.stat(databasePath)).size);
196 return {
197 beforeBytes,
198 afterBytes,
199 deletedEventCount: result.deletedEventCount,
200 deletedReceiptCount: result.deletedReceiptCount,
201 };
202 },
203 (effect, databasePath) =>
204 effect.pipe(
205 Effect.mapError((cause) =>
206 isDomainError(cause) ? cause : new DatabaseCompactError({ path: databasePath, cause }),
207 ),
208 ),
209 );
210​
211 const removeLegacyDatabase = Effect.fn("DatabaseMaintenance.removeLegacyDatabase")(
212 function* (databasePath: string) {
213 const legacy = legacyPath(databasePath);
214 if (!(yield* fs.exists(legacy))) return;
215 // Delete the database before WAL to preserve commits if unlink fails.
216 const removeFiles = Effect.forEach(
217 ["", "-wal", "-shm"],
218 (suffix) => fs.remove(legacy + suffix, { force: true }),
219 { discard: true },
220 );
221 const connection = NodeSqliteClient.layer({ filename: legacy });
222 if ((yield* HostProcess.Platform) === "win32") {
223 // Windows blocks unlink while any SQLite handle is open, including our own.
224 yield* lockExclusively(legacy).pipe(Effect.provide(connection));
225 yield* removeFiles;
226 } else {
227 yield* lockExclusively(legacy).pipe(
228 Effect.andThen(removeFiles),
229 Effect.provide(connection),
230 );
231 }
232 },
233 (effect, databasePath) =>
234 effect.pipe(
235 Effect.mapError((cause) =>
236 cause._tag === "DatabaseInUseError"
237 ? cause
238 : new LegacyDatabaseRemoveError({ path: legacyPath(databasePath), cause }),
239 ),
240 ),
241 );
242​
243 return DatabaseMaintenance.of({ inspect, compact, removeLegacyDatabase });
244});
245​
246export const layer = Layer.effect(DatabaseMaintenance, make);
247​
248/** Settings' Reclaim writes the request; the failure stays for Settings until the next request. */
249export const reclaimFiles = (path: Path.Path, databasePath: string) => ({
250 request: path.join(path.dirname(databasePath), "reclaim-requested"),
251 failure: path.join(path.dirname(databasePath), "reclaim-failed"),
252});
253​
254/** Runs a repair that Settings requested. The server calls this on exit, once its database is closed. */
255export const runRequestedReclaim = Effect.fn("DatabaseMaintenance.runRequestedReclaim")(
256 function* (databasePath: string) {
257 const fs = yield* FileSystem.FileSystem;
258 const files = reclaimFiles(yield* Path.Path, databasePath);
259 if (!(yield* fs.exists(files.request))) return;
260 // One attempt per request, so a repair killed midway (it rolls back) cannot delay later exits.
261 yield* fs.remove(files.request, { force: true });
262 yield* Effect.logInfo("Reclaiming database space before the restart. This can take minutes.");
263 const maintenance = yield* DatabaseMaintenance;
264 yield* maintenance.compact(databasePath).pipe(
265 // Worker threads and agent processes can hold the file for a moment after the server stops.
266 Effect.retry({
267 times: 10,
268 while: (error) => error._tag === "DatabaseInUseError",
269 schedule: Schedule.spaced("1 second"),
270 }),
271 Effect.matchEffect({
272 onSuccess: (result) =>
273 fs
274 .remove(files.failure, { force: true })
275 .pipe(Effect.andThen(Effect.logInfo("Reclaimed database space", result))),
276 onFailure: (error) =>
277 fs
278 .writeFileString(
279 files.failure,
280 error._tag === "DatabaseInUseError"
281 ? "Another program kept the database open. Close other T3 Code apps and t3 commands on this machine, then try again."
282 : error.message,
283 )
284 .pipe(
285 Effect.andThen(Effect.logWarning("Database space reclamation failed", { error })),
286 ),
287 }),
288 );
289 },
290 Effect.catchCause((cause) => Effect.logWarning("Database space reclamation failed", { cause })),
291);
292​
293// SQLite's search order for its temporary files (unixTempFileDir in os_unix.c).
294const sqliteTempDirectory = Effect.gen(function* () {
295 if ((yield* HostProcess.Platform) === "win32") return NodeOS.tmpdir();
296 const fs = yield* FileSystem.FileSystem;
297 const env = yield* HostProcess.Environment;
298 for (const directory of [env.SQLITE_TMPDIR, env.TMPDIR, "/var/tmp", "/usr/tmp", "/tmp"]) {
299 if (directory === undefined || directory === "") continue;
300 const info = yield* fs.stat(directory).pipe(Effect.option);
301 if (Option.isNone(info) || info.value.type !== "Directory") continue;
302 // SQLite skips directories it cannot write to and search: osAccess(zDir, 03).
303 const usable = yield* Effect.tryPromise({
304 try: () => NodeFSP.access(directory, NodeFSP.constants.W_OK | NodeFSP.constants.X_OK),
305 catch: (cause) => new DiskSpaceCheckError({ path: directory, cause }),
306 }).pipe(
307 Effect.as(true),
308 Effect.orElseSucceed(() => false),
309 );
310 if (usable) return directory;
311 }
312 return ".";
313});
314​
315const freeBytes = (directory: string) =>
316 Effect.tryPromise({
317 try: () => NodeFSP.statfs(directory),
318 catch: (cause) => new DiskSpaceCheckError({ path: directory, cause }),
319 }).pipe(Effect.map((stats) => stats.bavail * stats.bsize));
320​
321/**
322 * VACUUM copies the live pages to a temporary file, then writes them again to the WAL.
323 * Returns the free space the repair needs when either file system has less, else null.
324 */
325export const reclaimSpaceShortfall = Effect.fn("DatabaseMaintenance.reclaimSpaceShortfall")(
326 function* (databasePath: string, liveBytes: number) {
327 const fs = yield* FileSystem.FileSystem;
328 const path = yield* Path.Path;
329 const databaseDirectory = path.dirname(databasePath);
330 const tempDirectory = yield* sqliteTempDirectory;
331 const copyBytes = Math.ceil(liveBytes * 1.1);
332 const [databaseFree, tempFree, databaseDevice, tempDevice] = yield* Effect.all([
333 freeBytes(databaseDirectory),
334 freeBytes(tempDirectory),
335 fs.stat(databaseDirectory).pipe(Effect.map((info) => info.dev)),
336 fs.stat(tempDirectory).pipe(Effect.map((info) => info.dev)),
337 ]);
338 if (databaseDevice === tempDevice) {
339 return databaseFree < 2 * copyBytes
340 ? { neededBytes: 2 * copyBytes, freeBytes: databaseFree }
341 : null;
342 }
343 if (databaseFree < copyBytes) return { neededBytes: copyBytes, freeBytes: databaseFree };
344 return tempFree < copyBytes ? { neededBytes: copyBytes, freeBytes: tempFree } : null;
345 },
346);