LichessStatTgWeb/LichessClientTG_bot/events.py
vrubelroman a7571f13c1
All checks were successful
CI/CD Pipeline / build-and-deploy (push) Successful in 16s
v1.5.1: not-found players paused, tests in repo + CI, log-based daily summary, docs pruned
- players absent from two consecutive bulk answers (deleted/renamed on Lichess) are paused
  like closed accounts with their own notice; ❓ mark; stats service answers 404 instead
  of "0 games" for unknown users
- /getgamers table stays unmarked, a legend line under it lists closed / not-found players
- daily SUMMARY is computed from events.log (survives restarts); lichess_429 comes from the
  stats service /health, which now exposes lichess_429_24h / lichess_429_total
- admin /status reads its numbers through Database.get_admin_stats
- tests/: 36 bot + 15 service unittest cases, run_tests.sh runs them inside the real images,
  CI runs them after the build and before pushing/deploying
- docs: USER_GUIDE/about/API_DOCUMENTATION rewritten for the current code, ARCHITECTURE.md and
  two sub-READMEs removed, 7 obsolete helper scripts removed, CURRENT_STATE updated
- .claude/agents/designer.md: Telegram-aware designer role

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

233 lines
9 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 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')
def summarize_day(date_str: str, path: Optional[str] = None) -> dict:
"""
Daily totals for the UTC day `date_str` (YYYY-MM-DD, the date part of the
line timestamps), counted from events.log and its first rotated backup
(events.log.1), so a restart during the day loses nothing (the former
in-memory counters did). Used by periodic.write_daily_summary for the
SUMMARY line; `path` overrides EVENTS_LOG_PATH (tests).
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
Never raises: an unreadable file counts as empty (and is logged).
"""
base = path or EVENTS_LOG_PATH
totals = {key: 0 for key in SUMMARY_COUNTERS}
try:
for file_path in (base + ".1", base):
if not os.path.exists(file_path):
continue
with open(file_path, "r", encoding="utf-8", errors="replace") as f:
for line in f:
if not line.startswith(date_str):
continue
parsed = parse_event_line(line)
if parsed is None or parsed[1] != "EVT":
continue
_, _, name, fields = parsed
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
except Exception as e:
logger.warning(f"Could not summarise {base} for {date_str}: {e!r}")
return totals
def last_summary_line() -> str:
"""The last SUMMARY line of events.log (used by the admin bot's /status), or '' if none / no file."""
try:
if not os.path.exists(EVENTS_LOG_PATH):
return ""
last = ""
with open(EVENTS_LOG_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 ""