peppa/packages/db/src/client.ts
peppa-bot ae7400e4f1
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 49с
peppa/build build: success за 35с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1639с
peppa-ci / ci (pull_request) Successful in 29m27s
PEP-316: любая транзакция берёт блокировку записи первой — «database is locked» при записи из другого процесса
27.11.2026 в 11:27 веб потерял отчёт шага проверки с ошибкой «database is locked»: в этот момент
в базу писал другой процесс. `db.transaction` по умолчанию начиналась как читающая (BEGIN), а
читающей транзакции SQLite не даёт ждать блокировку записи: первая запись получает отказ сразу,
busy_timeout не работает. Утренняя правка результата проверок обернула чтение и запись в такую
транзакцию и гонку не убрала; так же были устроены ещё 15 транзакций ядра (команда агентов,
подписки, чаты, журнал подключений).

- db/client.ts: транзакция всегда начинается с BEGIN IMMEDIATE — ждёт свою очередь и видит то,
  что сохранили другие.
- Тест db-write-lock.test.ts с настоящим вторым процессом (mock-db-writer держит блокировку
  записи): отчёт проверки и транзакция «прочитал — записал» ждут и сохраняются. До исправления
  оба случая падали той же ошибкой, что на проде, сразу и без ожидания.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-27 13:02:47 +05:00

133 lines
5.2 KiB
TypeScript

// drizzle on Node's built-in node:sqlite (PEP-36). drizzle-orm 0.45 has no node:sqlite
// driver (only 1.0 beta/rc does), but node:sqlite's API is close to better-sqlite3's, so a
// thin client lets drizzle's better-sqlite3 *session* run on it. drizzle-orm/better-sqlite3
// itself is not imported: its driver.js loads the native better-sqlite3 package.
// Every Peppa process (web, bot, watchdog, each hook and MCP server) opens the file itself;
// WAL lets readers run next to the single writer, busy_timeout makes writers queue.
import { DatabaseSync, type StatementSync } from "node:sqlite";
import { mkdirSync } from "node:fs";
import { dirname } from "node:path";
import { probed } from "./probe.ts";
export const BUSY_TIMEOUT_MS = 5000;
const BUSY_RETRIES = 3;
const isBusy = (e: unknown) => /SQLITE_BUSY|database is locked/i.test(String((e as Error)?.message ?? e));
/** SQLITE_BUSY after busy_timeout already waited: try a few more times before giving up. */
function retryBusy<T>(fn: () => T): T {
for (let attempt = 1; ; attempt++) {
try {
return fn();
} catch (e) {
if (!isBusy(e) || attempt >= BUSY_RETRIES) throw e;
}
}
}
type Params = unknown[];
class Statement {
private stmt: StatementSync;
private rawStmt: StatementSync | null = null;
private db: DatabaseSync;
private sql: string;
constructor(db: DatabaseSync, sql: string) {
this.db = db;
this.sql = sql;
this.stmt = db.prepare(sql);
}
run(...p: Params) {
return probed(this.sql, () => retryBusy(() => this.stmt.run(...(p as never[]))));
}
all(...p: Params) {
return probed(this.sql, () => retryBusy(() => this.stmt.all(...(p as never[]))));
}
get(...p: Params) {
return probed(this.sql, () => retryBusy(() => this.stmt.get(...(p as never[]))));
}
/** The same statement returning rows as arrays (drizzle maps columns by position). */
raw() {
if (!this.rawStmt) {
this.rawStmt = this.db.prepare(this.sql);
this.rawStmt.setReturnArrays(true);
}
const s = this.rawStmt;
const sql = this.sql;
return {
all: (...p: Params) => probed(sql, () => retryBusy(() => s.all(...(p as never[])))),
get: (...p: Params) => probed(sql, () => retryBusy(() => s.get(...(p as never[])))),
};
}
}
export class SqliteClient {
readonly path: string;
private readOnly: boolean;
private conn: DatabaseSync | null = null;
private cache = new Map<string, Statement>();
constructor(path: string, opts: { readOnly?: boolean } = {}) {
this.path = path;
this.readOnly = opts.readOnly ?? false;
}
/**
* The connection, opened on first use: importing a module that creates the client (the
* web's lib/db.ts during `next build`) must not create the database file.
*/
get db(): DatabaseSync {
if (this.conn) return this.conn;
if (this.path !== ":memory:" && !this.readOnly) mkdirSync(dirname(this.path), { recursive: true });
const db = new DatabaseSync(this.path, { readOnly: this.readOnly });
// busy_timeout first: any statement before it can fail at once with SQLITE_BUSY_RECOVERY
// when many processes open the file together (bench/sqlite/README.md).
db.exec(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`);
if (!this.readOnly) retryBusy(() => db.exec("PRAGMA journal_mode = WAL"));
db.exec("PRAGMA synchronous = NORMAL");
db.exec("PRAGMA foreign_keys = ON");
return (this.conn = db);
}
prepare(sql: string) {
let s = this.cache.get(sql);
if (!s) this.cache.set(sql, (s = new Statement(this.db, sql)));
return s;
}
exec(sql: string) {
retryBusy(() => this.db.exec(sql));
}
/** better-sqlite3's transaction API; the callback must be synchronous. */
transaction<T>(fn: (...a: never[]) => T) {
const run =
(begin: string) =>
(...a: never[]): T => {
retryBusy(() => this.db.exec(begin));
try {
const r = fn(...a);
if (r && typeof (r as { then?: unknown }).then === "function") {
throw new Error("SQLite transactions must be synchronous: no async callback, no await inside db.transaction()");
}
this.db.exec("COMMIT");
return r;
} catch (e) {
if (this.db.isTransaction) this.db.exec("ROLLBACK");
throw e;
}
};
// PEP-316: every transaction takes the write lock first. Many processes write to this file, and
// SQLite refuses a transaction that began as a reader (plain BEGIN) at its first write — at
// once, busy_timeout does not wait for it — whenever another process is writing: «database is
// locked» (27.11.2026, a CI report lost). drizzle asks for `deferred` unless told otherwise,
// so `deferred` is immediate here too: a transaction waits for its turn and then sees
// what the others stored.
return { deferred: run("BEGIN IMMEDIATE"), immediate: run("BEGIN IMMEDIATE"), exclusive: run("BEGIN EXCLUSIVE") };
}
/** Changes committed by other connections since the last call (PRAGMA data_version). */
dataVersion(): number {
return Number((this.db.prepare("PRAGMA data_version").get() as { data_version: number }).data_version);
}
close() {
if (this.conn?.isOpen) this.conn.close();
this.conn = null;
this.cache.clear();
}
}