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
12// Size the -wal file is cut back to on the first commit after a WAL reset.
13export const WAL_SIZE_LIMIT_BYTES = 32 * 1024 * 1024;
14
15const layerSetup = Layer.effectDiscard(
16 Effect.gen(function* () {
17 const sql = yield* SqlClient.SqlClient;
18 // CLI and server write from separate processes; wait rather than fail with SQLITE_BUSY.
19 yield* sql`PRAGMA busy_timeout = 5000;`;
20 yield* sql`PRAGMA foreign_keys = ON;`;
21 // Only an empty file can switch modes here; an existing database needs the
22 // offline VACUUM that `t3 doctor` runs, which rebuilds it with pointer maps.
23 const tables = yield* sql<{
24 readonly count: number;
25 }>`SELECT COUNT(*) AS count FROM sqlite_schema WHERE type = 'table'`;
26 if (tables[0]?.count === 0) yield* sql`PRAGMA auto_vacuum = INCREMENTAL;`;
27 yield* sql`PRAGMA journal_mode = WAL;`;
28 // FULL fsyncs the WAL on every commit, on the main thread. Every provider
29 // event is its own commit, so a slow or busy disk stalls the event loop
30 // and clients drop. In WAL mode NORMAL only fsyncs at checkpoints. It
31 // cannot corrupt the database and an app crash loses nothing; an OS crash
32 // or power loss can roll back commits since the last checkpoint.
33 yield* sql`PRAGMA synchronous = NORMAL;`;
34 // Checkpoints are now the only sync, and macOS fsync() does not flush the
35 // drive cache. F_FULLFSYNC makes them reach disk; other platforms ignore it.
36 // Per-commit fullfsync stays off.
37 yield* sql`PRAGMA checkpoint_fullfsync = ON;`;
38 // PASSIVE checkpoints never shrink the -wal file, so it otherwise keeps its
39 // largest size until the last connection closes.
40 yield* sql.unsafe(`PRAGMA journal_size_limit = ${WAL_SIZE_LIMIT_BYTES};`);
41 yield* runMigrations();
42 // Without sqlite_stat1 the planner guesses at index selectivity. 0x10012
43 // analyzes tables whose indexes lack stats or whose row count changed 10x,
44 // under a temporary analysis_limit. Otherwise it only checks table sizes.
45 yield* sql`PRAGMA optimize = 0x10012;`;
46 }),
47);
48
49export const layerFromPath = Effect.fn("makeSqlitePersistenceLive")(function* (dbPath: string) {
50 const fs = yield* FileSystem.FileSystem;
51 const path = yield* Path.Path;
52 yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });
53
54 return Layer.provideMerge(
55 layerSetup,
56 NodeSqliteClient.layer({
57 filename: dbPath,
58 readerWorker: true,
59 // Checkpoints sync the database, with F_FULLFSYNC on macOS. Run them off
60 // the event loop so a slow flush cannot stall clients.
61 checkpointWorker: true,
62 spanAttributes: {
63 "db.name": path.basename(dbPath),
64 "service.name": "t3code-server",
65 },
66 }),
67 );
68}, Layer.unwrap);
69
70export const layerMemory = Layer.provideMerge(
71 layerSetup,
72 NodeSqliteClient.layer({ filename: ":memory:" }),
73);
74
75export const layerConfig = Layer.unwrap(
76 Effect.gen(function* () {
77 const { dbPath } = yield* ServerConfig.ServerConfig;
78 yield* initializeV2Database(dbPath);
79 return layerFromPath(dbPath);
80 }),
81);