SPB Git

Repository Public

sync.ts 20.4 KB 282 lines typescript

1/**2 * Synchronisation with the course repository.3 *4 * The repository is content, never code: it is read by the adapter of importer.ts (YAML core schema, size5 * limits, confined paths) into a throw-away directory, and what comes out is compared, field by field,6 * with the studio's working copy:7 *8 *   base      what the previous import brought (remembered per field and per section)9 *   local     the working copy now (possibly edited in the studio)10 *   incoming  what the repository says now11 *12 *   incoming = base                     nothing to do13 *   incoming ≠ base, local = base       update (the instructor did not touch it)14 *   incoming ≠ base, local ≠ base       CONFLICT — the local value is kept unless the instructor picks the other15 *16 * Applying an import only ever changes the working copy: new sessions arrive as drafts, nothing is17 * published, and live publications are untouched. Applying the same source twice changes nothing.18 */19import { mkdir, readFile, rm } from "node:fs/promises";20import { join, resolve } from "node:path";21import { env } from "../lib/env";22import { Figures, Manifest, SECTION_KEYS, type SectionKey, type Session } from "../modules/content-schema/schema";23import { audit, getBlob, getJson, putBlob, putJson } from "./audit";24import { randomId, sha256 } from "./crypto";25import { all, get, now, run, setMeta, tx } from "./db";26import { ApiError } from "./http";27import { importCourse } from "./importer";28import { log } from "./log";29import {30  IMPORT_FIELDS, fingerprint, getCourseRow, isBootstrapped, listSections, listSessions, workingManifest, writeCourse, writeSection, writeSession,31  type CourseBase, type CourseData, type ImportField, type SessionBase, type SessionData, type SessionState,32} from "./content";33import { COURSE_TARGET, publishPlan } from "./publish";3435export interface IncomingSession { id: string; number: number; slug: string; aliases: string[]; base: SessionBase; source: Session["source"]; sections: Partial<Record<SectionKey, { sha256: string; count: number | null }>> }36export interface Incoming { sourceHash: string; files: number; course: CourseBase; sessions: IncomingSession[] }3738export interface FieldChange { key: string; label: string; kind: "update" | "conflict" | "add" | "remove"; base: string | null; local: string | null; incoming: string | null }39export interface SessionDiff { id: string; title: string; kind: "added" | "removed" | "changed" | "unchanged"; changes: FieldChange[] }40export interface ImportDiff { sourceHash: string; course: FieldChange[]; sessions: SessionDiff[]; counts: { added: number; removed: number; changed: number; unchanged: number; updates: number; conflicts: number } }41export type Decision = "local" | "incoming";4243const FIELD_LABEL: Record<ImportField, string> = { title: "Titre", short: "Titre court", part: "Partie", level: "Niveau", outcomes: "Résultats d'apprentissage", dependsOn: "Préalables", tags: "Thèmes", effortMinutes: "Effort estimé" };44const SECTION_LABEL: Record<SectionKey, string> = { quiz: "Quiz", glossary: "Glossaire", figures: "Figures", lab: "Laboratoire", script: "Scénario de narration", bibliography: "Références", slides: "Diapositives" };45const show = (v: unknown): string | null => (v === null || v === undefined ? null : typeof v === "string" ? v : Array.isArray(v) ? (v.every((x) => typeof x === "string") ? v.join(" · ") : JSON.stringify(v)) : JSON.stringify(v));46const showSection = (s: { sha256: string; count: number | null } | null | undefined) => (s ? `${s.count !== null ? `${s.count} élément${s.count > 1 ? "s" : ""} · ` : ""}empreinte ${s.sha256.slice(0, 10)}` : null);47const same = (a: unknown, b: unknown) => fingerprint(a ?? null) === fingerprint(b ?? null);4849/**50 * Reads a snapshot directory (course.manifest.json + import/**) as produced by the importer. Section bodies51 * and figures are stored in the blob table as they are read; a file whose hash does not match is skipped.52 */53export async function readSnapshot(dir: string): Promise<{ incoming: Incoming; manifest: Manifest; warnings: string[] }> {54  const manifest = Manifest.parse(JSON.parse(await readFile(join(dir, "course.manifest.json"), "utf8")));55  const warnings: string[] = [], sessions: IncomingSession[] = [];56  for (const s of manifest.sessions) {57    const sections: IncomingSession["sections"] = {};58    for (const key of SECTION_KEYS) {59      const ref = s.sections[key];60      if (!ref) continue;61      const body = await readFile(join(dir, "import", ref.path)).catch(() => null);62      if (!body || sha256(body) !== ref.sha256) { warnings.push(`${s.id}.${key} : fichier absent ou altéré, section ignorée`); continue; }63      if (key === "figures") {64        const figures = Figures.safeParse(JSON.parse(body.toString("utf8")));65        if (!figures.success) { warnings.push(`${s.id}.figures : liste illisible, section ignorée`); continue; }66        let ok = true;67        for (const f of figures.data.figures) {68          const svg = await readFile(join(dir, "import", "sessions", s.id, f.file)).catch(() => null);69          if (!svg || sha256(svg) !== f.sha256) { warnings.push(`${s.id}.figures : ${f.file} absent ou altéré, section ignorée`); ok = false; break; }70          putBlob(svg);71        }72        if (!ok) continue;73      }74      putBlob(body);75      sections[key] = { sha256: ref.sha256, count: ref.count ?? null };76    }77    sessions.push({78      id: s.id, number: s.number, slug: s.slug, aliases: s.aliases, source: s.source, sections,79      base: { title: s.title, short: s.short, part: s.part, level: s.level, outcomes: s.outcomes, dependsOn: s.dependsOn, tags: s.tags, effortMinutes: s.effortMinutes },80    });81  }82  const { license: _license, ...course } = manifest.course; void _license;83  return { incoming: { sourceHash: manifest.import.sourceHash, files: manifest.import.files, course: { course, author: manifest.author, parts: manifest.parts }, sessions }, manifest, warnings };84}8586/* ---- First start: the committed snapshot becomes the working copy and the first public plan ---- */8788/**89 * Seeds an empty studio from the snapshot committed with the application, so that the public site reads90 * exactly the same plan before and after the database exists. States come from the snapshot's editorial91 * layer; nothing that was not public becomes public.92 */93export async function bootstrap(actor = "system", dir = resolve("content")): Promise<boolean> {94  if (isBootstrapped()) return false;95  const { incoming, manifest } = await readSnapshot(dir);96  return tx(() => {97    if (isBootstrapped()) return false;98    const data: CourseData = { course: manifest.course, author: manifest.author, parts: manifest.parts, diagrams: manifest.diagrams, exposeTags: manifest.exposeTags, redirects: manifest.redirects, import: manifest.import };99    writeCourse(data, incoming.course, actor);100    for (const s of incoming.sessions) {101      const m = manifest.sessions.find((x) => x.id === s.id)!;102      const state: SessionState = m.publication === "planned" ? "planned" : m.publication === "draft" ? "draft" : "preview";103      writeSession(s.id, { state, base: s.base, data: { ...s.base, number: s.number, slug: s.slug, aliases: s.aliases, source: s.source, revisions: m.revisions } }, actor);104      // A snapshot that says « public » is not a decision taken in the studio: public material starts as « preview ».105      for (const [key, ref] of Object.entries(s.sections)) writeSection(s.id, key as SectionKey, { sha256: ref!.sha256, count: ref!.count, baseSha: ref!.sha256, visibility: m.sections[key as SectionKey]!.visibility === "private" ? "private" : "preview" }, actor);106    }107    run("INSERT INTO imports (id, source, source_hash, incoming_sha, warnings, status, summary, created_at, created_by, applied_at) VALUES (?, ?, ?, ?, '[]', 'applied', ?, ?, ?, ?)",108      `imp_${randomId(6)}`, "Instantané livré avec l'application", incoming.sourceHash, putJson(incoming), `${incoming.sessions.length} séances`, now(), actor, now());109    setMeta("bootstrapped", now());110    audit("studio.bootstrapped", { actor, target: "course", detail: { sessions: incoming.sessions.length, sourceHash: incoming.sourceHash } });111    publishPlan({ confirm: COURSE_TARGET, note: "Plan initial (instantané livré avec l'application)" }, actor);112    return true;113  });114}115116/* ---- Diff ---- */117118function fieldChange(key: string, label: string, base: unknown, local: unknown, incoming: unknown): FieldChange | null {119  if (same(incoming, base) || same(incoming, local)) return null;120  return { key, label, kind: same(local, base) ? "update" : "conflict", base: show(base), local: show(local), incoming: show(incoming) };121}122123export function diffIncoming(incoming: Incoming): ImportDiff {124  const cur = getCourseRow(), sessions = listSessions(), byId = new Map(sessions.map((s) => [s.id, s]));125  const course: FieldChange[] = [];126  for (const [key, label] of [["course", "Identité du cours"], ["author", "Auteur"], ["parts", "Parties"]] as const) {127    const local = key === "course" ? (({ license: _l, ...rest }) => { void _l; return rest; })(cur.data.course) : cur.data[key];128    const c = fieldChange(`course.${key}`, label, cur.base[key], local, incoming.course[key]);129    if (c) course.push(c);130  }131  const out: SessionDiff[] = [];132  for (const inc of incoming.sessions) {133    const row = byId.get(inc.id);134    if (!row) { out.push({ id: inc.id, title: inc.base.title, kind: "added", changes: [{ key: `${inc.id}`, label: "Nouvelle séance", kind: "add", base: null, local: null, incoming: `${inc.base.title} — ${Object.keys(inc.sections).length ? `avec ${Object.keys(inc.sections).map((k) => SECTION_LABEL[k as SectionKey].toLowerCase()).join(", ")}` : "plan seulement"}` }] }); continue; }135    const changes: FieldChange[] = [];136    for (const f of IMPORT_FIELDS) { const c = fieldChange(`${inc.id}.${f}`, FIELD_LABEL[f], row.base?.[f], row.data[f], inc.base[f]); if (c) changes.push(c); }137    const local = new Map(listSections(inc.id).map((s) => [s.key, s]));138    for (const key of SECTION_KEYS) {139      const l = local.get(key), i = inc.sections[key];140      if (i && !l) changes.push({ key: `${inc.id}.section.${key}`, label: SECTION_LABEL[key], kind: "add", base: null, local: null, incoming: showSection(i) });141      else if (i && l && i.sha256 !== l.baseSha && i.sha256 !== l.sha256) changes.push({ key: `${inc.id}.section.${key}`, label: SECTION_LABEL[key], kind: l.sha256 === l.baseSha ? "update" : "conflict", base: l.baseSha ? `empreinte ${l.baseSha.slice(0, 10)}` : null, local: showSection(l), incoming: showSection(i) });142      else if (!i && l?.baseSha) changes.push({ key: `${inc.id}.section.${key}`, label: SECTION_LABEL[key], kind: "remove", base: `empreinte ${l.baseSha.slice(0, 10)}`, local: showSection(l), incoming: null });143    }144    out.push({ id: inc.id, title: row.data.title, kind: changes.length ? "changed" : "unchanged", changes });145  }146  const seen = new Set(incoming.sessions.map((s) => s.id));147  for (const row of sessions) if (!seen.has(row.id) && row.inSource) out.push({ id: row.id, title: row.data.title, kind: "removed", changes: [{ key: row.id, label: "Séance absente du dépôt", kind: "remove", base: row.data.title, local: row.data.title, incoming: null }] });148  const flat = [...course, ...out.flatMap((s) => s.changes)];149  return {150    sourceHash: incoming.sourceHash, course, sessions: out.sort((a, b) => a.id.localeCompare(b.id)),151    counts: {152      added: out.filter((s) => s.kind === "added").length, removed: out.filter((s) => s.kind === "removed").length, changed: out.filter((s) => s.kind === "changed").length,153      unchanged: out.filter((s) => s.kind === "unchanged").length, updates: flat.filter((c) => c.kind === "update").length, conflicts: flat.filter((c) => c.kind === "conflict").length,154    },155  };156}157export const diffIsEmpty = (d: ImportDiff) => !d.course.length && d.sessions.every((s) => s.kind === "unchanged");158159/* ---- Prepare (read the repository, store the result, show the diff) ---- */160161export interface ImportRecord { id: string; source: string; sourceHash: string; status: "pending" | "applied" | "discarded"; warnings: string[]; summary: string | null; createdAt: string; createdBy: string; appliedAt: string | null }162interface RawImport { id: string; source: string; source_hash: string; incoming_sha: string; warnings: string; status: ImportRecord["status"]; summary: string | null; created_at: string; created_by: string; applied_at: string | null }163const toRecord = (r: RawImport): ImportRecord => ({ id: r.id, source: r.source, sourceHash: r.source_hash, status: r.status, warnings: JSON.parse(r.warnings) as string[], summary: r.summary, createdAt: r.created_at, createdBy: r.created_by, appliedAt: r.applied_at });164export const listImports = (limit = 20) => all<RawImport>("SELECT * FROM imports ORDER BY created_at DESC LIMIT ?", limit).map(toRecord);165166/**167 * Reads a checkout of the course repository and records what it contains as a pending import. Nothing of168 * the working copy changes here. Incomplete sessions are tolerated: they come back as warnings.169 */170export async function prepareImport(repoDir: string, label: string, actor: string): Promise<{ record: ImportRecord; diff: ImportDiff }> {171  if (!isBootstrapped()) await bootstrap(actor);172  const id = `imp_${randomId(6)}`, out = join(env.dataDir, "work", id);173  await mkdir(out, { recursive: true });174  try {175    let outcome;176    try { outcome = await importCourse({ repo: repoDir, out, publication: {} }); }177    catch (e) { throw new ApiError(422, "unreadable_source", `Le dépôt du cours n'a pas pu être lu : ${e instanceof Error ? e.message.slice(0, 300) : "erreur inconnue"}`); }178    const { incoming, warnings } = await readSnapshot(out);179    const notes = [...outcome.report.warnings, ...outcome.report.sessions.flatMap((s) => s.warnings.map((w) => `${s.id} — ${w}`)), ...warnings];180    tx(() => {181      run("UPDATE imports SET status = 'discarded' WHERE status = 'pending'"); // one pending import at a time182      run("INSERT INTO imports (id, source, source_hash, incoming_sha, warnings, status, created_at, created_by) VALUES (?, ?, ?, ?, ?, 'pending', ?, ?)", id, label.slice(0, 200), incoming.sourceHash, putJson(incoming), JSON.stringify(notes.slice(0, 500)), now(), actor);183      audit("import.prepared", { actor, target: `import:${id}`, detail: { source: label, sourceHash: incoming.sourceHash, sessions: incoming.sessions.length, warnings: notes.length } });184    });185    log("info", "import.prepared", { id, source: label, sessions: incoming.sessions.length, warnings: notes.length });186    return { record: getImport(id), diff: diffIncoming(incoming) };187  } finally { await rm(out, { recursive: true, force: true }); }188}189190export function getImport(id: string): ImportRecord {191  const r = get<RawImport>("SELECT * FROM imports WHERE id = ?", id);192  if (!r) throw new ApiError(404, "not_found", "Importation introuvable.");193  return toRecord(r);194}195const incomingOf = (id: string) => getJson<Incoming>(get<{ incoming_sha: string }>("SELECT incoming_sha FROM imports WHERE id = ?", id)?.incoming_sha);196export function importDiff(id: string): ImportDiff {197  const inc = incomingOf(id);198  if (!inc) throw new ApiError(404, "not_found", "Importation introuvable.");199  return diffIncoming(inc);200}201202export function discardImport(id: string, actor: string): void {203  const r = run("UPDATE imports SET status = 'discarded' WHERE id = ? AND status = 'pending'", id);204  if (Number(r.changes)) audit("import.discarded", { actor, target: `import:${id}` });205}206207/* ---- Apply ---- */208209/**210 * Applies a pending import to the working copy. `decisions` maps the key of each conflict to "local" (keep211 * the studio's value — the default) or "incoming" (take the repository's). Everything lands as a draft.212 */213export function applyImport(id: string, decisions: Record<string, Decision>, actor: string): { applied: number; kept: number; added: number; diff: ImportDiff } {214  return tx(() => {215    const record = getImport(id), incoming = incomingOf(id)!;216    if (record.status !== "pending") throw new ApiError(409, "not_pending", "Cette importation a déjà été appliquée ou abandonnée.");217    const diff = diffIncoming(incoming);218    const pick = (c: FieldChange | undefined): boolean => Boolean(c) && (c!.kind === "update" || c!.kind === "add" || (c!.kind === "conflict" && decisions[c!.key] === "incoming"));219    let applied = 0, kept = 0, added = 0;220    const count = (c: FieldChange | undefined) => { if (!c) return; if (pick(c)) applied++; else if (c.kind === "conflict") kept++; };221222    const cur = getCourseRow(), data = { ...cur.data };223    for (const key of ["course", "author", "parts"] as const) {224      const c = diff.course.find((x) => x.key === `course.${key}`);225      count(c);226      if (!pick(c)) continue;227      if (key === "course") data.course = { ...incoming.course.course, license: cur.data.course.license };228      else if (key === "author") data.author = incoming.course.author;229      else data.parts = incoming.course.parts;230    }231    data.import = { sourceHash: incoming.sourceHash, files: incoming.files };232    writeCourse(data, incoming.course, actor);233234    const rows = new Map(listSessions().map((s) => [s.id, s])), taken = new Set([...rows.values()].flatMap((s) => [s.data.slug, ...s.data.aliases]));235    for (const inc of incoming.sessions) {236      const row = rows.get(inc.id), sd = diff.sessions.find((s) => s.id === inc.id);237      if (!row) {238        let slug = inc.slug;239        for (let i = 2; taken.has(slug); i++) slug = `${inc.slug}-${i}`;240        const aliases = inc.aliases.filter((a) => !taken.has(a) && a !== slug);241        [slug, ...aliases].forEach((s) => taken.add(s));242        const next: SessionData = { ...inc.base, number: inc.number, slug, aliases, source: inc.source, revisions: [] };243        writeSession(inc.id, { state: Object.keys(inc.sections).length ? "draft" : "planned", data: next, base: inc.base }, actor);244        for (const [key, s] of Object.entries(inc.sections)) writeSection(inc.id, key as SectionKey, { sha256: s!.sha256, count: s!.count, baseSha: s!.sha256, visibility: "private" }, actor);245        added++; applied++;246        continue;247      }248      const next: SessionData = { ...row.data, source: inc.source };249      for (const f of IMPORT_FIELDS) {250        const c = sd?.changes.find((x) => x.key === `${inc.id}.${f}`);251        count(c);252        if (pick(c)) (next as unknown as Record<string, unknown>)[f] = inc.base[f];253      }254      const local = new Map(listSections(inc.id).map((s) => [s.key, s]));255      let hasMaterial = local.size > 0;256      for (const key of SECTION_KEYS) {257        const l = local.get(key), i = inc.sections[key], c = sd?.changes.find((x) => x.key === `${inc.id}.section.${key}`);258        count(c);259        if (i && (!l || pick(c))) { writeSection(inc.id, key, { sha256: i.sha256, count: i.count, baseSha: i.sha256, visibility: l?.visibility ?? "private" }, actor); hasMaterial = true; }260        else if (l && (l.baseSha ?? null) !== (i?.sha256 ?? null)) run("UPDATE sections SET base_sha256 = ? WHERE session_id = ? AND key = ?", i?.sha256 ?? null, inc.id, key); // the local copy is kept; remember what the source says now261      }262      const changed = !same(next, row.data) || !same(row.base, inc.base) || !row.inSource || (row.state === "planned" && hasMaterial);263      if (changed) writeSession(inc.id, { state: row.state === "planned" && hasMaterial ? "draft" : row.state, data: next, base: inc.base }, actor);264    }265    const seen = new Set(incoming.sessions.map((s) => s.id));266    for (const row of rows.values()) if (!seen.has(row.id) && row.inSource) writeSession(row.id, { state: row.state, data: row.data, base: row.base, inSource: false }, actor);267268    try { workingManifest(); }269    catch (e) {270      const issue = (e as { issues?: { message: string }[] }).issues?.[0]?.message ?? (e instanceof Error ? e.message : "manifeste invalide");271      throw new ApiError(409, "invalid_result", `Importation refusée : le cours deviendrait incohérent (${issue}). Rien n'a été modifié.`);272    }273    const summary = `${applied} changement${applied > 1 ? "s" : ""} appliqué${applied > 1 ? "s" : ""}, ${added} séance${added > 1 ? "s" : ""} ajoutée${added > 1 ? "s" : ""}, ${kept} conflit${kept > 1 ? "s" : ""} résolu${kept > 1 ? "s" : ""} en gardant la version du studio`;274    run("UPDATE imports SET status = 'applied', applied_at = ?, summary = ? WHERE id = ?", now(), summary, id);275    audit("import.applied", { actor, target: `import:${id}`, detail: { source: record.source, sourceHash: incoming.sourceHash, applied, kept, added, decisions } });276    return { applied, kept, added, diff };277  });278}279280/** Figure bytes by hash, for the content routes (only called after the permission check). */281export const figureBytes = (hash: string) => getBlob(hash);282
Files main
Menu

Theme