Open History to see the last commit
1import * as Effect from "effect/Effect";
2import * as Layer from "effect/Layer";
3import * as FileSystem from "effect/FileSystem";
4import * as Path from "effect/Path";
5import * as SqlClient from "effect/sql/SqlClient";
6import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
7
8import { runMigrations } from "./Migrations.ts";
9import { initializeV2Database } from "./initializeV2Database.ts";
10import * as ServerConfig from "../config.ts";
11
12const WAL_SIZE_LIMIT_BYTES = 128 * 1024 * 1024;
13
14const layerSetup = Layer.effectDiscard(
15 Effect.gen(function* () {
16 const sql = yield* SqlClient.SqlClient;
17 // CLI and server write from separate processes; wait rather than fail with SQLITE_BUSY.
18 yield* sql`PRAGMA busy_timeout = 5000;`;
19 yield* sql`PRAGMA foreign_keys = ON;`;
20 // Existing databases need doctor's offline VACUUM to add pointer maps for this mode.
21 const tables = yield* sql<{
22 readonly count: number;
23 }>`SELECT COUNT(*) AS count FROM sqlite_schema WHERE type = 'table'`;
24 if (tables[0]?.count === 0) yield* sql`PRAGMA auto_vacuum = INCREMENTAL;`;
25 yield* sql`PRAGMA journal_mode = WAL;`;
26 // FULL fsyncs every event commit on the main thread; NORMAL syncs only at WAL checkpoints.
27 // App crashes lose nothing; OS crashes or power loss can roll back post-checkpoint commits without corruption.
28 yield* sql`PRAGMA synchronous = NORMAL;`;
29 // macOS fsync misses drive caches; F_FULLFSYNC flushes them at checkpoints and is ignored elsewhere.
30 yield* sql`PRAGMA checkpoint_fullfsync = ON;`;
31 // Keep statement journals and sort spills off the main thread's disk path.
32 // Large statements and open savepoints can increase peak memory use.
33 yield* sql`PRAGMA temp_store = MEMORY;`;
34 // PASSIVE checkpoints retain peak WAL size until the last connection closes.
35 yield* sql.unsafe(`PRAGMA journal_size_limit = ${WAL_SIZE_LIMIT_BYTES};`);
36 yield* runMigrations();
37 // Collecting stats scans every page, and stale small-table stats cause scans after growth; use indexes by default.
38 // Connections cache stats; reload after deleting them.
39 const statTables = yield* sql`SELECT 1 FROM sqlite_schema WHERE name = 'sqlite_stat1'`;
40 if (statTables.length > 0) {
41 yield* sql`DELETE FROM sqlite_stat1;`;
42 yield* sql`ANALYZE sqlite_schema;`;
43 }
44 }).pipe(Effect.withSpan("Sqlite.setup")),
45);
46
47export const layerFromPath = Effect.fn("makeSqlitePersistenceLive")(function* (dbPath: string) {
48 const fs = yield* FileSystem.FileSystem;
49 const path = yield* Path.Path;
50 yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });
51
52 return Layer.provideMerge(
53 layerSetup,
54 NodeSqliteClient.layer({
55 filename: dbPath,
56 // A long thread can exceed SQLite's default 2 MiB page cache. Apply these
57 // connection-local limits to the writer and its read-only worker.
58 cacheSizeKiB: 256 * 1024,
59 mmapSizeBytes: 2 * 1024 * 1024 * 1024,
60 readerWorker: true,
61 // Run checkpoint fsyncs off the event loop so slow disk flushes cannot stall clients.
62 checkpointWorker: true,
63 spanAttributes: {
64 "db.name": path.basename(dbPath),
65 "service.name": "t3code-server",
66 },
67 }),
68 );
69}, Layer.unwrap);
70
71export const layerMemory = Layer.provideMerge(
72 layerSetup,
73 NodeSqliteClient.layer({ filename: ":memory:" }),
74);
75
76export const layerConfig = Layer.unwrap(
77 Effect.gen(function* () {
78 const { dbPath } = yield* ServerConfig.ServerConfig;
79 yield* initializeV2Database(dbPath);
80 return layerFromPath(dbPath);
81 }),
82);