Skip to content

Commit e55982f

Browse files
refactor(server): doctor failures are distinct tagged errors with the database path
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 951d56b commit e55982f

2 files changed

Lines changed: 117 additions & 79 deletions

File tree

‎apps/server/src/persistence/DatabaseMaintenance.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ it.layer(DatabaseMaintenance.layer.pipe(Layer.provideMerge(NodeServices.layer)))
2727
);
2828
yield* fs.writeFileString(dbPath, "not a database");
2929
const failure = yield* Effect.flip(maintenance.inspect(dbPath));
30-
assert.equal(failure.reason, "inspect");
30+
assert.equal(failure._tag, "DatabaseInspectError");
3131
}).pipe(Effect.scoped),
3232
);
3333

@@ -69,7 +69,7 @@ it.layer(DatabaseMaintenance.layer.pipe(Layer.provideMerge(NodeServices.layer)))
6969
yield* sql`SELECT value FROM retained_data`;
7070
return yield* maintenance.compact(dbPath).pipe(Effect.flip);
7171
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dbPath })));
72-
assert.equal(refused.reason, "running");
72+
assert.equal(refused._tag, "DatabaseInUseError");
7373
assert.equal((yield* fs.stat(dbPath)).size, sizeBefore);
7474

7575
const result = yield* maintenance.compact(dbPath);

‎apps/server/src/persistence/DatabaseMaintenance.ts‎

Lines changed: 115 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -11,26 +11,48 @@ import * as EventStore from "../orchestration-v2/EventStore.ts";
1111
import * as ProjectionMaintenance from "../orchestration-v2/ProjectionMaintenance.ts";
1212
import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
1313

14-
export class DatabaseMaintenanceError extends Schema.TaggedError<DatabaseMaintenanceError>()(
15-
"DatabaseMaintenanceError",
16-
{
17-
reason: Schema.Literals(["running", "missing", "invalid-projections", "inspect", "compact"]),
18-
cause: Schema.optional(Schema.Defect()),
19-
},
14+
export class DatabaseMissingError extends Schema.TaggedError<DatabaseMissingError>()(
15+
"DatabaseMissingError",
16+
{ path: Schema.String },
2017
) {
2118
override get message() {
22-
switch (this.reason) {
23-
case "running":
24-
return "Stop the T3 Code server and desktop app before compacting the database.";
25-
case "missing":
26-
return "No existing T3 Code database was found in this data directory.";
27-
case "invalid-projections":
28-
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.";
29-
case "inspect":
30-
return "Could not read the database. Check that this user can open it.";
31-
case "compact":
32-
return "Database compaction failed. Check that no other process has the database open and enough disk space is available.";
33-
}
19+
return "No existing T3 Code database was found in this data directory.";
20+
}
21+
}
22+
23+
export 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+
32+
export 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+
41+
export 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+
50+
export 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.";
3456
}
3557
}
3658

@@ -44,7 +66,7 @@ export class DatabaseMaintenance extends Context.Service<
4466
readonly reclaimableBytes: number;
4567
readonly incrementalVacuumEnabled: boolean;
4668
},
47-
DatabaseMaintenanceError
69+
DatabaseMissingError | DatabaseInspectError
4870
>;
4971
/** Compacts history, then VACUUMs into incremental auto_vacuum. Refuses while a server has it open. */
5072
readonly compact: (databasePath: string) => Effect.Effect<
@@ -54,12 +76,17 @@ export class DatabaseMaintenance extends Context.Service<
5476
readonly deletedEventCount: number;
5577
readonly deletedReceiptCount: number;
5678
},
57-
DatabaseMaintenanceError
79+
| DatabaseMissingError
80+
| DatabaseInUseError
81+
| DatabaseProjectionsInvalidError
82+
| DatabaseCompactError
5883
>;
5984
}
6085
>()("t3/persistence/DatabaseMaintenance") {}
6186

