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