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 Schema from "effect/Schema";
6import * as SqlClient from "effect/sql/SqlClient";
7import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
8
9import { hasPendingMigrations, runMigrations } from "./Migrations.ts";
10import { initializeV2Database } from "./initializeV2Database.ts";
11import * as ServerConfig from "../config.ts";
12import * as ServerOwnership from "../serverOwnership.ts";
13
14const WAL_SIZE_LIMIT_BYTES = 128 * 1024 * 1024;
15
16export class ServerOwnsDatabaseError extends Schema.TaggedError<ServerOwnsDatabaseError>()(
17 "ServerOwnsDatabaseError",
18 { stateDir: Schema.String },
19) {
20 override get message(): string {
21 return `Another T3 Code process, usually a running server, owns ${this.stateDir}, and this CLI would change its database schema. Use the \`t3\` that matches the running server, or stop that server, then retry. The database was not changed.`;
22 }
23}
24
25// CLI commands open the server's database from another process; migrating behind its owner changes the schema it runs on.
26const runMigrationsAsOwner = Effect.fn("SqlitePersistence.runMigrationsAsOwner")(function* () {
27 // With nothing pending, runMigrations only validates the recorded history and writes nothing.
28 if (!(yield* hasPendingMigrations())) return yield* runMigrations();
29 const { serverRuntimeStatePath } = yield* ServerConfig.ServerConfig;
30 yield* ServerOwnership.holdServerOwnershipLock(serverRuntimeStatePath).pipe(
31 Effect.catchTags({
32 ServerAlreadyRunningError: ({ stateDir }) =>
33 Effect.fail(new ServerOwnsDatabaseError({ stateDir })),
34 }),
35 );
36 yield* runMigrations();
37}, Effect.scoped);
38
39const makeLayerSetup = <E, R>(migrate: Effect.Effect<unknown, E, R>) =>
40 Layer.effectDiscard(
41 Effect.gen(function* () {
42 const sql = yield* SqlClient.SqlClient;
43 // CLI and server write from separate processes; wait rather than fail with SQLITE_BUSY.
44 yield* sql`PRAGMA busy_timeout = 5000;`;
45 yield* sql`PRAGMA foreign_keys = ON;`;
46 // Existing databases need doctor's offline VACUUM to add pointer maps for this mode.
47 const tables = yield* sql<{
48 readonly count: number;
49 }>`SELECT COUNT(*) AS count FROM sqlite_schema WHERE type = 'table'`;
50 if (tables[0]?.count === 0) yield* sql`PRAGMA auto_vacuum = INCREMENTAL;`;
51 yield* sql`PRAGMA journal_mode = WAL;`;
52 // FULL fsyncs every event commit on the main thread; NORMAL syncs only at WAL checkpoints.
53 // App crashes lose nothing; OS crashes or power loss can roll back post-checkpoint commits without corruption.
54 yield* sql`PRAGMA synchronous = NORMAL;`;
55 // macOS fsync misses drive caches; F_FULLFSYNC flushes them at checkpoints and is ignored elsewhere.
56 yield* sql`PRAGMA checkpoint_fullfsync = ON;`;
57 // Keep statement journals and sort spills off the main thread's disk path.
58 // Large statements and open savepoints can increase peak memory use.
59 yield* sql`PRAGMA temp_store = MEMORY;`;
60 // PASSIVE checkpoints retain peak WAL size until the last connection closes.
61 yield* sql.unsafe(`PRAGMA journal_size_limit = ${WAL_SIZE_LIMIT_BYTES};`);
62 yield* migrate;
63 // Collecting stats scans every page, and stale small-table stats cause scans after growth; use indexes by default.
64 // Connections cache stats; reload after deleting them.
65 const statTables = yield* sql`SELECT 1 FROM sqlite_schema WHERE name = 'sqlite_stat1'`;
66 if (statTables.length > 0) {
67 yield* sql`DELETE FROM sqlite_stat1;`;
68 yield* sql`ANALYZE sqlite_schema;`;
69 }
70 }).pipe(Effect.withSpan("Sqlite.setup")),
71 );
72
73const layerSetup = makeLayerSetup(runMigrations());
74
75const makeLayerFromPath = <E, R>(setup: Layer.Layer<never, E, R>) =>
76 Effect.fn("makeSqlitePersistenceLive")(function* (dbPath: string) {
77 const fs = yield* FileSystem.FileSystem;
78 const path = yield* Path.Path;
79 yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });
80
81 return Layer.provideMerge(
82 setup,
83 NodeSqliteClient.layer({
84 filename: dbPath,
85 readerWorker: true,
86 // Run checkpoint fsyncs off the event loop so slow disk flushes cannot stall clients.
87 checkpointWorker: true,
88 spanAttributes: {
89 "db.name": path.basename(dbPath),
90 "service.name": "t3code-server",
91 },
92 }),
93 );
94 }, Layer.unwrap);
95
96export const layerFromPath = makeLayerFromPath(layerSetup);
97
98export const layerMemory = Layer.provideMerge(
99 layerSetup,
100 NodeSqliteClient.layer({ filename: ":memory:" }),
101);
102
103const makeLayerConfig = <E, R>(
104 fromPath: (dbPath: string) => Layer.Layer<SqlClient.SqlClient, E, R>,
105) =>
106 Layer.unwrap(
107 Effect.gen(function* () {
108 const { dbPath } = yield* ServerConfig.ServerConfig;
109 yield* initializeV2Database(dbPath);
110 return fromPath(dbPath);
111 }),
112 );
113
114export const layerConfig = makeLayerConfig(layerFromPath);
115
116/** For CLI commands: pending migrations run only while no server owns the T3 home. */
117export const layerCliConfig = makeLayerConfig(
118 makeLayerFromPath(makeLayerSetup(runMigrationsAsOwner())),
119);