Open History to see the last commit
1import { DATABASE_COMPACTION_RECOMMENDED_BYTES } from "@t3tools/contracts";
2import * as Console from "effect/Console";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import { Command, Flag, GlobalFlag, Prompt } from "effect/cli";
6
7import * as BootService from "../cloud/bootService.ts";
8import * as DatabaseMaintenance from "../persistence/DatabaseMaintenance.ts";
9import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
10import * as CliService from "./service.ts";
11
12const formatBytes = (bytes: number) =>
13 bytes >= 1024 ** 3
14 ? `${(bytes / 1024 ** 3).toFixed(2)} GiB`
15 : bytes >= 1024 ** 2
16 ? `${(bytes / 1024 ** 2).toFixed(1)} MiB`
17 : `${Math.ceil(bytes / 1024)} KiB`;
18
19export const runDoctor = Effect.fn("runDoctor")(function* (
20 databasePath: string,
21 options: { readonly fix: boolean; readonly dryRun: boolean; readonly interactive?: boolean },
22) {
23 const maintenance = yield* DatabaseMaintenance.DatabaseMaintenance;
24 const status = yield* maintenance.inspect(databasePath);
25 yield* Console.log(
26 `Database: ${formatBytes(status.databaseBytes)}, ${formatBytes(status.reclaimableBytes)} reclaimable.`,
27 );
28 if (status.incrementalVacuumEnabled && status.reclaimableBytes === 0) {
29 yield* Console.log("Nothing to repair.");
30 return;
31 }
32 const recommended =
33 !status.incrementalVacuumEnabled ||
34 status.reclaimableBytes >= DATABASE_COMPACTION_RECOMMENDED_BYTES;
35 const repairs = [
36 {
37 id: "database" as const,
38 title: "Reclaim database space",
39 description: status.incrementalVacuumEnabled
40 ? "Returns unused space to disk."
41 : "Returns unused space to disk and turns on automatic shrinking.",
42 recommended,
43 },
44 ];
45 for (const repair of repairs) {
46 yield* Console.log(
47 `\n${repair.title}${repair.recommended ? " (recommended)" : ""}\n ${repair.description}\n Pauses the background service, if installed, while it runs and may need temporary disk space.`,
48 );
49 }
50 if (options.dryRun) {
51 yield* Console.log("\nDry run: nothing changed.");
52 return;
53 }
54 const interactive = options.interactive ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
55 if (!options.fix && !interactive) {
56 yield* Console.log(
57 "\nRun in a terminal to choose repairs, or pass --fix for the recommended ones.",
58 );
59 return;
60 }
61 const selected = options.fix
62 ? repairs.filter((repair) => repair.recommended).map((repair) => repair.id)
63 : yield* Prompt.run(
64 Prompt.MultiSelect({
65 message: "Choose repairs to run",
66 choices: repairs.map((repair) => ({
67 title: repair.title + (repair.recommended ? " (recommended)" : ""),
68 value: repair.id,
69 selected: repair.recommended,
70 })),
71 }),
72 ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed([]) }));
73 if (selected.length === 0) {
74 yield* Console.log(
75 options.fix
76 ? "No recommended repairs; nothing changed."
77 : "No repairs selected; nothing changed.",
78 );
79 return;
80 }
81 const service = yield* BootService.BootService;
82 yield* Console.log("\nReclaiming database space. This can take several minutes...");
83 // Report inside the pause: a repair that succeeded is worth knowing about
84 // even when starting the service again fails afterwards.
85 yield* service.withStopped(
86 maintenance
87 .compact(databasePath)
88 .pipe(
89 Effect.tap((result) =>
90 Console.log(
91 `Done: ${formatBytes(result.beforeBytes)} -> ${formatBytes(result.afterBytes)}, ${result.deletedEventCount} superseded events removed.`,
92 ),
93 ),
94 ),
95 );
96});
97
98export const doctorCommand = Command.make("doctor", {
99 ...projectLocationFlags,
100 fix: Flag.Boolean("fix").pipe(
101 Flag.withDescription("Apply the recommended repairs without prompting."),
102 Flag.withDefault(false),
103 ),
104 dryRun: Flag.Boolean("dry-run").pipe(
105 Flag.withDescription("Show the repairs without changing anything, even with --fix."),
106 Flag.withDefault(false),
107 ),
108}).pipe(
109 Command.withDescription(
110 "Inspect this T3 Code data directory and repair it. Pauses and restarts the background service as needed.",
111 ),
112 Command.withHandler((flags) =>
113 Effect.gen(function* () {
114 const logLevel = yield* GlobalFlag.LogLevel;
115 const config = yield* resolveCliAuthConfig(flags, logLevel);
116 yield* runDoctor(config.dbPath, { fix: flags.fix, dryRun: flags.dryRun }).pipe(
117 Effect.provide(Layer.merge(DatabaseMaintenance.layer, CliService.layer(config))),
118 );
119 }),
120 ),
121);