Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DatabaseStorage.ts

146 lines6.3 KB

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 * Deletes superseded history every few hours and hands freed pages back to
36 * the filesystem every minute. Deleted events are always superseded by a
37 * retained event with a higher sequence, so a client replaying from an older
38 * cursor still reaches the same state; no replay boundary is published.
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 const compactedAtPath = path.join(path.dirname(config.dbPath), "compacted-at");
100 const compact = Effect.gen(function* () {
101 const result = yield* maintenance.compactEventStore;
102 const completedAt = yield* Clock.currentTimeMillis;
103 yield* fs.writeFileString(compactedAtPath, String(completedAt)).pipe(Effect.ignore);
104 if (result.deletedEventCount > 0 || result.deletedReceiptCount > 0) {
105 yield* Effect.logInfo("Compacted orchestration history", result);
106 }
107 }).pipe(
108 Effect.catch((cause) =>
109 Effect.logWarning("Orchestration history compaction failed", { cause }),
110 ),
111 );
112 const lastCompactedAt = yield* fs.readFileString(compactedAtPath).pipe(
113 Effect.map(Number),
114 Effect.orElseSucceed(() => Number.NaN),
115 );
116 const intervalMs = Duration.toMillis(COMPACTION_INTERVAL);
117 const untilDueMs = Number.isFinite(lastCompactedAt)
118 ? lastCompactedAt + intervalMs - (yield* Clock.currentTimeMillis)
119 : 0;
120 const firstCompactionDelay = Duration.millis(
121 Math.min(intervalMs, Math.max(Duration.toMillis(Duration.minutes(1)), untilDueMs)),
122 );
123​
124 yield* forkParked(
125 Effect.sleep(firstCompactionDelay).pipe(
126 Effect.andThen(
127 compact.pipe(
128 Effect.andThen(publishStatus),
129 Effect.repeat(Schedule.spaced(COMPACTION_INTERVAL)),
130 ),
131 ),
132 ),
133 );
134 yield* forkParked(
135 publishStatus.pipe(
136 Effect.andThen(Effect.sleep("1 minute")),
137 Effect.andThen(
138 reclaim.pipe(Effect.andThen(publishStatus), Effect.repeat(Schedule.spaced("1 minute"))),
139 ),
140 ),
141 );
142​
143 return DatabaseStorage.of({ reclaim, status: SubscriptionRef.changes(statusRef) });
144});
145​
146export const layer = Layer.effect(DatabaseStorage, make);