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/unstable/sql/SqlClient";
6import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
7
8import { runMigrations } from "../Migrations.ts";
9import { ServerConfig } from "../../config.ts";
10
11// Size the -wal file is cut back to on the first commit after a WAL reset.
12export const WAL_SIZE_LIMIT_BYTES = 32 * 1024 * 1024;
13
14const setup = 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 yield* sql`PRAGMA journal_mode = WAL;`;
21 // PASSIVE checkpoints never shrink the -wal file, so it otherwise keeps its
22 // largest size until the last connection closes.
23 yield* sql.unsafe(`PRAGMA journal_size_limit = ${WAL_SIZE_LIMIT_BYTES};`);
24 yield* runMigrations();
25 }),
26);
27
28export const makeSqlitePersistenceLive = Effect.fn("makeSqlitePersistenceLive")(function* (
29 dbPath: string,
30) {
31 const fs = yield* FileSystem.FileSystem;
32 const path = yield* Path.Path;
33 yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });
34
35 return Layer.provideMerge(
36 setup,
37 NodeSqliteClient.layer({
38 filename: dbPath,
39 spanAttributes: {
40 "db.name": path.basename(dbPath),
41 "service.name": "t3code-server",
42 },
43 }),
44 );
45}, Layer.unwrap);
46
47export const SqlitePersistenceMemory = Layer.provideMerge(
48 setup,
49 NodeSqliteClient.layer({ filename: ":memory:" }),
50);
51
52export const layerConfig = Layer.unwrap(
53 Effect.gen(function* () {
54 const { dbPath } = yield* ServerConfig;
55 return makeSqlitePersistenceLive(dbPath);
56 }),
57);