Skip to content

Commit 025c652

Browse files
fix(server): make doctor output easier to read
1 parent c4f3363 commit 025c652

3 files changed

Lines changed: 136 additions & 42 deletions

File tree

‎apps/server/src/cli/doctor.ts‎

Lines changed: 22 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,14 @@ import * as Config from "effect/Config";
22
import * as Layer from "effect/Layer";
33
import * as Path from "effect/Path";
44
import { FetchHttpClient } from "effect/http";
5-
import * as Console from "effect/Console";
65
import * as Effect from "effect/Effect";
76
import * as Option from "effect/Option";
87
import { Command, Flag, Prompt } from "effect/cli";
98

109
import packageJson from "../../package.json" with { type: "json" };
1110
import * as BootService from "../cloud/bootService.ts";
1211
import * as ProcessRunner from "../processRunner.ts";
13-
import { createDoctorProgress } from "./doctorProgress.ts";
12+
import { createDoctorProgress, doctorEmphasis } from "./doctorProgress.ts";
1413
import { baseDirFlag } from "./config.ts";
1514
import { resolveBaseDir } from "../os-jank.ts";
1615
import * as DatabaseMaintenance from "../persistence/DatabaseMaintenance.ts";
@@ -20,15 +19,18 @@ export interface DoctorRepair {
2019
readonly title: string;
2120
readonly description: string;
2221
readonly recommended: boolean;
22+
readonly details: ReadonlyArray<string>;
2323
}
2424

