GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(server): t3 doctor warns how long reclaiming takes and shows each… · incognitojam/styal@b264e11

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • apps/server/src
    • cli
      • doctor.test.ts
      • doctor.ts
    • persistence
      • DatabaseMaintenance.test.ts
      • DatabaseMaintenance.ts
  • docs/user
    • background-service.md
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎apps/server/src/cli/doctor.test.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/cli/doctor.test.ts
+74Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import * as NodeServices from "@effect/platform-node/NodeServices";
22
import { assert, it } from "@effect/vitest";
3+
import * as Console from "effect/Console";
34
import * as Effect from "effect/Effect";
45
import * as Layer from "effect/Layer";
6+
import * as TestClock from "effect/testing/TestClock";
57

68
import * as BootService from "../cloud/bootService.ts";
79
import { runDoctor } from "./doctor.ts";
@@ -53,3 +55,75 @@ it.effect(
5355
assert.deepEqual(calls, ["pause", "compact", "resume"]);
5456
}),
5557
);
58+
59+
it.effect("warns how long reclaiming can take and reports each step with its elapsed time", () =>
60+
Effect.gen(function* () {
61+
const output: string[] = [];
62+
const steps = [
63+
["prune-events", "65 seconds"],
64+
["vacuum", "701 seconds"],
65+
["rebuild-search", "1 second"],
66+
["checkpoint", "1 second"],
67+
] as const;
68+
yield* runDoctor("/test/statev2.sqlite", { fix: true, dryRun: false, interactive: false }).pipe(
69+
Effect.provide(
70+
Layer.mergeAll(
71+
NodeServices.layer,
72+
Layer.mock(BootService.BootService)({
73+
withStopped: (operation) =>
74+
Effect.sync(() => output.push("<pause>")).pipe(
75+
Effect.andThen(operation),
76+
Effect.ensuring(Effect.sync(() => output.push("<resume>"))),
77+
),
78+
}),
79+
Layer.succeed(DatabaseMaintenance, {
80+
inspect: () =>
81+
Effect.succeed({
82+
databaseBytes: 12.8 * 1024 ** 3,
83+
reclaimableBytes: 0,
84+
incrementalVacuumEnabled: false,
85+
legacyDatabaseBytes: null,
86+
}),
87+
compact: (_databasePath, onStep) =>
88+
Effect.gen(function* () {
89+
for (const [step, duration] of steps) {
90+
if (onStep) yield* onStep(step);
91+
yield* TestClock.adjust(duration);
92+
}
93+
return {
94+
beforeBytes: 12.8 * 1024 ** 3,
95+
afterBytes: 12.8 * 1024 ** 3,
96+
deletedEventCount: 0,
97+
deletedReceiptCount: 0,
98+
};
99+
}),
100+
removeLegacyDatabase: () => Effect.void,
101+
}),
102+
),
103+
),
104+
Effect.provideService(Console.Console, {
105+
...globalThis.console,
106+
log: (...args: ReadonlyArray<unknown>) => {
107+
output.push(...args.join(" ").split("\n"));
108+
},
109+
}),
110+
);
111+
112+
const paused = output.indexOf("<pause>");
113+
const resumed = output.indexOf("<resume>");
114+
assert.isAbove(paused, -1, "the repair must run with the service paused");
115+
const beforePause = output.slice(0, paused).join("\n");
116+
const description = beforePause.slice(beforePause.indexOf("Reclaim database space"));
117+
assert.include(description, "12.80 GiB", "the repair must state the database size up front");
118+
assert.match(description, /hour/, "the repair must warn it can take over an hour");
119+
const progress = output
120+
.slice(paused + 1, resumed)
121+
.filter((line) => line.trim() !== "" && !line.trim().startsWith("Done"))
122+
.map((line) => /\[(\d+:\d{2})\]/.exec(line)?.[1] ?? `unprefixed: ${line}`);
123+
assert.deepEqual(
124+
progress,
125+
["0:00", "1:05", "12:46", "12:47"],
126+
"each compaction step must print one line with the elapsed time as it starts",
127+
);
128+
}),
129+
);
Collapse file

‎apps/server/src/cli/doctor.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/cli/doctor.ts
+29-5Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { DATABASE_COMPACTION_RECOMMENDED_BYTES } from "@t3tools/contracts";
2+
import * as Clock from "effect/Clock";
23
import * as Console from "effect/Console";
34
import * as Effect from "effect/Effect";
45
import * as Layer from "effect/Layer";
@@ -16,6 +17,18 @@ const formatBytes = (bytes: number) =>
1617
? `${(bytes / 1024 ** 2).toFixed(1)} MiB`
1718
: `${Math.ceil(bytes / 1024)} KiB`;
1819

