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

DatabaseMaintenance.ts

244 lines9.2 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";
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 }
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 }
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 }
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 }
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 }
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 }
69​
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 /** Deletes only the pre-0.1.0 database; earlier versions still use it. */
97 readonly removeLegacyDatabase: (
98 databasePath: string,
99 ) => Effect.Effect<void, DatabaseInUseError | LegacyDatabaseRemoveError>;
100 }
101>()("t3/persistence/DatabaseMaintenance") {}
102​
103const isDomainError = Schema.is(
104 Schema.Union([DatabaseMissingError, DatabaseInUseError, DatabaseProjectionsInvalidError]),
105);
106​
107const readStorage = Effect.gen(function* () {
108 const sql = yield* SqlClient.SqlClient;
109 const pages = yield* sql<{ readonly page_count: number }>`PRAGMA page_count`;
110 const free = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
111 const size = yield* sql<{ readonly page_size: number }>`PRAGMA page_size`;
112 const mode = yield* sql<{ readonly auto_vacuum: number }>`PRAGMA auto_vacuum`;
113 const pageSize = size[0]?.page_size ?? 0;
114 return {
115 databaseBytes: (pages[0]?.page_count ?? 0) * pageSize,
116 reclaimableBytes: (free[0]?.freelist_count ?? 0) * pageSize,
117 incrementalVacuumEnabled: mode[0]?.auto_vacuum === 2,
118 };
119});
120​
121/**
122 * Holds an exclusive lock on the connection's database. In WAL mode this is
123 * refused while any other connection has the file open, even an idle one,
124 * which is how a running server or desktop app is detected.
125 */
126const lockExclusively = Effect.fn("DatabaseMaintenance.lockExclusively")(function* (
127 databasePath: string,
128) {
129 const sql = yield* SqlClient.SqlClient;
130 yield* sql`PRAGMA busy_timeout = 0`;
131 yield* sql`PRAGMA locking_mode = EXCLUSIVE`;
132 yield* sql`BEGIN EXCLUSIVE`.pipe(
133 Effect.mapError((cause) =>
134 isSqlError(cause) && cause.reason._tag === "LockTimeoutError"
135 ? new DatabaseInUseError({ path: databasePath, cause })
136 : cause,
137 ),
138 );
139 yield* sql`COMMIT`;
140});
141​
142const make = Effect.gen(function* () {
143 const fs = yield* FileSystem.FileSystem;
144 const path = yield* Path.Path;
145 const legacyPath = (databasePath: string) =>
146 path.join(path.dirname(databasePath), "state.sqlite");
147​
148 const locate = Effect.fn("DatabaseMaintenance.locate")(function* (databasePath: string) {
149 if (!(yield* fs.exists(databasePath))) {
150 return yield* new DatabaseMissingError({ path: databasePath });
151 }
152 });
153​
154 const inspect = Effect.fn("DatabaseMaintenance.inspect")(
155 function* (databasePath: string) {
156 yield* locate(databasePath);
157 const storage = yield* readStorage.pipe(
158 Effect.provide(NodeSqliteClient.layer({ filename: databasePath, readonly: true })),
159 );
160 const legacy = legacyPath(databasePath);
161 const legacyDatabaseBytes = (yield* fs.exists(legacy))
162 ? Number((yield* fs.stat(legacy)).size)
163 : null;
164 return { ...storage, legacyDatabaseBytes };
165 },
166 (effect, databasePath) =>
167 effect.pipe(
168 Effect.mapError((cause) =>
169 isDomainError(cause) ? cause : new DatabaseInspectError({ path: databasePath, cause }),
170 ),
171 ),
172 );
173​
174 const compact = Effect.fn("DatabaseMaintenance.compact")(
175 function* (databasePath: string) {
176 yield* locate(databasePath);
177 const beforeBytes = Number((yield* fs.stat(databasePath)).size);
178 const result = yield* Effect.gen(function* () {
179 const sql = yield* SqlClient.SqlClient;
180 yield* lockExclusively(databasePath);
181 const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
182 if (!(yield* maintenance.verify).valid) {
183 return yield* new DatabaseProjectionsInvalidError({ path: databasePath });
184 }
185 const summary = yield* maintenance.compactEventStore();
186 if (!(yield* maintenance.verify).valid) {
187 return yield* new DatabaseProjectionsInvalidError({ path: databasePath });
188 }
189 // VACUUM is required to enable incremental auto_vacuum on existing databases.
190 yield* sql`PRAGMA auto_vacuum = INCREMENTAL`;
191 yield* sql`VACUUM`;
192 yield* rebuildMessageSearch(sql);
193 yield* sql`PRAGMA wal_checkpoint(TRUNCATE)`;
194 return summary;
195 }).pipe(
196 Effect.provide(
197 ProjectionMaintenance.layer.pipe(
198 Layer.provide(Layer.merge(EventStore.layer, ProjectionStore.layer)),
199 Layer.provideMerge(NodeSqliteClient.layer({ filename: databasePath })),
200 ),
201 ),
202 );
203 const afterBytes = Number((yield* fs.stat(databasePath)).size);
204 return {
205 beforeBytes,
206 afterBytes,
207 deletedEventCount: result.deletedEventCount,
208 deletedReceiptCount: result.deletedReceiptCount,
209 };
210 },
211 (effect, databasePath) =>
212 effect.pipe(
213 Effect.mapError((cause) =>
214 isDomainError(cause) ? cause : new DatabaseCompactError({ path: databasePath, cause }),
215 ),
216 ),
217 );
218​
219 const removeLegacyDatabase = Effect.fn("DatabaseMaintenance.removeLegacyDatabase")(
220 function* (databasePath: string) {
221 const legacy = legacyPath(databasePath);
222 if (!(yield* fs.exists(legacy))) return;
223 // Older servers may use this file; hold its lock and delete the database before WAL to preserve commits on failure.
224 yield* Effect.gen(function* () {
225 yield* lockExclusively(legacy);
226 for (const suffix of ["", "-wal", "-shm"]) {
227 yield* fs.remove(legacy + suffix, { force: true });
228 }
229 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: legacy })));
230 },
231 (effect, databasePath) =>
232 effect.pipe(
233 Effect.mapError((cause) =>
234 cause._tag === "DatabaseInUseError"
235 ? cause
236 : new LegacyDatabaseRemoveError({ path: legacyPath(databasePath), cause }),
237 ),
238 ),
239 );
240​
241 return DatabaseMaintenance.of({ inspect, compact, removeLegacyDatabase });
242});
243​
244export const layer = Layer.effect(DatabaseMaintenance, make);