Open History to see the last commit
1import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Path from "effect/Path";
7import * as Schema from "effect/Schema";
8import * as SqlClient from "effect/sql/SqlClient";
9import { isSqlError } from "effect/sql/SqlError";
10
11import * as EventStore from "../orchestration-v2/EventStore.ts";
12import * as ProjectionMaintenance from "../orchestration-v2/ProjectionMaintenance.ts";
13import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
14import { rebuildMessageSearch } from "../orchestration-v2/messageSearchIndex.ts";
15
16export class DatabaseMissingError extends Schema.TaggedError<DatabaseMissingError>()(
17 "DatabaseMissingError",
18 { path: Schema.String },
19) {
20 override get message() {
21 return "No existing T3 Code database was found in this data directory.";
22 }
23}
24
25export class DatabaseInUseError extends Schema.TaggedError<DatabaseInUseError>()(
26 "DatabaseInUseError",
27 { path: Schema.String, cause: Schema.Defect() },
28) {
29 override get message() {
30 return "Stop the T3 Code server and desktop app, including any version before 0.1.0, before repairing the database.";
31 }
32}
33
34export class DatabaseProjectionsInvalidError extends Schema.TaggedError<DatabaseProjectionsInvalidError>()(
35 "DatabaseProjectionsInvalidError",
36 { path: Schema.String },
37) {
38 override get message() {
39 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.";
40 }
41}
42
43export class DatabaseInspectError extends Schema.TaggedError<DatabaseInspectError>()(
44 "DatabaseInspectError",
45 { path: Schema.String, cause: Schema.Defect() },
46) {
47 override get message() {
48 return "Could not read the database. Check that this user can open it.";
49 }
50}
51
52export class DatabaseCompactError extends Schema.TaggedError<DatabaseCompactError>()(
53 "DatabaseCompactError",
54 { path: Schema.String, cause: Schema.Defect() },
55) {
56 override get message() {
57 return "Database compaction failed. Check that no other process has the database open and enough disk space is available.";
58 }
59}
60
61export class LegacyDatabaseRemoveError extends Schema.TaggedError<LegacyDatabaseRemoveError>()(
62 "LegacyDatabaseRemoveError",
63 { path: Schema.String, cause: Schema.Defect() },
64) {
65 override get message() {
66 return "Could not delete the database from before 0.1.0. Check that this user can write to the data directory.";
67 }
68}
69
70/** Offline inspection and repair of a T3 state database, for `t3 doctor`. */
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 /**
98 * Deletes the database from before 0.1.0 kept beside this one. Versions
99 * before 0.1.0 read only that file; this one stays intact.
100 */
101 readonly removeLegacyDatabase: (
102 databasePath: string,
103 ) => Effect.Effect<void, DatabaseInUseError | LegacyDatabaseRemoveError>;
104 }
105>()("t3/persistence/DatabaseMaintenance") {}
106
107const isDomainError = Schema.is(
108 Schema.Union([DatabaseMissingError, DatabaseInUseError, DatabaseProjectionsInvalidError]),
109);
110
111const readStorage = Effect.gen(function* () {
112 const sql = yield* SqlClient.SqlClient;
113 const pages = yield* sql<{ readonly page_count: number }>`PRAGMA page_count`;
114 const free = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
115 const size = yield* sql<{ readonly page_size: number }>`PRAGMA page_size`;
116 const mode = yield* sql<{ readonly auto_vacuum: number }>`PRAGMA auto_vacuum`;
117 const pageSize = size[0]?.page_size ?? 0;
118 return {
119 databaseBytes: (pages[0]?.page_count ?? 0) * pageSize,
120 reclaimableBytes: (free[0]?.freelist_count ?? 0) * pageSize,
121 incrementalVacuumEnabled: mode[0]?.auto_vacuum === 2,
122 };
123});
124
125/**
126 * Holds an exclusive lock on the connection's database. In WAL mode this is
127 * refused while any other connection has the file open, even an idle one,
128 * which is how a running server or desktop app is detected.
129 */
130const lockExclusively = Effect.fn("DatabaseMaintenance.lockExclusively")(function* (
131 databasePath: string,
132) {
133 const sql = yield* SqlClient.SqlClient;
134 yield* sql`PRAGMA busy_timeout = 0`;
135 yield* sql`PRAGMA locking_mode = EXCLUSIVE`;
136 yield* sql`BEGIN EXCLUSIVE`.pipe(
137 Effect.mapError((cause) =>
138 isSqlError(cause) && cause.reason._tag === "LockTimeoutError"
139 ? new DatabaseInUseError({ path: databasePath, cause })
140 : cause,
141 ),
142 );
143 yield* sql`COMMIT`;
144});
145
146const make = Effect.gen(function* () {
147 const fs = yield* FileSystem.FileSystem;
148 const path = yield* Path.Path;
149 const legacyPath = (databasePath: string) =>
150 path.join(path.dirname(databasePath), "state.sqlite");
151
152 const locate = Effect.fn("DatabaseMaintenance.locate")(function* (databasePath: string) {
153 if (!(yield* fs.exists(databasePath))) {
154 return yield* new DatabaseMissingError({ path: databasePath });
155 }
156 });
157
158 const inspect = Effect.fn("DatabaseMaintenance.inspect")(
159 function* (databasePath: string) {
160 yield* locate(databasePath);
161 const storage = yield* readStorage.pipe(
162 Effect.provide(NodeSqliteClient.layer({ filename: databasePath, readonly: true })),
163 );
164 const legacy = legacyPath(databasePath);
165 const legacyDatabaseBytes = (yield* fs.exists(legacy))
166 ? Number((yield* fs.stat(legacy)).size)
167 : null;
168 return { ...storage, legacyDatabaseBytes };
169 },
170 (effect, databasePath) =>
171 effect.pipe(
172 Effect.mapError((cause) =>
173 isDomainError(cause) ? cause : new DatabaseInspectError({ path: databasePath, cause }),
174 ),
175 ),
176 );
177
178 const compact = Effect.fn("DatabaseMaintenance.compact")(
179 function* (databasePath: string) {
180 yield* locate(databasePath);
181 const beforeBytes = Number((yield* fs.stat(databasePath)).size);
182 const result = yield* Effect.gen(function* () {
183 const sql = yield* SqlClient.SqlClient;
184 // Held through compaction and VACUUM.
185 yield* lockExclusively(databasePath);
186 const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
187 if (!(yield* maintenance.verify).valid) {
188 return yield* new DatabaseProjectionsInvalidError({ path: databasePath });
189 }
190 const summary = yield* maintenance.compactEventStore;
191 if (!(yield* maintenance.verify).valid) {
192 return yield* new DatabaseProjectionsInvalidError({ path: databasePath });
193 }
194 // VACUUM rebuilds the file, which is the only way to switch an existing
195 // database to incremental auto_vacuum; the server reclaims online after.
196 yield* sql`PRAGMA auto_vacuum = INCREMENTAL`;
197 yield* sql`VACUUM`;
198 yield* rebuildMessageSearch(sql);
199 yield* sql`PRAGMA wal_checkpoint(TRUNCATE)`;
200 return summary;
201 }).pipe(
202 Effect.provide(
203 ProjectionMaintenance.layer.pipe(
204 Layer.provide(Layer.merge(EventStore.layer, ProjectionStore.layer)),
205 Layer.provideMerge(NodeSqliteClient.layer({ filename: databasePath })),
206 ),
207 ),
208 );
209 const afterBytes = Number((yield* fs.stat(databasePath)).size);
210 return {
211 beforeBytes,
212 afterBytes,
213 deletedEventCount: result.deletedEventCount,
214 deletedReceiptCount: result.deletedReceiptCount,
215 };
216 },
217 (effect, databasePath) =>
218 effect.pipe(
219 Effect.mapError((cause) =>
220 isDomainError(cause) ? cause : new DatabaseCompactError({ path: databasePath, cause }),
221 ),
222 ),
223 );
224
225 const removeLegacyDatabase = Effect.fn("DatabaseMaintenance.removeLegacyDatabase")(
226 function* (databasePath: string) {
227 const legacy = legacyPath(databasePath);
228 if (!(yield* fs.exists(legacy))) return;
229 // A version before 0.1.0 may still be running against it. Keep the lock
230 // while deleting, and delete the database before its WAL so a failure
231 // never leaves it without committed transactions.
232 yield* Effect.gen(function* () {
233 yield* lockExclusively(legacy);
234 for (const suffix of ["", "-wal", "-shm"]) {
235 yield* fs.remove(legacy + suffix, { force: true });
236 }
237 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: legacy })));
238 },
239 (effect, databasePath) =>
240 effect.pipe(
241 Effect.mapError((cause) =>
242 cause._tag === "DatabaseInUseError"
243 ? cause
244 : new LegacyDatabaseRemoveError({ path: legacyPath(databasePath), cause }),
245 ),
246 ),
247 );
248
249 return DatabaseMaintenance.of({ inspect, compact, removeLegacyDatabase });
250});
251
252export const layer = Layer.effect(DatabaseMaintenance, make);