Open History to see the last commit
1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as NetService from "@t3tools/shared/Net";
5import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
6import { assert, it } from "@effect/vitest";
7import * as ConfigProvider from "effect/ConfigProvider";
8import * as Console from "effect/Console";
9import * as Effect from "effect/Effect";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as Path from "effect/Path";
13import { Command } from "effect/cli";
14import * as SqlClient from "effect/sql/SqlClient";
15import * as TestClock from "effect/testing/TestClock";
16import * as TestConsole from "effect/testing/TestConsole";
17
18import * as BootService from "../cloud/bootService.ts";
19import { doctorCommand, runDoctor } from "./doctor.ts";
20import { DatabaseMaintenance } from "../persistence/DatabaseMaintenance.ts";
21import * as ProcessRunner from "../processRunner.ts";
22import { acquireServerOwnership } from "../serverOwnership.ts";
23import { makePersistedServerRuntimeState } from "../serverRuntimeState.ts";
24
25// An empty home, so no boot service unit installed on this machine is read.
26const layerHost = Layer.mergeAll(
27 ProcessRunner.layer,
28 Layer.effect(
29 HostProcess.HomeDirectory,
30 Effect.gen(function* () {
31 return yield* (yield* FileSystem.FileSystem).makeTempDirectoryScoped();
32 }),
33 ),
34 Layer.succeed(HostProcess.Environment, {}),
35).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)));
36
37it.effect("doctor --dry-run leaves the data directory and uploads alone", () =>
38 Effect.gen(function* () {
39 const fs = yield* FileSystem.FileSystem;
40 const path = yield* Path.Path;
41 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-doctor-dry-run-" });
42 const stateDir = path.join(baseDir, "userdata");
43 const attachmentsDir = path.join(stateDir, "attachments");
44 const upload = path.join(attachmentsDir, "upload.part");
45 yield* fs.makeDirectory(attachmentsDir, { recursive: true });
46 yield* fs.writeFileString(upload, "partial upload");
47 yield* fs.utimes(upload, 0, 0);
48 yield* TestClock.setTime(2 * 60 * 60 * 1_000);
49 yield* SqlClient.SqlClient.pipe(
50 Effect.flatMap((sql) => sql`CREATE TABLE fixture (id INTEGER)`),
51 Effect.provide(NodeSqliteClient.layer({ filename: path.join(stateDir, "statev2.sqlite") })),
52 );
53
54 yield* Command.runWith(doctorCommand, { version: "0.0.0" })([
55 "--base-dir",
56 baseDir,
57 "--fix",
58 "--dry-run",
59 ]).pipe(
60 Effect.provide(
61 ConfigProvider.layer(
62 ConfigProvider.fromEnv({
63 env: {
64 T3CODE_PORT: "3773",
65 T3CODE_TRACE_FILE: path.join(baseDir, "trace", "trace.ndjson"),
66 },
67 }),
68 ),
69 ),
70 );
71
72 assert.isTrue(yield* fs.exists(upload));
73 assert.deepEqual(yield* fs.readDirectory(baseDir), ["userdata"]);
74 assert.deepEqual((yield* fs.readDirectory(stateDir)).toSorted(), [
75 "attachments",
76 "statev2.sqlite",
77 ]);
78 }).pipe(Effect.provide(Layer.mergeAll(layerHost, NetService.layer))),
79);
80
81it.effect(
82 "--fix locks the home while the service is paused, names a server that holds it, keeps the V1 database, and --dry-run changes nothing",
83 () =>
84 Effect.gen(function* () {
85 const fs = yield* FileSystem.FileSystem;
86 const path = yield* Path.Path;
87 const stateDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-doctor-" });
88 const serverRuntimeStatePath = path.join(stateDir, "server-runtime.json");
89 const calls: string[] = [];
90 const services =
91 yield* Effect.context<Effect.Services<ReturnType<typeof acquireServerOwnership>>>();
92 // Stands in for a server launched for the same home, for example over SSH.
93 const startServer = Effect.scoped(acquireServerOwnership(serverRuntimeStatePath)).pipe(
94 Effect.result,
95 Effect.map((result) =>
96 calls.push(result._tag === "Success" ? "server started" : result.failure._tag),
97 ),
98 Effect.provide(services),
99 );
100 const doctor = (dryRun: boolean) =>
101 runDoctor(
102 { dbPath: path.join(stateDir, "statev2.sqlite"), serverRuntimeStatePath },
103 { fix: true, dryRun, interactive: false },
104 ).pipe(
105 Effect.provide(
106 Layer.mergeAll(
107 Layer.mock(BootService.BootService)({
108 withStopped: (operation) =>
109 Effect.sync(() => calls.push("pause")).pipe(
110 Effect.andThen(operation),
111 Effect.ensuring(Effect.sync(() => calls.push("resume"))),
112 ),
113 }),
114 Layer.succeed(DatabaseMaintenance, {
115 inspect: () =>
116 Effect.succeed({
117 databaseBytes: 2000,
118 reclaimableBytes: 1000,
119 incrementalVacuumEnabled: false,
120 legacyDatabaseBytes: 4000,
121 legacyOnlyRecords: { projects: 0, threads: 0 },
122 }),
123 compact: () =>
124 startServer.pipe(
125 Effect.map(() => {
126 calls.push("compact");
127 return {
128 beforeBytes: 2000,
129 afterBytes: 1000,
130 deletedEventCount: 1,
131 deletedReceiptCount: 0,
132 };
133 }),
134 ),
135 removeLegacyDatabase: () => Effect.sync(() => calls.push("remove legacy")),
136 }),
137 ),
138 ),
139 );
140 yield* doctor(true);
141 assert.deepEqual(calls, []);
142 yield* doctor(false);
143 yield* startServer;
144 assert.deepEqual(calls, [
145 "pause",
146 "ServerAlreadyRunningError",
147 "compact",
148 "resume",
149 "server started",
150 ]);
151
152 calls.length = 0;
153 const state = yield* makePersistedServerRuntimeState({
154 config: { host: undefined, devUrl: undefined },
155 port: 3773,
156 });
157 const refused = yield* Effect.scoped(
158 acquireServerOwnership(serverRuntimeStatePath).pipe(
159 Effect.tap((owner) => owner.publish(state)),
160 Effect.andThen(doctor(false)),
161 ),
162 ).pipe(Effect.flip);
163 assert.equal(
164 refused.message,
165 `Stop T3 Code server process ${state.pid}, which the background service did not start, before repairing the database.`,
166 );
167 assert.deepEqual(calls, ["pause", "resume"]);
168 }).pipe(Effect.provide(layerHost)),
169);
170
171it.effect("reports sizes just under the next unit in that unit", () =>
172 Effect.gen(function* () {
173 yield* runDoctor(
174 { dbPath: "/test/statev2.sqlite", serverRuntimeStatePath: "/test/server-runtime.json" },
175 { fix: false, dryRun: true },
176 ).pipe(
177 Effect.provide(
178 Layer.mergeAll(
179 Layer.mock(BootService.BootService)({}),
180 Layer.mock(DatabaseMaintenance)({
181 inspect: () =>
182 Effect.succeed({
183 databaseBytes: 1024 ** 3 - 4096,
184 reclaimableBytes: 1024 ** 2 - 512,
185 incrementalVacuumEnabled: true,
186 legacyDatabaseBytes: null,
187 legacyOnlyRecords: null,
188 }),
189 }),
190 ),
191 ),
192 );
193 const [summary] = yield* TestConsole.logLines;
194 assert.strictEqual(summary, "Database: 1.00 GiB, 1.0 MiB reclaimable.");
195 }).pipe(Effect.provide(Layer.merge(layerHost, TestConsole.layer))),
196);
197
198it.effect("warns how long reclaiming can take and reports each step with its elapsed time", () =>
199 Effect.gen(function* () {
200 const output: string[] = [];
201 const steps = [
202 ["prune-events", "65 seconds"],
203 ["vacuum", "701 seconds"],
204 ["rebuild-search", "1 second"],
205 ["checkpoint", "1 second"],
206 ] as const;
207 const stateDir = yield* (yield* FileSystem.FileSystem).makeTempDirectoryScoped();
208 const path = yield* Path.Path;
209 yield* runDoctor(
210 {
211 dbPath: path.join(stateDir, "statev2.sqlite"),
212 serverRuntimeStatePath: path.join(stateDir, "server-runtime.json"),
213 },
214 { fix: true, dryRun: false, interactive: false },
215 ).pipe(
216 Effect.provide(
217 Layer.mergeAll(
218 Layer.mock(BootService.BootService)({
219 withStopped: (operation) =>
220 Effect.sync(() => output.push("<pause>")).pipe(
221 Effect.andThen(operation),
222 Effect.ensuring(Effect.sync(() => output.push("<resume>"))),
223 ),
224 }),
225 Layer.succeed(DatabaseMaintenance, {
226 inspect: () =>
227 Effect.succeed({
228 databaseBytes: 12.8 * 1024 ** 3,
229 reclaimableBytes: 0,
230 incrementalVacuumEnabled: false,
231 legacyDatabaseBytes: null,
232 legacyOnlyRecords: null,
233 }),
234 compact: (_databasePath, onStep) =>
235 Effect.gen(function* () {
236 for (const [step, duration] of steps) {
237 if (onStep) yield* onStep(step);
238 yield* TestClock.adjust(duration);
239 }
240 return {
241 beforeBytes: 12.8 * 1024 ** 3,
242 afterBytes: 12.8 * 1024 ** 3,
243 deletedEventCount: 1,
244 deletedReceiptCount: 0,
245 };
246 }),
247 removeLegacyDatabase: () => Effect.void,
248 }),
249 ),
250 ),
251 Effect.provideService(Console.Console, {
252 ...globalThis.console,
253 log: (...args: ReadonlyArray<unknown>) => {
254 output.push(...args.join(" ").split("\n"));
255 },
256 }),
257 );
258
259 const paused = output.indexOf("<pause>");
260 const resumed = output.indexOf("<resume>");
261 assert.isAbove(paused, -1, "the repair must run with the service paused");
262 const beforePause = output.slice(0, paused).join("\n");
263 const description = beforePause.slice(beforePause.indexOf("Reclaim database space"));
264 assert.include(description, "12.80 GiB", "the repair must state the database size up front");
265 assert.match(description, /hour/, "the repair must warn it can take over an hour");
266 const progress = output
267 .slice(paused + 1, resumed)
268 .filter((line) => line.trim() !== "" && !line.trim().startsWith("Done"))
269 .map((line) => /\[(\d+:\d{2})\]/.exec(line)?.[1] ?? `unprefixed: ${line}`);
270 assert.deepEqual(
271 progress,
272 ["0:00", "1:05", "12:46", "12:47"],
273 "each compaction step must print one line with the elapsed time as it starts",
274 );
275 assert.include(output, "Done in 12:48: 12.80 GiB -> 12.80 GiB, 1 superseded event removed.");
276 }).pipe(Effect.provide(layerHost)),
277);