20+
const formatElapsed = (nanos: bigint) => {
21+
const seconds = Number(nanos / 1_000_000_000n);
22+
return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
23+
};
24+
25+
const COMPACT_STEP_LABELS: Record<DatabaseMaintenance.DatabaseCompactStep, string> = {
26+
"prune-events": "Removing superseded events",
27+
vacuum: "Rewriting the database file",
28+
"rebuild-search": "Rebuilding the search index",
29+
checkpoint: "Flushing the write-ahead log",
30+
};
31+
1932
export const runDoctor = Effect.fn("runDoctor")(function* (
2033
databasePath: string,
2134
options: { readonly fix: boolean; readonly dryRun: boolean; readonly interactive?: boolean },
@@ -41,7 +54,7 @@ export const runDoctor = Effect.fn("runDoctor")(function* (
4154
status.incrementalVacuumEnabled
4255
? "Returns unused space to disk."
4356
: "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.`,
57+
}\n Rewrites the whole ${formatBytes(status.databaseBytes)} database, which can take more than an hour on a large database or slow disk.\n Pauses the background service, if installed, while it runs and may need temporary disk space.`,
4558
recommended:
4659
!status.incrementalVacuumEnabled ||
4760
status.reclaimableBytes >= DATABASE_COMPACTION_RECOMMENDED_BYTES,
@@ -100,15 +113,26 @@ export const runDoctor = Effect.fn("runDoctor")(function* (
100113
}
101114
if (selected.includes("database")) {
102115
const service = yield* BootService.BootService;
103-
yield* Console.log("\nReclaiming database space. This can take several minutes...");
116+
yield* Console.log("\nReclaiming database space. Each step is shown as it starts.");
117+
const startedAt = yield* Clock.monotonicTimeNanos;
118+
const reportStep = (step: DatabaseMaintenance.DatabaseCompactStep) =>
119+
Clock.monotonicTimeNanos.pipe(
120+
Effect.flatMap((now) =>
121+
Console.log(` [${formatElapsed(now - startedAt)}] ${COMPACT_STEP_LABELS[step]}`),
122+
),
123+
);
104124
// Report the repair before restarting, which can fail independently.
105125
yield* service.withStopped(
106126
maintenance
107-
.compact(databasePath)
127+
.compact(databasePath, reportStep)
108128
.pipe(
109129
Effect.tap((result) =>
110-
Console.log(
111-
`Done: ${formatBytes(result.beforeBytes)} -> ${formatBytes(result.afterBytes)}, ${result.deletedEventCount} superseded events removed.`,
130+
Clock.monotonicTimeNanos.pipe(
131+
Effect.flatMap((now) =>
132+
Console.log(
133+
`Done in ${formatElapsed(now - startedAt)}: ${formatBytes(result.beforeBytes)} -> ${formatBytes(result.afterBytes)}, ${result.deletedEventCount} superseded events removed.`,
134+
),
135+
),
112136
),
113137
),
114138
),
Collapse file

‎apps/server/src/persistence/DatabaseMaintenance.test.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/persistence/DatabaseMaintenance.test.ts
+15-11Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -227,18 +227,22 @@ it.layer(DatabaseMaintenance.layer.pipe(Layer.provideMerge(NodeServices.layer)))
227227
const clock = yield* Clock.Clock;
228228
const pauses: number[] = [];
229229
let activeNanos = 0n;
230-
const result = yield* maintenance.compact(dbPath).pipe(
231-
Effect.provideService(Clock.Clock, {
232-
...clock,
233-
// Exceed the background budget whenever the compactor checks elapsed time.
234-
monotonicTimeNanos: Effect.sync(() => (activeNanos += 30_000_000n)),
235-
sleep: (duration) =>
236-
Effect.sync(() => {
237-
pauses.push(Duration.toMillis(duration));
238-
}),
239-
}),
240-
);
230+
const steps: string[] = [];
231+
const result = yield* maintenance
232+
.compact(dbPath, (step) => Effect.sync(() => steps.push(step)))
233+
.pipe(
234+
Effect.provideService(Clock.Clock, {
235+
...clock,
236+
// Exceed the background budget whenever the compactor checks elapsed time.
237+
monotonicTimeNanos: Effect.sync(() => (activeNanos += 30_000_000n)),
238+
sleep: (duration) =>
239+
Effect.sync(() => {
240+
pauses.push(Duration.toMillis(duration));
241+
}),
242+
}),
243+
);
241244
assert.deepEqual(pauses, [], "offline doctor must not throttle compaction");
245+
assert.deepEqual(steps, ["prune-events", "vacuum", "rebuild-search", "checkpoint"]);
242246
assert.equal(result.deletedReceiptCount, 51);
243247
assert.isBelow(result.afterBytes, result.beforeBytes - 3 * 1024 * 1024);
244248
yield* Effect.gen(function* () {
Collapse file

‎apps/server/src/persistence/DatabaseMaintenance.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/persistence/DatabaseMaintenance.ts
+18-3Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@ export class DiskSpaceCheckError extends Schema.TaggedError<DiskSpaceCheckError>
7171
}
7272
}
7373

74+
export type DatabaseCompactStep = "prune-events" | "vacuum" | "rebuild-search" | "checkpoint";
75+
7476
export class DatabaseMaintenance extends Context.Service<
7577
DatabaseMaintenance,
7678
{
@@ -84,8 +86,14 @@ export class DatabaseMaintenance extends Context.Service<
8486
},
8587
DatabaseMissingError | DatabaseInspectError
8688
>;
87-
/** Compacts history, then VACUUMs into incremental auto_vacuum. Refuses while a server has it open. */
88-
readonly compact: (databasePath: string) => Effect.Effect<
89+
/**
90+
* Compacts history, then VACUUMs into incremental auto_vacuum. Refuses while a server has it open.
91+
* Calls `onStep` as each step starts; VACUUM time grows with the whole database size.
92+
*/
93+
readonly compact: (
94+
databasePath: string,
95+
onStep?: (step: DatabaseCompactStep) => Effect.Effect<void>,
96+
) => Effect.Effect<
8997
{
9098
readonly beforeBytes: number;
9199
readonly afterBytes: number;
@@ -171,18 +179,25 @@ const make = Effect.gen(function* () {
171179
);
172180

173181
const compact = Effect.fn("DatabaseMaintenance.compact")(
174-
function* (databasePath: string) {
182+
function* (
183+
databasePath: string,
184+
onStep: (step: DatabaseCompactStep) => Effect.Effect<void> = () => Effect.void,
185+
) {
175186
yield* locate(databasePath);
176187
const beforeBytes = Number((yield* fs.stat(databasePath)).size);
177188
const result = yield* Effect.gen(function* () {
178189
const sql = yield* SqlClient.SqlClient;
179190
yield* lockExclusively(databasePath);
180191
const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
192+
yield* onStep("prune-events");
181193
const summary = yield* maintenance.pruneEventStore();
194+
yield* onStep("vacuum");
182195
// VACUUM is required to enable incremental auto_vacuum on existing databases.
183196
yield* sql`PRAGMA auto_vacuum = INCREMENTAL`;
184197
yield* sql`VACUUM`;
198+
yield* onStep("rebuild-search");
185199
yield* rebuildMessageSearch(sql);
200+
yield* onStep("checkpoint");
186201
yield* sql`PRAGMA wal_checkpoint(TRUNCATE)`;
187202
return summary;
188203
}).pipe(
Collapse file

‎docs/user/background-service.md‎

Copy file name to clipboardExpand all lines: docs/user/background-service.md
+7-5Lines changed: 7 additions & 5 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -184,11 +184,13 @@ the repair fails. Quit a server you started by hand, or the desktop app, first:
184184
the repair refuses to touch a database that is in use. Use `--base-dir` for a
185185
different data directory.
186186

187-
The repair can take several minutes on a large database. It rebuilds the
188-
database through a temporary copy, so it needs free space of about twice the
189-
data still in use (the database size minus the reclaimable space): once in the
190-
system temporary directory (on Linux and macOS, `TMPDIR`, or `/var/tmp` when it
191-
is not set) and once next to the database for its write-ahead log.
187+
The repair's time grows with the size of the whole database, not only the
188+
space it reclaims, and can exceed an hour on a large database or a slow disk;
189+
`t3 doctor` shows each step as it runs. It rebuilds the database through a
190+
temporary copy, so it needs free space of about twice the data still in use
191+
(the database size minus the reclaimable space): once in the system temporary
192+
directory (on Linux and macOS, `TMPDIR`, or `/var/tmp` when it is not set) and
193+
once next to the database for its write-ahead log.
192194

193195
If you upgraded from a version before 0.1.0, its database (`state.sqlite`) is
194196
still kept next to the current one so you can roll back. `t3 doctor` offers to

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.