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 Schema from "effect/Schema";
7import * as SqlClient from "effect/sql/SqlClient";
8import { isSqlError } from "effect/sql/SqlError";
9
10import * as EventStore from "../orchestration-v2/EventStore.ts";
11import * as ProjectionMaintenance from "../orchestration-v2/ProjectionMaintenance.ts";
12import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
13
14export class DatabaseMissingError extends Schema.TaggedError<DatabaseMissingError>()(
15 "DatabaseMissingError",
16 { path: Schema.String },
17) {
18 override get message() {
19 return "No existing T3 Code database was found in this data directory.";
20 }
21}
22
23export class DatabaseInUseError extends Schema.TaggedError<DatabaseInUseError>()(
24 "DatabaseInUseError",
25 { path: Schema.String, cause: Schema.Defect() },
26) {
27 override get message() {
28 return "Stop the T3 Code server and desktop app before compacting the database.";
29 }
30}
31
32export class DatabaseProjectionsInvalidError extends Schema.TaggedError<DatabaseProjectionsInvalidError>()(
33 "DatabaseProjectionsInvalidError",
34 { path: Schema.String },
35) {
36 override get message() {
37 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.";
38 }
39}
40
41export class DatabaseInspectError extends Schema.TaggedError<DatabaseInspectError>()(
42 "DatabaseInspectError",
43 { path: Schema.String, cause: Schema.Defect() },
44) {
45 override get message() {
46 return "Could not read the database. Check that this user can open it.";
47 }
48}
49
50export class DatabaseCompactError extends Schema.TaggedError<DatabaseCompactError>()(
51 "DatabaseCompactError",
52 { path: Schema.String, cause: Schema.Defect() },
53) {
54 override get message() {
55 return "Database compaction failed. Check that no other process has the database open and enough disk space is available.";
56 }
57}
58
59/** Offline inspection and repair of a T3 state database, for `t3 doctor`. */
60export class DatabaseMaintenance extends Context.Service<
61 DatabaseMaintenance,
62 {
63 readonly inspect: (databasePath: string) => Effect.Effect<
64 {
65 readonly databaseBytes: number;
66 readonly reclaimableBytes: number;
67 readonly incrementalVacuumEnabled: boolean;
68 },
69 DatabaseMissingError | DatabaseInspectError
70 >;
71 /** Compacts history, then VACUUMs into incremental auto_vacuum. Refuses while a server has it open. */
72 readonly compact: (databasePath: string) => Effect.Effect<
73 {
74 readonly beforeBytes: number;
75 readonly afterBytes: number;
76 readonly deletedEventCount: number;
77 readonly deletedReceiptCount: number;
78 },
79 | DatabaseMissingError
80 | DatabaseInUseError
81 | DatabaseProjectionsInvalidError
82 | DatabaseCompactError
83 >;
84 }
85>()("t3/persistence/DatabaseMaintenance") {}
86
87const isDomainError = Schema.is(
88 Schema.Union([DatabaseMissingError, DatabaseInUseError, DatabaseProjectionsInvalidError]),
89);
90
91const readStorage = Effect.gen(function* () {
92 const sql = yield* SqlClient.SqlClient;
93 const pages = yield* sql<{ readonly page_count: number }>`PRAGMA page_count`;
94 const free = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
95 const size = yield* sql<{ readonly page_size: number }>`PRAGMA page_size`;
96 const mode = yield* sql<{ readonly auto_vacuum: number }>`PRAGMA auto_vacuum`;
97 const pageSize = size[0]?.page_size ?? 0;
98 return {
99 databaseBytes: (pages[0]?.page_count ?? 0) * pageSize,
100 reclaimableBytes: (free[0]?.freelist_count ?? 0) * pageSize,
101 incrementalVacuumEnabled: mode[0]?.auto_vacuum === 2,
102 };
103});
104
105const make = Effect.gen(function* () {
106 const fs = yield* FileSystem.FileSystem;
107
108 const locate = Effect.fn("DatabaseMaintenance.locate")(function* (databasePath: string) {
109 if (!(yield* fs.exists(databasePath))) {
110 return yield* new DatabaseMissingError({ path: databasePath });
111 }
112 });
113
114 const inspect = Effect.fn("DatabaseMaintenance.inspect")(
115 function* (databasePath: string) {
116 yield* locate(databasePath);
117 return yield* readStorage.pipe(
118 Effect.provide(NodeSqliteClient.layer({ filename: databasePath, readonly: true })),
119 );
120 },
121 (effect, databasePath) =>
122 effect.pipe(
123 Effect.mapError((cause) =>
124 isDomainError(cause) ? cause : new DatabaseInspectError({ path: databasePath, cause }),
125 ),
126 ),
127 );
128
129 const compact = Effect.fn("DatabaseMaintenance.compact")(
130 function* (databasePath: string) {
131 yield* locate(databasePath);
132 const beforeBytes = Number((yield* fs.stat(databasePath)).size);
133 const result = yield* Effect.gen(function* () {
134 const sql = yield* SqlClient.SqlClient;
135 // Hold an exclusive lock through compaction and VACUUM. In WAL mode this
136 // is refused while any other connection has the file open, even an idle
137 // one, which is how a running server or desktop app is detected.
138 yield* sql`PRAGMA busy_timeout = 0`;
139 yield* sql`PRAGMA locking_mode = EXCLUSIVE`;
140 yield* sql`BEGIN EXCLUSIVE`.pipe(
141 Effect.mapError((cause) =>
142 isSqlError(cause) && cause.reason._tag === "LockTimeoutError"
143 ? new DatabaseInUseError({ path: databasePath, cause })
144 : cause,
145 ),
146 );
147 yield* sql`COMMIT`;
148 const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
149 if (!(yield* maintenance.verify).valid) {
150 return yield* new DatabaseProjectionsInvalidError({ path: databasePath });
151 }
152 const summary = yield* maintenance.compactEventStore;
153 if (!(yield* maintenance.verify).valid) {
154 return yield* new DatabaseProjectionsInvalidError({ path: databasePath });
155 }
156 // VACUUM rebuilds the file, which is the only way to switch an existing
157 // database to incremental auto_vacuum; the server reclaims online after.
158 yield* sql`PRAGMA auto_vacuum = INCREMENTAL`;
159 yield* sql`VACUUM`;
160 yield* sql`PRAGMA wal_checkpoint(TRUNCATE)`;
161 return summary;
162 }).pipe(
163 Effect.provide(
164 ProjectionMaintenance.layer.pipe(
165 Layer.provide(Layer.merge(EventStore.layer, ProjectionStore.layer)),
166 Layer.provideMerge(NodeSqliteClient.layer({ filename: databasePath })),
167 ),
168 ),
169 );
170 const afterBytes = Number((yield* fs.stat(databasePath)).size);
171 return {
172 beforeBytes,
173 afterBytes,
174 deletedEventCount: result.deletedEventCount,
175 deletedReceiptCount: result.deletedReceiptCount,
176 };
177 },
178 (effect, databasePath) =>
179 effect.pipe(
180 Effect.mapError((cause) =>
181 isDomainError(cause) ? cause : new DatabaseCompactError({ path: databasePath, cause }),
182 ),
183 ),
184 );
185
186 return DatabaseMaintenance.of({ inspect, compact });
187});
188
189export const layer = Layer.effect(DatabaseMaintenance, make);