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 const publishStatus = Effect.gen(function* () {
53 if (!doctorTargetsThisDatabase) return;
54 const pages = yield* sql<{ readonly page_count: number }>`PRAGMA page_count`;
55 const free = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
56 const size = yield* sql<{ readonly page_size: number }>`PRAGMA page_size`;
57 const mode = yield* sql<{ readonly auto_vacuum: number }>`PRAGMA auto_vacuum`;
58 const pageSize = size[0]?.page_size ?? 0;
59 const next: DatabaseStorageStatus = {
60 databaseBytes: (pages[0]?.page_count ?? 0) * pageSize,
61 reclaimableBytes: (free[0]?.freelist_count ?? 0) * pageSize,
62 incrementalVacuumEnabled: mode[0]?.auto_vacuum === 2,
63 compactCommand,
64 };
65 // Every set reaches each open Storage page; most passes change nothing.
66 if (!Equal.equals(yield* SubscriptionRef.get(statusRef), next)) {
67 yield* SubscriptionRef.set(statusRef, next);
68 }
69 }).pipe(
70 Effect.catch((cause) => Effect.logWarning("Database storage inspection failed", { cause })),
71 );
72
73 const reclaim = Effect.gen(function* () {
74 const mode = yield* sql<{ readonly auto_vacuum: number }>`PRAGMA auto_vacuum`;
75 if (mode[0]?.auto_vacuum !== 2) return;
76 // The driver steps once per statement; incremental_vacuum frees one page per step. Yield between pages.
77 for (let page = 0; page < RECLAIM_PAGES_PER_PASS; page++) {
78 const free = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
79 if ((free[0]?.freelist_count ?? 0) === 0) break;
80 yield* sql`PRAGMA incremental_vacuum(1)`;
81 yield* Effect.yieldNow;
82 }
83 }).pipe(
84 Effect.catch((cause) => Effect.logWarning("Database space reclamation failed", { cause })),
85 );
86
87 // Even a pass that deletes nothing scans the event store. Persist completion
88 // so restarting does not trigger another scan before the six-hour interval.
89 const compactedAtPath = path.join(path.dirname(config.dbPath), "compacted-at");
90 const compact = Effect.gen(function* () {
91 let sliceStarted = yield* Clock.monotonicTimeNanos;
92 const betweenPages = Effect.gen(function* () {
93 const elapsed = (yield* Clock.monotonicTimeNanos) - sliceStarted;
94 if (elapsed < 25_000_000n) return;
95 // Keep background maintenance at 10% duty, including pages that exceed the budget.
96 yield* Effect.sleep((Number(elapsed) / 1_000_000) * 9);
97 sliceStarted = yield* Clock.monotonicTimeNanos;
98 });
99 const result = yield* maintenance.compactEventStore(betweenPages);
100 const completedAt = yield* Clock.currentTimeMillis;
101 yield* fs.writeFileString(compactedAtPath, String(completedAt)).pipe(Effect.ignore);
102 if (result.deletedEventCount > 0 || result.deletedReceiptCount > 0) {
103 yield* Effect.logInfo("Compacted orchestration history", result);
104 }
105 }).pipe(
106 Effect.catch((cause) =>
107 Effect.logWarning("Orchestration history compaction failed", { cause }),
108 ),
109 );
110 const lastCompactedAt = yield* fs.readFileString(compactedAtPath).pipe(
111 Effect.map(Number),
112 Effect.orElseSucceed(() => Number.NaN),
113 );
114 const intervalMs = Duration.toMillis(COMPACTION_INTERVAL);
115 const untilDueMs = Number.isFinite(lastCompactedAt)
116 ? lastCompactedAt + intervalMs - (yield* Clock.currentTimeMillis)
117 : 0;
118 const firstCompactionDelay = Duration.millis(
119 Math.min(intervalMs, Math.max(Duration.toMillis(Duration.minutes(1)), untilDueMs)),
120 );
121
122 yield* forkParked(
123 Effect.sleep(firstCompactionDelay).pipe(
124 Effect.andThen(
125 compact.pipe(
126 Effect.andThen(publishStatus),
127 Effect.repeat(Schedule.spaced(COMPACTION_INTERVAL)),
128 ),
129 ),
130 ),
131 );
132 yield* forkParked(
133 publishStatus.pipe(
134 Effect.andThen(Effect.sleep("1 minute")),
135 Effect.andThen(
136 reclaim.pipe(Effect.andThen(publishStatus), Effect.repeat(Schedule.spaced("1 minute"))),
137 ),
138 ),
139 );
140
141 return DatabaseStorage.of({ reclaim, status: SubscriptionRef.changes(statusRef) });
142});
143
144export const layer = Layer.effect(DatabaseStorage, make);