Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Vision8 * File : server/src/retention.ts9 * Module : server10 * 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// Rétention et capacité : purge des plus anciens segments non protégés, seuils, garde-fous disque.43import fs from 'node:fs';44import path from 'node:path';45import type { Config } from './config.ts';46import { addEvent, getSetting, setSetting, type DB } from './db.ts';47import { logger } from './log.ts';48import { deleteArchiveFile, diskStats, verifyVolume } from './storage.ts';4950const log = logger('retention');51const GB = 1024 ** 3;5253export type RetentionSettings = { days: number; maxArchiveGB: number };5455export function retentionSettings(cfg: Config, db: DB): RetentionSettings {56 const s = getSetting<Partial<RetentionSettings>>(db, 'retention', {});57 return {58 days: clamp(Number(s.days ?? cfg.retention.days), 1, 3650),59 maxArchiveGB: clamp(Number(s.maxArchiveGB ?? cfg.retention.maxArchiveGB), 1, 100000),60 };61}62const clamp = (v: number, a: number, b: number) => (Number.isFinite(v) ? Math.max(a, Math.min(b, v)) : a);6364export function archiveBytes(db: DB): number {65 const r = db.prepare("SELECT COALESCE(SUM(size_bytes), 0) AS b FROM segments WHERE state IN ('archived','recovered')").get() as { b: number };66 return r.b;67}6869function purge(cfg: Config, db: DB, rows: { id: number; rel_path: string; size_bytes: number; start_ms: number; camera_id: string }[]): number {70 let freed = 0;71 for (const r of rows) {72 try {73 deleteArchiveFile(cfg, r.rel_path);74 db.prepare('DELETE FROM segments WHERE id = ?').run(r.id);75 freed += r.size_bytes;76 } catch (e: any) {77 log.error('purge refusée', { rel: r.rel_path, err: String(e?.message || e) });78 }79 }80 return freed;81}8283export type RetentionReport = { purgedSegments: number; purgedBytes: number; level: 'ok' | 'warning' | 'high' | 'critical'; suspended: boolean };8485/** Une passe de rétention. Ne supprime rien si l'identité du volume n'est pas confirmée. */86export function runRetention(cfg: Config, db: DB): RetentionReport {87 const out: RetentionReport = { purgedSegments: 0, purgedBytes: 0, level: 'ok', suspended: getSetting(db, 'recording_suspended', false) };88 if (!verifyVolume(cfg).ok) return out;89 const rs = retentionSettings(cfg, db);90 const sel = "SELECT id, rel_path, size_bytes, start_ms, camera_id FROM segments WHERE protected = 0 AND state IN ('archived','recovered')";91 let oldestPurged: number | null = null;92 let newestPurged: number | null = null;93 const account = (rows: any[]) => {94 if (!rows.length) return;95 out.purgedBytes += purge(cfg, db, rows);96 out.purgedSegments += rows.length;97 oldestPurged = Math.min(oldestPurged ?? Infinity, rows[0].start_ms);98 newestPurged = Math.max(newestPurged ?? 0, rows[rows.length - 1].start_ms);99 };100101 // 1. âge102 const cutoff = Date.now() - rs.days * 86400000;103 for (;;) {104 const rows = db.prepare(`${sel} AND start_ms < ? ORDER BY start_ms LIMIT 500`).all(cutoff) as any[];105 if (!rows.length) break;106 account(rows);107 }108 // lignes « missing » périmées109 db.prepare("DELETE FROM segments WHERE state = 'missing' AND start_ms < ?").run(cutoff);110111 // 2. quota d'archive et marge de sécurité du disque112 const quota = rs.maxArchiveGB * GB;113 // on ne supprime que le strict nécessaire, du plus ancien au plus récent114 const over = () => archiveBytes(db) > quota || diskStats(cfg.archiveDir).freeBytes < cfg.retention.minFreeGB * GB;115 for (let i = 0; i < 20000 && over(); i++) {116 const rows = db.prepare(`${sel} ORDER BY start_ms LIMIT 1`).all() as any[];117 if (!rows.length) break;118 account(rows);119 }120 if (out.purgedSegments) {121 addEvent(db, {122 type: 'retention_purge',123 severity: 'info',124 message: `Purge de ${out.purgedSegments} segment(s), ${(out.purgedBytes / GB).toFixed(2)} Go libérés`,125 data: { segments: out.purgedSegments, bytes: out.purgedBytes, fromMs: oldestPurged, toMs: newestPurged },126 });127 cleanEmptyDirs(cfg.archiveDir, cfg.archiveDir);128 }129130 // 3. seuils 80 / 90 / 95 % du quota, et garde-fou « disque critique »131 const used = archiveBytes(db);132 const free = diskStats(cfg.archiveDir).freeBytes;133 const pct = (used / quota) * 100;134 out.level = pct >= 95 ? 'critical' : pct >= 90 ? 'high' : pct >= 80 ? 'warning' : 'ok';135 const prevLevel = getSetting<string>(db, 'storage_level', 'ok');136 if (prevLevel !== out.level) {137 setSetting(db, 'storage_level', out.level);138 if (out.level !== 'ok') addEvent(db, { type: 'storage_threshold', severity: out.level === 'warning' ? 'warning' : 'critical', message: `Archive à ${pct.toFixed(0)} % du quota (${rs.maxArchiveGB} Go)`, data: { pct } });139 }140 const mustSuspend = free < cfg.retention.criticalFreeGB * GB;141 if (mustSuspend && !out.suspended) {142 setSetting(db, 'recording_suspended', true);143 out.suspended = true;144 addEvent(db, { type: 'recording_suspended', severity: 'critical', message: `Espace disque critique (${(free / GB).toFixed(1)} Go libres) : enregistrement arrêté pour protéger le disque système` });145 } else if (!mustSuspend && out.suspended && free > (cfg.retention.criticalFreeGB + 5) * GB) {146 setSetting(db, 'recording_suspended', false);147 out.suspended = false;148 addEvent(db, { type: 'recording_unsuspended', severity: 'info', message: 'Espace disque rétabli : enregistrement repris' });149 }150 return out;151}152153function cleanEmptyDirs(dir: string, root: string): void {154 let entries: fs.Dirent[] = [];155 try {156 entries = fs.readdirSync(dir, { withFileTypes: true });157 } catch {158 return;159 }160 for (const e of entries) if (e.isDirectory()) cleanEmptyDirs(path.join(dir, e.name), root);161 if (dir !== root && path.dirname(dir) !== root) {162 try {163 if (fs.readdirSync(dir).length === 0) fs.rmdirSync(dir);164 } catch {165 /* rien */166 }167 }168}169170/** Rotation simple des journaux PM2 de l'application (le cluster n'a pas pm2-logrotate) : 20 Mo, un exemplaire précédent. */171export function rotateLogs(extra?: string): void {172 const dir = path.join(process.env.HOME || '', '.pm2', 'logs');173 let files: string[] = [];174 try {175 files = fs.readdirSync(dir).filter((f) => /^vision-(core|api|backup)-(out|error)(-\d+)?\.log$/.test(f));176 } catch {177 return;178 }179 const all = files.map((f) => path.join(dir, f));180 if (extra) all.push(extra);181 for (const p of all) {182 try {183 if (fs.statSync(p).size > 20 * 1024 * 1024) {184 fs.copyFileSync(p, p + '.1');185 fs.truncateSync(p, 0);186 }187 } catch {188 /* rien */189 }190 }191}192193/** Ménage des dossiers annexes gérés (exports expirés, quarantaine, cache de lecture, vieilles métriques). */194export function housekeeping(cfg: Config, db: DB): void {195 const now = Date.now();196 const expired = db.prepare('SELECT id, file_name FROM exports WHERE expires_ms IS NOT NULL AND expires_ms < ?').all(now) as { id: string; file_name: string | null }[];197 for (const e of expired) {198 if (/^[a-f0-9]{24}$/.test(e.id)) {199 try {200 fs.unlinkSync(path.join(cfg.exportsDir, `${e.id}.mp4`));201 } catch {202 /* rien */203 }204 }205 db.prepare('DELETE FROM exports WHERE id = ?').run(e.id);206 }207 rotateLogs(path.join(cfg.dataDir, 'logs', 'core.log'));208 pruneOld(cfg.quarantineDir, 7 * 86400000);209 pruneOld(cfg.eventsDir, 30 * 86400000);210 pruneCache(cfg.cacheDir, cfg.retention.playbackCacheGB * GB);211 db.prepare('DELETE FROM metrics WHERE ts_ms < ?').run(now - 14 * 86400000);212 db.prepare('DELETE FROM events WHERE ts_ms < ?').run(now - 365 * 86400000);213 db.prepare('DELETE FROM audit_log WHERE ts_ms < ?').run(now - 365 * 86400000);214 try {215 db.prepare('DELETE FROM push_devices WHERE session_id NOT IN (SELECT id FROM sessions WHERE revoked_ms IS NULL AND expires_ms > ?)').run(now);216 } catch {217 /* table absente avant la migration 002 */218 }219 db.prepare('DELETE FROM sessions WHERE expires_ms < ? OR (revoked_ms IS NOT NULL AND revoked_ms < ?)').run(now - 7 * 86400000, now - 7 * 86400000);220}221222function pruneOld(dir: string, maxAgeMs: number): void {223 let entries: fs.Dirent[] = [];224 try {225 entries = fs.readdirSync(dir, { withFileTypes: true });226 } catch {227 return;228 }229 for (const e of entries) {230 const p = path.join(dir, e.name);231 if (e.isDirectory()) pruneOld(p, maxAgeMs);232 else {233 try {234 if (Date.now() - fs.statSync(p).mtimeMs > maxAgeMs) fs.unlinkSync(p);235 } catch {236 /* rien */237 }238 }239 }240}241242export function pruneCache(dir: string, maxBytes: number): void {243 let files: { p: string; size: number; atime: number }[] = [];244 try {245 files = fs246 .readdirSync(dir)247 .filter((f) => /^\d+(\.h264)?\.mp4$/.test(f) || f.endsWith('.tmp'))248 .map((f) => {249 const p = path.join(dir, f);250 const s = fs.statSync(p);251 return { p, size: s.size, atime: Math.max(s.atimeMs, s.mtimeMs) };252 });253 } catch {254 return;255 }256 let total = files.reduce((a, f) => a + f.size, 0);257 files.sort((a, b) => a.atime - b.atime);258 for (const f of files) {259 const stale = Date.now() - f.atime > 6 * 3600000;260 if (total <= maxBytes && !stale) continue;261 try {262 fs.unlinkSync(f.p);263 total -= f.size;264 } catch {265 /* rien */266 }267 }268}269