Open History to see the last commit
1import { DATABASE_COMPACTION_RECOMMENDED_BYTES } from "@t3tools/contracts";
2import * as Clock from "effect/Clock";
3import * as Console from "effect/Console";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import { Command, Flag, GlobalFlag, Prompt } from "effect/cli";
7
8import * as BootService from "../cloud/bootService.ts";
9import * as DatabaseMaintenance from "../persistence/DatabaseMaintenance.ts";
10import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
11import * as CliService from "./service.ts";
12
13const formatBytes = (bytes: number) =>
14 bytes >= 1024 ** 3
15 ? `${(bytes / 1024 ** 3).toFixed(2)} GiB`
16 : bytes >= 1024 ** 2
17 ? `${(bytes / 1024 ** 2).toFixed(1)} MiB`
18 : `${Math.ceil(bytes / 1024)} KiB`;
19
20const formatElapsed = (nanos: bigint) => {
21 const seconds = Number(nanos / 1_000_000_000n);
22 return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
23};
24
25const COMPACT_STEP_LABELS: Record<DatabaseMaintenance.DatabaseCompactStep, string> = {
26 "prune-events": "Removing superseded events",
27 vacuum: "Rewriting the database file",
28 "rebuild-search": "Rebuilding the search index",
29 checkpoint: "Flushing the write-ahead log",
30};
31
32export const runDoctor = Effect.fn("runDoctor")(function* (
33 databasePath: string,
34 options: { readonly fix: boolean; readonly dryRun: boolean; readonly interactive?: boolean },
35) {
36 const maintenance = yield* DatabaseMaintenance.DatabaseMaintenance;
37 const status = yield* maintenance.inspect(databasePath);
38 yield* Console.log(
39 `Database: ${formatBytes(status.databaseBytes)}, ${formatBytes(status.reclaimableBytes)} reclaimable.`,
40 );
41 if (status.legacyDatabaseBytes !== null) {
42 yield* Console.log(
43 `Database from before 0.1.0: ${formatBytes(status.legacyDatabaseBytes)}, kept for rolling back.`,
44 );
45 }
46 const repairs = [
47 ...(status.incrementalVacuumEnabled && status.reclaimableBytes === 0
48 ? []
49 : [
50 {
51 id: "database" as const,
52 title: "Reclaim database space",
53 description: `${
54 status.incrementalVacuumEnabled
55 ? "Returns unused space to disk."
56 : "Returns unused space to disk and turns on automatic shrinking."
57 }\n Rewrites the whole ${formatBytes(status.databaseBytes)} database, which can take more than an hour on a large database or slow disk.\n Pauses the background service, if installed, while it runs and may need temporary disk space.`,
58 recommended:
59 !status.incrementalVacuumEnabled ||
60 status.reclaimableBytes >= DATABASE_COMPACTION_RECOMMENDED_BYTES,
61 },
62 ]),
63 ...(status.legacyDatabaseBytes === null
64 ? []
65 : [
66 {
67 id: "legacy" as const,
68 title: "Delete the database from before 0.1.0",
69 description: `Frees ${formatBytes(status.legacyDatabaseBytes)}. Your threads and settings are already in the current database.\n Warning: after this, a T3 Code version before 0.1.0 starts with no threads or settings, so you can no longer roll back.`,
70 recommended: false,
71 },
72 ]),
73 ];
74 if (repairs.length === 0) {
75 yield* Console.log("Nothing to repair.");
76 return;
77 }
78 for (const repair of repairs) {
79 yield* Console.log(
80 `\n${repair.title}${repair.recommended ? " (recommended)" : ""}\n ${repair.description}`,
81 );
82 }
83 if (options.dryRun) {
84 yield* Console.log("\nDry run: nothing changed.");
85 return;
86 }
87 const interactive = options.interactive ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
88 if (!options.fix && !interactive) {
89 yield* Console.log(
90 "\nRun in a terminal to choose repairs, or pass --fix for the recommended ones.",
91 );
92 return;
93 }
94 const selected = options.fix
95 ? repairs.filter((repair) => repair.recommended).map((repair) => repair.id)
96 : yield* Prompt.run(
97 Prompt.MultiSelect({
98 message: "Choose repairs to run",
99 choices: repairs.map((repair) => ({
100 title: repair.title + (repair.recommended ? " (recommended)" : ""),
101 value: repair.id,
102 selected: repair.recommended,
103 })),
104 }),
105 ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed([]) }));
106 if (selected.length === 0) {
107 yield* Console.log(
108 options.fix
109 ? "No recommended repairs; nothing changed."
110 : "No repairs selected; nothing changed.",
111 );
112 return;
113 }
114 if (selected.includes("database")) {
115 const service = yield* BootService.BootService;
116 yield* Console.log("\nReclaiming database space. Each step is shown as it starts.");
117 const startedAt = yield* Clock.monotonicTimeNanos;
118 const reportStep = (step: DatabaseMaintenance.DatabaseCompactStep) =>
119 Clock.monotonicTimeNanos.pipe(
120 Effect.flatMap((now) =>
121 Console.log(` [${formatElapsed(now - startedAt)}] ${COMPACT_STEP_LABELS[step]}`),
122 ),
123 );
124 // Report the repair before restarting, which can fail independently.
125 yield* service.withStopped(
126 maintenance
127 .compact(databasePath, reportStep)
128 .pipe(
129 Effect.tap((result) =>
130 Clock.monotonicTimeNanos.pipe(
131 Effect.flatMap((now) =>
132 Console.log(
133 `Done in ${formatElapsed(now - startedAt)}: ${formatBytes(result.beforeBytes)} -> ${formatBytes(result.afterBytes)}, ${result.deletedEventCount} superseded events removed.`,
134 ),
135 ),
136 ),
137 ),
138 ),
139 );
140 }
141 if (selected.includes("legacy")) {
142 // Only pre-0.1.0 servers use this file; removal refuses while they hold it open.
143 yield* maintenance.removeLegacyDatabase(databasePath);
144 yield* Console.log("\nDeleted the database from before 0.1.0.");
145 }
146});
147
148export const doctorCommand = Command.make("doctor", {
149 ...projectLocationFlags,
150 fix: Flag.Boolean("fix").pipe(
151 Flag.withDescription("Apply the recommended repairs without prompting."),
152 Flag.withDefault(false),
153 ),
154 dryRun: Flag.Boolean("dry-run").pipe(
155 Flag.withDescription("Show the repairs without changing anything, even with --fix."),
156 Flag.withDefault(false),
157 ),
158}).pipe(
159 Command.withDescription(
160 "Inspect this T3 Code data directory and repair it. Pauses and restarts the background service as needed.",
161 ),
162 Command.withHandler((flags) =>
163 Effect.gen(function* () {
164 const logLevel = yield* GlobalFlag.LogLevel;
165 const config = yield* resolveCliAuthConfig(flags, logLevel);
166 yield* runDoctor(config.dbPath, { fix: flags.fix, dryRun: flags.dryRun }).pipe(
167 Effect.provide(Layer.merge(DatabaseMaintenance.layer, CliService.layer(config))),
168 );
169 }),
170 ),
171);