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// Bound each reclaim pass to one minute of churn.
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// Deleted events have newer retained replacements; old cursors replay to the same state.
35const make = Effect.gen(function* () {
36 const sql = yield* SqlClient.SqlClient;
37 const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
38 const config = yield* ServerConfig.ServerConfig;
39 const fs = yield* FileSystem.FileSystem;
40 const path = yield* Path.Path;
41 const statusRef = yield* SubscriptionRef.make<DatabaseStorageStatus | null>(null);
42
43 // The notice shows host-shell quoting verbatim; desktop needs its launcher because t3 is absent from PATH.
44 const { command: compactCommand } = yield* resolveHostCliCommand("doctor", [
45 "--base-dir",
46 config.baseDir,
47 ]);
48 // doctor --base-dir targets userdata, not implicit dev homes; suppress status to avoid touching the live install.
49 const doctorTargetsThisDatabase =
50 path.resolve(config.dbPath) ===
51 path.resolve(config.baseDir, "userdata", path.basename(config.dbPath));
52 // Only VACUUM changes these, and doctor refuses to VACUUM while a server has the database open.
53 let layout: { readonly pageSize: number; readonly incrementalVacuum: boolean } | undefined;
54 const readLayout = Effect.suspend(() =>
55 layout !== undefined
56 ? Effect.succeed(layout)
57 : Effect.gen(function* () {
58 const size = yield* sql<{ readonly page_size: number }>`PRAGMA page_size`;
59 const mode = yield* sql<{ readonly auto_vacuum: number }>`PRAGMA auto_vacuum`;
60 layout = {
61 pageSize: size[0]?.page_size ?? 0,
62 incrementalVacuum: mode[0]?.auto_vacuum === 2,
63 };
64 return layout;
65 }),
66 );
67 const publishStatus = Effect.gen(function* () {
68 if (!doctorTargetsThisDatabase) return;
69 const { pageSize, incrementalVacuum } = yield* readLayout;
70 const pages = yield* sql<{ readonly page_count: number }>`PRAGMA page_count`;
71 const free = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
72 const next: DatabaseStorageStatus = {
73 databaseBytes: (pages[0]?.page_count ?? 0) * pageSize,
74 reclaimableBytes: (free[0]?.freelist_count ?? 0) * pageSize,
75 incrementalVacuumEnabled: incrementalVacuum,
76 compactCommand,
77 };
78 // Every set reaches each open Storage page; most passes change nothing.
79 if (!Equal.equals(yield* SubscriptionRef.get(statusRef), next)) {
80 yield* SubscriptionRef.set(statusRef, next);
81 }
82 }).pipe(
83 Effect.catch((cause) => Effect.logWarning("Database storage inspection failed", { cause })),
84 );
85
86 const reclaim = Effect.gen(function* () {
87 if (!(yield* readLayout).incrementalVacuum) return;
88 // The driver steps once per statement; incremental_vacuum frees one page per step. Yield between pages.
89 for (let page = 0; page < RECLAIM_PAGES_PER_PASS; page++) {
90 const free = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
91 if ((free[0]?.freelist_count ?? 0) === 0) break;
92 yield* sql`PRAGMA incremental_vacuum(1)`;
93 yield* Effect.yieldNow;
94 }
95 }).pipe(
96 Effect.catch((cause) => Effect.logWarning("Database space reclamation failed", { cause })),
97 );
98
99 // Even a pass that deletes nothing scans the event store. Persist completion
100 // so restarting does not trigger another scan before the six-hour interval.
101 const compactedAtPath = path.join(path.dirname(config.dbPath), "compacted-at");
102 const compact = Effect.gen(function* () {
103 let sliceStarted = yield* Clock.monotonicTimeNanos;
104 const betweenPages = Effect.gen(function* () {
105 const elapsed = (yield* Clock.monotonicTimeNanos) - sliceStarted;
106 if (elapsed < 25_000_000n) return;
107 // Keep background maintenance at 10% duty, including pages that exceed the budget.
108 yield* Effect.sleep((Number(elapsed) / 1_000_000) * 9);
109 sliceStarted = yield* Clock.monotonicTimeNanos;
110 });
111 const result = yield* maintenance.compactEventStore(betweenPages);
112 const completedAt = yield* Clock.currentTimeMillis;
113 yield* fs.writeFileString(compactedAtPath, String(completedAt)).pipe(Effect.ignore);
114 if (result.deletedEventCount > 0 || result.deletedReceiptCount > 0) {
115 yield* Effect.logInfo("Compacted orchestration history", result);
116 }
117 }).pipe(
118 Effect.catch((cause) =>
119 Effect.logWarning("Orchestration history compaction failed", { cause }),
120 ),
121 );
122 const lastCompactedAt = yield* fs.readFileString(compactedAtPath).pipe(
123 Effect.map(Number),
124 Effect.orElseSucceed(() => Number.NaN),
125 );
126 const intervalMs = Duration.toMillis(COMPACTION_INTERVAL);
127 const untilDueMs = Number.isFinite(lastCompactedAt)
128 ? lastCompactedAt + intervalMs - (yield* Clock.currentTimeMillis)
129 : 0;
130 const firstCompactionDelay = Duration.millis(
131 Math.min(intervalMs, Math.max(Duration.toMillis(Duration.minutes(1)), untilDueMs)),
132 );
133
134 yield* forkParked(
135 Effect.sleep(firstCompactionDelay).pipe(
136 Effect.andThen(
137 compact.pipe(
138 Effect.andThen(publishStatus),
139 Effect.repeat(Schedule.spaced(COMPACTION_INTERVAL)),
140 ),
141 ),
142 ),
143 );
144 yield* forkParked(
145 publishStatus.pipe(
146 Effect.andThen(Effect.sleep("1 minute")),
147 Effect.andThen(
148 reclaim.pipe(Effect.andThen(publishStatus), Effect.repeat(Schedule.spaced("1 minute"))),
149 ),
150 ),
151 );
152
153 return DatabaseStorage.of({ reclaim, status: SubscriptionRef.changes(statusRef) });
154});
155
156export const layer = Layer.effect(DatabaseStorage, make);