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