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 * as Option from "effect/Option";
7import { Command, Flag, GlobalFlag, Prompt } from "effect/cli";
8
9import * as BootService from "../cloud/bootService.ts";
10import * as DatabaseMaintenance from "../persistence/DatabaseMaintenance.ts";
11import * as ServerOwnership from "../serverOwnership.ts";
12import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
13import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
14import * as CliService from "./service.ts";
15
16// Pick the unit after rounding, so a size just under 1 GiB reads "1.00 GiB", not "1024.0 MiB".
17const formatBytes = (bytes: number) => {
18 const mebibytes = (bytes / 1024 ** 2).toFixed(1);
19 const kibibytes = Math.ceil(bytes / 1024);
20 return Number(mebibytes) >= 1024
21 ? `${(bytes / 1024 ** 3).toFixed(2)} GiB`
22 : kibibytes >= 1024
23 ? `${mebibytes} MiB`
24 : `${kibibytes} KiB`;
25};
26
27const formatElapsed = (nanos: bigint) => {
28 const seconds = Number(nanos / 1_000_000_000n);
29 return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
30};
31
32const COMPACT_STEP_LABELS: Record<DatabaseMaintenance.DatabaseCompactStep, string> = {
33 "prune-events": "Removing superseded events",
34 vacuum: "Rewriting the database file",
35 "rebuild-search": "Rebuilding the search index",
36 checkpoint: "Flushing the write-ahead log",
37};
38
39// Holding the server lock refuses a server launched mid-repair, such as one started over SSH.
40// Lock only: acquireServerOwnership would also refuse the older service doctor just stopped.
41const lockServerHome = Effect.fn("runDoctor.lockServerHome")(function* (paths: {
42 readonly dbPath: string;
43 readonly serverRuntimeStatePath: string;
44}) {
45 yield* ServerOwnership.holdServerOwnershipLock(paths.serverRuntimeStatePath).pipe(
46 Effect.catchTags({
47 ServerAlreadyRunningError: Effect.fn("runDoctor.nameServerHolder")(function* (cause) {
48 const owner = yield* readPersistedServerRuntimeState(paths.serverRuntimeStatePath).pipe(
49 Effect.map(Option.filter((state) => isProcessAlive(state.pid))),
50 Effect.orElseSucceed(() => Option.none()),
51 );
52 return yield* new DatabaseMaintenance.DatabaseInUseError({
53 path: paths.dbPath,
54 cause,
55 ...(Option.isSome(owner) && {
56 pid: owner.value.pid,
57 serviceManaged: owner.value.serviceManaged === true,
58 }),
59 });
60 }),
61 }),
62 );
63});
64
65export const runDoctor = Effect.fn("runDoctor")(function* (
66 paths: { readonly dbPath: string; readonly serverRuntimeStatePath: string },
67 options: { readonly fix: boolean; readonly dryRun: boolean; readonly interactive?: boolean },
68) {
69 const databasePath = paths.dbPath;
70 const maintenance = yield* DatabaseMaintenance.DatabaseMaintenance;
71 const status = yield* maintenance.inspect(databasePath);
72 yield* Console.log(
73 `Database: ${formatBytes(status.databaseBytes)}, ${formatBytes(status.reclaimableBytes)} reclaimable.`,
74 );
75 const legacyRecords = status.legacyOnlyRecords;
76 if (status.legacyDatabaseBytes !== null) {
77 yield* Console.log(
78 `Database from before 0.1.0: ${formatBytes(status.legacyDatabaseBytes)}, kept for rolling back.`,
79 );
80 if (legacyRecords === null) {
81 yield* Console.log(
82 " Could not check for missing projects or threads. Keep the old database.",
83 );
84 } else if (legacyRecords.projects > 0 || legacyRecords.threads > 0) {
85 yield* Console.log(
86 ` The current database is missing legacy records. Projects missing: ${legacyRecords.projects}. Threads missing: ${legacyRecords.threads}. Keep the old database for recovery.`,
87 );
88 }
89 }
90 const repairs = [
91 ...(status.incrementalVacuumEnabled && status.reclaimableBytes === 0
92 ? []
93 : [
94 {
95 id: "database" as const,
96 title: "Reclaim database space",
97 description: `${
98 status.incrementalVacuumEnabled
99 ? "Returns unused space to disk."
100 : "Returns unused space to disk and turns on automatic shrinking."
101 }\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.`,
102 recommended:
103 !status.incrementalVacuumEnabled ||
104 status.reclaimableBytes >= DATABASE_COMPACTION_RECOMMENDED_BYTES,
105 },
106 ]),
107 ...(status.legacyDatabaseBytes === null ||
108 legacyRecords === null ||
109 legacyRecords.projects > 0 ||
110 legacyRecords.threads > 0
111 ? []
112 : [
113 {
114 id: "legacy" as const,
115 title: "Delete the database from before 0.1.0",
116 description: `Frees ${formatBytes(status.legacyDatabaseBytes)}.\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.`,
117 recommended: false,
118 },
119 ]),
120 ];
121 if (repairs.length === 0) {
122 yield* Console.log("Nothing to repair.");
123 return;
124 }
125 for (const repair of repairs) {
126 yield* Console.log(
127 `\n${repair.title}${repair.recommended ? " (recommended)" : ""}\n ${repair.description}`,
128 );
129 }
130 if (options.dryRun) {
131 yield* Console.log("\nDry run: nothing changed.");
132 return;
133 }
134 const interactive = options.interactive ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
135 if (!options.fix && !interactive) {
136 yield* Console.log(
137 "\nRun in a terminal to choose repairs, or pass --fix for the recommended ones.",
138 );
139 return;
140 }
141 const selected = options.fix
142 ? repairs.filter((repair) => repair.recommended).map((repair) => repair.id)
143 : yield* Prompt.run(
144 Prompt.MultiSelect({
145 message: "Choose repairs to run",
146 choices: repairs.map((repair) => ({
147 title: repair.title + (repair.recommended ? " (recommended)" : ""),
148 value: repair.id,
149 selected: repair.recommended,
150 })),
151 }),
152 ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed([]) }));
153 if (selected.length === 0) {
154 yield* Console.log(
155 options.fix
156 ? "No recommended repairs; nothing changed."
157 : "No repairs selected; nothing changed.",
158 );
159 return;
160 }
161 if (selected.includes("database")) {
162 const service = yield* BootService.BootService;
163 yield* Console.log("\nReclaiming database space. Each step is shown as it starts.");
164 const startedAt = yield* Clock.monotonicTimeNanos;
165 const reportStep = (step: DatabaseMaintenance.DatabaseCompactStep) =>
166 Clock.monotonicTimeNanos.pipe(
167 Effect.flatMap((now) =>
168 Console.log(` [${formatElapsed(now - startedAt)}] ${COMPACT_STEP_LABELS[step]}`),
169 ),
170 );
171 // Report the repair before restarting, which can fail independently.
172 yield* service.withStopped(
173 lockServerHome(paths).pipe(
174 Effect.andThen(maintenance.compact(databasePath, reportStep)),
175 Effect.tap((result) =>
176 Clock.monotonicTimeNanos.pipe(
177 Effect.flatMap((now) =>
178 Console.log(
179 `Done in ${formatElapsed(now - startedAt)}: ${formatBytes(result.beforeBytes)} -> ${formatBytes(result.afterBytes)}, ${result.deletedEventCount} superseded events removed.`,
180 ),
181 ),
182 ),
183 ),
184 Effect.scoped,
185 ),
186 );
187 }
188 if (selected.includes("legacy")) {
189 // Only pre-0.1.0 servers use this file; removal refuses while they hold it open.
190 yield* maintenance.removeLegacyDatabase(databasePath);
191 yield* Console.log("\nDeleted the database from before 0.1.0.");
192 }
193});
194
195export const doctorCommand = Command.make("doctor", {
196 ...projectLocationFlags,
197 fix: Flag.Boolean("fix").pipe(
198 Flag.withDescription("Apply the recommended repairs without prompting."),
199 Flag.withDefault(false),
200 ),
201 dryRun: Flag.Boolean("dry-run").pipe(
202 Flag.withDescription("Show the repairs without changing anything, even with --fix."),
203 Flag.withDefault(false),
204 ),
205}).pipe(
206 Command.withDescription(
207 "Inspect this T3 Code data directory and repair it. Pauses and restarts the background service as needed.",
208 ),
209 Command.withHandler((flags) =>
210 Effect.gen(function* () {
211 const logLevel = yield* GlobalFlag.LogLevel;
212 const config = yield* resolveCliAuthConfig(flags, logLevel);
213 yield* runDoctor(config, { fix: flags.fix, dryRun: flags.dryRun }).pipe(
214 Effect.provide(Layer.merge(DatabaseMaintenance.layer, CliService.layer(config))),
215 );
216 }),
217 ),
218);