LichessStatTgWeb/LichessClientTG_bot/events.py
vrubelroman 6351e18795 admin bot: /status redesigned around health, growth and activity; raw counters moved to /counters
- /status: verdict line (✅/⚠️, UTC time), 🩺 health (errors today/yesterday,
  Lichess 429 per 24 h from /health, age of the last player-status refresh,
  closed/not-found players, users who blocked the bot in 7 days), 📈 growth
  table (users/gamers/subscriptions: total, +today, +yesterday, +7 days,
  users without gamers), ⚡ activity today vs yesterday (commands, active
  users, notifications, Lichess requests). Flags: errors >= 10, any 429,
  status older than 30 min, no SUMMARY for yesterday, journal missing.
  Blocks fail independently (only a DB failure breaks the whole message).
- /counters: all raw command counters sorted by total + last SUMMARY as is.
- Database.get_admin_overview replaces get_admin_stats.
- events.summarize_days (one pass over events.log.1 + events.log, extra
  keys active_users/blocked/status_refresh_failed/cmd_by_name/lines),
  last_summary(); last_summary_line reads the rotated backup too.
- LichessAPI.get_service_health(timeout).
- Designer spec in docs/design/admin_status.md; README, CURRENT_STATE,
  CHANGELOG (Unreleased) updated; 25 new tests (61 bot tests total).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-21 06:16:53 +00:00

300 lines
12 KiB
Python

