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

Sqlite.ts

180 lines7.8 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 Predicate from "effect/Predicate";
6import * as Schema from "effect/Schema";
7import * as SqlClient from "effect/sql/SqlClient";
8import * as SqlError from "effect/sql/SqlError";
9import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
10​
11import { hasPendingMigrations, runMigrations } from "./Migrations.ts";
12import { initializeV2Database } from "./initializeV2Database.ts";
13import * as ServerConfig from "../config.ts";
14import * as ServerOwnership from "../serverOwnership.ts";
15​
16const WAL_SIZE_LIMIT_BYTES = 128 * 1024 * 1024;
17​
18export class ServerOwnsDatabaseError extends Schema.TaggedError<ServerOwnsDatabaseError>()(
19 "ServerOwnsDatabaseError",
20 { stateDir: Schema.String },
21) {
22 override get message(): string {
23 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.`;
24 }
26​
27// SQLITE_CORRUPT and SQLITE_NOTADB; node:sqlite reports extended codes whose low byte is the primary code.
28const DAMAGED_SQLITE_CODES = new Set([11, 26]);
29​
30const isDamagedDatabase = (error: SqlError.SqlError): boolean => {
31 const seen = new Set<unknown>();
32 let cause: unknown = error.cause;
33 while (Predicate.isObject(cause) && !seen.has(cause)) {
34 seen.add(cause);
35 if (typeof cause.errcode === "number" && DAMAGED_SQLITE_CODES.has(cause.errcode & 0xff)) {
36 return true;
37 }
38 cause = cause.cause;
39 }
40 return false;
41};
42​
43// Keeps the SqlError type so callers' error channels do not change; the original stays as the cause.
44const damagedDatabaseError = (dbPath: string, cause: SqlError.SqlError) =>
45 new SqlError.SqlError({
46 reason: new SqlError.UnknownError({
47 cause,
48 operation: "open",
49 message: `The T3 Code database at ${dbPath} is damaged or is not a SQLite database, so T3 Code cannot start. To recover, quit T3 Code, then move that file and any -wal and -shm files next to it out of the folder, or replace them with a backup. T3 Code creates a new database on the next start.`,
50 }),
51 });
52​
53// CLI commands open the server's database from another process; migrating behind its owner changes the schema it runs on.
54const runMigrationsAsOwner = Effect.fn("SqlitePersistence.runMigrationsAsOwner")(function* () {
55 // With nothing pending, runMigrations only validates the recorded history and writes nothing.
56 if (!(yield* hasPendingMigrations())) return yield* runMigrations();
57 const { serverRuntimeStatePath } = yield* ServerConfig.ServerConfig;
58 yield* ServerOwnership.holdServerOwnershipLock(serverRuntimeStatePath).pipe(
59 Effect.catchTags({
60 ServerAlreadyRunningError: ({ stateDir }) =>
61 Effect.fail(new ServerOwnsDatabaseError({ stateDir })),
62 }),
63 );
64 yield* runMigrations();
65}, Effect.scoped);
66​
67// Index builds over large tables take minutes; on the main connection they block the event loop,
68// so requests hang instead of getting the listener's 503. A fresh database stays on the main
69// connection, which must create the first table for its auto_vacuum setting to apply.
70const runMigrationsOffMainThread = Effect.fn("SqlitePersistence.runMigrationsOffMainThread")(
71 function* (dbPath: string) {
72 const sql = yield* SqlClient.SqlClient;
73 const tables = yield* sql<{
74 readonly count: number;
75 }>`SELECT COUNT(*) AS count FROM sqlite_schema WHERE type = 'table'`;
76 if (!tables[0]?.count || !(yield* hasPendingMigrations())) return yield* runMigrations();
77 return yield* Effect.gen(function* () {
78 const worker = yield* SqlClient.SqlClient;
79 yield* worker`PRAGMA foreign_keys = ON;`;
80 yield* worker`PRAGMA synchronous = NORMAL;`;
81 yield* worker`PRAGMA temp_store = MEMORY;`;
82 return yield* runMigrations();
83 }).pipe(Effect.provide(NodeSqliteClient.layerWorker(dbPath)));
84 },
85);
86​
87const makeLayerSetup = <E, R>(migrate: Effect.Effect<unknown, E, R>) =>
88 Layer.effectDiscard(
89 Effect.gen(function* () {
90 const sql = yield* SqlClient.SqlClient;
91 // CLI and server write from separate processes; wait rather than fail with SQLITE_BUSY.
92 yield* sql`PRAGMA busy_timeout = 5000;`;
93 yield* sql`PRAGMA foreign_keys = ON;`;
94 // Existing databases need doctor's offline VACUUM to add pointer maps for this mode.
95 const tables = yield* sql<{
96 readonly count: number;
97 }>`SELECT COUNT(*) AS count FROM sqlite_schema WHERE type = 'table'`;
98 if (tables[0]?.count === 0) yield* sql`PRAGMA auto_vacuum = INCREMENTAL;`;
99 yield* sql`PRAGMA journal_mode = WAL;`;
100 // FULL fsyncs every event commit on the main thread; NORMAL syncs only at WAL checkpoints.
101 // App crashes lose nothing; OS crashes or power loss can roll back post-checkpoint commits without corruption.
102 yield* sql`PRAGMA synchronous = NORMAL;`;
103 // macOS fsync misses drive caches; F_FULLFSYNC flushes them at checkpoints and is ignored elsewhere.
104 yield* sql`PRAGMA checkpoint_fullfsync = ON;`;
105 // Keep statement journals and sort spills off the main thread's disk path.
106 // Large statements and open savepoints can increase peak memory use.
107 yield* sql`PRAGMA temp_store = MEMORY;`;
108 // PASSIVE checkpoints retain peak WAL size until the last connection closes.
109 yield* sql.unsafe(`PRAGMA journal_size_limit = ${WAL_SIZE_LIMIT_BYTES};`);
110 yield* migrate;
111 // Collecting stats scans every page, and stale small-table stats cause scans after growth; use indexes by default.
112 // Connections cache stats; reload after deleting them.
113 const statTables = yield* sql`SELECT 1 FROM sqlite_schema WHERE name = 'sqlite_stat1'`;
114 if (statTables.length > 0) {
115 yield* sql`DELETE FROM sqlite_stat1;`;
116 yield* sql`ANALYZE sqlite_schema;`;
117 }
118 }).pipe(Effect.withSpan("Sqlite.setup")),
119 );
120​
121const layerSetup = makeLayerSetup(runMigrations());
122​
123const makeLayerFromPath = <E, R>(makeSetup: (dbPath: string) => Layer.Layer<never, E, R>) =>
124 Effect.fn("makeSqlitePersistenceLive")(function* (dbPath: string) {
125 const fs = yield* FileSystem.FileSystem;
126 const path = yield* Path.Path;
127 yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });
128​
129 return Layer.provideMerge(
130 makeSetup(dbPath),
131 NodeSqliteClient.layer({
132 filename: dbPath,
133 readerWorker: true,
134 // Run checkpoint fsyncs off the event loop so slow disk flushes cannot stall clients.
135 checkpointWorker: true,
136 spanAttributes: {
137 "db.name": path.basename(dbPath),
138 "service.name": "t3code-server",
139 },
140 }),
141 ).pipe(
142 Layer.catchTag("SqlError", (error) =>
143 Layer.effect(
144 SqlClient.SqlClient,
145 Effect.fail(
146 SqlError.isSqlError(error) && isDamagedDatabase(error)
147 ? damagedDatabaseError(dbPath, error)
148 : error,
149 ),
150 ),
151 ),
152 );
153 }, Layer.unwrap);
154​
155export const layerFromPath = makeLayerFromPath((dbPath) =>
156 makeLayerSetup(runMigrationsOffMainThread(dbPath)),
157);
158​
159export const layerMemory = Layer.provideMerge(
160 layerSetup,
161 NodeSqliteClient.layer({ filename: ":memory:" }),
162);
163​
164const makeLayerConfig = <E, R>(
165 fromPath: (dbPath: string) => Layer.Layer<SqlClient.SqlClient, E, R>,
166) =>
167 Layer.unwrap(
168 Effect.gen(function* () {
169 const { dbPath } = yield* ServerConfig.ServerConfig;
170 yield* initializeV2Database(dbPath);
171 return fromPath(dbPath);
172 }),
173 );
174​
175export const layerConfig = makeLayerConfig(layerFromPath);
176​
177/** For CLI commands: pending migrations run only while no server owns the T3 home. */
178export const layerCliConfig = makeLayerConfig(
179 makeLayerFromPath(() => makeLayerSetup(runMigrationsAsOwner())),
180);