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 = 32 * 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 // PASSIVE checkpoints retain peak WAL size until the last connection closes.
32 yield* sql.unsafe(`PRAGMA journal_size_limit = ${WAL_SIZE_LIMIT_BYTES};`);
33 yield* runMigrations();
34 // Collecting stats scans every page, and stale small-table stats cause scans after growth; use indexes by default.
35 // Connections cache stats; reload after deleting them.
36 const statTables = yield* sql`SELECT 1 FROM sqlite_schema WHERE name = 'sqlite_stat1'`;
37 if (statTables.length > 0) {
38 yield* sql`DELETE FROM sqlite_stat1;`;
39 yield* sql`ANALYZE sqlite_schema;`;
40 }
41 }),
42);
43
44export const layerFromPath = Effect.fn("makeSqlitePersistenceLive")(function* (dbPath: string) {
45 const fs = yield* FileSystem.FileSystem;
46 const path = yield* Path.Path;
47 yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });
48
49 return Layer.provideMerge(
50 layerSetup,
51 NodeSqliteClient.layer({
52 filename: dbPath,
53 readerWorker: true,
54 // Run checkpoint fsyncs off the event loop so slow disk flushes cannot stall clients.
55 checkpointWorker: true,
56 spanAttributes: {
57 "db.name": path.basename(dbPath),
58 "service.name": "t3code-server",
59 },
60 }),
61 );
62}, Layer.unwrap);
63
64export const layerMemory = Layer.provideMerge(
65 layerSetup,
66 NodeSqliteClient.layer({ filename: ":memory:" }),
67);
68
69export const layerConfig = Layer.unwrap(
70 Effect.gen(function* () {
71 const { dbPath } = yield* ServerConfig.ServerConfig;
72 yield* initializeV2Database(dbPath);
73 return layerFromPath(dbPath);
74 }),
75);