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

doctor.test.ts

227 lines8.7 KB

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