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