Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Vision8 * File : server/src/cli/backup.ts9 * Module : cli10 * Repository : https://git.spboucher.ai/maclustr-vision11 * Project Website : https://camera.spboucher.ai12 * Created : 2026-11-3013 * Last Modified : 2026-11-3014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Sauvegarde et restauration du catalogue (API de backup SQLite, cohérente même pendant l'enregistrement).43// Usage : backup.ts create | list | verify <fichier> | restore <fichier>44import fs from 'node:fs';45import path from 'node:path';46import { backup, DatabaseSync } from 'node:sqlite';47import { loadConfig } from '../config.ts';48import { openDb } from '../db.ts';4950const cfg = loadConfig();51const dir = path.join(cfg.dataDir, 'backups');52fs.mkdirSync(dir, { recursive: true, mode: 0o700 });53const KEEP = 14;5455function verify(file: string): { ok: boolean; detail: string } {56 try {57 const db = new DatabaseSync(file, { readOnly: true });58 const r = db.prepare('PRAGMA integrity_check').get() as Record<string, string>;59 const seg = db.prepare('SELECT COUNT(*) AS n FROM segments').get() as { n: number };60 const mig = db.prepare('SELECT COUNT(*) AS n FROM schema_migrations').get() as { n: number };61 db.close();62 const res = Object.values(r)[0];63 return { ok: res === 'ok', detail: `integrity=${res} segments=${seg.n} migrations=${mig.n}` };64 } catch (e: any) {65 return { ok: false, detail: String(e?.message || e) };66 }67}6869const cmd = process.argv[2];70if (cmd === 'create') {71 const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z');72 const out = path.join(dir, `vision-${stamp}.db`);73 const src = openDb(cfg.dbPath);74 await backup(src, out);75 src.close();76 fs.chmodSync(out, 0o600);77 const v = verify(out);78 if (!v.ok) {79 console.error(`sauvegarde invalide : ${v.detail}`);80 process.exit(1);81 }82 const all = fs.readdirSync(dir).filter((f) => /^vision-\d{8}T\d{6}Z\.db$/.test(f)).sort();83 for (const old of all.slice(0, Math.max(0, all.length - KEEP))) fs.unlinkSync(path.join(dir, old));84 console.log(`sauvegarde ${out} (${(fs.statSync(out).size / 1e6).toFixed(2)} Mo) · ${v.detail}`);85} else if (cmd === 'list') {86 for (const f of fs.readdirSync(dir).filter((x) => x.endsWith('.db')).sort()) console.log(f, `${(fs.statSync(path.join(dir, f)).size / 1e6).toFixed(2)} Mo`);87} else if (cmd === 'verify' && process.argv[3]) {88 const v = verify(path.resolve(process.argv[3]));89 console.log(v.ok ? `ok · ${v.detail}` : `INVALIDE · ${v.detail}`);90 process.exit(v.ok ? 0 : 1);91} else if (cmd === 'restore' && process.argv[3]) {92 // À exécuter services arrêtés (scripts/restore.sh s'en charge). L'ancienne base est conservée à côté.93 const file = path.resolve(process.argv[3]);94 const v = verify(file);95 if (!v.ok) {96 console.error(`refus : sauvegarde invalide (${v.detail})`);97 process.exit(1);98 }99 const keep = `${cfg.dbPath}.avant-restauration-${Date.now()}`;100 if (fs.existsSync(cfg.dbPath)) fs.renameSync(cfg.dbPath, keep);101 for (const ext of ['-wal', '-shm']) {102 try {103 fs.unlinkSync(cfg.dbPath + ext);104 } catch {105 /* rien */106 }107 }108 fs.copyFileSync(file, cfg.dbPath);109 fs.chmodSync(cfg.dbPath, 0o600);110 console.log(`base restaurée depuis ${file} · ${v.detail}\nancienne base conservée : ${keep}\nau redémarrage, vision-core réconcilie le catalogue avec les fichiers présents.`);111} else {112 console.error('usage : backup.ts create | list | verify <fichier> | restore <fichier>');113 process.exit(2);114}115