Spaces:
Sleeping
Sleeping
File size: 2,020 Bytes
5936c9d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | /**
* 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 }
|