Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

doctor.ts

147 lines5.6 KB

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 recommended: false,
58 },
59 ]),
60 ];
61 if (repairs.length === 0) {
62 yield* Console.log("Nothing to repair.");
63 return;
64 }
65 for (const repair of repairs) {
66 yield* Console.log(
67 `\n${repair.title}${repair.recommended ? " (recommended)" : ""}\n ${repair.description}`,
68 );
69 }
70 if (options.dryRun) {
71 yield* Console.log("\nDry run: nothing changed.");
72 return;
73 }
74 const interactive = options.interactive ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
75 if (!options.fix && !interactive) {
76 yield* Console.log(
77 "\nRun in a terminal to choose repairs, or pass --fix for the recommended ones.",
78 );
79 return;
80 }
81 const selected = options.fix
82 ? repairs.filter((repair) => repair.recommended).map((repair) => repair.id)
83 : yield* Prompt.run(
84 Prompt.MultiSelect({
85 message: "Choose repairs to run",
86 choices: repairs.map((repair) => ({
87 title: repair.title + (repair.recommended ? " (recommended)" : ""),
88 value: repair.id,
89 selected: repair.recommended,
90 })),
91 }),
92 ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed([]) }));
93 if (selected.length === 0) {
94 yield* Console.log(
95 options.fix
96 ? "No recommended repairs; nothing changed."
97 : "No repairs selected; nothing changed.",
98 );
99 return;
100 }
101 if (selected.includes("database")) {
102 const service = yield* BootService.BootService;
103 yield* Console.log("\nReclaiming database space. This can take several minutes...");
104 // Report the repair before restarting, which can fail independently.
105 yield* service.withStopped(
106 maintenance
107 .compact(databasePath)
108 .pipe(
109 Effect.tap((result) =>
110 Console.log(
111 `Done: ${formatBytes(result.beforeBytes)} -> ${formatBytes(result.afterBytes)}, ${result.deletedEventCount} superseded events removed.`,
112 ),
113 ),
114 ),
115 );
116 }
117 if (selected.includes("legacy")) {
118 // Only pre-0.1.0 servers use this file; removal refuses while they hold it open.
119 yield* maintenance.removeLegacyDatabase(databasePath);
120 yield* Console.log("\nDeleted the database from before 0.1.0.");
121 }
122});
123​
124export const doctorCommand = Command.make("doctor", {
125 ...projectLocationFlags,
126 fix: Flag.Boolean("fix").pipe(
127 Flag.withDescription("Apply the recommended repairs without prompting."),
128 Flag.withDefault(false),
129 ),
130 dryRun: Flag.Boolean("dry-run").pipe(
131 Flag.withDescription("Show the repairs without changing anything, even with --fix."),
132 Flag.withDefault(false),
133 ),
134}).pipe(
135 Command.withDescription(
136 "Inspect this T3 Code data directory and repair it. Pauses and restarts the background service as needed.",
137 ),
138 Command.withHandler((flags) =>
139 Effect.gen(function* () {
140 const logLevel = yield* GlobalFlag.LogLevel;
141 const config = yield* resolveCliAuthConfig(flags, logLevel);
142 yield* runDoctor(config.dbPath, { fix: flags.fix, dryRun: flags.dryRun }).pipe(
143 Effect.provide(Layer.merge(DatabaseMaintenance.layer, CliService.layer(config))),
144 );
145 }),
146 ),
147);