Files
WhatIDo/worker.js
T
dev ef4d7cc472 Тесты и опросы: генерация ИИ, критерии оценки, версия 2.0
- ИИ-генерация черновиков тестов (lib/quiz-ai.js, quiz-ai-jobs, quiz-ai.selftest.js)
- Критерии оценки (quiz_grade_scales/quiz_grade_ranges, lib/quiz-grades.js, public/js/grade-scales.js)
- Версия 2.0 формата бэкапа, добавление таблиц тестов в BACKUP_TABLES
- Обновление AGENTS.md под новый функционал тестов/опросов
2026-12-02 14:27:57 +03:00

2580 lines
93 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const IDLE_MIN_MS = 2000;
const IDLE_MAX_MS = 60000;
const REQUEST_TIMEOUT_MS = parseInt(process.env.AI_REQUEST_TIMEOUT_MS || '120000', 10);
const MAX_INPUT_CHARS = 2000;
const MIN_TEXT_CHARS = 4;
const crypto = require('crypto');
const { textDiff, FIELD_LABELS } = require('./diff');
const { saveFeedbackVersion } = require('./lib/feedback-versions');
const { aiHttpErrorFromResponse } = require('./lib/ai-errors');
const PHOTO_MAX_ATTEMPTS = 3;
const PHOTO_AI_TIMEOUT_MS = Math.max(1000, parseInt(process.env.PHOTO_AI_TIMEOUT_MS || '300000', 10) || 300000);
const PHOTO_AI_FACE_TIMEOUT_MS = Math.max(PHOTO_AI_TIMEOUT_MS, parseInt(process.env.PHOTO_AI_FACE_TIMEOUT_MS || '600000', 10) || 600000);
const PHOTO_AI_DEFAULT_MODEL = 'x2plus';
const PHOTO_AI_DEFAULT_FACE_MODEL = String(process.env.PHOTO_AI_FACE_MODEL || 'gfpgan').trim() || 'gfpgan';
const PHOTO_AI_DEFAULT_STRENGTH = 0.7;
const PHOTO_AI_ACTIONS = new Set(['ai', 'ai_face', 'ai_upscale']);
const PHOTO_SOFT_MAX_RETRIES = Math.max(1, parseInt(process.env.PHOTO_AI_SOFT_MAX_RETRIES || '60', 10) || 60);
const PHOTO_SOFT_BACKOFF_MS = Math.max(1000, parseInt(process.env.PHOTO_AI_SOFT_BACKOFF_MS || '10000', 10) || 10000);
const PHOTO_SOFT_BACKOFF_MAX_MS = Math.max(PHOTO_SOFT_BACKOFF_MS, parseInt(process.env.PHOTO_AI_SOFT_BACKOFF_MAX_MS || '300000', 10) || 300000);
function isTimeoutFailure(e) {
const name = e && e.name;
return name === 'TimeoutError' || name === 'AbortError';
}
function isSoftStatus(status) {
return status === 408 || status === 425 || status === 429 || status >= 500;
}
function failureReason(e) {
const parts = [];
let cur = e;
for (let i = 0; cur && i < 5; i++) {
const code = cur.code || (cur.errors && cur.errors.code);
if (code && !parts.includes(code)) parts.push(code);
cur = cur.cause;
}
return parts.join(', ');
}
function softFailure(message, e) {
const reason = e ? failureReason(e) || (e.message || '') : '';
const err = new Error(reason ? `${message} (${reason})` : message);
err.soft = true;
return err;
}
function createPhotoEnhanceWorker({ pool, getSetting, logAudit, invalidateEntries, sharp, photoAiUrl, storage, bus, notifyEvent, faceTimeoutMs, defaultModel, defaultFaceModel }) {
const AI_URL = photoAiUrl || process.env.PHOTO_AI_URL || '';
const IDLE_MIN = 2000;
const IDLE_MAX = 30000;
const AI_TIMEOUT_MS = PHOTO_AI_TIMEOUT_MS;
const AI_FACE_TIMEOUT_MS = Math.max(AI_TIMEOUT_MS, parseInt(faceTimeoutMs, 10) || PHOTO_AI_FACE_TIMEOUT_MS);
const DEFAULT_MODEL = String(defaultModel || PHOTO_AI_DEFAULT_MODEL).trim() || PHOTO_AI_DEFAULT_MODEL;
const DEFAULT_FACE_MODEL = String(defaultFaceModel || PHOTO_AI_DEFAULT_FACE_MODEL).trim() || PHOTO_AI_DEFAULT_FACE_MODEL;
async function sendNotification(job, payload) {
if (!notifyEvent) return;
try {
await notifyEvent(job, payload);
} catch (e) {
console.error('Photo worker notification failed:', e.message);
}
}
let started = false;
let stopped = false;
let idleMs = IDLE_MIN;
let wake = null;
let processing = false;
let currentId = null;
let startedAt = null;
const stats = { jobs: 0, done: 0, errors: 0, soft_retries: 0, last_at: null, last_error: null };
const softTries = new Map();
const CONFIG = {
idle_min_ms: IDLE_MIN,
idle_max_ms: IDLE_MAX,
ai_timeout_ms: AI_TIMEOUT_MS,
face_timeout_ms: AI_FACE_TIMEOUT_MS,
max_attempts: PHOTO_MAX_ATTEMPTS,
soft_max_retries: PHOTO_SOFT_MAX_RETRIES,
soft_backoff_ms: PHOTO_SOFT_BACKOFF_MS,
soft_backoff_max_ms: PHOTO_SOFT_BACKOFF_MAX_MS,
ai_url: AI_URL,
default_model: DEFAULT_MODEL,
face_model: DEFAULT_FACE_MODEL,
};
function sleep(ms) {
return new Promise((resolve) => {
const t = setTimeout(() => { wake = null; resolve(); }, ms);
wake = () => { clearTimeout(t); wake = null; resolve(); };
});
}
function wakeLocal() {
if (wake) wake();
}
function notify() {
wakeLocal();
if (bus) bus.publish();
}
if (bus) bus.subscribe(wakeLocal);
async function isEnabled() {
const v = await getSetting('photo_worker_enabled', 'true');
return String(v) !== 'false';
}
async function claimNext() {
const client = await pool.connect();
try {
await client.query('BEGIN');
const { rows } = await client.query(
`SELECT j.id, j.entry_id, j.group_photo_id, j.action, j.params
FROM photo_jobs j
WHERE j.status = 'pending'
ORDER BY j.id ASC LIMIT 1 FOR UPDATE SKIP LOCKED`
);
if (!rows.length) {
await client.query('COMMIT');
return null;
}
await client.query(`UPDATE photo_jobs SET status = 'processing' 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();
}
}
async function enhanceWithSharp(srcKey, params) {
if (!sharp) throw new Error('sharp недоступен на сервере');
const p = params || {};
const clamp = (v, min, max, def) => {
const n = parseFloat(v);
return Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : def;
};
const brightness = clamp(p.brightness, 10, 300, 100);
const contrast = clamp(p.contrast, 10, 300, 100);
const saturate = clamp(p.saturate, 0, 300, 100);
const sharpAmt = clamp(p.sharp, 0, 100, 0);
const denoise = clamp(p.denoise, 0, 100, 0);
const srcPath = await storage.localize(srcKey);
if (!srcPath) throw new Error('Файл фото не найден');
let pipeline = sharp(srcPath).rotate();
if (denoise > 0) pipeline = pipeline.median(denoise > 70 ? 5 : 3);
pipeline = pipeline.modulate({ brightness: brightness / 100, saturation: saturate / 100 });
if (contrast !== 100) {
const a = contrast / 100;
pipeline = pipeline.linear(a, 128 * (1 - a));
}
if (sharpAmt > 0) {
pipeline = pipeline.sharpen({ sigma: 0.5 + (sharpAmt / 100) * 1.5, m1: 0, m2: 1 + sharpAmt / 50 });
}
const newName = crypto.randomBytes(12).toString('hex') + '.jpg';
const out = await pipeline.jpeg({ quality: 92, mozjpeg: true }).toBuffer();
await storage.put(newName, out);
return `/uploads/${newName}`;
}
function aiParams(job) {
const p = job && job.params && typeof job.params === 'object' ? job.params : {};
const face = String(p.face || (job && job.action === 'ai_face' ? 'face' : 'off')).trim().toLowerCase() || 'off';
const strength = Number(p.strength);
return {
model: String(p.model || DEFAULT_MODEL).trim().toLowerCase() || DEFAULT_MODEL,
face,
face_model: String(p.face_model || DEFAULT_FACE_MODEL).trim().toLowerCase() || DEFAULT_FACE_MODEL,
strength: Number.isFinite(strength) ? strength : PHOTO_AI_DEFAULT_STRENGTH,
timeout_ms: face === 'off' ? AI_TIMEOUT_MS : AI_FACE_TIMEOUT_MS,
};
}
function aiMeta(source) {
const o = source && typeof source === 'object' ? source : {};
const num = (v) => (Number.isFinite(Number(v)) && v !== null && v !== '' ? Number(v) : null);
return {
model: o.model ? String(o.model) : null,
face: o.face ? String(o.face) : null,
face_model: o.face_model ? String(o.face_model) : null,
faces_found: num(o.faces_found),
device: o.device ? String(o.device) : null,
elapsed_ms: num(o.elapsed_ms),
warnings: Array.isArray(o.warnings) ? o.warnings.map((w) => String(w).slice(0, 300)).slice(0, 5) : [],
};
}
async function readErrorBody(resp) {
try {
const text = (await resp.text()).trim();
if (!text) return null;
let data = null;
try { data = JSON.parse(text); } catch (e) {}
if (data && typeof data === 'object' && !Array.isArray(data)) {
return String(data.error || data.detail || '').slice(0, 400) || null;
}
return text.slice(0, 400);
} catch (e) {
return null;
}
}
async function runAiEnhance(srcKey, job) {
if (!AI_URL) throw new Error('PHOTO_AI_URL не настроен');
const opt = aiParams(job);
const buf = await storage.getBuffer(srcKey);
if (!buf) throw new Error('Файл фото не найден');
const fd = new FormData();
fd.append('image', new Blob([buf], { type: 'image/jpeg' }), 'photo.jpg');
fd.append('scale', '2');
fd.append('model', opt.model);
fd.append('face', opt.face);
fd.append('face_model', opt.face_model);
fd.append('strength', String(opt.strength));
let resp;
try {
resp = await fetch(AI_URL.replace(/\/+$/, '') + '/enhance', {
method: 'POST',
headers: { Accept: 'application/json' },
body: fd,
signal: AbortSignal.timeout(opt.timeout_ms),
});
} catch (e) {
if (isTimeoutFailure(e)) {
throw new Error(`ИИ-сервис не ответил за ${Math.round(opt.timeout_ms / 1000)} с`);
}
throw softFailure('ИИ-сервис недоступен', e);
}
if (!resp.ok) {
const retryAfter = resp.headers.get('retry-after');
const detail = `ИИ-сервис ответил ${resp.status}${retryAfter ? ` (Retry-After: ${retryAfter})` : ''}`;
const reason = await readErrorBody(resp);
const message = reason ? `${detail}: ${reason}` : detail;
if (isSoftStatus(resp.status)) throw softFailure(message);
throw new Error(message);
}
const contentType = resp.headers.get('content-type') || '';
if (!contentType.includes('application/json')) {
const out = Buffer.from(await resp.arrayBuffer());
return {
out,
meta: aiMeta({
model: resp.headers.get('x-photo-ai-model') || opt.model,
face: resp.headers.get('x-photo-ai-face') || opt.face,
face_model: opt.face === 'off' ? null : opt.face_model,
device: resp.headers.get('x-photo-ai-device'),
elapsed_ms: resp.headers.get('x-photo-ai-elapsed-ms'),
}),
};
}
let data;
try {
data = await resp.json();
} catch (e) {
throw new Error('ИИ-сервис вернул нечитаемый JSON');
}
if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('ИИ-сервис вернул неожиданный JSON');
if (data.ok === false) throw new Error(String(data.error || 'ИИ-сервис вернул ошибку').slice(0, 500));
if (typeof data.image_base64 !== 'string' || !data.image_base64) throw new Error('ИИ-сервис не вернул изображение');
let out;
try {
out = Buffer.from(data.image_base64, 'base64');
} catch (e) {
throw new Error('ИИ-сервис вернул изображение в нечитаемом base64');
}
if (!out.length) throw new Error('ИИ-сервис вернул пустое изображение');
return {
out,
meta: aiMeta({
model: data.model || opt.model,
face: data.face || opt.face,
face_model: data.face_model || (opt.face === 'off' ? null : opt.face_model),
faces_found: data.faces_found,
device: data.device,
elapsed_ms: data.elapsed_ms,
warnings: data.warnings,
}),
};
}
function cpuPostParams(job) {
const p = job && job.params && typeof job.params === 'object' ? job.params.cpu : null;
if (!p || typeof p !== 'object') return null;
const num = (v, min, max, def) => {
const n = Number(v);
return Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : def;
};
return {
clarity: num(p.clarity, 0, 100, 0),
denoise: num(p.denoise, 0, 100, 0),
sharp: num(p.sharp, 0, 100, 0),
brightness: num(p.brightness, 40, 200, 100),
contrast: num(p.contrast, 40, 200, 100),
saturate: num(p.saturate, 0, 200, 100),
warmth: num(p.warmth, -100, 100, 0),
quality: num(p.quality, 70, 100, 92),
scale: num(p.scale, 1, 2, 1),
};
}
function cpuPostIsNoop(c) {
if (!c) return true;
return c.clarity === 0 && c.denoise === 0 && c.sharp === 0
&& c.brightness === 100 && c.contrast === 100 && c.saturate === 100
&& c.warmth === 0 && c.quality >= 92 && c.scale === 1;
}
async function cpuFinishBuffer(buf, c) {
if (!sharp || !c || cpuPostIsNoop(c)) return buf;
let img = sharp(buf);
const meta = await img.metadata();
if (c.scale > 1 && (meta.width || 0) > 0) {
img = img.resize({
width: Math.round((meta.width || 1) * c.scale),
height: Math.round((meta.height || 1) * c.scale),
kernel: 'lanczos3',
fit: 'fill',
});
}
if (c.denoise > 0) {
img = img.median(c.denoise > 70 ? 5 : 3);
img = img.blur(c.denoise > 70 ? 0.6 : 0.4);
}
if (c.clarity > 0) {
try {
img = img.clahe({
width: Math.max(64, Math.round((meta.width || 800) / 8)),
height: Math.max(64, Math.round((meta.height || 600) / 8)),
maxSlope: Math.max(1, Math.min(100, Math.round(1 + (c.clarity / 100) * 2.2))),
});
} catch (e) {}
}
img = img.modulate({ brightness: c.brightness / 100, saturation: c.saturate / 100 });
if (Math.abs(c.warmth) > 0.5) {
const t = c.warmth / 100;
img = t > 0
? img.modulate({ brightness: c.brightness / 100, saturation: c.saturate / 100, tint: Math.min(1, t * 0.25) })
: img.tint({ r: 255, g: Math.round(255 - t * 12), b: Math.round(255 + t * 22) });
}
if (c.contrast !== 100) {
const a = c.contrast / 100;
img = img.linear(a, 128 * (1 - a));
}
if (c.sharp > 0) {
img = img.sharpen({ sigma: 0.4 + (c.sharp / 100) * 1.4, m1: 0, m2: 1 + c.sharp / 60 });
}
return img.jpeg({ quality: Math.round(c.quality), mozjpeg: true }).toBuffer();
}
async function enhanceWithAi(srcKey, job) {
const { out, meta } = await runAiEnhance(srcKey, job);
const finalBuf = await cpuFinishBuffer(out, cpuPostParams(job));
const newName = crypto.randomBytes(12).toString('hex') + '.jpg';
await storage.put(newName, finalBuf);
return { path: `/uploads/${newName}`, meta };
}
async function applyResult(job, newPath, meta) {
const m = meta || {};
await pool.query(
`UPDATE photo_jobs SET status = 'done', after_path = $1, error = NULL, finished_at = now() WHERE id = $2`,
[newPath, job.id]
);
if (logAudit) {
await logAudit(null, 'photo.job.preview', {
entry_id: job.entry_id || null,
group_photo_id: job.group_photo_id || null,
job_id: job.id,
action: job.action,
after_path: newPath,
model: m.model,
face: m.face,
face_model: m.face_model,
device: m.device,
faces_found: m.faces_found,
elapsed_ms: m.elapsed_ms,
warnings: m.warnings && m.warnings.length ? m.warnings : null,
});
}
const isGroup = !!job.group_photo_id;
const title = job.action === 'ai_face'
? (isGroup ? 'Фото группы обработано нейросетью с восстановлением лиц: {group}' : 'Фото обработано нейросетью с восстановлением лиц: {student}')
: job.action === 'ai_upscale'
? (isGroup ? 'Фото группы обработано нейросетью (апскейл): {group}' : 'Фото обработано нейросетью (апскейл): {student}')
: job.action === 'ai'
? (isGroup ? 'Фото группы обработано нейросетью: {group}' : 'Фото обработано нейросетью: {student}')
: (isGroup ? 'Фото группы улучшено на сервере: {group}' : 'Фото улучшено на сервере: {student}');
const warn = m.warnings && m.warnings.length ? ' · ' + m.warnings.join('; ').slice(0, 300) : '';
const body = isGroup
? `Группа {group} · фото #${job.group_photo_id} · результат ждёт применения${warn}`
: `Группа {group} · запись #${job.entry_id} · результат ждёт применения${warn}`;
await sendNotification(job, {
type: 'photo.job.done',
title,
body,
target: {
job_id: job.id,
action: job.action,
after_path: newPath,
model: m.model,
face: m.face,
face_model: m.face_model,
device: m.device,
faces_found: m.faces_found,
elapsed_ms: m.elapsed_ms,
group_photo_id: job.group_photo_id || null,
entry_id: job.entry_id || null,
},
});
}
async function softRetry(job, message) {
const n = (softTries.get(job.id) || 0) + 1;
if (n <= PHOTO_SOFT_MAX_RETRIES) {
softTries.set(job.id, n);
stats.soft_retries++;
await pool.query(`UPDATE photo_jobs SET status = 'pending', error = $1 WHERE id = $2`, [message, job.id]);
if (logAudit && (n === 1 || n % 10 === 0)) {
await logAudit(null, 'photo.job.soft_retry', {
entry_id: job.entry_id || null,
group_photo_id: job.group_photo_id || null,
job_id: job.id,
soft_attempt: n,
soft_limit: PHOTO_SOFT_MAX_RETRIES,
error: message,
});
}
const delay = Math.min(PHOTO_SOFT_BACKOFF_MS * Math.pow(2, n - 1), PHOTO_SOFT_BACKOFF_MAX_MS);
return { ok: false, delay };
}
softTries.delete(job.id);
const text = `${message} — ИИ-сервис недоступен, мягкие повторы исчерпаны (${PHOTO_SOFT_MAX_RETRIES}), задание остановлено`;
await pool.query(
`UPDATE photo_jobs SET status = 'error', error = $1, finished_at = now() WHERE id = $2`,
[text, job.id]
);
stats.errors++;
stats.last_error = text;
if (logAudit) {
await logAudit(null, 'photo.job.error', { entry_id: job.entry_id || null, group_photo_id: job.group_photo_id || null, job_id: job.id, error: text, soft_attempts: PHOTO_SOFT_MAX_RETRIES });
}
const isGroup = !!job.group_photo_id;
await sendNotification(job, {
type: 'photo.job.error',
title: isGroup ? 'Ошибка обработки фото группы: {group}' : 'Ошибка обработки фото: {student}',
body: isGroup ? `Группа {group} · фото #${job.group_photo_id} · ${text}` : `Группа {group} · запись #${job.entry_id} · ${text}`,
target: { job_id: job.id, action: job.action, error: text, group_photo_id: job.group_photo_id || null, entry_id: job.entry_id || null },
});
return { ok: true, delay: 0 };
}
async function processOne(job) {
stats.jobs++;
let photoPath = null;
if (job.group_photo_id) {
const { rows } = await pool.query('SELECT photo_path FROM group_photos WHERE id = $1', [job.group_photo_id]);
if (rows.length) photoPath = rows[0].photo_path;
} else {
const { rows } = await pool.query('SELECT photo_path FROM entries WHERE id = $1', [job.entry_id]);
if (rows.length) photoPath = rows[0].photo_path;
}
if (!photoPath) {
const errMsg = job.group_photo_id ? 'У фото группы не найден путь' : 'У записи нет фото';
await pool.query(
`UPDATE photo_jobs SET status = 'error', error = $1, finished_at = now() WHERE id = $2`,
[errMsg, job.id]
);
stats.errors++;
stats.last_at = new Date().toISOString();
stats.last_error = errMsg;
const isGroup = !!job.group_photo_id;
await sendNotification(job, {
type: 'photo.job.error',
title: isGroup ? 'Ошибка обработки фото группы: {group}' : 'Ошибка обработки фото: {student}',
body: isGroup ? `Группа {group} · фото #${job.group_photo_id} · нет фото для обработки` : `Группа {group} · запись #${job.entry_id} · у записи нет фото для обработки`,
target: { job_id: job.id, action: job.action, group_photo_id: job.group_photo_id || null, entry_id: job.entry_id || null },
});
return { ok: true, delay: 0 };
}
try {
const result = PHOTO_AI_ACTIONS.has(job.action)
? await enhanceWithAi(photoPath, job)
: { path: await enhanceWithSharp(photoPath, job.params), meta: null };
await applyResult(job, result.path, result.meta);
softTries.delete(job.id);
stats.done++;
stats.last_at = new Date().toISOString();
stats.last_error = null;
return { ok: true, delay: 0 };
} catch (e) {
const message = (e && e.message ? e.message : 'error').slice(0, 500);
stats.last_at = new Date().toISOString();
stats.last_error = message;
if (e && e.soft) return await softRetry(job, message);
const { rows: cur } = await pool.query('SELECT attempts FROM photo_jobs WHERE id = $1', [job.id]);
const tries = ((cur[0] && cur[0].attempts) || 0) + 1;
if (tries < PHOTO_MAX_ATTEMPTS) {
await pool.query(`UPDATE photo_jobs SET status = 'pending', attempts = $1, error = $2 WHERE id = $3`, [tries, message, job.id]);
if (logAudit) await logAudit(null, 'photo.job.retry', { entry_id: job.entry_id || null, group_photo_id: job.group_photo_id || null, job_id: job.id, attempt: tries, error: message });
return { ok: false, delay: 0 };
}
softTries.delete(job.id);
await pool.query(
`UPDATE photo_jobs SET status = 'error', attempts = $1, error = $2, finished_at = now() WHERE id = $3`,
[tries, message, job.id]
);
stats.errors++;
if (logAudit) await logAudit(null, 'photo.job.error', { entry_id: job.entry_id, job_id: job.id, error: message });
const isGroup = !!job.group_photo_id;
await sendNotification(job, {
type: 'photo.job.error',
title: isGroup ? 'Ошибка обработки фото группы: {group}' : 'Ошибка обработки фото: {student}',
body: isGroup ? `Группа {group} · фото #${job.group_photo_id} · ${message}` : `Группа {group} · запись #${job.entry_id} · ${message}`,
target: { job_id: job.id, action: job.action, error: message, group_photo_id: job.group_photo_id || null, entry_id: job.entry_id || null },
});
return { ok: true, delay: 0 };
}
}
async function loop() {
while (!stopped) {
let job = null;
try {
if (!(await isEnabled())) {
await sleep(IDLE_MAX);
continue;
}
job = await claimNext();
} catch (e) {
console.error('Photo worker claim error:', e);
await sleep(IDLE_MAX);
continue;
}
if (!job) {
await sleep(idleMs);
idleMs = Math.min(idleMs * 2, IDLE_MAX);
continue;
}
idleMs = IDLE_MIN;
processing = true;
currentId = job.id;
let res = { ok: true, delay: 0 };
try {
res = await processOne(job);
} catch (e) {
console.error('Photo worker process error:', e);
} finally {
processing = false;
currentId = null;
}
if (!res || !res.ok) await sleep((res && res.delay) || IDLE_MAX);
}
}
async function resetStale() {
await pool.query(`UPDATE photo_jobs SET status = 'pending' WHERE status = 'processing'`);
}
function start() {
if (started) return;
started = true;
startedAt = Date.now();
resetStale()
.catch((e) => console.error('Photo worker reset error:', e))
.finally(() => { loop().catch((e) => console.error('Photo worker loop error:', e)); });
}
function getInfo() {
return {
started_at: startedAt ? new Date(startedAt).toISOString() : null,
uptime_ms: startedAt ? Date.now() - startedAt : 0,
processing,
current_id: currentId,
config: CONFIG,
...stats,
};
}
return { start, notify, getInfo };
}
function createEntryAutoChecker({ pool, getSetting, logAudit, aiUrl, defaultPrompt, model, bus }) {
const AI_URL = aiUrl || process.env.AI_URL || 'http://text-corrector:8080';
const MODEL = model || process.env.AI_MODEL || 'qwen2.5-1.5b-instruct-q4_k_m.gguf';
const DEFAULT_PROMPT = defaultPrompt || process.env.AI_PROMPT || 'Ты — редактор текстов. Исправь ТОЛЬКО грамматические, орфографические и пунктуационные ошибки в тексте. Приведи к правильному регистру буквы. НЕ меняй слова, структуру предложений, стиль или смысл текста. Верни ТОЛЬКО исправленный текст без пояснений.';
let started = false;
let stopped = false;
let idleMs = IDLE_MIN_MS;
let wake = null;
let processing = false;
let currentId = null;
let startedAt = null;
const stats = { checks: 0, corrected: 0, unchanged: 0, errors: 0, last_at: null, last_error: null };
const attempts = new Map();
const MAX_ATTEMPTS = 3;
const CONFIG = {
idle_min_ms: IDLE_MIN_MS,
idle_max_ms: IDLE_MAX_MS,
request_timeout_ms: REQUEST_TIMEOUT_MS,
max_input_chars: MAX_INPUT_CHARS,
min_text_chars: MIN_TEXT_CHARS,
max_attempts: MAX_ATTEMPTS,
model: MODEL,
ai_url: AI_URL,
};
function sleep(ms) {
return new Promise((resolve) => {
const t = setTimeout(() => { wake = null; resolve(); }, ms);
wake = () => { clearTimeout(t); wake = null; resolve(); };
});
}
function wakeLocal() {
if (wake) wake();
}
function notify() {
wakeLocal();
if (bus) bus.publish();
}
if (bus) bus.subscribe(wakeLocal);
async function isEnabled() {
const v = await getSetting('ai_autocheck_enabled', 'true');
return String(v) !== 'false';
}
async function claimNext() {
const client = await pool.connect();
try {
await client.query('BEGIN');
const { rows } = await client.query(
`SELECT id, description, description_original FROM entries
WHERE ai_status = 'pending' AND deleted_at IS NULL
ORDER BY id ASC LIMIT 1 FOR UPDATE SKIP LOCKED`
);
if (!rows.length) {
await client.query('COMMIT');
return null;
}
await client.query(`UPDATE entries SET ai_status = 'processing' 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();
}
}
async function resolveActiveProfile() {
try {
const active = await getSetting('ai_active_profile', 'native');
if (active && active !== 'native') {
const raw = await getSetting('ai_profiles', '[]');
const list = JSON.parse(raw || '[]');
if (Array.isArray(list)) {
return list.find(p => p && p.id === active && p.base_url && p.model) || null;
}
}
} catch (e) {}
return null;
}
function normalizeOpenAiBase(base) {
let b = String(base || '').trim().replace(/\/+$/, '');
if (!/^https?:\/\//i.test(b)) return null;
if (!/\/v1$/i.test(b)) b += '/v1';
return b;
}
async function callModel(text, systemPrompt) {
const profile = await resolveActiveProfile();
const headers = { 'Content-Type': 'application/json' };
let url;
let model;
let maxTokens;
if (profile) {
const base = normalizeOpenAiBase(profile.base_url);
if (!base) throw new Error('Некорректный base_url профиля ИИ');
url = `${base}/chat/completions`;
model = profile.model;
if (profile.api_key) headers.Authorization = `Bearer ${profile.api_key}`;
maxTokens = parseInt(profile.max_tokens, 10) || Math.min(4096, Math.max(1024, text.length * 2 + 512));
} else {
url = `${AI_URL.replace(/\/+$/, '')}/v1/chat/completions`;
model = MODEL;
maxTokens = Math.min(256, Math.max(128, text.length + 64));
}
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
try {
const res = await fetch(url, {
method: 'POST',
headers,
signal: controller.signal,
body: JSON.stringify({
model,
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: text },
],
temperature: 0.1,
max_tokens: maxTokens,
}),
});
if (!res.ok) throw await aiHttpErrorFromResponse(res);
const data = await res.json();
const choice = data.choices && data.choices[0];
const content = (choice && choice.message && choice.message.content || '').trim();
if (!content) {
throw new Error(`Модель вернула пустой ответ (finish_reason=${choice && choice.finish_reason || 'unknown'})`);
}
return content;
} finally {
clearTimeout(timer);
}
}
function sanitize(original, out) {
if (!out) return original;
const o = out.trim();
if (!o) return original;
if (o.length > original.length * 4 + 80) return original;
return o;
}
async function processOne(row) {
const original = String(row.description_original ?? row.description ?? '').trim();
if (original.length < MIN_TEXT_CHARS) {
await pool.query(`UPDATE entries SET ai_status = 'skipped', ai_checked_at = now() WHERE id = $1`, [row.id]);
return true;
}
const prompt = (await getSetting('ai_prompt', DEFAULT_PROMPT)) || DEFAULT_PROMPT;
const input = original.length > MAX_INPUT_CHARS ? original.slice(0, MAX_INPUT_CHARS) : original;
try {
const out = await callModel(input, prompt);
const checked = sanitize(input, out);
const changed = checked !== input;
await pool.query(
`UPDATE entries SET description_ai = $1, description = $1, ai_status = 'done', ai_error = NULL, ai_checked_at = now() WHERE id = $2`,
[changed ? checked : original, row.id]
);
attempts.delete(row.id);
stats.checks++;
if (changed) stats.corrected++; else stats.unchanged++;
stats.last_at = new Date().toISOString();
stats.last_error = null;
if (logAudit) {
const d = textDiff(String(row.description ?? ''), changed ? checked : original);
await logAudit(null, 'entry.ai.auto-check', {
id: row.id,
source: 'ai',
changed,
fields: changed ? ['description'] : [],
changes: changed
? [{ field: 'description', label: FIELD_LABELS.description, stats: d.stats, diff: d.segments, truncated: d.truncated }]
: []
});
}
return true;
} catch (e) {
const message = (e && e.message ? e.message : 'error').slice(0, 500);
const tries = (attempts.get(row.id) || 0) + 1;
stats.last_at = new Date().toISOString();
stats.last_error = message;
if (tries < MAX_ATTEMPTS) {
attempts.set(row.id, tries);
await pool.query(`UPDATE entries SET ai_status = 'pending', ai_error = $1 WHERE id = $2`, [message, row.id]);
if (logAudit) await logAudit(null, 'entry.ai.retry', { id: row.id, attempt: tries, error: message });
return false;
}
attempts.delete(row.id);
stats.errors++;
await pool.query(
`UPDATE entries SET ai_status = 'error', ai_error = $1, ai_checked_at = now() WHERE id = $2`,
[message, row.id]
);
if (logAudit) await logAudit(null, 'entry.ai.error', { id: row.id, error: message });
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('AI auto-check claim error:', e);
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('AI auto-check process error:', e);
} finally {
processing = false;
currentId = null;
}
if (!ok) await sleep(IDLE_MAX_MS);
}
}
async function resetStale() {
await pool.query(`UPDATE entries SET ai_status = 'pending' WHERE ai_status = 'processing'`);
}
function start() {
if (started) return;
started = true;
startedAt = Date.now();
resetStale()
.catch((e) => console.error('AI auto-check reset error:', e))
.finally(() => { loop().catch((e) => console.error('AI auto-check loop error:', e)); });
}
function getStats() {
return { ...stats, processing };
}
function getInfo() {
return {
started_at: startedAt ? new Date(startedAt).toISOString() : null,
uptime_ms: startedAt ? Date.now() - startedAt : 0,
processing,
current_id: currentId,
config: CONFIG,
...stats,
};
}
return { start, notify, getStats, getInfo };
}
const LESSON_TOPIC_POSITION_LABELS = {
first: 'первое занятие модуля',
middle: 'промежуточное занятие модуля',
last: 'последнее занятие модуля',
};
function lessonTopicPosition(topic) {
const m = /(\d+)\s*\/\s*(\d+)\s*$/.exec(String(topic || '').trim());
if (!m) return null;
const n = parseInt(m[1], 10);
const total = parseInt(m[2], 10);
if (!Number.isInteger(n) || !Number.isInteger(total) || total < 1 || n < 1 || n > total) return null;
const kind = n === total ? 'last' : n === 1 ? 'first' : 'middle';
return { kind, n, total, label: `${LESSON_TOPIC_POSITION_LABELS[kind]} (${n} из ${total})` };
}
function createLessonReportChecker({ pool, getSetting, logAudit, aiUrl, model, defaultPrompt, bus, onDone }) {
const AI_URL = aiUrl || process.env.AI_URL || 'http://text-corrector:8080';
const MODEL = model || process.env.AI_MODEL || 'qwen2.5-1.5b-instruct-q4_k_m.gguf';
const DEFAULT_PROMPT = defaultPrompt || '';
const TIMEOUT_MS = Math.max(5000, parseInt(process.env.LESSON_AI_TIMEOUT_MS || '120000', 10) || 120000);
const MIN_CHARS = 20;
const MAX_INPUT_CHARS = 4000;
const TEXT_MAX = 5000;
const MAX_ATTEMPTS = 3;
let started = false;
let stopped = false;
let idleMs = IDLE_MIN_MS;
let wake = null;
let processing = false;
let currentId = null;
let startedAt = null;
const stats = { checks: 0, formatted: 0, unchanged: 0, errors: 0, last_at: null, last_error: null };
const attempts = new Map();
function sleep(ms) {
return new Promise((resolve) => {
const t = setTimeout(() => { wake = null; resolve(); }, ms);
wake = () => { clearTimeout(t); wake = null; resolve(); };
});
}
function wakeLocal() {
if (wake) wake();
}
function notify() {
wakeLocal();
if (bus) bus.publish();
}
if (bus) bus.subscribe(wakeLocal);
async function isEnabled() {
return String(await getSetting('lesson_ai_enabled', 'true')) !== 'false';
}
async function claimNext() {
const client = await pool.connect();
try {
await client.query('BEGIN');
const { rows } = await client.query(
`SELECT lr.id, lr.text, lr.text_original, lr.lesson_date, lr.lesson_time, lr.topic, lr.author_id,
g.name AS group_name, g.branch_id
FROM lesson_reports lr
JOIN groups g ON g.id = lr.group_id
WHERE lr.ai_status = 'pending'
ORDER BY lr.id ASC LIMIT 1 FOR UPDATE OF lr SKIP LOCKED`
);
if (!rows.length) {
await client.query('COMMIT');
return null;
}
await client.query(`UPDATE lesson_reports SET ai_status = 'processing' 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();
}
}
async function resolveActiveProfile() {
try {
const active = await getSetting('ai_active_profile', 'native');
if (active && active !== 'native') {
const raw = await getSetting('ai_profiles', '[]');
const list = JSON.parse(raw || '[]');
if (Array.isArray(list)) {
return list.find(p => p && p.id === active && p.base_url && p.model) || null;
}
}
} catch (e) {}
return null;
}
function normalizeOpenAiBase(base) {
const b = String(base || '').trim().replace(/\/+$/, '');
if (!/^https?:\/\//i.test(b)) return null;
if (!/\/v1$/i.test(b)) return b + '/v1';
return b;
}
async function callModel(userText, systemPrompt) {
const profile = await resolveActiveProfile();
const headers = { 'Content-Type': 'application/json' };
let url;
let model;
let maxTokens;
if (profile) {
const base = normalizeOpenAiBase(profile.base_url);
if (!base) throw new Error('Некорректный base_url профиля ИИ');
url = `${base}/chat/completions`;
model = profile.model;
if (profile.api_key) headers.Authorization = `Bearer ${profile.api_key}`;
maxTokens = parseInt(profile.max_tokens, 10) || Math.min(4096, Math.max(1024, userText.length * 2 + 512));
} else {
url = `${AI_URL.replace(/\/+$/, '')}/v1/chat/completions`;
model = MODEL;
maxTokens = Math.min(1536, Math.max(512, userText.length + 512));
}
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
try {
const res = await fetch(url, {
method: 'POST',
headers,
signal: controller.signal,
body: JSON.stringify({
model,
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userText },
],
temperature: 0.1,
max_tokens: maxTokens,
}),
});
if (!res.ok) throw await aiHttpErrorFromResponse(res);
const data = await res.json();
const choice = data.choices && data.choices[0];
return (choice && choice.message && choice.message.content || '').trim();
} finally {
clearTimeout(timer);
}
}
function normalizeOutput(out) {
let s = String(out || '').trim();
if (!s) return '';
s = s.replace(/^```[a-zA-Z]*\s*/, '').replace(/```$/, '').trim();
s = s.replace(/^(?:итоговый|результативный|готовый|итог)\s*текст\s*(?:отчёта|отчета|report)?\s*[:—-]\s*/i, '').trim();
s = s.replace(/^["'«”]+/, '').replace(/["'«»"]+$/, '').trim();
s = s.replace(/\r\n/g, '\n').replace(/\n{3,}/g, '\n\n');
return s;
}
async function finish(row, status, text, error, aiText) {
await pool.query(
`UPDATE lesson_reports SET
text = $1, text_ai = $2, ai_status = $3, ai_error = $4, ai_checked_at = now(), updated_at = now()
WHERE id = $5`,
[text, aiText, status, error || null, row.id]
);
attempts.delete(row.id);
stats.last_at = new Date().toISOString();
stats.last_error = error || null;
if (onDone) await onDone({ row, status, text, aiText, error: error || null });
}
async function processOne(row) {
const original = String(row.text_original || row.text || '').trim();
if (original.length < MIN_CHARS) {
await finish(row, 'skipped', original, null, null);
stats.unchanged++;
return true;
}
const prompt = (await getSetting('lesson_ai_prompt', DEFAULT_PROMPT)) || DEFAULT_PROMPT;
const date = String(row.lesson_date).slice(0, 10);
const time = row.lesson_time ? String(row.lesson_time).slice(0, 5) : '';
const input = original.length > MAX_INPUT_CHARS ? original.slice(0, MAX_INPUT_CHARS) : original;
const topic = String(row.topic || '').trim();
const position = lessonTopicPosition(topic);
const context = [
`Группа: ${row.group_name || '—'}`,
`Дата занятия: ${date}`,
time ? `Время занятия: ${time}` : '',
topic ? `Тема занятия: ${topic}` : '',
position ? `Позиция темы: ${position.label}` : '',
'',
'Текст отчёта:',
input,
].filter(l => l !== '').join('\n');
try {
const out = normalizeOutput(await callModel(context, prompt));
if (!out || out.length > TEXT_MAX) {
const reason = out ? 'Модель вернула слишком длинный текст' : 'Модель вернула пустой ответ';
await finish(row, 'error', original, reason, null);
stats.errors++;
return true;
}
const changed = out !== original;
await finish(row, changed ? 'done' : 'skipped', changed ? out : original, null, changed ? out : null);
stats.checks++;
if (changed) stats.formatted++; else stats.unchanged++;
return true;
} catch (e) {
const message = (e && e.message ? e.message : 'error').slice(0, 500);
const tries = (attempts.get(row.id) || 0) + 1;
if (tries < MAX_ATTEMPTS) {
attempts.set(row.id, tries);
await pool.query(`UPDATE lesson_reports SET ai_status = 'pending', ai_error = $1 WHERE id = $2`, [message, row.id]);
if (logAudit) await logAudit(null, 'lesson_report.ai.retry', { id: row.id, attempt: tries, error: message });
return false;
}
await finish(row, 'error', original, message, null);
stats.errors++;
if (logAudit) await logAudit(null, 'lesson_report.ai.error', { id: row.id, error: message });
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('Lesson AI 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('Lesson AI process error:', e.message);
} finally {
processing = false;
currentId = null;
}
if (!ok) await sleep(IDLE_MAX_MS);
}
}
function resetStale() {
return pool.query(`UPDATE lesson_reports SET ai_status = 'pending' WHERE ai_status = 'processing'`);
}
function start() {
if (started) return;
started = true;
startedAt = Date.now();
resetStale()
.catch((e) => console.error('Lesson AI reset error:', e.message))
.finally(() => { loop().catch((e) => console.error('Lesson AI 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, timeout_ms: TIMEOUT_MS, model: MODEL, ai_url: AI_URL },
...stats,
};
}
return { start, stop, notify, getInfo };
}
function createFeedbackWriter(opts) {
const pool = opts.pool;
const getSetting = opts.getSetting;
const logAudit = opts.logAudit;
const aiUrl = (opts.aiUrl || process.env.AI_URL || 'http://text-corrector:8080');
const defaultPrompt = opts.defaultPrompt || '';
const bus = opts.bus;
const onDone = opts.onDone || (() => {});
const AI_MODEL = process.env.AI_MODEL || 'qwen2.5-1.5b-instruct-q4_k_m.gguf';
const TIMEOUT_MS = opts.timeoutMs || parseInt(process.env.FEEDBACK_AI_TIMEOUT_MS || '120000', 10) || 120000;
const MAX_ATTEMPTS = 3;
const IDLE_MIN_MS = 500;
const IDLE_MAX_MS = 30000;
const MIN_CHARS = 1;
const MAX_INPUT_CHARS = 6000;
const TEXT_MAX = 5000;
const MAX_TOKENS_CAP = 8192;
let running = false;
let timer = null;
let stopped = false;
let idleMs = IDLE_MIN_MS;
let inFlight = false;
function notify() {
if (!running || inFlight) return;
clearTimeout(timer);
timer = setTimeout(tick, 50);
}
if (bus && typeof bus.subscribe === 'function') {
try { bus.subscribe(notify); } catch (e) {}
}
async function getSettingValue(key, def) {
try {
const v = await getSetting(key, def);
return v;
} catch (e) {
return def;
}
}
async function getPersonalModels(authorId) {
if (!authorId) return [];
try {
const r = await pool.query(`SELECT value FROM user_settings WHERE user_id = $1 AND key = 'feedback_models'`, [authorId]);
const raw = r.rows[0] && r.rows[0].value;
if (!raw) return [];
const arr = JSON.parse(raw);
return Array.isArray(arr) ? arr : [];
} catch (e) {
return [];
}
}
async function resolveActiveProfile(profileId, authorId) {
try {
const active = await getSettingValue('ai_active_profile', 'native');
const profilesRaw = await getSettingValue('ai_profiles', '[]');
let profiles = [];
try { profiles = JSON.parse(profilesRaw); } catch (e) {}
if (profileId) {
const mine = await getPersonalModels(authorId);
const own = mine.find(x => String(x.id) === String(profileId));
if (own) return { type: 'profile', profile: own };
const p = profiles.find(x => String(x.id) === String(profileId));
if (p) return { type: 'profile', profile: p };
}
if (String(active) !== 'native') {
const p = profiles.find(x => String(x.id) === String(active));
if (p) return { type: 'profile', profile: p };
}
return { type: 'native', model: AI_MODEL, baseUrl: aiUrl };
} catch (e) {
return { type: 'native', model: AI_MODEL, baseUrl: aiUrl };
}
}
function normalizeOpenAiBase(baseUrl) {
const b = (baseUrl || '').replace(/\/$/, '');
return b.includes('/v1') ? b : `${b}/v1`;
}
async function callModel(systemPrompt, userText, profileId, authorId) {
const text = String(userText || '');
const resolved = await resolveActiveProfile(profileId, authorId);
const modelName = resolved.type === 'profile'
? (resolved.profile.model || AI_MODEL)
: (resolved.model || AI_MODEL);
if (text.length > MAX_INPUT_CHARS) {
return { content: text.slice(0, TEXT_MAX), model: modelName };
}
const controller = new AbortController();
const timerAbort = setTimeout(() => controller.abort(), TIMEOUT_MS);
try {
let url, headers, model, messages, maxTokens;
if (resolved.type === 'profile') {
const p = resolved.profile;
const base = normalizeOpenAiBase(p.base_url || aiUrl);
url = `${base}/chat/completions`;
headers = { 'Content-Type': 'application/json' };
if (p.api_key) headers.Authorization = `Bearer ${p.api_key}`;
model = p.model || AI_MODEL;
maxTokens = parseInt(p.max_tokens, 10) || Math.min(8192, Math.max(4096, text.length * 2 + 512));
} else {
const base = normalizeOpenAiBase(resolved.baseUrl || aiUrl);
url = `${base}/chat/completions`;
headers = { 'Content-Type': 'application/json' };
model = resolved.model || AI_MODEL;
maxTokens = Math.min(8192, Math.max(4096, text.length * 2 + 512));
}
messages = [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: text }
];
for (let i = 0; i < 2; i++) {
const res = await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify({ model, messages, temperature: 0.1, max_tokens: maxTokens }),
signal: controller.signal
});
if (!res.ok) throw await aiHttpErrorFromResponse(res);
const data = await res.json();
const choice = data.choices && data.choices[0];
const content = (choice && choice.message && choice.message.content || '').trim();
const finishReason = (choice && choice.finish_reason) || '';
if (!content && finishReason === 'length' && maxTokens < MAX_TOKENS_CAP) {
maxTokens = Math.min(MAX_TOKENS_CAP, maxTokens * 4);
continue;
}
return { content, finishReason, model: modelName };
}
return { content: '', finishReason: 'length', model: modelName };
} finally {
clearTimeout(timerAbort);
}
}
function normalizeOutput(s) {
let out = String(s || '').trim();
if (out.startsWith('```') && out.endsWith('```')) {
out = out.slice(3, -3).trim();
}
out = out.replace(/^(Итоговый текст:|Отзыв:)\s*/i, '');
out = out.replace(/^"|"$/g, '');
out = out.replace(/\n{3,}/g, '\n\n');
return out;
}
async function isEnabled() {
try {
const v = await getSettingValue('feedback_ai_enabled', 'true');
return String(v) !== 'false';
} catch (e) {
return true;
}
}
async function claimNext() {
const client = await pool.connect();
try {
await client.query('BEGIN');
const q = `SELECT f.*, g.name AS group_name, g.branch_id AS group_branch_id
FROM feedbacks f
LEFT JOIN groups g ON g.id = f.group_id
WHERE f.ai_status = 'pending' AND f.deleted_at IS NULL
ORDER BY f.id ASC
FOR UPDATE OF f SKIP LOCKED
LIMIT 1`;
const r = await client.query(q);
if (r.rows.length === 0) {
await client.query('ROLLBACK');
return null;
}
const row = r.rows[0];
await client.query(`UPDATE feedbacks SET ai_status='processing', updated_at=now() WHERE id=$1`, [row.id]);
await client.query('COMMIT');
row.branch_id = row.branch_id ?? row.group_branch_id ?? null;
return row;
} catch (e) {
try { await client.query('ROLLBACK'); } catch (e2) {}
throw e;
} finally {
client.release();
}
}
async function resolveFeedbackPrompt(row) {
let prompt = defaultPrompt;
try {
const base = await getSettingValue('feedback_ai_prompt', '');
if (base && base.trim()) prompt = base.trim();
} catch (e) {}
try {
if (row.author_id) {
const r = await pool.query(`SELECT value FROM user_settings WHERE user_id = $1 AND key = 'feedback_prompt'`, [row.author_id]);
const own = r.rows[0] && r.rows[0].value;
if (own && own.trim()) prompt = own.trim();
}
} catch (e) {}
return prompt;
}
async function processOne(row) {
if (row.text && String(row.text).trim().length >= MIN_CHARS) {
// allow overwrite only if empty? keep as done? but generate on request
}
let context = '';
context += `Группа: ${row.group_name || ''}\n`;
context += `Дата занятия: ${row.feedback_date || ''}\n`;
context += `Резидент: ${row.resident || ''}\n`;
context += `Тема занятия: ${row.topic || ''}\n`;
context += `Прошлый отзыв: ${row.past_review || 'нет'}\n`;
let shorts = [];
try {
const ids = Array.isArray(row.short_message_ids) ? row.short_message_ids : [];
if (ids.length) {
const sr = await pool.query(`SELECT resident, lesson_date, topic, message FROM short_messages WHERE id = ANY($1::int[]) AND deleted_at IS NULL ORDER BY id`, [ids]);
shorts = sr.rows;
}
} catch (e) {}
if (shorts.length) {
context += 'Короткие сообщения (выбраны):\n';
for (const s of shorts) {
context += `- ${s.lesson_date || ''} – ${s.topic || '-'} – ${s.message || ''}\n`;
}
}
const prompt = await resolveFeedbackPrompt(row);
const keys = {
group: row.group_name || '',
date: row.feedback_date || '',
resident: row.resident || '',
topic: row.topic || '',
past_review: row.past_review || 'нет',
shorts: shorts.length ? shorts.map(s => `- ${s.lesson_date || ''} – ${s.topic || '-'} – ${s.message || ''}`).join('\n') : 'нет',
context: context,
text: (row.text || '').trim(),
};
const hasKeys = /\{(group|date|resident|topic|past_review|shorts|context|text)\}/.test(prompt);
const systemPrompt = hasKeys
? prompt.replace(/\{(\w+)\}/g, (m, k) => (Object.prototype.hasOwnProperty.call(keys, k) ? String(keys[k]) : m))
: prompt + (context ? '\n\nКОНТЕКСТ:\n' + context : '');
const userMsg = row.text && row.text.trim() ? row.text : (context || 'Сформируй отзыв по контексту');
const t0 = Date.now();
let call;
try {
call = await callModel(systemPrompt, userMsg, row.ai_profile || null, row.author_id || null);
} catch (e) {
return { status: 'error', error: e.message || 'error', prompt: systemPrompt, input: userMsg, durationMs: Date.now() - t0 };
}
const durationMs = Date.now() - t0;
const meta = { prompt: systemPrompt, input: userMsg, output: call.content, model: call.model, durationMs };
let norm = normalizeOutput(call.content);
if (!norm) {
const reason = call.finishReason ? ` (finish_reason=${call.finishReason})` : '';
return { status: 'error', error: `Пустой ответ от модели${reason}`, ...meta };
}
if (norm.length > TEXT_MAX) norm = norm.slice(0, TEXT_MAX);
const oldText = (row.text || '').trim();
if (oldText && norm.trim() === oldText) {
return { status: 'skipped', text: oldText, ...meta };
}
return { status: 'done', text: norm, aiText: norm, ...meta };
}
function capStr(v, max) {
if (v == null) return null;
const s = String(v);
return s.length > max ? s.slice(0, max) : s;
}
function auditRun(row, res, attempt) {
const payload = {
id: row.id,
status: res.status,
attempt: attempt || 1,
model: res.model || null,
profile: row.ai_profile || 'native',
duration_ms: Number.isFinite(res.durationMs) ? Math.round(res.durationMs) : null,
prompt: capStr(res.prompt, 12000),
input: capStr(res.input, 6000),
error: res.error ? String(res.error).slice(0, 500) : null,
len_before: (row.text || '').length
};
if (res.status === 'error') {
Promise.resolve(logAudit(null, 'feedback.ai.error', payload)).catch(() => {});
return;
}
payload.output = capStr(res.output, 6000);
payload.changed = res.status === 'done';
payload.len_after = res.text ? res.text.length : null;
Promise.resolve(logAudit(null, 'feedback.ai.run', payload)).catch(() => {});
}
async function finish(row, res, attempt) {
const client = await pool.connect();
try {
await client.query('BEGIN');
const sets = [];
const params = [];
let i = 1;
sets.push(`ai_status=$${i++}`); params.push(res.status);
sets.push(`ai_checked_at=now()`);
if (res.error) { sets.push(`ai_error=$${i++}`); params.push(res.error); } else { sets.push(`ai_error=NULL`); }
sets.push(`ai_prompt=$${i++}`); params.push(res.prompt != null ? res.prompt : null);
sets.push(`ai_model=$${i++}`); params.push(res.model != null ? res.model : null);
sets.push(`ai_duration_ms=$${i++}`); params.push(Number.isFinite(res.durationMs) ? Math.round(res.durationMs) : null);
if (res.status === 'done' && res.text) { sets.push(`text=$${i++}`); params.push(res.text); }
sets.push(`updated_at=now()`);
params.push(row.id);
await client.query(`UPDATE feedbacks SET ${sets.join(', ')} WHERE id=$${i}`, params);
await client.query('COMMIT');
if (res.status === 'done' && res.text) {
try { await saveFeedbackVersion(pool, row.id, res.text, 'ai', row.author_id); } catch (e) {}
}
} catch (e) {
try { await client.query('ROLLBACK'); } catch (e2) {}
throw e;
} finally {
client.release();
}
auditRun(row, res, attempt);
try { onDone({ row, status: res.status, text: res.text || row.text, aiText: res.aiText, error: res.error }); } catch (e) {}
}
async function tick() {
if (stopped || !running || inFlight) return;
const enabled = await isEnabled();
if (!enabled) {
idleMs = Math.min(idleMs * 2, IDLE_MAX_MS);
timer = setTimeout(tick, idleMs);
return;
}
inFlight = true;
try {
let attempts = 0;
while (attempts < MAX_ATTEMPTS) {
attempts++;
const row = await claimNext();
if (!row) break;
let res;
try {
res = await processOne(row);
} catch (e) {
res = { status: 'error', error: e.message };
}
if (res.status === 'error' && attempts < MAX_ATTEMPTS) {
const client = await pool.connect();
try {
await client.query('BEGIN');
await client.query(`UPDATE feedbacks SET ai_status='pending', updated_at=now(), ai_error=$2 WHERE id=$1`, [row.id, res.error || 'error']);
await client.query('COMMIT');
} catch (e2) {
try { await client.query('ROLLBACK'); } catch (e3) {}
} finally {
client.release();
}
idleMs = IDLE_MIN_MS;
continue;
}
await finish(row, res, attempts);
idleMs = IDLE_MIN_MS;
}
} catch (e) {
idleMs = Math.min(idleMs * 2, IDLE_MAX_MS);
} finally {
inFlight = false;
timer = setTimeout(tick, idleMs);
}
}
async function resetStale() {
try {
await pool.query(`UPDATE feedbacks SET ai_status='pending', ai_error=NULL, ai_checked_at=NULL WHERE ai_status='processing'`);
} catch (e) {}
}
function start() {
if (running) return;
running = true;
stopped = false;
idleMs = IDLE_MIN_MS;
resetStale().finally(() => { tick(); });
}
function stop() {
running = false;
stopped = true;
if (timer) { clearTimeout(timer); timer = null; }
}
function getInfo() {
return { running, inFlight, idleMs };
}
return { start, stop, notify, getInfo };
}
function createFarewellWorker(opts) {
const pool = opts.pool;
const logAudit = opts.logAudit;
const aiUrl = (opts.aiUrl || process.env.AI_URL || 'http://text-corrector:8080');
const defaultPrompt = opts.defaultPrompt || '';
const bus = opts.bus;
const onDone = opts.onDone || (() => {});
const AI_MODEL = process.env.AI_MODEL || 'qwen2.5-1.5b-instruct-q4_k_m.gguf';
const TIMEOUT_MS = opts.timeoutMs || parseInt(process.env.FAREWELL_AI_TIMEOUT_MS || '180000', 10) || 180000;
const MAX_ATTEMPTS = 3;
const IDLE_MIN_MS = 500;
const IDLE_MAX_MS = 30000;
const TEXT_MAX = 8000;
const MAX_INPUT_CHARS = 20000;
const MAX_FEEDBACKS = 30;
const FEEDBACK_TEXT_CAP = 2500;
const MAX_TOKENS_CAP = 8192;
let running = false;
let timer = null;
let stopped = false;
let idleMs = IDLE_MIN_MS;
let inFlight = false;
function notify() {
if (!running || inFlight) return;
clearTimeout(timer);
timer = setTimeout(tick, 50);
}
if (bus && typeof bus.subscribe === 'function') {
try { bus.subscribe(notify); } catch (e) {}
}
async function getPersonalModels(authorId) {
if (!authorId) return [];
try {
const r = await pool.query(`SELECT value FROM user_settings WHERE user_id = $1 AND key = 'feedback_models'`, [authorId]);
const raw = r.rows[0] && r.rows[0].value;
if (!raw) return [];
const arr = JSON.parse(raw);
return Array.isArray(arr) ? arr : [];
} catch (e) {
return [];
}
}
async function resolveActiveProfile(profileId, authorId) {
try {
const activeRow = await pool.query(`SELECT value FROM settings WHERE key = 'ai_active_profile'`);
const active = (activeRow.rows[0] && activeRow.rows[0].value) || 'native';
const profilesRow = await pool.query(`SELECT value FROM settings WHERE key = 'ai_profiles'`);
let profiles = [];
try { profiles = JSON.parse((profilesRow.rows[0] && profilesRow.rows[0].value) || '[]'); } catch (e) {}
if (profileId) {
const mine = await getPersonalModels(authorId);
const own = mine.find(x => String(x.id) === String(profileId));
if (own) return { type: 'profile', profile: own };
const p = profiles.find(x => String(x.id) === String(profileId));
if (p) return { type: 'profile', profile: p };
}
if (String(active) !== 'native') {
const p = profiles.find(x => String(x.id) === String(active));
if (p) return { type: 'profile', profile: p };
}
return { type: 'native', model: AI_MODEL, baseUrl: aiUrl };
} catch (e) {
return { type: 'native', model: AI_MODEL, baseUrl: aiUrl };
}
}
function normalizeOpenAiBase(baseUrl) {
const b = (baseUrl || '').replace(/\/$/, '');
return b.includes('/v1') ? b : `${b}/v1`;
}
async function callModel(systemPrompt, userText, profileId, authorId) {
const text = String(userText || '');
const resolved = await resolveActiveProfile(profileId, authorId);
const modelName = resolved.type === 'profile'
? (resolved.profile.model || AI_MODEL)
: (resolved.model || AI_MODEL);
if (text.length > MAX_INPUT_CHARS) {
return { content: text.slice(0, TEXT_MAX), model: modelName, finishReason: 'input_truncated' };
}
const controller = new AbortController();
const timerAbort = setTimeout(() => controller.abort(), TIMEOUT_MS);
try {
let url, headers, model, maxTokens;
if (resolved.type === 'profile') {
const p = resolved.profile;
const base = normalizeOpenAiBase(p.base_url || aiUrl);
url = `${base}/chat/completions`;
headers = { 'Content-Type': 'application/json' };
if (p.api_key) headers.Authorization = `Bearer ${p.api_key}`;
model = p.model || AI_MODEL;
maxTokens = parseInt(p.max_tokens, 10) || Math.min(8192, Math.max(4096, text.length * 2 + 512));
} else {
const base = normalizeOpenAiBase(resolved.baseUrl || aiUrl);
url = `${base}/chat/completions`;
headers = { 'Content-Type': 'application/json' };
model = resolved.model || AI_MODEL;
maxTokens = Math.min(8192, Math.max(4096, text.length * 2 + 512));
}
const messages = [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: text }
];
for (let i = 0; i < 2; i++) {
const res = await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify({ model, messages, temperature: 0.4, max_tokens: maxTokens }),
signal: controller.signal
});
if (!res.ok) throw await aiHttpErrorFromResponse(res);
const data = await res.json();
const choice = data.choices && data.choices[0];
const content = (choice && choice.message && choice.message.content || '').trim();
const finishReason = (choice && choice.finish_reason) || '';
if (!content && finishReason === 'length' && maxTokens < MAX_TOKENS_CAP) {
maxTokens = Math.min(MAX_TOKENS_CAP, maxTokens * 4);
continue;
}
return { content, finishReason, model: modelName };
}
return { content: '', finishReason: 'length', model: modelName };
} finally {
clearTimeout(timerAbort);
}
}
function normalizeOutput(s) {
let out = String(s || '').trim();
if (out.startsWith('```') && out.endsWith('```')) {
out = out.slice(3, -3).trim();
}
out = out.replace(/^(Прощальное сообщение:|Сообщение:|Итоговый текст:)\s*/i, '');
out = out.replace(/^"|"$/g, '');
out = out.replace(/\n{3,}/g, '\n\n');
return out;
}
async function claimNext() {
const client = await pool.connect();
try {
await client.query('BEGIN');
const q = `SELECT * FROM farewell_messages
WHERE ai_status = 'pending' AND deleted_at IS NULL
ORDER BY id ASC
FOR UPDATE SKIP LOCKED
LIMIT 1`;
const r = await client.query(q);
if (r.rows.length === 0) {
await client.query('ROLLBACK');
return null;
}
const row = r.rows[0];
await client.query(`UPDATE farewell_messages SET ai_status='processing', updated_at=now() WHERE id=$1`, [row.id]);
await client.query('COMMIT');
return row;
} catch (e) {
try { await client.query('ROLLBACK'); } catch (e2) {}
throw e;
} finally {
client.release();
}
}
async function resolveFarewellPrompt(row) {
let prompt = defaultPrompt;
try {
if (row.author_id) {
const r = await pool.query(`SELECT value FROM user_settings WHERE user_id = $1 AND key = 'farewell_prompt'`, [row.author_id]);
const own = r.rows[0] && r.rows[0].value;
if (own && own.trim()) prompt = own.trim();
}
} catch (e) {}
return prompt;
}
async function processOne(row) {
let sources = [];
const ids = Array.isArray(row.source_feedback_ids) ? row.source_feedback_ids.slice(0, MAX_FEEDBACKS) : [];
if (ids.length) {
try {
const fr = await pool.query(
`SELECT f.feedback_date, f.topic, f.text, g.name AS group_name
FROM feedbacks f LEFT JOIN groups g ON g.id = f.group_id
WHERE f.id = ANY($1::int[]) AND f.deleted_at IS NULL
ORDER BY f.feedback_date ASC, f.id ASC`,
[ids]
);
sources = fr.rows;
} catch (e) {}
}
const fmtDateRu = d => {
const s = String(d || '');
return /^\d{4}-\d{2}-\d{2}$/.test(s) ? `${s.slice(8, 10)}.${s.slice(5, 7)}.${s.slice(0, 4)}` : s;
};
const feedbacksBlock = sources.length
? 'Отзывы по пройденным модулям резидента (используй как основу содержания):\nЗаписи упорядочены ХРОНОЛОГИЧЕСКИ — от самого старого к самому новому, каждая помечена датой в квадратных скобках [ДД.ММ.ГГГГ]. Учитывай эти даты и последовательность развития резидента.\n'
+ sources.map(s => {
const body = String(s.text || '').replace(/\s+/g, ' ').trim().slice(0, FEEDBACK_TEXT_CAP);
return `[${fmtDateRu(s.feedback_date)}] - ${s.topic || 'без темы'} : ${body}`;
}).join('\n\n')
: 'Отзывы по пройденным модулям резидента: не выбраны';
let context = '';
context += `Ученик: ${row.resident || ''}\n`;
context += `Тема: ${row.topic || 'не указана'}\n`;
if (row.message_date) context += `Дата прощального сообщения: ${fmtDateRu(row.message_date)}\n`;
context += feedbacksBlock + '\n';
if (row.template_text && String(row.template_text).trim()) {
context += `Прошлое прощальное сообщение (шаблон):\n${String(row.template_text).slice(0, FEEDBACK_TEXT_CAP)}\n`;
}
const draft = row.ai_prompt == null ? String(row.text || '').trim() : '';
if (draft) {
context += `Черновик автора прощального сообщения (возьми за основу, аккуратно переработай: грамотность, порядок мыслей, стиль):\n${draft.slice(0, FEEDBACK_TEXT_CAP)}\n`;
}
let systemPrompt = await resolveFarewellPrompt(row);
if (!systemPrompt) systemPrompt = 'Напиши прощальное сообщение об ученике по переданному контексту. Только готовый текст, без пояснений.';
const wish = String(row.prompt || '').trim();
const keys = {
resident: row.resident || '',
topic: row.topic || '',
wishes: wish || 'нет',
feedbacks: feedbacksBlock,
context: context,
};
const hasKeys = /\{(resident|topic|wishes|feedbacks|context)\}/.test(systemPrompt);
if (hasKeys) {
systemPrompt = systemPrompt.replace(/\{(\w+)\}/g, (m, k) => (Object.prototype.hasOwnProperty.call(keys, k) ? String(keys[k]) : m));
} else if (wish) {
systemPrompt += `\n\nПОЖЕЛАНИЯ АВТОРА (соблюдай их):\n${wish.slice(0, 8000)}`;
}
const userMsg = context || 'Сформируй прощальное сообщение';
const t0 = Date.now();
let call;
try {
call = await callModel(systemPrompt, userMsg, row.ai_profile || null, row.author_id || null);
} catch (e) {
return { status: 'error', error: e.message || 'error', prompt: systemPrompt, input: userMsg, durationMs: Date.now() - t0 };
}
const durationMs = Date.now() - t0;
const meta = { prompt: systemPrompt, input: userMsg, output: call.content, model: call.model, durationMs };
let norm = normalizeOutput(call.content);
if (!norm) {
const reason = call.finishReason ? ` (finish_reason=${call.finishReason})` : '';
return { status: 'error', error: `Пустой ответ от модели${reason}`, ...meta };
}
if (norm.length > TEXT_MAX) norm = norm.slice(0, TEXT_MAX);
return { status: 'done', text: norm, ...meta };
}
function capStr(v, max) {
if (v == null) return null;
const s = String(v);
return s.length > max ? s.slice(0, max) : s;
}
function auditRun(row, res, attempt) {
if (!logAudit) return;
const payload = {
id: row.id,
status: res.status,
attempt: attempt || 1,
model: res.model || null,
profile: row.ai_profile || 'native',
duration_ms: Number.isFinite(res.durationMs) ? Math.round(res.durationMs) : null,
prompt: capStr(res.prompt, 12000),
input: capStr(res.input, 12000),
error: res.error ? String(res.error).slice(0, 500) : null,
};
if (res.status === 'error') {
Promise.resolve(logAudit(null, 'farewell.ai.error', payload)).catch(() => {});
return;
}
payload.output = capStr(res.output, 8000);
payload.len_after = res.text ? res.text.length : null;
Promise.resolve(logAudit(null, 'farewell.ai.run', payload)).catch(() => {});
}
async function finish(row, res, attempt) {
const client = await pool.connect();
try {
await client.query('BEGIN');
const sets = [];
const params = [];
let i = 1;
sets.push(`ai_status=$${i++}`); params.push(res.status);
if (res.error) { sets.push(`ai_error=$${i++}`); params.push(res.error); } else { sets.push(`ai_error=NULL`); }
sets.push(`ai_prompt=$${i++}`); params.push(res.prompt != null ? res.prompt : null);
sets.push(`ai_model=$${i++}`); params.push(res.model != null ? res.model : null);
sets.push(`ai_duration_ms=$${i++}`); params.push(Number.isFinite(res.durationMs) ? Math.round(res.durationMs) : null);
if (res.status === 'done' && res.text) { sets.push(`text=$${i++}`); params.push(res.text); }
sets.push(`updated_at=now()`);
params.push(row.id);
await client.query(`UPDATE farewell_messages SET ${sets.join(', ')} WHERE id=$${i}`, params);
await client.query('COMMIT');
} catch (e) {
try { await client.query('ROLLBACK'); } catch (e2) {}
throw e;
} finally {
client.release();
}
auditRun(row, res, attempt);
try { onDone({ row, status: res.status, text: res.text, error: res.error }); } catch (e) {}
}
async function tick() {
if (stopped || !running || inFlight) return;
inFlight = true;
try {
let attempts = 0;
while (attempts < MAX_ATTEMPTS) {
attempts++;
const row = await claimNext();
if (!row) break;
let res;
try {
res = await processOne(row);
} catch (e) {
res = { status: 'error', error: e.message };
}
if (res.status === 'error' && attempts < MAX_ATTEMPTS) {
const client = await pool.connect();
try {
await client.query('BEGIN');
await client.query(`UPDATE farewell_messages SET ai_status='pending', updated_at=now(), ai_error=$2 WHERE id=$1`, [row.id, res.error || 'error']);
await client.query('COMMIT');
} catch (e2) {
try { await client.query('ROLLBACK'); } catch (e3) {}
} finally {
client.release();
}
idleMs = IDLE_MIN_MS;
continue;
}
await finish(row, res, attempts);
idleMs = IDLE_MIN_MS;
}
} catch (e) {
idleMs = Math.min(idleMs * 2, IDLE_MAX_MS);
} finally {
inFlight = false;
timer = setTimeout(tick, idleMs);
}
}
async function resetStale() {
try {
await pool.query(`UPDATE farewell_messages SET ai_status='pending', ai_error=NULL WHERE ai_status='processing' AND deleted_at IS NULL`);
} catch (e) {}
}
function start() {
if (running) return;
running = true;
stopped = false;
idleMs = IDLE_MIN_MS;
resetStale().finally(() => { tick(); });
}
function stop() {
running = false;
stopped = true;
if (timer) { clearTimeout(timer); timer = null; }
}
function getInfo() {
return { running, inFlight, idleMs };
}
return { start, stop, notify, getInfo };
}
function createNoteTitleWorker({ pool, getSetting, logAudit, aiUrl, model, defaultPrompt, bus, onDone }) {
const AI_URL = aiUrl || process.env.AI_URL || 'http://text-corrector:8080';
const MODEL = model || process.env.AI_MODEL || 'qwen2.5-1.5b-instruct-q4_k_m.gguf';
const DEFAULT_PROMPT = defaultPrompt || '';
const TIMEOUT_MS = Math.max(5000, parseInt(process.env.NOTE_AI_TIMEOUT_MS || '60000', 10) || 60000);
const MIN_CHARS = 10;
const MAX_INPUT_CHARS = 2000;
const TITLE_MAX = 100;
const MAX_ATTEMPTS = 3;
let started = false;
let stopped = false;
let idleMs = IDLE_MIN_MS;
let wake = null;
let processing = false;
let currentId = null;
let startedAt = null;
const stats = { checks: 0, generated: 0, skipped: 0, errors: 0, last_at: null, last_error: null };
const attempts = new Map();
function sleep(ms) {
return new Promise((resolve) => {
const t = setTimeout(() => { wake = null; resolve(); }, ms);
wake = () => { clearTimeout(t); wake = null; resolve(); };
});
}
function wakeLocal() {
if (wake) wake();
}
function notify() {
wakeLocal();
if (bus) bus.publish();
}
if (bus) bus.subscribe(wakeLocal);
async function isEnabled() {
return String(await getSetting('notes_ai_enabled', 'true')) !== 'false';
}
async function claimNext() {
const client = await pool.connect();
try {
await client.query('BEGIN');
const { rows } = await client.query(
`SELECT id, user_id, note, tags
FROM user_notes
WHERE ai_status = 'pending' AND title = '' AND deleted_at IS NULL
ORDER BY id ASC LIMIT 1 FOR UPDATE SKIP LOCKED`
);
if (!rows.length) {
await client.query('COMMIT');
return null;
}
await client.query(`UPDATE user_notes SET ai_status = 'processing' 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();
}
}
async function resolveActiveProfile() {
try {
const active = await getSetting('ai_active_profile', 'native');
if (active && active !== 'native') {
const raw = await getSetting('ai_profiles', '[]');
const list = JSON.parse(raw || '[]');
if (Array.isArray(list)) {
return list.find(p => p && p.id === active && p.base_url && p.model) || null;
}
}
} catch (e) {}
return null;
}
function normalizeOpenAiBase(base) {
const b = String(base || '').trim().replace(/\/+$/, '');
if (!/^https?:\/\//i.test(b)) return null;
if (!/\/v1$/i.test(b)) return b + '/v1';
return b;
}
async function callModel(userText, systemPrompt) {
const profile = await resolveActiveProfile();
const headers = { 'Content-Type': 'application/json' };
let url;
let modelName;
let maxTokens;
if (profile) {
const base = normalizeOpenAiBase(profile.base_url);
if (!base) throw new Error('Некорректный base_url профиля ИИ');
url = `${base}/chat/completions`;
modelName = profile.model;
if (profile.api_key) headers.Authorization = `Bearer ${profile.api_key}`;
maxTokens = parseInt(profile.max_tokens, 10) || Math.min(4096, Math.max(1024, userText.length * 2 + 512));
} else {
url = `${AI_URL.replace(/\/+$/, '')}/v1/chat/completions`;
modelName = MODEL;
maxTokens = Math.min(512, Math.max(128, userText.length + 256));
}
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
try {
const res = await fetch(url, {
method: 'POST',
headers,
signal: controller.signal,
body: JSON.stringify({
model: modelName,
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userText },
],
temperature: 0.2,
max_tokens: maxTokens,
}),
});
if (!res.ok) throw await aiHttpErrorFromResponse(res);
const data = await res.json();
const choice = data.choices && data.choices[0];
return (choice && choice.message && choice.message.content || '').trim();
} finally {
clearTimeout(timer);
}
}
function normalizeTitle(out) {
let s = String(out || '').trim();
if (!s) return '';
s = s.replace(/^```[a-zA-Z]*\s*/, '').replace(/```$/, '').trim();
s = s.split(/\r?\n/).map(l => l.trim()).filter(Boolean)[0] || '';
s = s.replace(/^(?:заголовок|title)\s*[:—-]\s*/i, '').trim();
s = s.replace(/^["'«”]+/, '').replace(/["'«»"]+$/, '').trim();
if (s.length > TITLE_MAX) s = s.slice(0, TITLE_MAX).trim();
return s;
}
async function finish(row, status, title, error) {
await pool.query(
`UPDATE user_notes SET
title = CASE WHEN $1 <> '' THEN $1 ELSE title END,
ai_status = $2, updated_at = now()
WHERE id = $3 AND ai_status = 'processing' AND deleted_at IS NULL`,
[title || '', status, row.id]
);
attempts.delete(row.id);
stats.last_at = new Date().toISOString();
stats.last_error = error || null;
if (onDone) await onDone({ row, status, title: title || '', error: error || null });
}
async function processOne(row) {
const text = String(row.note || '').trim();
if (text.length < MIN_CHARS) {
await finish(row, 'skipped', '', null);
stats.skipped++;
return true;
}
const prompt = DEFAULT_PROMPT;
const tags = String(row.tags || '').trim();
const input = text.length > MAX_INPUT_CHARS ? text.slice(0, MAX_INPUT_CHARS) : text;
const context = [tags ? `Теги: ${tags}` : '', 'Текст заметки:', input].filter(l => l !== '').join('\n');
try {
const title = normalizeTitle(await callModel(context, prompt));
if (!title) {
const reason = 'Модель вернула пустой ответ';
await finish(row, 'error', '', reason);
stats.errors++;
return true;
}
await finish(row, 'done', title, null);
stats.checks++;
stats.generated++;
return true;
} catch (e) {
const message = (e && e.message ? e.message : 'error').slice(0, 500);
const tries = (attempts.get(row.id) || 0) + 1;
if (tries < MAX_ATTEMPTS) {
attempts.set(row.id, tries);
await pool.query(`UPDATE user_notes SET ai_status = 'pending' WHERE id = $1`, [row.id]);
if (logAudit) await logAudit(null, 'note.ai.retry', { id: row.id, attempt: tries, error: message });
return false;
}
await finish(row, 'error', '', message);
stats.errors++;
if (logAudit) await logAudit(null, 'note.ai.error', { id: row.id, error: message });
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('Note title AI 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('Note title AI process error:', e.message);
} finally {
processing = false;
currentId = null;
}
if (!ok) await sleep(IDLE_MAX_MS);
}
}
function resetStale() {
return pool.query(`UPDATE user_notes SET ai_status = 'pending' WHERE ai_status = 'processing'`);
}
function start() {
if (started) return;
started = true;
startedAt = Date.now();
resetStale()
.catch((e) => console.error('Note title AI reset error:', e.message))
.finally(() => { loop().catch((e) => console.error('Note title AI 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, timeout_ms: TIMEOUT_MS, model: MODEL, ai_url: AI_URL },
...stats,
};
}
return { start, stop, notify, getInfo };
}
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 wakeLocal() {
if (wake) wake();
}
function notify() {
wakeLocal();
if (bus) bus.publish();
}
if (bus) bus.subscribe(wakeLocal);
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 };
}
function createQuizAiWorker({ pool, generate, onDone, bus }) {
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 = { generated: 0, errors: 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 wakeLocal() {
if (wake) wake();
}
function notify() {
wakeLocal();
if (bus) bus.publish();
}
if (bus) bus.subscribe(wakeLocal);
async function claimNext() {
const client = await pool.connect();
try {
await client.query('BEGIN');
const { rows } = await client.query(
`SELECT id, user_id, prompt, kind, question_count, difficulty, profile
FROM quiz_ai_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 quiz_ai_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();
}
}
async function processOne(row) {
try {
const result = await generate(row);
const saved = await pool.query(
`UPDATE quiz_ai_jobs
SET status = 'done', quiz_id = $2, questions = $3, model = $4, error = NULL,
updated_at = now(), finished_at = now()
WHERE id = $1 RETURNING *`,
[row.id, result.quiz.id, result.questions, result.model]
);
stats.generated++;
stats.last_at = new Date().toISOString();
if (onDone && saved.rows.length) {
await onDone({ row: saved.rows[0], result, status: 'done' })
.catch(e => console.error('Quiz AI onDone error:', e.message));
}
} catch (e) {
const message = String(e && e.message ? e.message : e).slice(0, 500);
const saved = await pool.query(
`UPDATE quiz_ai_jobs
SET status = 'error', error = $2, updated_at = now(), finished_at = now()
WHERE id = $1 RETURNING *`,
[row.id, message]
).catch(() => null);
stats.errors++;
stats.last_error = message;
stats.last_at = new Date().toISOString();
if (onDone) {
await onDone({ row: saved && saved.rows.length ? saved.rows[0] : row, status: 'error', error: message })
.catch(err => console.error('Quiz AI onDone error:', err.message));
}
}
}
async function loop() {
while (!stopped) {
let row = null;
try {
row = await claimNext();
} catch (e) {
console.error('Quiz AI 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;
try {
await processOne(row);
} catch (e) {
console.error('Quiz AI process error:', e.message);
} finally {
processing = false;
currentId = null;
}
sincePrune++;
if (sincePrune >= 25) {
sincePrune = 0;
pool.query(`DELETE FROM quiz_ai_jobs WHERE status IN ('done', 'error') AND updated_at < now() - interval '7 days'`)
.catch(e => console.error('Quiz AI prune error:', e.message));
}
}
}
function resetStale() {
return pool.query(
`UPDATE quiz_ai_jobs
SET status = 'error', error = 'Генерация прервана перезапуском сервера',
updated_at = now(), finished_at = now()
WHERE status = 'processing'`
);
}
function start() {
if (started) return;
started = true;
startedAt = Date.now();
resetStale()
.catch(e => console.error('Quiz AI reset error:', e.message))
.finally(() => { loop().catch(e => console.error('Quiz AI 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 },
...stats,
};
}
return { start, stop, notify, getInfo };
}
const DIGEST_PUBLISH_INTERVAL_MS = Math.max(10000, parseInt(process.env.DIGEST_PUBLISH_INTERVAL_MS || '60000', 10) || 60000);
function createDigestPublisher({ pool, onDone }) {
let timer = null;
let stopped = false;
async function tick() {
if (stopped) return;
try {
const { rows } = await pool.query(
`UPDATE digests
SET published_at = now()
WHERE post_at IS NOT NULL AND post_at <= now() AND published_at IS NULL
RETURNING id, title, author_id, post_at, published_at`
);
for (const d of rows) {
if (onDone) await onDone(d).catch(() => {});
}
} catch (e) {
console.error('Digest publisher tick:', e.message);
}
if (!stopped) timer = setTimeout(tick, DIGEST_PUBLISH_INTERVAL_MS);
}
function start() {
stopped = false;
tick();
}
function stop() {
stopped = true;
if (timer) { clearTimeout(timer); timer = null; }
}
function notify() { /* time-based, no external wake needed */ }
return { start, stop, notify };
}
module.exports = { createEntryAutoChecker, createPhotoEnhanceWorker, createLessonReportChecker, createFeedbackWriter, createNoteTitleWorker, createFaceScanWorker, createQuizAiWorker, createDigestPublisher, createFarewellWorker, lessonTopicPosition };