Open History to see the last commit
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 Path from "effect/Path";
8import * as Schema from "effect/Schema";
9import * as SqlClient from "effect/sql/SqlClient";
10import { isSqlError } from "effect/sql/SqlError";
11
12import * as ProjectionMaintenance from "../orchestration-v2/ProjectionMaintenance.ts";
13import { rebuildMessageSearch } from "../orchestration-v2/messageSearchIndex.ts";
14
15export class DatabaseMissingError extends Schema.TaggedError<DatabaseMissingError>()(
16 "DatabaseMissingError",
17 { path: Schema.String },
18) {
19 override get message() {
20 return "No existing T3 Code database was found in this data directory.";
21 }
22}
23
24export class DatabaseInUseError extends Schema.TaggedError<DatabaseInUseError>()(
25 "DatabaseInUseError",
26 { path: Schema.String, cause: Schema.Defect() },
27) {
28 override get message() {
29 return "Stop the T3 Code server and desktop app, including any version before 0.1.0, before repairing the database.";
30 }
31}
32
33export class DatabaseInspectError extends Schema.TaggedError<DatabaseInspectError>()(
34 "DatabaseInspectError",
35 { path: Schema.String, cause: Schema.Defect() },
36) {
37 override get message() {
38 return "Could not read the database. Check that this user can open it.";
39 }
40}
41
42export class DatabaseCompactError extends Schema.TaggedError<DatabaseCompactError>()(
43 "DatabaseCompactError",
44 { path: Schema.String, cause: Schema.Defect() },
45) {
46 override get message() {
47 return "Database compaction failed. Check that no other process has the database open and enough disk space is available.";
48 }
49}
50
51export class LegacyDatabaseRemoveError extends Schema.TaggedError<LegacyDatabaseRemoveError>()(
52 "LegacyDatabaseRemoveError",
53 { path: Schema.String, cause: Schema.Defect() },
54) {
55 override get message() {
56 return "Could not delete the database from before 0.1.0. Check that this user can write to the data directory.";
57 }
58}
59
60export class DatabaseMaintenance extends Context.Service<
61 DatabaseMaintenance,
62 {
63 readonly inspect: (databasePath: string) => Effect.Effect<
64 {
65 readonly databaseBytes: number;
66 readonly reclaimableBytes: number;
67 readonly incrementalVacuumEnabled: boolean;
68 /** Size of the database from before 0.1.0 still kept beside it, or null. */
69 readonly legacyDatabaseBytes: number | null;
70 },
71 DatabaseMissingError | DatabaseInspectError
72 >;
73 /** Compacts history, then VACUUMs into incremental auto_vacuum. Refuses while a server has it open. */
74 readonly compact: (databasePath: string) => Effect.Effect<
75 {
76 readonly beforeBytes: number;
77 readonly afterBytes: number;
78 readonly deletedEventCount: number;
79 readonly deletedReceiptCount: number;
80 },
81 DatabaseMissingError | DatabaseInUseError | DatabaseCompactError
82 >;
83 /** Deletes only the pre-0.1.0 database; earlier versions still use it. */
84 readonly removeLegacyDatabase: (
85 databasePath: string,
86 ) => Effect.Effect<void, DatabaseInUseError | LegacyDatabaseRemoveError>;
87 }
88>()("t3/persistence/DatabaseMaintenance") {}
89
90const isDomainError = Schema.is(Schema.Union([DatabaseMissingError, DatabaseInUseError]));
91
92const readStorage = Effect.gen(function* () {
93 const sql = yield* SqlClient.SqlClient;
94 const pages = yield* sql<{ readonly page_count: number }>`PRAGMA page_count`;
95 const free = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
96 const size = yield* sql<{ readonly page_size: number }>`PRAGMA page_size`;
97 const mode = yield* sql<{ readonly auto_vacuum: number }>`PRAGMA auto_vacuum`;
98 const pageSize = size[0]?.page_size ?? 0;
99 return {
100 databaseBytes: (pages[0]?.page_count ?? 0) * pageSize,
101 reclaimableBytes: (free[0]?.freelist_count ?? 0) * pageSize,
102 incrementalVacuumEnabled: mode[0]?.auto_vacuum === 2,
103 };
104});
105
106/**
107 * Holds an exclusive lock on the connection's database. In WAL mode this is
108 * refused while any other connection has the file open, even an idle one,
109 * which is how a running server or desktop app is detected.
110 */
111const lockExclusively = Effect.fn("DatabaseMaintenance.lockExclusively")(function* (
112 databasePath: string,
113) {
114 const sql = yield* SqlClient.SqlClient;
115 yield* sql`PRAGMA busy_timeout = 0`;
116 yield* sql`PRAGMA locking_mode = EXCLUSIVE`;
117 yield* sql`BEGIN EXCLUSIVE`.pipe(
118 Effect.mapError((cause) =>
119 isSqlError(cause) && cause.reason._tag === "LockTimeoutError"
120 ? new DatabaseInUseError({ path: databasePath, cause })
121 : cause,
122 ),
123 );
124 yield* sql`COMMIT`;
125});
126
127const make = Effect.gen(function* () {
128 const fs = yield* FileSystem.FileSystem;
129 const path = yield* Path.Path;
130 const legacyPath = (databasePath: string) =>
131 path.join(path.dirname(databasePath), "state.sqlite");
132
133 const locate = Effect.fn("DatabaseMaintenance.locate")(function* (databasePath: string) {
134 if (!(yield* fs.exists(databasePath))) {
135 return yield* new DatabaseMissingError({ path: databasePath });
136 }
137 });
138
139 const inspect = Effect.fn("DatabaseMaintenance.inspect")(
140 function* (databasePath: string) {
141 yield* locate(databasePath);
142 const storage = yield* readStorage.pipe(
143 Effect.provide(NodeSqliteClient.layer({ filename: databasePath, readonly: true })),
144 );
145 const legacy = legacyPath(databasePath);
146 const legacyDatabaseBytes = (yield* fs.exists(legacy))
147 ? Number((yield* fs.stat(legacy)).size)
148 : null;
149 return { ...storage, legacyDatabaseBytes };
150 },
151 (effect, databasePath) =>
152 effect.pipe(
153 Effect.mapError((cause) =>
154 isDomainError(cause) ? cause : new DatabaseInspectError({ path: databasePath, cause }),
155 ),
156 ),
157 );
158
159 const compact = Effect.fn("DatabaseMaintenance.compact")(
160 function* (databasePath: string) {
161 yield* locate(databasePath);
162 const beforeBytes = Number((yield* fs.stat(databasePath)).size);
163 const result = yield* Effect.gen(function* () {
164 const sql = yield* SqlClient.SqlClient;
165 yield* lockExclusively(databasePath);
166 const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
167 const summary = yield* maintenance.pruneEventStore();
168 // VACUUM is required to enable incremental auto_vacuum on existing databases.
169 yield* sql`PRAGMA auto_vacuum = INCREMENTAL`;
170 yield* sql`VACUUM`;
171 yield* rebuildMessageSearch(sql);
172 yield* sql`PRAGMA wal_checkpoint(TRUNCATE)`;
173 return summary;
174 }).pipe(
175 Effect.provide(
176 ProjectionMaintenance.layer.pipe(
177 Layer.provideMerge(NodeSqliteClient.layer({ filename: databasePath })),
178 ),
179 ),
180 );
181 const afterBytes = Number((yield* fs.stat(databasePath)).size);
182 return {
183 beforeBytes,
184 afterBytes,
185 deletedEventCount: result.deletedEventCount,
186 deletedReceiptCount: result.deletedReceiptCount,
187 };
188 },
189 (effect, databasePath) =>
190 effect.pipe(
191 Effect.mapError((cause) =>
192 isDomainError(cause) ? cause : new DatabaseCompactError({ path: databasePath, cause }),
193 ),
194 ),
195 );
196
197 const removeLegacyDatabase = Effect.fn("DatabaseMaintenance.removeLegacyDatabase")(
198 function* (databasePath: string) {
199 const legacy = legacyPath(databasePath);
200 if (!(yield* fs.exists(legacy))) return;
201 // Delete the database before WAL to preserve commits if unlink fails.
202 const removeFiles = Effect.forEach(
203 ["", "-wal", "-shm"],
204 (suffix) => fs.remove(legacy + suffix, { force: true }),
205 { discard: true },
206 );
207 const connection = NodeSqliteClient.layer({ filename: legacy });
208 if ((yield* HostProcess.Platform) === "win32") {
209 // Windows blocks unlink while any SQLite handle is open, including our own.
210 yield* lockExclusively(legacy).pipe(Effect.provide(connection));
211 yield* removeFiles;
212 } else {
213 yield* lockExclusively(legacy).pipe(
214 Effect.andThen(removeFiles),
215 Effect.provide(connection),
216 );
217 }
218 },
219 (effect, databasePath) =>
220 effect.pipe(
221 Effect.mapError((cause) =>
222 cause._tag === "DatabaseInUseError"
223 ? cause
224 : new LegacyDatabaseRemoveError({ path: legacyPath(databasePath), cause }),
225 ),
226 ),
227 );
228
229 return DatabaseMaintenance.of({ inspect, compact, removeLegacyDatabase });
230});
231
232export const layer = Layer.effect(DatabaseMaintenance, make);