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
12export const 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 // Only an empty file can switch modes here; an existing database needs the
21 // offline VACUUM that `t3 doctor` runs, which rebuilds it with pointer maps.
22 const tables = yield* sql<{
23 readonly count: number;
24 }>`SELECT COUNT(*) AS count FROM sqlite_schema WHERE type = 'table'`;
25 if (tables[0]?.count === 0) yield* sql`PRAGMA auto_vacuum = INCREMENTAL;`;
26 yield* sql`PRAGMA journal_mode = WAL;`;
27 // FULL fsyncs the WAL on every commit, on the main thread. Every provider
28 // event is its own commit, so a slow or busy disk stalls the event loop
29 // and clients drop. In WAL mode NORMAL only fsyncs at checkpoints. It
30 // cannot corrupt the database and an app crash loses nothing; an OS crash
31 // or power loss can roll back commits since the last checkpoint.
32 yield* sql`PRAGMA synchronous = NORMAL;`;
33 // Checkpoints are now the only sync, and macOS fsync() does not flush the
34 // drive cache. F_FULLFSYNC makes them reach disk; other platforms ignore it.
35 yield* sql`PRAGMA checkpoint_fullfsync = ON;`;
36 // PASSIVE checkpoints never shrink the -wal file, so it otherwise keeps its
37 // largest size until the last connection closes.
38 yield* sql.unsafe(`PRAGMA journal_size_limit = ${WAL_SIZE_LIMIT_BYTES};`);
39 yield* runMigrations();
40 // No planner statistics. Collecting them reads every page of the large
41 // tables, and stats taken while a table was small make the planner scan it
42 // once it grows. Without them SQLite assumes large tables and uses indexes;
43 // the few queries that still pick a worse index name theirs with INDEXED BY.
44 // Older builds collected stats, so clear them. A connection loads stats
45 // when it opens, so this one must reload them after the delete.
46 const statTables = yield* sql`SELECT 1 FROM sqlite_schema WHERE name = 'sqlite_stat1'`;
47 if (statTables.length > 0) {
48 yield* sql`DELETE FROM sqlite_stat1;`;
49 yield* sql`ANALYZE sqlite_schema;`;
50 }
51 }),
52);
53
54export const layerFromPath = Effect.fn("makeSqlitePersistenceLive")(function* (dbPath: string) {
55 const fs = yield* FileSystem.FileSystem;
56 const path = yield* Path.Path;
57 yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });
58
59 return Layer.provideMerge(
60 layerSetup,
61 NodeSqliteClient.layer({
62 filename: dbPath,
63 readerWorker: true,
64 // Checkpoints sync the database, with F_FULLFSYNC on macOS. Run them off
65 // the event loop so a slow flush cannot stall clients.
66 checkpointWorker: true,
67 spanAttributes: {
68 "db.name": path.basename(dbPath),
69 "service.name": "t3code-server",
70 },
71 }),
72 );
73}, Layer.unwrap);
74
75export const layerMemory = Layer.provideMerge(
76 layerSetup,
77 NodeSqliteClient.layer({ filename: ":memory:" }),
78);
79
80export const layerConfig = Layer.unwrap(
81 Effect.gen(function* () {
82 const { dbPath } = yield* ServerConfig.ServerConfig;
83 yield* initializeV2Database(dbPath);
84 return layerFromPath(dbPath);
85 }),
86);