Open History to see the last commit
1import 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 Path from "effect/Path";
10import * as Schedule from "effect/Schedule";
11import * as Stream from "effect/Stream";
12import * as SubscriptionRef from "effect/SubscriptionRef";
13import * as SqlClient from "effect/sql/SqlClient";
14
15import { resolveHostCliCommand } from "../cli/invocation.ts";
16import * as ServerConfig from "../config.ts";
17import * as ProjectionMaintenance from "../orchestration-v2/ProjectionMaintenance.ts";
18import { forkParked } from "../serverActivation.ts";
19
20/** Pages returned per reclaim pass; one minute of churn, not a backlog. */
21const RECLAIM_PAGES_PER_PASS = 1024;
22const COMPACTION_INTERVAL = Duration.hours(6);
23
24export class DatabaseStorage extends Context.Service<
25 DatabaseStorage,
26 {
27 /** Return free pages to the filesystem on databases with incremental auto_vacuum. */
28 readonly reclaim: Effect.Effect<void>;
29 /** Current file accounting, re-published after each maintenance pass. Null until first read. */
30 readonly status: Stream.Stream<DatabaseStorageStatus | null>;
31 }
32>()("t3/persistence/DatabaseStorage") {}
33
34/**
35 * Compacts history every few hours and hands freed pages back to the
36 * filesystem every minute. Superseded events are replaced by a retained event
37 * with a higher sequence; expired events raise their thread's replay floor, so
38 * a client resuming from below it gets a snapshot instead.
39 */
40const make = Effect.gen(function* () {
41 const sql = yield* SqlClient.SqlClient;
42 const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
43 const config = yield* ServerConfig.ServerConfig;
44 const fs = yield* FileSystem.FileSystem;
45 const path = yield* Path.Path;
46 const statusRef = yield* SubscriptionRef.make<DatabaseStorageStatus | null>(null);
47
48 // The notice shows this verbatim; quote for the host's shell. Desktop
49 // installs have no `t3` on PATH, so the command names their launcher.
50 const { command: compactCommand } = yield* resolveHostCliCommand("doctor", [
51 "--base-dir",
52 config.baseDir,
53 ]);
54 // `t3 doctor --base-dir` repairs <baseDir>/userdata. A dev server without
55 // an explicit home keeps its state in <baseDir>/dev instead, so there the
56 // command would target the live install; publish no status at all.
57 const doctorTargetsThisDatabase =
58 path.resolve(config.dbPath) ===
59 path.resolve(config.baseDir, "userdata", path.basename(config.dbPath));
60 const publishStatus = Effect.gen(function* () {
61 if (!doctorTargetsThisDatabase) return;
62 const pages = yield* sql<{ readonly page_count: number }>`PRAGMA page_count`;
63 const free = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
64 const size = yield* sql<{ readonly page_size: number }>`PRAGMA page_size`;
65 const mode = yield* sql<{ readonly auto_vacuum: number }>`PRAGMA auto_vacuum`;
66 const pageSize = size[0]?.page_size ?? 0;
67 const next: DatabaseStorageStatus = {
68 databaseBytes: (pages[0]?.page_count ?? 0) * pageSize,
69 reclaimableBytes: (free[0]?.freelist_count ?? 0) * pageSize,
70 incrementalVacuumEnabled: mode[0]?.auto_vacuum === 2,
71 compactCommand,
72 };
73 // Every set reaches each open Storage page; most passes change nothing.
74 if (!Equal.equals(yield* SubscriptionRef.get(statusRef), next)) {
75 yield* SubscriptionRef.set(statusRef, next);
76 }
77 }).pipe(
78 Effect.catch((cause) => Effect.logWarning("Database storage inspection failed", { cause })),
79 );
80
81 const reclaim = Effect.gen(function* () {
82 const mode = yield* sql<{ readonly auto_vacuum: number }>`PRAGMA auto_vacuum`;
83 if (mode[0]?.auto_vacuum !== 2) return;
84 // The driver steps a statement without result columns once, and each
85 // step of incremental_vacuum frees one page. Yield between pages so
86 // client requests can run.
87 for (let page = 0; page < RECLAIM_PAGES_PER_PASS; page++) {
88 const free = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
89 if ((free[0]?.freelist_count ?? 0) === 0) break;
90 yield* sql`PRAGMA incremental_vacuum(1)`;
91 yield* Effect.yieldNow;
92 }
93 }).pipe(
94 Effect.catch((cause) => Effect.logWarning("Database space reclamation failed", { cause })),
95 );
96
97 // Even a pass that deletes nothing scans the event store. Persist completion
98 // so restarting does not trigger another scan before the six-hour interval.
99 // Renamed when the compaction policy changes, so an upgrade runs the new
100 // policy a minute after start instead of up to six hours later.
101 const compactedAtPath = path.join(path.dirname(config.dbPath), "history-retained-at");
102 const compact = Effect.gen(function* () {
103 // 10% duty cycle. Unpaced, the first retention pass on a large database
104 // stalled foreground writes for seconds behind WAL checkpoints.
105 let sliceStarted = yield* Clock.monotonicTimeNanos;
106 const pace = Effect.gen(function* () {
107 const elapsedMs = Number((yield* Clock.monotonicTimeNanos) - sliceStarted) / 1_000_000;
108 if (elapsedMs < 25) return;
109 yield* Effect.sleep(Duration.millis(elapsedMs * 9));
110 sliceStarted = yield* Clock.monotonicTimeNanos;
111 });
112 const result = yield* maintenance.compactEventStore.pipe(
113 Effect.provideService(ProjectionMaintenance.CompactionPacer, pace),
114 );
115 const completedAt = yield* Clock.currentTimeMillis;
116 yield* fs.writeFileString(compactedAtPath, String(completedAt)).pipe(Effect.ignore);
117 if (result.deletedEventCount > 0 || result.deletedReceiptCount > 0) {
118 yield* Effect.logInfo("Compacted orchestration history", result);
119 }
120 }).pipe(
121 Effect.catch((cause) =>
122 Effect.logWarning("Orchestration history compaction failed", { cause }),
123 ),
124 );
125 const lastCompactedAt = yield* fs.readFileString(compactedAtPath).pipe(
126 Effect.map(Number),
127 Effect.orElseSucceed(() => Number.NaN),
128 );
129 const intervalMs = Duration.toMillis(COMPACTION_INTERVAL);
130 const untilDueMs = Number.isFinite(lastCompactedAt)
131 ? lastCompactedAt + intervalMs - (yield* Clock.currentTimeMillis)
132 : 0;
133 const firstCompactionDelay = Duration.millis(
134 Math.min(intervalMs, Math.max(Duration.toMillis(Duration.minutes(1)), untilDueMs)),
135 );
136
137 yield* forkParked(
138 Effect.sleep(firstCompactionDelay).pipe(
139 Effect.andThen(
140 compact.pipe(
141 Effect.andThen(publishStatus),
142 Effect.repeat(Schedule.spaced(COMPACTION_INTERVAL)),
143 ),
144 ),
145 ),
146 );
147 yield* forkParked(
148 publishStatus.pipe(
149 Effect.andThen(Effect.sleep("1 minute")),
150 Effect.andThen(
151 reclaim.pipe(Effect.andThen(publishStatus), Effect.repeat(Schedule.spaced("1 minute"))),
152 ),
153 ),
154 );
155
156 return DatabaseStorage.of({ reclaim, status: SubscriptionRef.changes(statusRef) });
157});
158
159export const layer = Layer.effect(DatabaseStorage, make);