62-
const isDatabaseMaintenanceError = Schema.is(DatabaseMaintenanceError);
87+
const isDomainError = Schema.is(
88+
Schema.Union([DatabaseMissingError, DatabaseInUseError, DatabaseProjectionsInvalidError]),
89+
);
6390

6491
const readStorage = Effect.gen(function* () {
6592
const sql = yield* SqlClient.SqlClient;
@@ -80,70 +107,81 @@ const make = Effect.gen(function* () {
80107

81108
const locate = Effect.fn("DatabaseMaintenance.locate")(function* (databasePath: string) {
82109
if (!(yield* fs.exists(databasePath))) {
83-
return yield* new DatabaseMaintenanceError({ reason: "missing" });
110+
return yield* new DatabaseMissingError({ path: databasePath });
84111
}
85112
});
86113

87-
const asMaintenanceError = (reason: "inspect" | "compact") =>
88-
Effect.mapError((cause: unknown) =>
89-
isDatabaseMaintenanceError(cause) ? cause : new DatabaseMaintenanceError({ reason, cause }),
90-
);
91-
92-
const inspect = Effect.fn("DatabaseMaintenance.inspect")(function* (databasePath: string) {
93-
yield* locate(databasePath);
94-
return yield* readStorage.pipe(
95-
Effect.provide(NodeSqliteClient.layer({ filename: databasePath, readonly: true })),
96-
);
97-
}, asMaintenanceError("inspect"));
98-
99-
const compact = Effect.fn("DatabaseMaintenance.compact")(function* (databasePath: string) {
100-
yield* locate(databasePath);
101-
const beforeBytes = Number((yield* fs.stat(databasePath)).size);
102-
const result = yield* Effect.gen(function* () {
103-
const sql = yield* SqlClient.SqlClient;
104-
// Hold an exclusive lock through compaction and VACUUM. In WAL mode this
105-
// is refused while any other connection has the file open, even an idle
106-
// one, which is how a running server or desktop app is detected.
107-
yield* sql`PRAGMA busy_timeout = 0`;
108-
yield* sql`PRAGMA locking_mode = EXCLUSIVE`;
109-
yield* sql`BEGIN EXCLUSIVE`.pipe(
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(
110123
Effect.mapError((cause) =>
111-
isSqlError(cause) && cause.reason._tag === "LockTimeoutError"
112-
? new DatabaseMaintenanceError({ reason: "running", cause })
113-
: 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+
),
114168
),
115169
);
116-
yield* sql`COMMIT`;
117-
const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
118-
if (!(yield* maintenance.verify).valid) {
119-
return yield* new DatabaseMaintenanceError({ reason: "invalid-projections" });
120-
}
121-
const summary = yield* maintenance.compactEventStore;
122-
if (!(yield* maintenance.verify).valid) {
123-
return yield* new DatabaseMaintenanceError({ reason: "invalid-projections" });
124-
}
125-
// VACUUM rebuilds the file, which is the only way to switch an existing
126-
// database to incremental auto_vacuum; the server reclaims online after.
127-
yield* sql`PRAGMA auto_vacuum = INCREMENTAL`;
128-
yield* sql`VACUUM`;
129-
yield* sql`PRAGMA wal_checkpoint(TRUNCATE)`;
130-
return summary;
131-
}).pipe(
132-
Effect.provide(
133-
ProjectionMaintenance.layer.pipe(
134-
Layer.provide(Layer.merge(EventStore.layer, ProjectionStore.layer)),
135-
Layer.provideMerge(NodeSqliteClient.layer({ filename: databasePath })),
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 }),
136182
),
137183
),
138-
);
139-
const afterBytes = Number((yield* fs.stat(databasePath)).size);
140-
return {
141-
beforeBytes,
142-
afterBytes,
143-
deletedEventCount: result.deletedEventCount,
144-
deletedReceiptCount: result.deletedReceiptCount,
145-
};
146-
}, asMaintenanceError("compact"));
184+
);
147185

148186
return DatabaseMaintenance.of({ inspect, compact });
149187
});

0 commit comments

Comments
 (0)