SPB Git

Repository Public

db.ts 10.3 KB 179 lines typescript

1/**2 * The studio database: one SQLite file (WAL) under ATLAS_DATA_DIR, opened with Node's built-in3 * `node:sqlite` (no native add-on to compile). It is shared by the Next server, the media worker and the4 * operator's command-line scripts; SQLite serialises their writes (busy_timeout).5 *6 * Migrations are forward-only and recorded in `schema_migrations`: opening a database applies whatever is7 * missing, each migration in its own transaction, and opening it again changes nothing.8 */9import { existsSync, mkdirSync } from "node:fs";10import { join } from "node:path";11import { DatabaseSync, type SQLInputValue } from "node:sqlite";12import { env } from "../lib/env";1314export interface Migration { name: string; sql: string }1516export const MIGRATIONS: Migration[] = [17  { name: "001_identity_and_audit", sql: `18    CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);19    CREATE TABLE editors (20      id TEXT PRIMARY KEY, name TEXT NOT NULL,21      role TEXT NOT NULL CHECK (role IN ('owner','publisher','author')),22      created_at TEXT NOT NULL, disabled_at TEXT);23    CREATE TABLE credentials (24      id TEXT PRIMARY KEY, editor_id TEXT NOT NULL REFERENCES editors(id) ON DELETE CASCADE,25      public_key BLOB NOT NULL, counter INTEGER NOT NULL, transports TEXT NOT NULL, name TEXT NOT NULL,26      device_type TEXT, backed_up INTEGER, created_at TEXT NOT NULL, last_used_at TEXT);27    CREATE TABLE auth_sessions (28      token_hash TEXT PRIMARY KEY, editor_id TEXT NOT NULL REFERENCES editors(id) ON DELETE CASCADE,29      csrf TEXT NOT NULL, created_at TEXT NOT NULL, expires_at TEXT NOT NULL, last_seen_at TEXT NOT NULL, ip TEXT, ua TEXT);30    CREATE TABLE enroll_tokens (31      token_hash TEXT PRIMARY KEY, editor_id TEXT NOT NULL REFERENCES editors(id) ON DELETE CASCADE,32      purpose TEXT NOT NULL CHECK (purpose IN ('setup','recovery')),33      created_at TEXT NOT NULL, created_by TEXT NOT NULL, expires_at TEXT NOT NULL, used_at TEXT);34    CREATE TABLE challenges (id TEXT PRIMARY KEY, challenge TEXT NOT NULL, kind TEXT NOT NULL, binding TEXT NOT NULL, expires_at TEXT NOT NULL);35    CREATE TABLE audit (36      id INTEGER PRIMARY KEY AUTOINCREMENT, at TEXT NOT NULL, actor TEXT NOT NULL, action TEXT NOT NULL,37      target TEXT, before_ref TEXT, after_ref TEXT, detail TEXT, ip TEXT);38    CREATE INDEX audit_action ON audit (action, at);39    CREATE INDEX audit_target ON audit (target, id);` },40  { name: "002_editorial_model", sql: `41    CREATE TABLE blobs (sha256 TEXT PRIMARY KEY, bytes INTEGER NOT NULL, body BLOB NOT NULL, created_at TEXT NOT NULL);42    CREATE TABLE course (43      id INTEGER PRIMARY KEY CHECK (id = 1), data TEXT NOT NULL, base TEXT NOT NULL,44      rev INTEGER NOT NULL DEFAULT 1, updated_at TEXT NOT NULL, updated_by TEXT NOT NULL);45    CREATE TABLE course_sessions (46      id TEXT PRIMARY KEY, state TEXT NOT NULL CHECK (state IN ('planned','draft','preview')),47      data TEXT NOT NULL, base TEXT, in_source INTEGER NOT NULL DEFAULT 1,48      rev INTEGER NOT NULL DEFAULT 1, updated_at TEXT NOT NULL, updated_by TEXT NOT NULL);49    CREATE TABLE sections (50      session_id TEXT NOT NULL REFERENCES course_sessions(id) ON DELETE CASCADE, key TEXT NOT NULL,51      sha256 TEXT NOT NULL REFERENCES blobs(sha256), visibility TEXT NOT NULL CHECK (visibility IN ('private','preview','public')),52      count INTEGER, base_sha256 TEXT, updated_at TEXT NOT NULL, updated_by TEXT NOT NULL,53      PRIMARY KEY (session_id, key));54    CREATE TABLE capsules (55      session_id TEXT NOT NULL REFERENCES course_sessions(id) ON DELETE CASCADE, id TEXT NOT NULL,56      position INTEGER NOT NULL, data TEXT NOT NULL,57      status TEXT NOT NULL CHECK (status IN ('empty','queued','processing','ready','failed')),58      master_sha TEXT, updated_at TEXT NOT NULL, updated_by TEXT NOT NULL,59      PRIMARY KEY (session_id, id));60    CREATE TABLE resources (61      session_id TEXT NOT NULL REFERENCES course_sessions(id) ON DELETE CASCADE, id TEXT NOT NULL,62      data TEXT NOT NULL, current_version INTEGER NOT NULL, updated_at TEXT NOT NULL, updated_by TEXT NOT NULL,63      PRIMARY KEY (session_id, id));64    CREATE TABLE resource_versions (65      session_id TEXT NOT NULL, resource_id TEXT NOT NULL, version INTEGER NOT NULL,66      path TEXT NOT NULL, bytes INTEGER NOT NULL, sha256 TEXT NOT NULL, mime TEXT NOT NULL, filename TEXT NOT NULL,67      note TEXT, created_at TEXT NOT NULL, created_by TEXT NOT NULL,68      PRIMARY KEY (session_id, resource_id, version),69      FOREIGN KEY (session_id, resource_id) REFERENCES resources(session_id, id) ON DELETE CASCADE);70    CREATE TABLE publications (71      id INTEGER PRIMARY KEY AUTOINCREMENT, target TEXT NOT NULL, version INTEGER NOT NULL,72      kind TEXT NOT NULL CHECK (kind IN ('publish','rollback','withdraw','archive')),73      payload_sha TEXT REFERENCES blobs(sha256), live_from TEXT NOT NULL, cancelled_at TEXT, cancelled_by TEXT,74      note TEXT, created_at TEXT NOT NULL, created_by TEXT NOT NULL,75      UNIQUE (target, version));76    CREATE TABLE imports (77      id TEXT PRIMARY KEY, source TEXT NOT NULL, source_hash TEXT NOT NULL, incoming_sha TEXT NOT NULL REFERENCES blobs(sha256),78      warnings TEXT NOT NULL, status TEXT NOT NULL CHECK (status IN ('pending','applied','discarded')),79      summary TEXT, created_at TEXT NOT NULL, created_by TEXT NOT NULL, applied_at TEXT);` },80  { name: "003_uploads_and_jobs", sql: `81    CREATE TABLE uploads (82      id TEXT PRIMARY KEY, purpose TEXT NOT NULL, filename TEXT NOT NULL, size INTEGER NOT NULL,83      chunk_size INTEGER NOT NULL, total_chunks INTEGER NOT NULL, fingerprint TEXT NOT NULL, context TEXT NOT NULL,84      status TEXT NOT NULL CHECK (status IN ('open','complete','failed','aborted')),85      sha256 TEXT, error TEXT, result TEXT, created_at TEXT NOT NULL, created_by TEXT NOT NULL, completed_at TEXT);86    CREATE INDEX uploads_fingerprint ON uploads (fingerprint, size, purpose);87    CREATE TABLE upload_chunks (88      upload_id TEXT NOT NULL REFERENCES uploads(id) ON DELETE CASCADE, n INTEGER NOT NULL,89      sha256 TEXT NOT NULL, bytes INTEGER NOT NULL, PRIMARY KEY (upload_id, n));90    CREATE TABLE masters (91      sha256 TEXT PRIMARY KEY, filename TEXT NOT NULL, ext TEXT NOT NULL, bytes INTEGER NOT NULL,92      probe TEXT, created_at TEXT NOT NULL, created_by TEXT NOT NULL);93    CREATE TABLE jobs (94      id INTEGER PRIMARY KEY AUTOINCREMENT, kind TEXT NOT NULL, payload TEXT NOT NULL,95      state TEXT NOT NULL CHECK (state IN ('queued','running','succeeded','failed','cancelled')),96      attempts INTEGER NOT NULL DEFAULT 0, max_attempts INTEGER NOT NULL DEFAULT 3, run_after TEXT NOT NULL,97      cancel_requested INTEGER NOT NULL DEFAULT 0, locked_by TEXT, heartbeat_at TEXT,98      progress REAL NOT NULL DEFAULT 0, step TEXT, error TEXT, result TEXT, log TEXT,99      created_at TEXT NOT NULL, created_by TEXT NOT NULL, started_at TEXT, finished_at TEXT);100    CREATE INDEX jobs_state ON jobs (state, run_after);` },101];102103/** Applies every migration that the database has not recorded yet. Returns the names applied by this call. */104export function migrate(db: DatabaseSync, migrations: Migration[] = MIGRATIONS): string[] {105  db.exec("CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at TEXT NOT NULL)");106  const done = new Map((db.prepare("SELECT version, name FROM schema_migrations").all() as { version: number; name: string }[]).map((r) => [r.version, r.name]));107  const applied: string[] = [];108  migrations.forEach((m, i) => {109    const version = i + 1, known = done.get(version);110    if (known !== undefined) {111      if (known !== m.name) throw new Error(`Base de données incompatible : la migration ${version} s'appelle « ${known} », le code attend « ${m.name} ».`);112      return;113    }114    db.exec("BEGIN IMMEDIATE");115    try {116      db.exec(m.sql);117      db.prepare("INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)").run(version, m.name, new Date().toISOString());118      db.exec("COMMIT");119    } catch (err) { db.exec("ROLLBACK"); throw err; }120    applied.push(m.name);121  });122  if (done.size > migrations.length) throw new Error("Base de données plus récente que le code : mettre l'application à jour avant de l'ouvrir.");123  return applied;124}125126export const dbPath = (dataDir = env.dataDir) => join(dataDir, "atlas.db");127export const dbExists = (dataDir = env.dataDir) => existsSync(dbPath(dataDir));128129export function openDb(path: string): DatabaseSync {130  const db = new DatabaseSync(path);131  db.exec("PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 8000; PRAGMA synchronous = NORMAL;");132  migrate(db);133  return db;134}135136type G = typeof globalThis & { __atlasDb?: { path: string; db: DatabaseSync } };137138/** The process-wide handle. Creates the database (and the data directory) on first use. */139export function db(): DatabaseSync {140  const g = globalThis as G, path = dbPath();141  if (g.__atlasDb?.path !== path) {142    g.__atlasDb?.db.close();143    mkdirSync(env.dataDir, { recursive: true, mode: 0o700 });144    g.__atlasDb = { path, db: openDb(path) };145  }146  return g.__atlasDb.db;147}148149/** For read paths of the public site: the handle if a database exists, null otherwise (never creates one). */150export function dbIfExists(): DatabaseSync | null {151  const g = globalThis as G;152  if (g.__atlasDb?.path === dbPath()) return g.__atlasDb.db;153  return dbExists() ? db() : null;154}155156export function closeDb(): void {157  const g = globalThis as G;158  g.__atlasDb?.db.close();159  g.__atlasDb = undefined;160}161162export const now = () => new Date().toISOString();163164/** Runs `fn` in a write transaction. Nested calls join the outer transaction. */165export function tx<T>(fn: () => T): T {166  const d = db();167  if (d.isTransaction) return fn();168  d.exec("BEGIN IMMEDIATE");169  try { const r = fn(); d.exec("COMMIT"); return r; }170  catch (err) { if (d.isTransaction) d.exec("ROLLBACK"); throw err; }171}172173export const get = <T>(sql: string, ...params: SQLInputValue[]) => db().prepare(sql).get(...params) as T | undefined;174export const all = <T>(sql: string, ...params: SQLInputValue[]) => db().prepare(sql).all(...params) as T[];175export const run = (sql: string, ...params: SQLInputValue[]) => db().prepare(sql).run(...params);176177export const getMeta = (key: string) => get<{ value: string }>("SELECT value FROM meta WHERE key = ?", key)?.value ?? null;178export const setMeta = (key: string, value: string) => { run("INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value", key, value); };179
Files main
Menu

Theme