Open History to see the last commit
1import type { DatabaseStorageStatus } from "@t3tools/contracts";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as Equal from "effect/Equal";
5import * as Layer from "effect/Layer";
6import * as Path from "effect/Path";
7import * as Schedule from "effect/Schedule";
8import * as Stream from "effect/Stream";
9import * as SubscriptionRef from "effect/SubscriptionRef";
10import * as SqlClient from "effect/sql/SqlClient";
11
12import { resolveHostCliCommand } from "../cli/invocation.ts";
13import * as ServerConfig from "../config.ts";
14import * as ProjectionMaintenance from "../orchestration-v2/ProjectionMaintenance.ts";
15import { forkParked } from "../serverActivation.ts";
16
17/** Pages returned per reclaim pass; one minute of churn, not a backlog. */
18const RECLAIM_PAGES_PER_PASS = 1024;
19
20export class DatabaseStorage extends Context.Service<
21 DatabaseStorage,
22 {
23 /** Return free pages to the filesystem on databases with incremental auto_vacuum. */
24 readonly reclaim: Effect.Effect<void>;
25 /** Current file accounting, re-published after each maintenance pass. Null until first read. */
26 readonly status: Stream.Stream<DatabaseStorageStatus | null>;
27 }
28>()("t3/persistence/DatabaseStorage") {}
29
30/**
31 * Deletes superseded history every few hours and hands freed pages back to
32 * the filesystem every minute. Deleted events are always superseded by a
33 * retained event with a higher sequence, so a client replaying from an older
34 * cursor still reaches the same state; no replay boundary is published.
35 */
36const make = Effect.gen(function* () {
37 const sql = yield* SqlClient.SqlClient;
38 const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
39 const config = yield* ServerConfig.ServerConfig;
40 const path = yield* Path.Path;
41 const statusRef = yield* SubscriptionRef.make<DatabaseStorageStatus | null>(null);
42
43 // The notice shows this verbatim; quote for the host's shell. Desktop
44 // installs have no `t3` on PATH, so the command names their launcher.
45 const { command: compactCommand } = yield* resolveHostCliCommand("doctor", [
46 "--base-dir",
47 config.baseDir,
48 ]);
49 // `t3 doctor --base-dir` repairs <baseDir>/userdata. A dev server without
50 // an explicit home keeps its state in <baseDir>/dev instead, so there the
51 // command would target the live install; publish no status at all.
52 const doctorTargetsThisDatabase =
53 path.resolve(config.dbPath) ===
54 path.resolve(config.baseDir, "userdata", path.basename(config.dbPath));
55 const publishStatus = Effect.gen(function* () {
56 if (!doctorTargetsThisDatabase) return;
57 const pages = yield* sql<{ readonly page_count: number }>`PRAGMA page_count`;
58 const free = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
59 const size = yield* sql<{ readonly page_size: number }>`PRAGMA page_size`;
60 const mode = yield* sql<{ readonly auto_vacuum: number }>`PRAGMA auto_vacuum`;
61 const pageSize = size[0]?.page_size ?? 0;
62 const next: DatabaseStorageStatus = {
63 databaseBytes: (pages[0]?.page_count ?? 0) * pageSize,
64 reclaimableBytes: (free[0]?.freelist_count ?? 0) * pageSize,
65 incrementalVacuumEnabled: mode[0]?.auto_vacuum === 2,
66 compactCommand,
67 };
68 // Every set reaches each open Storage page; most passes change nothing.
69 if (!Equal.equals(yield* SubscriptionRef.get(statusRef), next)) {
70 yield* SubscriptionRef.set(statusRef, next);
71 }
72 }).pipe(
73 Effect.catch((cause) => Effect.logWarning("Database storage inspection failed", { cause })),
74 );
75
76 const reclaim = Effect.gen(function* () {
77 const mode = yield* sql<{ readonly auto_vacuum: number }>`PRAGMA auto_vacuum`;
78 if (mode[0]?.auto_vacuum !== 2) return;
79 // The driver steps a statement without result columns once, and each
80 // step of incremental_vacuum frees one page. Yield between pages so
81 // client requests can run.
82 for (let page = 0; page < RECLAIM_PAGES_PER_PASS; page++) {
83 const free = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
84 if ((free[0]?.freelist_count ?? 0) === 0) break;
85 yield* sql`PRAGMA incremental_vacuum(1)`;
86 yield* Effect.yieldNow;
87 }
88 }).pipe(
89 Effect.catch((cause) => Effect.logWarning("Database space reclamation failed", { cause })),
90 );
91
92 const compact = maintenance.compactEventStore.pipe(
93 Effect.tap((result) =>
94 result.deletedEventCount > 0 || result.deletedReceiptCount > 0
95 ? Effect.logInfo("Compacted orchestration history", result)
96 : Effect.void,
97 ),
98 Effect.catch((cause) =>
99 Effect.logWarning("Orchestration history compaction failed", { cause }),
100 ),
101 );
102
103 yield* forkParked(
104 Effect.sleep("1 minute").pipe(
105 Effect.andThen(
106 compact.pipe(Effect.andThen(publishStatus), Effect.repeat(Schedule.spaced("6 hours"))),
107 ),
108 ),
109 );
110 yield* forkParked(
111 publishStatus.pipe(
112 Effect.andThen(Effect.sleep("1 minute")),
113 Effect.andThen(
114 reclaim.pipe(Effect.andThen(publishStatus), Effect.repeat(Schedule.spaced("1 minute"))),
115 ),
116 ),
117 );
118
119 return DatabaseStorage.of({ reclaim, status: SubscriptionRef.changes(statusRef) });
120});
121
122export const layer = Layer.effect(DatabaseStorage, make);