/** * Tiny in-memory activity log + health board. * * Every source reports here (`ok`, `fail`, `note`), and /api/status shows it on * the page, so "is it actually running?" is answered without reading server logs. */ const MAX_LINES = 200 const lines = [] const health = {} const now = () => Math.floor(Date.now() / 1000) function push(level, scope, message) { const line = { at: now(), level, scope, message: String(message || '').slice(0, 400) } lines.push(line) if (lines.length > MAX_LINES) lines.shift() const text = `[${scope}] ${line.message}` if (level === 'error') console.error(text) else console.log(text) } const info = (scope, message) => push('info', scope, message) const warn = (scope, message) => push('warn', scope, message) const error = (scope, message) => push('error', scope, message) /** Record the outcome of one run of a source (x-search, tg-catchup, invites …). */ function ok(name, detail = {}) { const entry = health[name] || (health[name] = { runs: 0, failures: 0 }) entry.runs += 1 entry.lastOk = now() entry.lastRun = entry.lastOk entry.error = null entry.streak = 0 Object.assign(entry, detail) } function fail(name, err, detail = {}) { const entry = health[name] || (health[name] = { runs: 0, failures: 0 }) entry.runs += 1 entry.failures += 1 entry.lastRun = now() entry.lastFail = entry.lastRun entry.streak = (entry.streak || 0) + 1 entry.error = String(err?.message || err || '未知错误').slice(0, 300) Object.assign(entry, detail) // Only log the first failure of a streak and then every 10th, to keep the log readable. if (entry.streak === 1 || entry.streak % 10 === 0) error(name, entry.error) } function set(name, detail) { const entry = health[name] || (health[name] = { runs: 0, failures: 0 }) Object.assign(entry, detail) } function snapshot() { return { health: JSON.parse(JSON.stringify(health)), lines: lines.slice(-80).reverse() } } module.exports = { info, warn, error, ok, fail, set, snapshot, now }