"""
Structured event log: one compact, grep-able line per thing a user or the
system did, kept apart from the noisy container log.
File: <dir of config.DATABASE_PATH>/events.log (i.e. the data volume, so it
survives container recreation), rotated at 10 MB x 5 backups. Line format:
2026-10-20T22:15:12Z EVT <name> key=value key2=value2 ...
2026-10-20T00:00:01Z SUMMARY date=2026-10-19 users=... checks=... ...
Values: ints as-is, True/False as 1/0, None as "-", strings truncated to 80
chars and repr-quoted when they contain a space or "=". Fields keep the order
they were passed in, so a name's lines always look alike and `grep -c "EVT
gamer_added"` / `grep "uid=12345"` answer the usual questions directly.
Both the bot and the admin-bot process import this and may write to the SAME
file (there is one data volume): that is acceptable here — the handler opens
the file in append mode and lines are short (one write() each), so they
interleave but never corrupt each other. Only the rotation itself can race
(two processes rotating at the same instant); the admin bot writes a handful
of lines a day, so it practically never triggers it.
event() never raises: a logging failure must not break the handler that
called it. The first failure is reported once to the normal logger.
"""
import logging
import os
import re
from typing import Dict, Iterable, Optional
import time
from logging.handlers import RotatingFileHandler
import config
# NOT getLogger(__name__): this module is named "events", which is exactly the
# dedicated file logger below; the warnings here must reach the container log.
logger = logging.getLogger("bot.events")
EVENTS_LOG_PATH = os.path.join(os.path.dirname(config.DATABASE_PATH), "events.log")
MAX_BYTES = 10 * 1024 * 1024
BACKUP_COUNT = 5
MAX_STR_LEN = 80
_events_logger = None
_setup_failed_reported = False
def _get_logger() -> logging.Logger:
"""Lazily build the dedicated 'events' logger (propagate=False: not in the container log)."""
global _events_logger
if _events_logger is not None:
return _events_logger
lg = logging.getLogger("events")
lg.setLevel(logging.INFO)
lg.propagate = False
if not lg.handlers:
handler = RotatingFileHandler(EVENTS_LOG_PATH, maxBytes=MAX_BYTES, backupCount=BACKUP_COUNT, encoding="utf-8")
handler.setFormatter(logging.Formatter("%(message)s"))
lg.addHandler(handler)
_events_logger = lg
return lg
def _fmt_value(value) -> str:
if value is None:
return "-"
if value is True:
return "1"
if value is False:
return "0"
if isinstance(value, int):
return str(value)
if isinstance(value, float):
return f"{value:.1f}"
s = str(value)
if len(s) > MAX_STR_LEN:
s = s[:MAX_STR_LEN]
if " " in s or "=" in s or s == "":
return repr(s)
return s
def _format_line(kind: str, name: str, fields: dict) -> str:
ts = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
parts = [ts, kind]
if name:
parts.append(name)
for key, value in fields.items():
parts.append(f"{key}={_fmt_value(value)}")
return " ".join(parts)
def _write(kind: str, name: str, fields: dict) -> None:
global _setup_failed_reported
try:
_get_logger().info(_format_line(kind, name, fields))
except Exception as e:
if not _setup_failed_reported:
_setup_failed_reported = True
logger.warning(f"events.log unavailable ({EVENTS_LOG_PATH}): {e!r}; events will be dropped")
def event(name: str, /, **fields) -> None:
"""Write one `EVT <name> k=v ...` line. Never raises. `name` is positional-only so a field may also be called name= (e.g. cmd name=start)."""
_write("EVT", name, fields)
def summary(**fields) -> None:
"""Write one `SUMMARY k=v ...` line (daily totals computed by summarize_day, see periodic.write_daily_summary). Never raises."""
_write("SUMMARY", "", fields)
def tail_events(limit: int = 30, needle: Optional[str] = None) -> list:
"""Last `limit` lines of events.log (optionally only those containing `needle`,
case-insensitive), oldest first. Used by the admin bot's /events. Reads the
rotated backup too (events.log.1) so a filter still finds older lines."""
try:
lines = []
for path in (EVENTS_LOG_PATH + ".1", EVENTS_LOG_PATH):
if os.path.exists(path):
with open(path, "r", encoding="utf-8", errors="replace") as f:
lines.extend(l.rstrip("\n") for l in f)
if needle:
low = needle.lower()
lines = [l for l in lines if low in l.lower()]
return lines[-limit:] if limit > 0 else []
except Exception as e:
logger.warning(f"Could not read {EVENTS_LOG_PATH}: {e!r}")
return []
# key=value tokens of an event line; a value is either repr-quoted (then it may
# contain spaces / '=') or a run of non-space characters.
_FIELD_RE = re.compile(r"""(\w+)=('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|\S+)""")
def parse_event_line(line: str):
"""
Split one events.log line into (date 'YYYY-MM-DD', kind 'EVT'|'SUMMARY',
name, fields dict). For a SUMMARY line name is ''. Field values are the
raw tokens as written (ints as digit strings, quoted strings with their
quotes). Returns None for a line that is not in the event format.
"""
parts = line.rstrip("\n").split(" ", 3)
if len(parts) < 2 or len(parts[0]) != 20 or parts[0][10] != "T" or parts[0][19] != "Z":
return None
ts, kind = parts[0], parts[1]
if kind == "EVT":
if len(parts) < 3:
return None
name, rest = parts[2], parts[3] if len(parts) > 3 else ""
elif kind == "SUMMARY":
name, rest = "", " ".join(parts[2:])
else:
return None
fields = {m.group(1): m.group(2) for m in _FIELD_RE.finditer(rest)}
return ts[:10], kind, name, fields
SUMMARY_COUNTERS = ('checks', 'skipped', 'notifications', 'errors',
'users_started', 'new_users', 'gamers_added', 'commands')
# Events that count as "a person did something" for the active_users figure of
# summarize_days (distinct uid per day). Background work (check, status_refresh,
# admin_notify ...) has no person behind it and is left out on purpose.
_ACTIVE_USER_EVENTS = ('cmd', 'callback', 'text', 'user_start')
def _new_day_totals() -> dict:
totals = {key: 0 for key in SUMMARY_COUNTERS}
totals.update({'active_users': set(), 'blocked': 0, 'status_refresh_failed': 0,
'cmd_by_name': {}, 'lines': 0})
return totals
def summarize_days(dates: Iterable[str], path: Optional[str] = None) -> Optional[Dict[str, dict]]:
"""
Daily totals for several UTC days (YYYY-MM-DD, the date part of the line
timestamps) in ONE pass over events.log and its first rotated backup
(events.log.1), so a restart during the day loses nothing (the former
in-memory counters did). `path` overrides EVENTS_LOG_PATH (tests).
Returns {date: totals} with, per day, the SUMMARY_COUNTERS
checks EVT check with decision=request (a games request was made)
skipped EVT check with decision=skip_* (window skipped on bulk status)
notifications EVT check with notified=1
errors EVT check_error + EVT tg_error
users_started EVT user_start
new_users EVT user_start with new=1
gamers_added EVT gamer_added
commands EVT cmd
plus, for the admin bot's /status:
active_users distinct uid over cmd / callback / text / user_start
blocked EVT blocked (a user blocked the bot)
status_refresh_failed EVT status_refresh with ok=0
cmd_by_name {command name: count} of EVT cmd
lines EVT lines of that day (0 = nothing logged: /status
prints "—" rather than zeros for such a day)
Returns None (not zeros) when the journal does not exist or cannot be read:
"no errors" and "no journal" must stay distinguishable. Never raises.
"""
base = path or EVENTS_LOG_PATH
wanted = {d: _new_day_totals() for d in dates}
files = [p for p in (base + ".1", base) if os.path.exists(p)]
if not files:
return None
try:
for file_path in files:
with open(file_path, "r", encoding="utf-8", errors="replace") as f:
for line in f:
totals = wanted.get(line[:10])
if totals is None:
continue
parsed = parse_event_line(line)
if parsed is None or parsed[1] != "EVT":
continue
_, _, name, fields = parsed
totals['lines'] += 1
if name in _ACTIVE_USER_EVENTS:
uid = fields.get("uid")
if uid and uid != "-":
totals['active_users'].add(uid)
if name == "check":
decision = fields.get("decision", "")
if decision == "request":
totals['checks'] += 1
elif decision.startswith("skip_"):
totals['skipped'] += 1
if fields.get("notified") == "1":
totals['notifications'] += 1
elif name in ("check_error", "tg_error"):
totals['errors'] += 1
elif name == "user_start":
totals['users_started'] += 1
if fields.get("new") == "1":
totals['new_users'] += 1
elif name == "gamer_added":
totals['gamers_added'] += 1
elif name == "cmd":
totals['commands'] += 1
cmd_name = fields.get("name", "-")
totals['cmd_by_name'][cmd_name] = totals['cmd_by_name'].get(cmd_name, 0) + 1
elif name == "blocked":
totals['blocked'] += 1
elif name == "status_refresh":
if fields.get("ok") == "0":
totals['status_refresh_failed'] += 1
except Exception as e:
logger.warning(f"Could not summarise {base}: {e!r}")
return None
for totals in wanted.values():
totals['active_users'] = len(totals['active_users'])
return wanted
def summarize_day(date_str: str, path: Optional[str] = None) -> dict:
"""
SUMMARY_COUNTERS totals for one UTC day — what periodic.write_daily_summary
puts into the SUMMARY line. A thin wrapper over summarize_days that keeps
the documented keys only; an unreadable or missing file counts as empty
here (the SUMMARY line is written regardless). Never raises.
"""
days = summarize_days([date_str], path)
if days is None:
return {key: 0 for key in SUMMARY_COUNTERS}
return {key: days[date_str][key] for key in SUMMARY_COUNTERS}
def last_summary_line() -> str:
"""The last SUMMARY line of events.log (used by the admin bot's /status), or '' if none / no file.
Reads the rotated backup too: after a rotation later in the day the midnight
SUMMARY lives only in events.log.1."""
try:
last = ""
for path in (EVENTS_LOG_PATH + ".1", EVENTS_LOG_PATH):
if not os.path.exists(path):
continue
with open(path, "r", encoding="utf-8", errors="replace") as f:
for line in f:
if " SUMMARY " in line:
last = line.rstrip("\n")
return last
except Exception as e:
logger.warning(f"Could not read last SUMMARY from {EVENTS_LOG_PATH}: {e!r}")
return ""
def last_summary() -> Optional[dict]:
"""
Fields of the last SUMMARY line as parse_event_line gives them (raw
strings, e.g. {'date': '2026-10-20', 'users': '624', ...}), or None when
there is no SUMMARY yet. The admin bot's /status compares fields['date']
with yesterday to see whether the bot was alive at midnight.
"""
parsed = parse_event_line(last_summary_line())
return parsed[3] if parsed else None