Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Sqlite.ts

78 lines3.3 KB

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 readerWorker: true,
57 // Run checkpoint fsyncs off the event loop so slow disk flushes cannot stall clients.
58 checkpointWorker: true,
59 spanAttributes: {
60 "db.name": path.basename(dbPath),
61 "service.name": "t3code-server",
62 },
63 }),
64 );
65}, Layer.unwrap);
66​
67export const layerMemory = Layer.provideMerge(
68 layerSetup,
69 NodeSqliteClient.layer({ filename: ":memory:" }),
70);
71​
72export const layerConfig = Layer.unwrap(
73 Effect.gen(function* () {
74 const { dbPath } = yield* ServerConfig.ServerConfig;
75 yield* initializeV2Database(dbPath);
76 return layerFromPath(dbPath);
77 }),
78);