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

DatabaseMaintenance.ts

250 lines9.5 KB

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 }
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 }
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 }
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 }
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 }
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 }
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 = Effect.fn("DatabaseMaintenance.lockExclusively")(function* (
130 databasePath: string,
131) {
132 const sql = yield* SqlClient.SqlClient;
133 yield* sql`PRAGMA busy_timeout = 0`;
134 yield* sql`PRAGMA locking_mode = EXCLUSIVE`;
135 yield* sql`BEGIN EXCLUSIVE`.pipe(
136 Effect.mapError((cause) =>
137 isSqlError(cause) && cause.reason._tag === "LockTimeoutError"
138 ? new DatabaseInUseError({ path: databasePath, cause })
139 : cause,
140 ),
141 );
142 yield* sql`COMMIT`;
143});
144​
145const make = Effect.gen(function* () {
146 const fs = yield* FileSystem.FileSystem;
147 const path = yield* Path.Path;
148 const legacyPath = (databasePath: string) =>
149 path.join(path.dirname(databasePath), "state.sqlite");
150​
151 const locate = Effect.fn("DatabaseMaintenance.locate")(function* (databasePath: string) {
152 if (!(yield* fs.exists(databasePath))) {
153 return yield* new DatabaseMissingError({ path: databasePath });
154 }
155 });
156​
157 const inspect = Effect.fn("DatabaseMaintenance.inspect")(
158 function* (databasePath: string) {
159 yield* locate(databasePath);
160 const storage = yield* readStorage.pipe(
161 Effect.provide(NodeSqliteClient.layer({ filename: databasePath, readonly: true })),
162 );
163 const legacy = legacyPath(databasePath);
164 const legacyDatabaseBytes = (yield* fs.exists(legacy))
165 ? Number((yield* fs.stat(legacy)).size)
166 : null;
167 return { ...storage, legacyDatabaseBytes };
168 },
169 (effect, databasePath) =>
170 effect.pipe(
171 Effect.mapError((cause) =>
172 isDomainError(cause) ? cause : new DatabaseInspectError({ path: databasePath, cause }),
173 ),
174 ),
175 );
176​
177 const compact = Effect.fn("DatabaseMaintenance.compact")(
178 function* (databasePath: string) {
179 yield* locate(databasePath);
180 const beforeBytes = Number((yield* fs.stat(databasePath)).size);
181 const result = yield* Effect.gen(function* () {
182 const sql = yield* SqlClient.SqlClient;
183 // Held through compaction and VACUUM.
184 yield* lockExclusively(databasePath);
185 const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
186 if (!(yield* maintenance.verify).valid) {
187 return yield* new DatabaseProjectionsInvalidError({ path: databasePath });
188 }
189 const summary = yield* maintenance.compactEventStore;
190 if (!(yield* maintenance.verify).valid) {
191 return yield* new DatabaseProjectionsInvalidError({ path: databasePath });
192 }
193 // VACUUM rebuilds the file, which is the only way to switch an existing
194 // database to incremental auto_vacuum; the server reclaims online after.
195 yield* sql`PRAGMA auto_vacuum = INCREMENTAL`;
196 yield* sql`VACUUM`;
197 yield* sql`PRAGMA wal_checkpoint(TRUNCATE)`;
198 return summary;
199 }).pipe(
200 Effect.provide(
201 ProjectionMaintenance.layer.pipe(
202 Layer.provide(Layer.merge(EventStore.layer, ProjectionStore.layer)),
203 Layer.provideMerge(NodeSqliteClient.layer({ filename: databasePath })),
204 ),
205 ),
206 );
207 const afterBytes = Number((yield* fs.stat(databasePath)).size);
208 return {
209 beforeBytes,
210 afterBytes,
211 deletedEventCount: result.deletedEventCount,
212 deletedReceiptCount: result.deletedReceiptCount,
213 };
214 },
215 (effect, databasePath) =>
216 effect.pipe(
217 Effect.mapError((cause) =>
218 isDomainError(cause) ? cause : new DatabaseCompactError({ path: databasePath, cause }),
219 ),
220 ),
221 );
222​
223 const removeLegacyDatabase = Effect.fn("DatabaseMaintenance.removeLegacyDatabase")(
224 function* (databasePath: string) {
225 const legacy = legacyPath(databasePath);
226 if (!(yield* fs.exists(legacy))) return;
227 // A version before 0.1.0 may still be running against it. Keep the lock
228 // while deleting, and delete the database before its WAL so a failure
229 // never leaves it without committed transactions.
230 yield* Effect.gen(function* () {
231 yield* lockExclusively(legacy);
232 for (const suffix of ["", "-wal", "-shm"]) {
233 yield* fs.remove(legacy + suffix, { force: true });
234 }
235 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: legacy })));
236 },
237 (effect, databasePath) =>
238 effect.pipe(
239 Effect.mapError((cause) =>
240 cause._tag === "DatabaseInUseError"
241 ? cause
242 : new LegacyDatabaseRemoveError({ path: legacyPath(databasePath), cause }),
243 ),
244 ),
245 );
246​
247 return DatabaseMaintenance.of({ inspect, compact, removeLegacyDatabase });
248});
249​
250export const layer = Layer.effect(DatabaseMaintenance, make);