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 const result = yield* maintenance.compactEventStore;
92 const completedAt = yield* Clock.currentTimeMillis;
93 yield* fs.writeFileString(compactedAtPath, String(completedAt)).pipe(Effect.ignore);
94 if (result.deletedEventCount > 0 || result.deletedReceiptCount > 0) {
95 yield* Effect.logInfo("Compacted orchestration history", result);
96 }
97 }).pipe(
98 Effect.catch((cause) =>
99 Effect.logWarning("Orchestration history compaction failed", { cause }),
100 ),
101 );
102 const lastCompactedAt = yield* fs.readFileString(compactedAtPath).pipe(
103 Effect.map(Number),
104 Effect.orElseSucceed(() => Number.NaN),
105 );
106 const intervalMs = Duration.toMillis(COMPACTION_INTERVAL);
107 const untilDueMs = Number.isFinite(lastCompactedAt)
108 ? lastCompactedAt + intervalMs - (yield* Clock.currentTimeMillis)
109 : 0;
110 const firstCompactionDelay = Duration.millis(
111 Math.min(intervalMs, Math.max(Duration.toMillis(Duration.minutes(1)), untilDueMs)),
112 );
113
114 yield* forkParked(
115 Effect.sleep(firstCompactionDelay).pipe(
116 Effect.andThen(
117 compact.pipe(
118 Effect.andThen(publishStatus),
119 Effect.repeat(Schedule.spaced(COMPACTION_INTERVAL)),
120 ),
121 ),
122 ),
123 );
124 yield* forkParked(
125 publishStatus.pipe(
126 Effect.andThen(Effect.sleep("1 minute")),
127 Effect.andThen(
128 reclaim.pipe(Effect.andThen(publishStatus), Effect.repeat(Schedule.spaced("1 minute"))),
129 ),
130 ),
131 );
132
133 return DatabaseStorage.of({ reclaim, status: SubscriptionRef.changes(statusRef) });
134});
135
136export const layer = Layer.effect(DatabaseStorage, make);