SPB Git

Repository Public

ops.ts 14.3 KB 182 lines typescript

1/**2 * Operator tools shared by the studio (« Outils »), the health endpoints and the command line:3 * health details, the link and integrity checker, and the validation of every caption file.4 */5import { createHash } from "node:crypto";6import { createReadStream, existsSync } from "node:fs";7import { stat } from "node:fs/promises";8import { join } from "node:path";9import { env } from "../lib/env";10import { Bibliography, Deck, Figures, Glossary, Quiz, type Session } from "../modules/content-schema/schema";11import { getBlob, getBlobText, getJson } from "./audit";12import { validateCaptions } from "./captions";13import { getCourseRow, isBootstrapped, listCapsules, listResources, listSections, listSessions } from "./content";14import { MIGRATIONS, all, db, dbExists, get } from "./db";15import { jobCounts, workerStatus } from "./jobs";16import { COURSE_TARGET, liveEntry, type PlanSnapshot } from "./publish";17import { paths, storageUsage } from "./storage";18import { configuredLadder, ffmpegStatus } from "./transcode";19import { readSidecar } from "./uploads";2021/* ---- Health ---- */2223export interface HealthDetails {24  status: "ok" | "degraded" | "error"; at: string;25  checks: {26    database: { ok: boolean; schema: number; expected: number; integrity: string };27    content: { ok: boolean; source: "studio" | "snapshot"; sessions: number; published: number; scheduled: number };28    storage: { ok: boolean; level: string; usedBytes: number; freeBytes: number | null; quotaBytes: number; message: string | null };29    worker: { ok: boolean; state: string; ageSeconds: number | null; queued: number; running: number; failed: number };30    ffmpeg: { ok: boolean; ffmpeg: string | null; ffprobe: string | null; message: string | null; ladder: string | null };31  };32}3334/**35 * Everything an operator needs to know at a glance. `degraded` means the public site works but the studio36 * cannot do part of its job (no worker, no ffmpeg, storage nearly full); `error` means the database is unusable.37 */38export async function healthDetails(): Promise<HealthDetails> {39  let database: HealthDetails["checks"]["database"] = { ok: false, schema: 0, expected: MIGRATIONS.length, integrity: "base absente" };40  let content: HealthDetails["checks"]["content"] = { ok: true, source: "snapshot", sessions: 0, published: 0, scheduled: 0 };41  let worker: HealthDetails["checks"]["worker"] = { ok: false, state: "absent", ageSeconds: null, queued: 0, running: 0, failed: 0 };42  if (dbExists()) {43    try {44      const schema = get<{ n: number }>("SELECT count(*) AS n FROM schema_migrations")!.n;45      const integrity = (db().prepare("PRAGMA quick_check").get() as { quick_check: string }).quick_check;46      database = { ok: integrity === "ok" && schema === MIGRATIONS.length, schema, expected: MIGRATIONS.length, integrity };47      if (isBootstrapped()) {48        const at = new Date().toISOString(), sessions = listSessions();49        const published = sessions.filter((s) => { const e = liveEntry(s.id, at); return e && (e.kind === "publish" || e.kind === "rollback"); }).length;50        content = { ok: Boolean(liveEntry(COURSE_TARGET, at)), source: "studio", sessions: sessions.length, published, scheduled: get<{ n: number }>("SELECT count(*) AS n FROM publications WHERE cancelled_at IS NULL AND live_from > ?", at)!.n };51      }52      const w = workerStatus(), counts = jobCounts();53      worker = { ok: w.state === "ok", state: w.state, ageSeconds: w.ageSeconds, queued: counts.queued ?? 0, running: counts.running ?? 0, failed: counts.failed ?? 0 };54    } catch (e) { database = { ...database, ok: false, integrity: e instanceof Error ? e.message.slice(0, 200) : "erreur" }; }55  } else database = { ok: true, schema: 0, expected: MIGRATIONS.length, integrity: "aucune base : le site sert l'instantané livré avec l'application" };56  const usage = await storageUsage(), ff = await ffmpegStatus(), ladder = configuredLadder();57  const checks: HealthDetails["checks"] = {58    database, content, worker,59    storage: { ok: usage.level !== "critical", level: usage.level, usedBytes: usage.usedBytes, freeBytes: usage.freeBytes, quotaBytes: usage.quotaBytes, message: usage.message },60    ffmpeg: { ok: ff.ok, ffmpeg: ff.ffmpeg, ffprobe: ff.ffprobe, message: ff.message, ladder: ladder.error },61  };62  const status = !checks.database.ok || !checks.content.ok ? "error" : checks.storage.ok && checks.storage.level === "ok" && checks.ffmpeg.ok && (checks.worker.ok || !dbExists()) ? "ok" : "degraded";63  return { status, at: new Date().toISOString(), checks };64}6566/* ---- Links and integrity ---- */6768export interface Finding { level: "error" | "warning" | "info"; where: string; message: string }69export interface CheckReport { at: string; findings: Finding[]; stats: Record<string, number> }7071const STATIC_ROUTES = new Set(["/", "/programme", "/parcours", "/laboratoires", "/ressources", "/glossaire", "/recherche", "/a-propos", "/accessibilite", "/confidentialite", "/conditions", "/schemas"]);72const fileOk = async (root: string, rel: string | undefined, bytes?: number) => { if (!rel) return false; const s = await stat(join(root, rel)).catch(() => null); return Boolean(s?.isFile()) && (bytes === undefined || s!.size === bytes); };73const hashFile = (file: string) => new Promise<string>((res, rej) => { const h = createHash("sha256"); createReadStream(file).on("data", (d) => h.update(d)).on("end", () => res(h.digest("hex"))).on("error", rej); });7475/**76 * Checks what the studio holds: references between sessions, section bodies against their schemas, links77 * written in Markdown, media and resource files on disk (with `deep`, their SHA-256 too), and that78 * everything a live publication names still exists. External links are listed, never fetched: the server79 * makes no outbound request for an address found in content.80 */81export async function checkLinks(o: { deep?: boolean } = {}): Promise<CheckReport> {82  const findings: Finding[] = [], stats = { sessions: 0, sections: 0, internalLinks: 0, externalLinks: 0, mediaFiles: 0, resourceFiles: 0, published: 0 };83  const add = (level: Finding["level"], where: string, message: string) => findings.push({ level, where, message });84  const course = getCourseRow().data, sessions = listSessions(), ids = new Set(sessions.map((s) => s.id));85  const slugs = new Set(sessions.flatMap((s) => [s.data.slug, ...s.data.aliases])), terms = new Map<string, string>();86  const checkLink = (where: string, url: string) => {87    if (/^https?:\/\//i.test(url)) { stats.externalLinks++; try { new URL(url); } catch { add("error", where, `adresse externe mal formée : ${url.slice(0, 120)}`); } return; }88    if (url.startsWith("#") || url.startsWith("mailto:")) return;89    if (!url.startsWith("/")) { add("warning", where, `lien relatif ou de schéma non pris en charge, il ne sera pas cliquable : ${url.slice(0, 120)}`); return; }90    stats.internalLinks++;91    const path = url.split(/[?#]/)[0]!.replace(/\/+$/, "") || "/", m = /^\/seances\/([^/]+)(\/regarder)?$/.exec(path);92    if (m ? !slugs.has(m[1]!) : !STATIC_ROUTES.has(path) && !/^\/schemas\/[a-z0-9-]+$/.test(path)) add("error", where, `lien interne vers une page qui n'existe pas : ${url.slice(0, 120)}`);93  };94  for (const s of sessions) {95    stats.sessions++;96    const where = `${s.id} — ${s.data.short}`;97    if (!course.parts.some((p) => p.id === s.data.part)) add("error", where, `partie inconnue : ${s.data.part}`);98    for (const d of s.data.dependsOn) if (!ids.has(d)) add("error", where, `préalable inconnu : ${d}`);99    for (const sec of listSections(s.id)) {100      stats.sections++;101      const text = getBlobText(sec.sha256);102      if (text === null) { add("error", `${where} · ${sec.key}`, "contenu absent de la base"); continue; }103      if (sec.key === "lab" || sec.key === "script") {104        for (const m of text.matchAll(/\[[^\]]*\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)|<((?:https?|javascript|data|file):[^>\s]+)>/g)) {105          const url = m[1] ?? m[2]!;106          if (/^(javascript|data|file|vbscript):/i.test(url)) add("error", `${where} · ${sec.key}`, `lien de schéma interdit (il ne sera pas rendu) : ${url.slice(0, 80)}`); else checkLink(`${where} · ${sec.key}`, url);107        }108        continue;109      }110      const schema = { quiz: Quiz, glossary: Glossary, figures: Figures, bibliography: Bibliography, slides: Deck }[sec.key];111      let parsed; try { parsed = schema.safeParse(JSON.parse(text)); } catch { parsed = { success: false as const }; }112      if (!parsed.success) { add("error", `${where} · ${sec.key}`, "contenu qui ne respecte plus son schéma"); continue; }113      if (sec.key === "slides") { const deck = parsed.data as Deck; if (!existsSync(join(env.dataDir, "slides", deck.dir, "deck.json"))) add("error", `${where} · diapositives`, "les images des diapositives sont absentes du stockage (dossier slides/)"); }114      if (sec.key === "figures") for (const f of (parsed.data as Figures).figures) if (!getBlob(f.sha256)) add("error", `${where} · figures`, `figure absente de la base : ${f.file}`);115      if (sec.key === "glossary") for (const t of (parsed.data as Glossary).terms) { const other = terms.get(t.id); if (other && other !== s.id) add("warning", `${where} · glossaire`, `le terme « ${t.term} » a le même identifiant qu'un terme de ${other} : leurs ancres se confondront`); terms.set(t.id, s.id); }116      if (sec.key === "bibliography") for (const e of (parsed.data as Bibliography).entries) if (e.url) checkLink(`${where} · références`, e.url);117    }118    for (const c of listCapsules(s.id)) {119      const cw = `${where} · capsule « ${c.data.title} »`, m = c.data.media;120      if (c.status === "failed") add("warning", cw, "le dernier traitement vidéo a échoué");121      if (c.status !== "ready") continue;122      for (const [label, key] of [["liste HLS", m.hls], ["MP4", m.mp4], ["affiche", m.poster], ["transcription", m.transcript], ["chapitres", m.chapters], ...m.captions.map((t) => [`sous-titres ${t.lang}`, t.path])] as [string, string | undefined][]) {123        if (!key) continue;124        stats.mediaFiles++;125        if (!(await fileOk(paths.media, key))) add("error", cw, `fichier absent du stockage : ${label}`);126      }127      if (!m.captions.length) add("warning", cw, "aucun sous-titre : la capsule ne pourra pas être publiée");128      if (!m.transcript) add("warning", cw, "aucune transcription : la capsule ne pourra pas être publiée");129    }130    for (const r of listResources(s.id)) {131      const rw = `${where} · ressource « ${r.data.title} »`;132      for (const v of r.versions) {133        stats.resourceFiles++;134        const current = v.version === r.currentVersion;135        if (!(await fileOk(paths.resources, v.path, v.bytes))) add(current ? "error" : "warning", rw, `fichier absent ou de taille différente (version ${v.version}${current ? ", version actuelle" : ""})`);136        else if (o.deep && (await hashFile(join(paths.resources, v.path))) !== v.sha256) add("error", rw, `somme de contrôle SHA-256 différente de celle consignée (version ${v.version})`);137      }138    }139    // What is online right now must exist on disk, whatever happened to the working copy since.140    const live = liveEntry(s.id);141    if (live && (live.kind === "publish" || live.kind === "rollback")) {142      stats.published++;143      const snap = getJson<Session>(live.payloadSha);144      for (const c of snap?.capsules ?? []) for (const key of [c.media.hls, c.media.mp4, c.media.poster, c.media.transcript, c.media.chapters, ...c.media.captions.map((t) => t.path)]) if (key && !(await fileOk(paths.media, key))) add("error", `${where} · EN LIGNE`, `un fichier de la capsule publiée « ${c.title} » manque : ${key.split("/").pop()}`);145      for (const r of snap?.resources ?? []) if (!(await fileOk(paths.resources, r.path, r.bytes))) add("error", `${where} · EN LIGNE`, `le fichier de la ressource publiée « ${r.title} » manque ou a changé`);146      for (const ref of Object.values(snap?.sections ?? {})) if (!getBlob(ref!.sha256)) add("error", `${where} · EN LIGNE`, "le contenu d'une section publiée manque dans la base");147    }148  }149  for (const r of course.redirects) checkLink(`Redirection ${r.from}`, r.to);150  const plan = getJson<PlanSnapshot>(liveEntry(COURSE_TARGET)?.payloadSha);151  if (!plan) add("error", "Plan du cours", "aucun plan n'est publié");152  if (stats.externalLinks) add("info", "Liens externes", `${stats.externalLinks} lien(s) vers d'autres sites : leur syntaxe est vérifiée, leur disponibilité ne l'est pas (le serveur ne contacte aucune adresse tirée du contenu).`);153  const order = { error: 0, warning: 1, info: 2 };154  return { at: new Date().toISOString(), findings: findings.sort((a, b) => order[a.level] - order[b.level]), stats };155}156157/** Resources and published media that are missing or altered: the « broken resources » of the dashboard. */158export async function brokenItems(): Promise<Finding[]> {159  if (!isBootstrapped()) return [];160  return (await checkLinks()).findings.filter((f) => f.level === "error" && /fichier|manque|somme|absent/.test(f.message));161}162163/* ---- Captions ---- */164165export interface CaptionCheck { session: string; capsule: string; title: string; lang: string; ok: boolean; cues: number; errors: string[]; warnings: string[] }166/** Re-validates every caption file attached in the studio against the current duration of its video. */167export async function validateAllCaptions(): Promise<{ at: string; tracks: CaptionCheck[]; missing: { session: string; capsule: string; title: string }[] }> {168  const tracks: CaptionCheck[] = [], missing: { session: string; capsule: string; title: string }[] = [];169  for (const row of all<{ session_id: string }>("SELECT DISTINCT session_id FROM capsules ORDER BY session_id")) for (const c of listCapsules(row.session_id)) {170    if (c.status === "ready" && !c.data.media.captions.length) missing.push({ session: c.sessionId, capsule: c.id, title: c.data.title });171    for (const t of c.data.media.captions) {172      const text = await readSidecar(t.path);173      if (text === null) { tracks.push({ session: c.sessionId, capsule: c.id, title: c.data.title, lang: t.lang, ok: false, cues: 0, errors: ["fichier absent du stockage"], warnings: [] }); continue; }174      const r = validateCaptions(text, { videoDuration: c.data.durationSeconds });175      tracks.push({ session: c.sessionId, capsule: c.id, title: c.data.title, lang: t.lang, ok: r.ok, cues: r.cues, errors: r.errors, warnings: r.warnings });176    }177  }178  return { at: new Date().toISOString(), tracks, missing };179}180181export const dataDirSummary = () => ({ dataDir: env.dataDir, database: join(env.dataDir, "atlas.db") });182
Files main
Menu

Theme