Open History to see the last commit
1import { DatabaseReclaimError, type DatabaseStorageStatus } from "@t3tools/contracts";
2import * as Clock from "effect/Clock";
3import * as Context from "effect/Context";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Equal from "effect/Equal";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as Path from "effect/Path";
11import * as Schedule from "effect/Schedule";
12import * as Stream from "effect/Stream";
13import * as SubscriptionRef from "effect/SubscriptionRef";
14import * as SqlClient from "effect/sql/SqlClient";
15
16import { resolveHostCliCommand } from "../cli/invocation.ts";
17import * as ServerConfig from "../config.ts";
18import * as ProjectionMaintenance from "../orchestration-v2/ProjectionMaintenance.ts";
19import * as DatabaseMaintenance from "./DatabaseMaintenance.ts";
20import { forkParked } from "../serverActivation.ts";
21
22// Bound each reclaim pass to one minute of churn.
23const RECLAIM_PAGES_PER_PASS = 1024;
24const COMPACTION_INTERVAL = Duration.hours(6);
25
26export class DatabaseStorage extends Context.Service<
27 DatabaseStorage,
28 {
29 /** Return free pages to the filesystem on databases with incremental auto_vacuum. */
30 readonly reclaim: Effect.Effect<void>;
31 /** Current file accounting, re-published after each maintenance pass. Null until first read. */
32 readonly status: Stream.Stream<DatabaseStorageStatus | null>;
33 /** Checks free space, then stops the server; its shutdown runs the offline repair. */
34 readonly requestReclaim: Effect.Effect<void, DatabaseReclaimError>;
35 }
36>()("t3/persistence/DatabaseStorage") {}
37
38/** Stops this server so its desktop app or background service starts it again; null when run by hand. */
39export const ServerRestart = Context.Reference<Effect.Effect<void> | null>(
40 "t3/persistence/DatabaseStorage/ServerRestart",
41 { defaultValue: () => null },
42);
43
44const formatGiB = (bytes: number) => `${(bytes / 1024 ** 3).toFixed(1)} GiB`;
45
46const make = Effect.gen(function* () {
47 const sql = yield* SqlClient.SqlClient;
48 const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
49 const config = yield* ServerConfig.ServerConfig;
50 const fs = yield* FileSystem.FileSystem;
51 const path = yield* Path.Path;
52 const statusRef = yield* SubscriptionRef.make<DatabaseStorageStatus | null>(null);
53 const restart = yield* ServerRestart;
54 const reclaimFiles = DatabaseMaintenance.reclaimFiles(path, config.dbPath);
55 let reclaimFailure = Option.getOrUndefined(
56 yield* fs.readFileString(reclaimFiles.failure).pipe(Effect.option),
57 );
58
59 // The notice shows host-shell quoting verbatim; desktop needs its launcher because t3 is absent from PATH.
60 const { command: compactCommand } = yield* resolveHostCliCommand("doctor", [
61 "--base-dir",
62 config.baseDir,
63 ]);
64 // doctor --base-dir targets userdata, not implicit dev homes; suppress status to avoid touching the live install.
65 const doctorTargetsThisDatabase =
66 path.resolve(config.dbPath) ===
67 path.resolve(config.baseDir, "userdata", path.basename(config.dbPath));
68 // Only VACUUM changes these, and doctor refuses to VACUUM while a server has the database open.
69 let layout:
70 | {
71 readonly pageSize: number;
72 readonly autoVacuum: number;
73 readonly incrementalVacuum: boolean;
74 }
75 | undefined;
76 const readLayout = Effect.suspend(() =>
77 layout !== undefined
78 ? Effect.succeed(layout)
79 : Effect.gen(function* () {
80 const size = yield* sql<{ readonly page_size: number }>`PRAGMA page_size`;
81 const mode = yield* sql<{ readonly auto_vacuum: number }>`PRAGMA auto_vacuum`;
82 const autoVacuum = mode[0]?.auto_vacuum ?? 0;
83 layout = {
84 pageSize: size[0]?.page_size ?? 0,
85 autoVacuum,
86 incrementalVacuum: autoVacuum === 2,
87 };
88 return layout;
89 }),
90 );
91 const readPages = Effect.gen(function* () {
92 const { pageSize, incrementalVacuum } = yield* readLayout;
93 const pages = yield* sql<{ readonly page_count: number }>`PRAGMA page_count`;
94 const free = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
95 return {
96 databaseBytes: (pages[0]?.page_count ?? 0) * pageSize,
97 reclaimableBytes: (free[0]?.freelist_count ?? 0) * pageSize,
98 incrementalVacuum,
99 };
100 });
101 const publishStatus = Effect.gen(function* () {
102 if (!doctorTargetsThisDatabase) return;
103 const { databaseBytes, reclaimableBytes, incrementalVacuum } = yield* readPages;
104 const next: DatabaseStorageStatus = {
105 databaseBytes,
106 reclaimableBytes,
107 incrementalVacuumEnabled: incrementalVacuum,
108 compactCommand,
109 canReclaim: restart !== null,
110 ...(reclaimFailure === undefined ? {} : { reclaimFailure }),
111 };
112 // Every set reaches each open Storage page; most passes change nothing.
113 if (!Equal.equals(yield* SubscriptionRef.get(statusRef), next)) {
114 yield* SubscriptionRef.set(statusRef, next);
115 }
116 }).pipe(
117 Effect.catch((cause) => Effect.logWarning("Database storage inspection failed", { cause })),
118 );
119
120 const reclaim = Effect.gen(function* () {
121 if (!(yield* readLayout).incrementalVacuum) return;
122 // The driver steps once per statement; incremental_vacuum frees one page per step. Yield between pages.
123 for (let page = 0; page < RECLAIM_PAGES_PER_PASS; page++) {
124 const free = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
125 if ((free[0]?.freelist_count ?? 0) === 0) break;
126 yield* sql`PRAGMA incremental_vacuum(1)`;
127 yield* Effect.yieldNow;
128 }
129 }).pipe(
130 Effect.catch((cause) => Effect.logWarning("Database space reclamation failed", { cause })),
131 );
132
133 // Even a pass that deletes nothing scans the event store. Persist completion
134 // so restarting does not trigger another scan before the six-hour interval.
135 const compactedAtPath = path.join(path.dirname(config.dbPath), "compacted-at");
136 const compact = Effect.gen(function* () {
137 let sliceStarted = yield* Clock.monotonicTimeNanos;
138 const betweenPages = Effect.gen(function* () {
139 const elapsed = (yield* Clock.monotonicTimeNanos) - sliceStarted;
140 if (elapsed < 25_000_000n) return;
141 // Keep background maintenance at 10% duty, including pages that exceed the budget.
142 yield* Effect.sleep((Number(elapsed) / 1_000_000) * 9);
143 sliceStarted = yield* Clock.monotonicTimeNanos;
144 });
145 const result = yield* maintenance.pruneEventStore(betweenPages);
146 const completedAt = yield* Clock.currentTimeMillis;
147 yield* fs.writeFileString(compactedAtPath, String(completedAt)).pipe(Effect.ignore);
148 if (result.deletedEventCount > 0 || result.deletedReceiptCount > 0) {
149 yield* Effect.logInfo("Compacted orchestration history", result);
150 }
151 }).pipe(
152 Effect.catch((cause) =>
153 Effect.logWarning("Orchestration history compaction failed", { cause }),
154 ),
155 );
156 const lastCompactedAt = yield* fs.readFileString(compactedAtPath).pipe(
157 Effect.map(Number),
158 Effect.orElseSucceed(() => Number.NaN),
159 );
160 const intervalMs = Duration.toMillis(COMPACTION_INTERVAL);
161 const untilDueMs = Number.isFinite(lastCompactedAt)
162 ? lastCompactedAt + intervalMs - (yield* Clock.currentTimeMillis)
163 : 0;
164 const firstCompactionDelay = Duration.millis(
165 Math.min(intervalMs, Math.max(Duration.toMillis(Duration.minutes(1)), untilDueMs)),
166 );
167
168 yield* forkParked(
169 Effect.sleep(firstCompactionDelay).pipe(
170 Effect.andThen(
171 compact.pipe(
172 Effect.andThen(publishStatus),
173 Effect.repeat(Schedule.spaced(COMPACTION_INTERVAL)),
174 ),
175 ),
176 ),
177 );
178 yield* forkParked(
179 publishStatus.pipe(
180 Effect.andThen(Effect.sleep("1 minute")),
181 Effect.andThen(
182 reclaim.pipe(Effect.andThen(publishStatus), Effect.repeat(Schedule.spaced("1 minute"))),
183 ),
184 ),
185 );
186
187 const requestReclaim = Effect.gen(function* () {
188 if (restart === null || !doctorTargetsThisDatabase) {
189 return yield* new DatabaseReclaimError({
190 reason: `Stop T3 Code on this machine, then run: ${compactCommand}`,
191 });
192 }
193 // Only databases without automatic shrinking need it; a stale dialog can ask after another client's repair.
194 if ((yield* readLayout).autoVacuum !== 0) {
195 return yield* new DatabaseReclaimError({
196 reason: "This database already shrinks on its own. Nothing to reclaim.",
197 });
198 }
199 const { databaseBytes, reclaimableBytes } = yield* readPages;
200 const shortfall = yield* DatabaseMaintenance.reclaimSpaceShortfall(
201 config.dbPath,
202 databaseBytes - reclaimableBytes,
203 ).pipe(
204 Effect.provideService(FileSystem.FileSystem, fs),
205 Effect.provideService(Path.Path, path),
206 );
207 if (shortfall !== null) {
208 return yield* new DatabaseReclaimError({
209 reason: `Reclaiming needs ${formatGiB(shortfall.neededBytes)} of free disk space on this machine. ${formatGiB(shortfall.freeBytes)} is free.`,
210 });
211 }
212 yield* fs.remove(reclaimFiles.failure, { force: true });
213 reclaimFailure = undefined;
214 yield* publishStatus;
215 const requestedAt = yield* Clock.currentTimeMillis;
216 // One step: a request interrupted between them would repair on some unrelated later exit.
217 yield* Effect.uninterruptible(
218 fs.writeFileString(reclaimFiles.request, String(requestedAt)).pipe(
219 // Reply before stopping: the restart closes this connection.
220 Effect.andThen(restart.pipe(Effect.delay("500 millis"), Effect.forkDetach)),
221 ),
222 );
223 yield* Effect.logInfo("Restarting to reclaim database space");
224 }).pipe(
225 Effect.mapError((cause) =>
226 cause._tag === "DatabaseReclaimError"
227 ? cause
228 : new DatabaseReclaimError({ reason: "Could not prepare the repair. Try again." }),
229 ),
230 Effect.withSpan("DatabaseStorage.requestReclaim"),
231 );
232
233 return DatabaseStorage.of({
234 reclaim,
235 status: SubscriptionRef.changes(statusRef),
236 requestReclaim,
237 });
238});
239
240export const layer = Layer.effect(DatabaseStorage, make);