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

Sqlite.ts

76 lines3.1 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​
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 yield* sql`PRAGMA optimize = 0x10012;`;
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 // Checkpoints sync the database, with F_FULLFSYNC on macOS. Run them off
55 // the event loop so a slow flush cannot stall clients.
56 checkpointWorker: true,
57 spanAttributes: {
58 "db.name": path.basename(dbPath),
59 "service.name": "t3code-server",
60 },
61 }),
62 );
63}, Layer.unwrap);
64​
65export const layerMemory = Layer.provideMerge(
66 layerSetup,
67 NodeSqliteClient.layer({ filename: ":memory:" }),
68);
69​
70export const layerConfig = Layer.unwrap(
71 Effect.gen(function* () {
72 const { dbPath } = yield* ServerConfig.ServerConfig;
73 yield* initializeV2Database(dbPath);
74 return layerFromPath(dbPath);
75 }),
76);