2525
export const chooseDoctorRepairs = (repairs: ReadonlyArray<DoctorRepair>) =>
2626
Prompt.run(
2727
Prompt.MultiSelect({
28-
message: "Choose repairs to run (Space toggles, Enter starts; Ctrl+C cancels)",
28+
message: "Choose repairs to run",
29+
selectAll: "Select all",
30+
selectNone: "Select none",
31+
inverseSelection: "Invert selection",
2932
choices: repairs.map((repair) => ({
30-
title: repair.title + (repair.recommended ? " (recommended)" : ""),
31-
description: repair.description,
33+
title: doctorEmphasis(repair.title) + (repair.recommended ? " · Recommended" : ""),
3234
value: repair.id,
3335
selected: repair.recommended,
3436
})),
@@ -42,60 +44,53 @@ export const runDoctor = Effect.fn("runDoctor")(function* (
4244
) {
4345
const maintenance = yield* DatabaseMaintenance.DatabaseMaintenance;
4446
const status = yield* maintenance.inspect(directory);
45-
const gib = (bytes: number) => (bytes / 1024 ** 3).toFixed(2);
46-
yield* Console.log(
47-
`Database: ${gib(status.databaseBytes)} GiB; reusable space: ${gib(status.reclaimableBytes)} GiB.`,
48-
);
47+
const progress = createDoctorProgress();
48+
progress.intro(status.databaseBytes, status.reclaimableBytes);
4949
const repairs: ReadonlyArray<DoctorRepair> =
5050
status.incrementalVacuumEnabled && status.reclaimableBytes === 0
5151
? []
5252
: [
5353
{
5454
id: "database",
5555
title: "Reclaim database space",
56-
description:
57-
"Compact history and enable automatic shrinking. Pauses the background service; may take several minutes and needs temporary disk space.",
56+
description: "Frees unused database space and enables automatic shrinking.",
57+
details: [
58+
"Pauses the background service. May take several minutes.",
59+
"Requires temporary free disk space.",
60+
],
5861
recommended: !status.incrementalVacuumEnabled || status.reclaimableBytes >= 1024 ** 3,
5962
},
6063
];
6164
if (repairs.length === 0) {
62-
yield* Console.log("No repairs available.");
65+
progress.note("Everything looks good. No repairs needed.");
6366
return;
6467
}
65-
for (const repair of repairs) {
66-
yield* Console.log(
67-
`${repair.recommended ? "[recommended]" : "[optional]"} ${repair.title}: ${repair.description}`,
68-
);
69-
}
68+
progress.repairs(repairs);
7069
if (options.dryRun) {
71-
yield* Console.log("Dry run: no repairs applied and no services stopped.");
70+
progress.note("Dry run complete. No changes made.");
7271
return;
7372
}
7473
const interactive = options.interactive ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
7574
if (!options.fix && !interactive) {
76-
yield* Console.log(
77-
"Run t3 doctor in a terminal to choose repairs, or use --fix to apply the recommended set.",
78-
);
75+
progress.note("Run in a terminal to choose repairs, or use --fix for the recommended set.");
7976
return;
8077
}
78+
if (!options.fix) progress.note("↑/↓ Move Space Select Enter Run Ctrl+C Cancel");
8179
const selected = options.fix
8280
? repairs.filter((repair) => repair.recommended).map((repair) => repair.id)
8381
: yield* chooseRepairs(repairs).pipe(Effect.catchTags({ QuitError: () => Effect.succeed([]) }));
8482
if (selected.length === 0) {
85-
yield* Console.log("No repairs selected.");
83+
progress.note("No repairs selected. No changes made.");
8684
return;
8785
}
8886
const service = yield* BootService.BootService;
89-
const progress = createDoctorProgress();
87+
progress.start();
9088
const report = (stage: Parameters<typeof progress.report>[0]) =>
9189
Effect.sync(() => progress.report(stage));
9290
const result = yield* service
9391
.withStopped(maintenance.compact(directory, report), report)
9492
.pipe(Effect.ensuring(Effect.sync(progress.finish)));
95-
progress.complete();
96-
yield* Console.log(
97-
`Removed ${result.deletedEventCount} events and ${result.deletedReceiptCount} receipts. Database: ${gib(result.beforeBytes)} → ${gib(result.afterBytes)} GiB.`,
98-
);
93+
progress.complete(result.beforeBytes, result.afterBytes);
9994
});
10095

10196
export const doctorCommand = Command.make("doctor", {

‎apps/server/src/cli/doctorProgress.test.ts‎

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,39 @@ it("reports stages and elapsed time as readable lines when redirected", () => {
1313
});
1414
progress.report("compacting-history");
1515
progress.report("reclaiming-space");
16-
progress.complete();
16+
progress.complete(1024 ** 3, 512 * 1024 ** 2);
1717
expect(output).toContain("Compacting history");
18-
expect(output).toContain("Reclaiming disk space (this may take several minutes)");
19-
expect(output).toContain("elapsed");
18+
expect(output).toContain("Reclaiming disk space");
19+
expect(output).toContain("s");
2020
expect(output).toContain("Repair complete");
21+
expect(output).toContain("Reclaimed 512.00 MiB");
2122
expect(output).not.toContain("");
2223
});
24+
25+
it("emphasizes recommendations and results in a color terminal", () => {
26+
const previous = process.env.NO_COLOR;
27+
const previousTerm = process.env.TERM;
28+
process.env.TERM = "xterm-256color";
29+
delete process.env.NO_COLOR;
30+
let output = "";
31+
try {
32+
const progress = createDoctorProgress({
33+
isTTY: true,
34+
columns: 80,
35+
write(chunk: string | Uint8Array) {
36+
output += chunk;
37+
return true;
38+
},
39+
});
40+
progress.intro(1024 ** 3, 512 * 1024 ** 2);
41+
progress.complete(1024 ** 3, 512 * 1024 ** 2);
42+
expect(output).toContain("\x1b[1;96mT3 Doctor");
43+
expect(output).toContain("\x1b[1;32m512.00 MiB");
44+
expect(output).toContain("\x1b[1;32m✓ Repair complete");
45+
} finally {
46+
if (previousTerm === undefined) delete process.env.TERM;
47+
else process.env.TERM = previousTerm;
48+
if (previous === undefined) delete process.env.NO_COLOR;
49+
else process.env.NO_COLOR = previous;
50+
}
51+
});
Lines changed: 82 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import type { DatabaseRepairStage } from "../persistence/DatabaseMaintenance.ts";
2-
import { createUpdateProgress } from "./updateProgress.ts";
32

43
export type DoctorStage = DatabaseRepairStage | "stopping-service" | "restarting-service";
54
const stages: ReadonlyArray<DoctorStage> = [
@@ -16,26 +15,97 @@ const labels: Record<DoctorStage, string> = {
1615
"checking-database": "Checking database",
1716
"compacting-history": "Compacting history",
1817
"verifying-history": "Verifying retained history",
19-
"reclaiming-space": "Reclaiming disk space (this may take several minutes)",
18+
"reclaiming-space": "Reclaiming disk space",
2019
checkpointing: "Finishing database writes",
2120
"restarting-service": "Restarting background service",
2221
};
2322

23+
export function formatDoctorBytes(bytes: number) {
24+
const unit = bytes >= 1024 ** 3 ? "GiB" : "MiB";
25+
return `${(bytes / 1024 ** (unit === "GiB" ? 3 : 2)).toFixed(2)} ${unit}`;
26+
}
27+
28+
export function doctorEmphasis(text: string) {
29+
return process.stderr.isTTY && process.env.TERM !== "dumb" && !process.env.NO_COLOR
30+
? `\x1b[1m${text}\x1b[22m`
31+
: text;
32+
}
33+
2434
/** The bar counts repair stages, not elapsed time or bytes processed. */
25-
export function createDoctorProgress(output?: Parameters<typeof createUpdateProgress>[0]) {
26-
const progress = createUpdateProgress(output);
27-
const started = performance.now();
35+
export function createDoctorProgress(
36+
output: Pick<NodeJS.WriteStream, "write" | "isTTY" | "columns"> = process.stderr,
37+
) {
38+
const interactive = output.isTTY && process.env.TERM !== "dumb";
39+
const color = interactive && !process.env.NO_COLOR;
40+
const style = (code: string, text: string) => (color ? `\x1b[${code}m${text}\x1b[0m` : text);
41+
const line = (text = "") => output.write(`${text}\n`);
42+
let lineOpen = false;
43+
let started = performance.now();
44+
const finish = () => {
45+
if (lineOpen) output.write("\r\x1b[2K");
46+
lineOpen = false;
47+
};
2848
return {
29-
finish: progress.finish,
49+
finish,
50+
intro(databaseBytes: number, reclaimableBytes: number) {
51+
line();
52+
line(` ${style("1;96", "T3 Doctor")}`);
53+
line(` ${style("2", "Check and repair this environment")}`);
54+
line();
55+
line(` Database ${style("1", formatDoctorBytes(databaseBytes))}`);
56+
line(` Space to reclaim ${style("1;32", formatDoctorBytes(reclaimableBytes))}`);
57+
line();
58+
},
59+
repairs(
60+
repairs: ReadonlyArray<{
61+
title: string;
62+
description: string;
63+
recommended: boolean;
64+
details: ReadonlyArray<string>;
65+
}>,
66+
) {
67+
line(` ${style("1", "Available repairs")}`);
68+
line();
69+
for (const repair of repairs) {
70+
line(
71+
` ${style("1", repair.title)} ${style(repair.recommended ? "1;32" : "2", repair.recommended ? "Recommended" : "Optional")}`,
72+
);
73+
line(` ${repair.description}`);
74+
for (const detail of repair.details) line(` ${style("2", detail)}`);
75+
line();
76+
}
77+
},
78+
note(message: string) {
79+
line(` ${message}`);
80+
line();
81+
},
82+
start() {
83+
started = performance.now();
84+
line(` ${style("1", "Repairing")}`);
85+
line();
86+
},
3087
report(stage: DoctorStage) {
88+
finish();
3189
const index = stages.indexOf(stage);
32-
const bar = "■".repeat(index) + "·".repeat(stages.length - index);
33-
progress.status(
34-
`[${bar}] ${labels[stage]} · ${((performance.now() - started) / 1000).toFixed(1)}s elapsed`,
35-
);
90+
const bar = style("96", "━".repeat(index)) + style("2", "─".repeat(stages.length - index));
91+
const elapsed = `${((performance.now() - started) / 1000).toFixed(1)}s`;
92+
const text = ` ${bar} ${style("1", labels[stage])} ${style("2", elapsed)}`;
93+
output.write(interactive ? `\r${text}` : `${text}\n`);
94+
lineOpen = Boolean(interactive);
3695
},
37-
complete() {
38-
progress.success(`Repair complete in ${((performance.now() - started) / 1000).toFixed(1)}s`);
96+
complete(beforeBytes: number, afterBytes: number) {
97+
finish();
98+
line(
99+
` ${style("1;32", "✓ Repair complete")} ${style("2", `${((performance.now() - started) / 1000).toFixed(1)}s`)}`,
100+
);
101+
line();
102+
line(
103+
` Database ${formatDoctorBytes(beforeBytes)} → ${style("1", formatDoctorBytes(afterBytes))}`,
104+
);
105+
line(
106+
` Reclaimed ${style("1;32", formatDoctorBytes(Math.max(0, beforeBytes - afterBytes)))}`,
107+
);
108+
line();
39109
},
40110
};
41111
}

0 commit comments

Comments
 (0)