faces: очередь проверки лиц и страница «Сканер лиц»

Вынести распознавание лиц с загрузки в фоновую очередь:
- таблица face_scan_jobs (pending/processing/done/error) + воркер
  createFaceScanWorker (FOR UPDATE SKIP LOCKED, backoff, retry, очистка хвоста)
- дедупликация активных задач частичным уникальным индексом, ON CONFLICT
  обновляет photo_path
- scanFacesForPhoto теперь бросает ошибку вместо возврата null
- ручные эндпоинты scan-unscanned/scan-faces/rescan только ставят задачи
  и отвечают { queued, skipped, total }

Уведомления и SSE:
- face.scan.done (по умолчанию выключено), face.recognized, face.scan.error
- notifyFaceScan определяет филиал по источнику, SSE face_scan_status
  обновляет открытый вьюер лиц

Новая админ-страница «Сканер лиц» (faces.html, faces.js):
- мониторинг очереди и воркера, библиотека лиц, ошибки, аудит
- действия: wake, retry, clear, rematch, scan-unscanned
- GET /api/faces/monitor, POST /api/faces/queue/{wake,clear}

Обновлены AGENTS.md, db/init.sql, db/migration.sql (сид notify_face_*),
public/js/{groups,journal,settings}.js, public/admin.js, public/settings.html
This commit is contained in:
dev
2026-10-11 00:37:50 +03:00
parent 22466629c8
commit 8137fd35d5
12 changed files with 1480 additions and 72 deletions
+186 -1
View File
@@ -1726,4 +1726,189 @@ function createNoteTitleWorker({ pool, getSetting, logAudit, aiUrl, model, defau
return { start, stop, notify, getInfo };
}
module.exports = { createEntryAutoChecker, createPhotoEnhanceWorker, createLessonReportChecker, createFeedbackWriter, createNoteTitleWorker, lessonTopicPosition };
const FACE_MAX_ATTEMPTS = Math.max(1, parseInt(process.env.FACE_SCAN_MAX_ATTEMPTS || '3', 10) || 3);
const FACE_KEEP_DONE_MS = Math.max(3600000, parseInt(process.env.FACE_SCAN_KEEP_DONE_MS || '604800000', 10) || 604800000);
function createFaceScanWorker({ pool, getSetting, logAudit, bus, scan, onDone }) {
const runScan = scan || (async () => { throw new Error('scan не передан воркеру'); });
let started = false;
let stopped = false;
let idleMs = IDLE_MIN_MS;
let wake = null;
let processing = false;
let currentId = null;
let startedAt = null;
let sincePrune = 0;
const stats = { scanned: 0, faces: 0, matched: 0, errors: 0, retries: 0, last_at: null, last_error: null };
function sleep(ms) {
return new Promise((resolve) => {
const t = setTimeout(() => { wake = null; resolve(); }, ms);
wake = () => { clearTimeout(t); wake = null; resolve(); };
});
}
function notify() {
if (wake) wake();
if (bus) bus.publish();
}
if (bus) bus.subscribe(() => notify());
async function isEnabled() {
return String(await getSetting('face_id_enabled', 'false')) === 'true';
}
async function claimNext() {
const client = await pool.connect();
try {
await client.query('BEGIN');
const { rows } = await client.query(
`SELECT id, source_type, source_id, photo_path, attempts
FROM face_scan_jobs
WHERE status = 'pending'
ORDER BY id ASC LIMIT 1 FOR UPDATE SKIP LOCKED`
);
if (!rows.length) {
await client.query('COMMIT');
return null;
}
await client.query(
`UPDATE face_scan_jobs SET status = 'processing', attempts = attempts + 1, updated_at = now() WHERE id = $1`,
[rows[0].id]
);
await client.query('COMMIT');
return rows[0];
} catch (e) {
await client.query('ROLLBACK').catch(() => {});
throw e;
} finally {
client.release();
}
}
function pruneFinished() {
return pool.query(
`DELETE FROM face_scan_jobs
WHERE status IN ('done', 'error') AND updated_at < now() - ($1 || ' milliseconds')::interval`,
[String(FACE_KEEP_DONE_MS)]
);
}
async function finish(row, status, result, error) {
const faces = status === 'done' ? Number(result && result.faces) || 0 : 0;
const matched = status === 'done' ? Number(result && result.matched) || 0 : 0;
const names = status === 'done' ? String((result && result.names) || '').slice(0, 500) : '';
await pool.query(
`UPDATE face_scan_jobs
SET status = $2, faces_found = $3, faces_matched = $4, matched_names = $5,
error = $6, updated_at = now()
WHERE id = $1`,
[row.id, status, faces, matched, names || null, error ? String(error).slice(0, 1000) : null]
);
if (status === 'done') {
stats.scanned++;
stats.faces += faces;
stats.matched += matched;
stats.last_at = new Date().toISOString();
} else {
stats.errors++;
stats.last_error = error ? String(error).slice(0, 300) : null;
}
if (onDone) await onDone({ row, status, faces, matched, names, error: error || null });
}
async function processOne(row) {
let result;
try {
result = await runScan({ sourceType: row.source_type, sourceId: row.source_id, photoPath: row.photo_path });
} catch (e) {
const message = String(e && e.message ? e.message : e).slice(0, 500);
const tries = (Number(row.attempts) || 0) + 1;
if (tries < FACE_MAX_ATTEMPTS) {
await pool.query(`UPDATE face_scan_jobs SET status = 'pending', error = $2, updated_at = now() WHERE id = $1`, [row.id, message]);
stats.retries++;
if (logAudit) await logAudit(null, 'face.scan.retry', { id: row.id, source_type: row.source_type, source_id: row.source_id, attempt: tries, error: message });
return false;
}
await finish(row, 'error', null, message);
if (logAudit) await logAudit(null, 'face.scan.error', { id: row.id, source_type: row.source_type, source_id: row.source_id, attempts: tries, error: message });
return true;
}
await finish(row, 'done', result, null);
return true;
}
async function loop() {
while (!stopped) {
let row = null;
try {
if (!(await isEnabled())) {
await sleep(IDLE_MAX_MS);
continue;
}
row = await claimNext();
} catch (e) {
console.error('Face scan claim error:', e.message);
await sleep(IDLE_MAX_MS);
continue;
}
if (!row) {
await sleep(idleMs);
idleMs = Math.min(idleMs * 2, IDLE_MAX_MS);
continue;
}
idleMs = IDLE_MIN_MS;
processing = true;
currentId = row.id;
let ok = true;
try {
ok = await processOne(row);
} catch (e) {
console.error('Face scan process error:', e.message);
} finally {
processing = false;
currentId = null;
}
if (!ok) await sleep(IDLE_MAX_MS);
if (++sincePrune >= 50) {
sincePrune = 0;
pruneFinished().catch(e => console.error('Face scan prune error:', e.message));
}
}
}
function resetStale() {
return pool.query(`UPDATE face_scan_jobs SET status = 'pending', updated_at = now() WHERE status = 'processing'`);
}
function start() {
if (started) return;
started = true;
startedAt = Date.now();
resetStale()
.catch(e => console.error('Face scan reset error:', e.message))
.finally(() => { loop().catch(e => console.error('Face scan loop error:', e.message)); });
}
function stop() {
stopped = true;
notify();
}
function getInfo() {
return {
started_at: startedAt ? new Date(startedAt).toISOString() : null,
uptime_ms: startedAt ? Date.now() - startedAt : 0,
processing,
current_id: currentId,
config: { idle_min_ms: IDLE_MIN_MS, idle_max_ms: IDLE_MAX_MS, max_attempts: FACE_MAX_ATTEMPTS, keep_done_ms: FACE_KEEP_DONE_MS },
...stats,
};
}
return { start, stop, notify, getInfo };
}
module.exports = { createEntryAutoChecker, createPhotoEnhanceWorker, createLessonReportChecker, createFeedbackWriter, createNoteTitleWorker, createFaceScanWorker, lessonTopicPosition };