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.legacyDatabaseBytes !== null) {
29 yield* Console.log(
30 `Database from before 0.1.0: ${formatBytes(status.legacyDatabaseBytes)}, kept for rolling back.`,
31 );
32 }
33 const repairs = [
34 ...(status.incrementalVacuumEnabled && status.reclaimableBytes === 0
35 ? []
36 : [
37 {
38 id: "database" as const,
39 title: "Reclaim database space",
40 description: `${
41 status.incrementalVacuumEnabled
42 ? "Returns unused space to disk."
43 : "Returns unused space to disk and turns on automatic shrinking."
44 }\n Pauses the background service, if installed, while it runs and may need temporary disk space.`,
45 recommended:
46 !status.incrementalVacuumEnabled ||
47 status.reclaimableBytes >= DATABASE_COMPACTION_RECOMMENDED_BYTES,
48 },
49 ]),
50 ...(status.legacyDatabaseBytes === null
51 ? []
52 : [
53 {
54 id: "legacy" as const,
55 title: "Delete the database from before 0.1.0",
56 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.`,
57 // Never chosen for you: deleting it gives up rolling back.
58 recommended: false,
59 },
60 ]),
61 ];
62 if (repairs.length === 0) {
63 yield* Console.log("Nothing to repair.");
64 return;
65 }
66 for (const repair of repairs) {
67 yield* Console.log(
68 `\n${repair.title}${repair.recommended ? " (recommended)" : ""}\n ${repair.description}`,
69 );
70 }
71 if (options.dryRun) {
72 yield* Console.log("\nDry run: nothing changed.");
73 return;
74 }
75 const interactive = options.interactive ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
76 if (!options.fix && !interactive) {
77 yield* Console.log(
78 "\nRun in a terminal to choose repairs, or pass --fix for the recommended ones.",
79 );
80 return;
81 }
82 const selected = options.fix
83 ? repairs.filter((repair) => repair.recommended).map((repair) => repair.id)
84 : yield* Prompt.run(
85 Prompt.MultiSelect({
86 message: "Choose repairs to run",
87 choices: repairs.map((repair) => ({
88 title: repair.title + (repair.recommended ? " (recommended)" : ""),
89 value: repair.id,
90 selected: repair.recommended,
91 })),
92 }),
93 ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed([]) }));
94 if (selected.length === 0) {
95 yield* Console.log(
96 options.fix
97 ? "No recommended repairs; nothing changed."
98 : "No repairs selected; nothing changed.",
99 );
100 return;
101 }
102 if (selected.includes("database")) {
103 const service = yield* BootService.BootService;
104 yield* Console.log("\nReclaiming database space. This can take several minutes...");
105 // Report inside the pause: a repair that succeeded is worth knowing about
106 // even when starting the service again fails afterwards.
107 yield* service.withStopped(
108 maintenance
109 .compact(databasePath)
110 .pipe(
111 Effect.tap((result) =>
112 Console.log(
113 `Done: ${formatBytes(result.beforeBytes)} -> ${formatBytes(result.afterBytes)}, ${result.deletedEventCount} superseded events removed.`,
114 ),
115 ),
116 ),
117 );
118 }
119 if (selected.includes("legacy")) {
120 // Only versions before 0.1.0 open this file, so the service keeps running;
121 // the removal itself refuses while one of those still has it open.
122 yield* maintenance.removeLegacyDatabase(databasePath);
123 yield* Console.log("\nDeleted the database from before 0.1.0.");
124 }
125});
126
127export const doctorCommand = Command.make("doctor", {
128 ...projectLocationFlags,
129 fix: Flag.Boolean("fix").pipe(
130 Flag.withDescription("Apply the recommended repairs without prompting."),
131 Flag.withDefault(false),
132 ),
133 dryRun: Flag.Boolean("dry-run").pipe(
134 Flag.withDescription("Show the repairs without changing anything, even with --fix."),
135 Flag.withDefault(false),
136 ),
137}).pipe(
138 Command.withDescription(
139 "Inspect this T3 Code data directory and repair it. Pauses and restarts the background service as needed.",
140 ),
141 Command.withHandler((flags) =>
142 Effect.gen(function* () {
143 const logLevel = yield* GlobalFlag.LogLevel;
144 const config = yield* resolveCliAuthConfig(flags, logLevel);
145 yield* runDoctor(config.dbPath, { fix: flags.fix, dryRun: flags.dryRun }).pipe(
146 Effect.provide(Layer.merge(DatabaseMaintenance.layer, CliService.layer(config))),
147 );
148 }),
149 ),
150);