- periodic report rebuilt in HTML: title with games count, mode lines, one <pre> table (± · colour · accuracy · opponent rating · opponent accuracy), 10-row cap, span note after catch-up; stats service returns tracked_rating_diff per game - /getgamers shows player state from the DB (played today / N days quiet / closed / not found, report period) without Lichess calls; ratings on a button - "player silent 30 days — keep?" prompt with keep/delete buttons, repeat 90 days - /today, /yesterday, /week: one message edited into the result, nav buttons - /year localised; active-gamer leftovers and N/A removed; one period wording - docker-compose.prod.yml: stats port 8002 bound to 127.0.0.1 - product review docs: user journeys, concepts, Mini App feasibility, proposal Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
861 lines
54 KiB
Python
861 lines
54 KiB
Python
"""
|
||
Periodic activity monitoring: one asyncio task per (user, gamer) pair with a
|
||
period set, plus the daily message-counter reset.
|
||
|
||
Pacing: every games/puzzles request made here goes to the LOCAL stats service
|
||
(LICHESS_STATS_API_BASE_URL). The real limiter for the shared Lichess token is
|
||
that service's SharedTokenGate (LichessWebServices/rate_limiter.py); the only
|
||
bot-side cap is `_request_slots` (config.PERIODIC_MAX_CONCURRENT_REQUESTS),
|
||
which bounds how many periodic HTTP requests are open at once so hundreds of
|
||
pairs don't each hold an idle connection while queued in the service.
|
||
|
||
Skipping: before each games request the pair consults the player's bulk status
|
||
(gamer_status, refreshed by player_status.py). If the player's total games count
|
||
has not changed since the pair's last request, nothing was played and the
|
||
window is skipped without any HTTP call; a closed account pauses the pair. See
|
||
_decide_skip / _skip_window_end for the exact rules and their safety argument.
|
||
"""
|
||
import asyncio
|
||
import html
|
||
import logging
|
||
import time
|
||
import zlib
|
||
from datetime import datetime, timedelta, timezone
|
||
from typing import Dict, Any
|
||
|
||
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
|
||
from telegram.error import Forbidden
|
||
|
||
import config
|
||
from database import Database
|
||
from lichess_api import LichessAPI, InvalidTokenError
|
||
from formatters import StatsFormatter, ROW_MODES
|
||
from i18n import t, format_count, format_day
|
||
from message_counters import MessageCounters
|
||
from notifications import AdminNotifier
|
||
from player_status import PlayerStatusRefresher
|
||
from events import event, summary, summarize_day
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
|
||
class PeriodicMonitor:
|
||
def __init__(self, db: Database, lichess_api: LichessAPI, counters: MessageCounters, notifier: AdminNotifier):
|
||
self.db = db
|
||
self.lichess_api = lichess_api
|
||
self.counters = counters
|
||
self.notifier = notifier
|
||
self.periodic_tasks = {} # Store periodic tasks
|
||
self.period_start_times = {} # Store start times for each gamer
|
||
self.application = None # telegram Application; set by bot.py once it is built
|
||
# At most this many periodic games/puzzles requests in flight to the local
|
||
# stats service at once (see module docstring).
|
||
self._request_slots = asyncio.Semaphore(config.PERIODIC_MAX_CONCURRENT_REQUESTS)
|
||
# Bulk player status refresh (player_status.py); run once before the periodic
|
||
# tasks start and then forever alongside them. None disables it (tests).
|
||
self.status_refresher = PlayerStatusRefresher(db, lichess_api, notifier)
|
||
self._status_refresh_task = None
|
||
# The daily SUMMARY line (write_daily_summary) is computed from
|
||
# events.log, not from in-memory counters: a restart during the day
|
||
# used to zero them.
|
||
|
||
async def start_periodic_task(self, gamer: Dict[str, Any], user_id: int, period_minutes: int):
|
||
"""Start periodic task for a gamer"""
|
||
task_key = f"{gamer['id']}_{user_id}"
|
||
|
||
# Cancel existing task if any
|
||
if task_key in self.periodic_tasks:
|
||
self.periodic_tasks[task_key].cancel()
|
||
logger.info(f"Cancelled existing periodic task for {gamer['username']}")
|
||
|
||
# Remove old start time
|
||
if task_key in self.period_start_times:
|
||
del self.period_start_times[task_key]
|
||
|
||
# Create new periodic task
|
||
task = asyncio.create_task(
|
||
self.periodic_check(gamer, user_id, period_minutes)
|
||
)
|
||
self.periodic_tasks[task_key] = task
|
||
|
||
async def stop_periodic_task(self, gamer_id: int, user_id: int):
|
||
"""Stop periodic task for a user-gamer pair."""
|
||
task_key = f"{gamer_id}_{user_id}"
|
||
task = self.periodic_tasks.pop(task_key, None)
|
||
if task:
|
||
task.cancel()
|
||
logger.info(f"Cancelled periodic task for gamer_id={gamer_id}, user_id={user_id}")
|
||
self.period_start_times.pop(task_key, None)
|
||
|
||
# Оповещать админ-бота о затяжной серии ошибок каждые ADMIN_NOTIFY_ERROR_THRESHOLD
|
||
# подряд идущих ошибок (~2 часа при капнутом бэкоффе в 300с на попытку)
|
||
ADMIN_NOTIFY_ERROR_THRESHOLD = 25
|
||
|
||
# How much longer than its configured period a (collapsed) check window may be
|
||
# before it is treated as a stale backlog and its notification is suppressed.
|
||
STALE_BACKLOG_THRESHOLD = timedelta(hours=2)
|
||
|
||
@classmethod
|
||
def _is_stale_backlog(cls, window: timedelta, period_minutes: int) -> bool:
|
||
"""
|
||
True when a check window exceeds the pair's configured period by more than
|
||
STALE_BACKLOG_THRESHOLD. Measured relative to period_minutes, not as an
|
||
absolute length: a normal on-schedule window for period_minutes >= 180
|
||
is itself longer than 2h and must still produce a notification (an
|
||
absolute 2h cut-off silently dropped every notification for such pairs).
|
||
"""
|
||
return window > timedelta(minutes=period_minutes) + cls.STALE_BACKLOG_THRESHOLD
|
||
|
||
@staticmethod
|
||
def _checkpoint_jitter_seconds(user_id: int, gamer_id: int, period_minutes: int) -> float:
|
||
"""
|
||
Deterministic per-(user, gamer) jitter applied whenever a checkpoint gets
|
||
pinned to "now" (backlog collapse / first check). Without this, every pair
|
||
sharing the same period_minutes re-locks onto the exact same wall-clock
|
||
phase on every bot restart, causing them all to become "due" in the same
|
||
instant forever after. Stable across restarts (unlike Python's salted
|
||
hash()), and capped well below STALE_BACKLOG_THRESHOLD so it never
|
||
interacts with backlog-notification suppression.
|
||
"""
|
||
jitter_cap = min(period_minutes * 60 * config.PERIODIC_CHECKPOINT_JITTER_FRACTION,
|
||
config.PERIODIC_CHECKPOINT_JITTER_MAX_SECONDS)
|
||
if jitter_cap <= 0:
|
||
return 0.0
|
||
digest = zlib.crc32(f"{user_id}:{gamer_id}".encode())
|
||
return digest % jitter_cap
|
||
|
||
# A bulk status older than this is ignored (the refresh loop is probably
|
||
# down); the check then runs exactly as it did before status existed.
|
||
STATUS_MAX_AGE_SECONDS = 3 * config.PLAYER_STATUS_REFRESH_MINUTES * 60
|
||
|
||
# Safety margin subtracted from a status's checked_at when it is used as a
|
||
# window end: checked_at is taken after the bulk answer arrived, while the
|
||
# counts are as of the moment Lichess read them (a round trip earlier), plus
|
||
# clock skew between this host and Lichess. 60 s costs nothing.
|
||
STATUS_SAFETY_MARGIN_SECONDS = 60
|
||
|
||
@classmethod
|
||
def _decide_skip(cls, status, pair_state, now_ts: float, has_token: bool, since_ts: float = None) -> str:
|
||
"""
|
||
Decide what to do with the window [since_ts, ...] of a pair, given the
|
||
player's latest bulk status (db.get_gamer_status) and the pair's skip state
|
||
(db.get_pair_check_state). Returns 'request', 'skip_unchanged' or
|
||
'skip_closed' (the latter for a closed account AND for one Lichess no
|
||
longer knows, status['not_found'] — deleted or renamed; both pause the
|
||
pair, periodic_check tells them apart by `reason`). Pure function, so it
|
||
is unit-testable.
|
||
|
||
Why an unchanged total is proof of "no games": perfs.*.games counts every
|
||
finished game, rated or casual, and never decreases — a rated game cannot
|
||
leave it unchanged (a casual one only inflates it, which errs towards
|
||
requesting). What the proof covers is the interval between the baseline's
|
||
refresh (<= the checkpoint, see the store rule in periodic_check) and the
|
||
current status's refresh — NOT the whole window, which is why
|
||
_skip_window_end caps the checkpoint advance at that refresh moment, and
|
||
why a status that does not reach past since_ts cannot justify a skip.
|
||
"""
|
||
if not status:
|
||
return 'request'
|
||
checked_at = status.get('checked_at')
|
||
if checked_at is None or now_ts - checked_at > cls.STATUS_MAX_AGE_SECONDS:
|
||
return 'request' # stale: fall back to today's behaviour
|
||
if since_ts is not None and checked_at - cls.STATUS_SAFETY_MARGIN_SECONDS <= since_ts:
|
||
return 'request' # status predates the window: proves nothing about it
|
||
if status.get('disabled') or status.get('not_found'):
|
||
return 'skip_closed'
|
||
if has_token:
|
||
# Puzzle activity is not visible in perfs.*.games; a token pair must
|
||
# still request every window to notice puzzles.
|
||
return 'request'
|
||
last_total = pair_state.get('last_games_total') if pair_state else None
|
||
if last_total is None or status.get('games_total') is None:
|
||
return 'request' # first time: learn the baseline
|
||
if status['games_total'] == last_total:
|
||
return 'skip_unchanged'
|
||
return 'request'
|
||
|
||
@classmethod
|
||
def _skip_window_end(cls, period_end_approx: datetime, status: Dict[str, Any]) -> datetime:
|
||
"""
|
||
Where the checkpoint may advance to when a window is skipped on the
|
||
strength of `status`: the planned window end, but never past the moment
|
||
the status was refreshed (minus the safety margin). A game finished after
|
||
that refresh is not in the status's total yet; if the checkpoint jumped
|
||
past it, the next (requested) window would start after the game and it
|
||
would never be reported. Capping here keeps the loss profile identical to
|
||
a real request: only a game still in progress at the moment the window is
|
||
closed can be missed, exactly as today.
|
||
"""
|
||
covered_until = datetime.fromtimestamp(status['checked_at'] - cls.STATUS_SAFETY_MARGIN_SECONDS)
|
||
return min(period_end_approx, covered_until)
|
||
|
||
# "Player quiet for N days — keep following?" (docs/design/product_concepts.md
|
||
# 2.7): asked once seen_at is this old, and again no sooner than
|
||
# SILENT_PROMPT_REPEAT_DAYS after the last question ("keep" counts as one).
|
||
SILENT_PROMPT_DAYS = 30
|
||
SILENT_PROMPT_REPEAT_DAYS = 90
|
||
|
||
@classmethod
|
||
def _silent_prompt_days(cls, status, silent_prompt_at, now_ts: float):
|
||
"""
|
||
How many whole days the player has been quiet when the owner should be
|
||
asked about them now, else None. Asked only for a player whose status
|
||
has a seen_at (bulk status, ms) at least SILENT_PROMPT_DAYS old and who
|
||
is neither closed nor gone (those get their own notice), and only if
|
||
the question was never asked or was asked more than
|
||
SILENT_PROMPT_REPEAT_DAYS ago. Pure function, unit-tested.
|
||
"""
|
||
if not status or status.get('disabled') or status.get('not_found'):
|
||
return None
|
||
seen_at = status.get('seen_at')
|
||
if seen_at is None:
|
||
return None
|
||
days = int((now_ts - seen_at / 1000) // 86400)
|
||
if days < cls.SILENT_PROMPT_DAYS:
|
||
return None
|
||
if silent_prompt_at is not None and now_ts - silent_prompt_at < cls.SILENT_PROMPT_REPEAT_DAYS * 86400:
|
||
return None
|
||
return days
|
||
|
||
def silent_prompt_text(self, username: str, days: int, seen_at_ms: int, lang: str) -> str:
|
||
"""The 2.7 message for a player quiet for `days` days, last seen at seen_at_ms (HTML)."""
|
||
seen_day = datetime.fromtimestamp(seen_at_ms / 1000).date()
|
||
return t('silent_prompt', lang, name=html.escape(username), days=format_count(days, 'days', lang),
|
||
date=format_day(seen_day, lang))
|
||
|
||
def silent_prompt_keyboard(self, gamer_id: int, lang: str) -> InlineKeyboardMarkup:
|
||
"""[✅ Да, оставить] [🗑 Удалить] -> sl:keep:<id> / sl:del:<id> (handled in bot.py)."""
|
||
return InlineKeyboardMarkup([[
|
||
InlineKeyboardButton(t('btn_silent_keep', lang), callback_data=f"sl:keep:{gamer_id}"),
|
||
InlineKeyboardButton(t('btn_silent_delete', lang), callback_data=f"sl:del:{gamer_id}"),
|
||
]])
|
||
|
||
async def _maybe_silent_prompt(self, user_id: int, gamer: Dict[str, Any], status, pair_state, task_key: str) -> bool:
|
||
"""
|
||
Send the "quiet for N days" question if it is due (_silent_prompt_days)
|
||
and record silent_prompt_at. Returns True when the user has blocked the
|
||
bot (the pair was stopped, the caller must return). Any other send
|
||
failure is logged and the question is retried at the next check. The
|
||
periodic check itself continues as usual after this.
|
||
"""
|
||
days = self._silent_prompt_days(status, pair_state.get('silent_prompt_at'), time.time())
|
||
if days is None:
|
||
return False
|
||
username = gamer['username']
|
||
try:
|
||
user_lang = self.db.get_user_language(user_id)
|
||
await self.application.bot.send_message(
|
||
chat_id=user_id,
|
||
text=self.silent_prompt_text(username, days, status['seen_at'], user_lang),
|
||
parse_mode='HTML',
|
||
reply_markup=self.silent_prompt_keyboard(gamer['id'], user_lang)
|
||
)
|
||
except Forbidden:
|
||
self._stop_pair_blocked(user_id, gamer, task_key)
|
||
return True
|
||
except Exception as notify_err:
|
||
logger.error(f"Failed to ask user {user_id} about quiet player {username}: {notify_err}")
|
||
return False
|
||
now_ts = int(time.time())
|
||
self.db.set_pair_silent_prompt_at(user_id, gamer['id'], now_ts)
|
||
pair_state['silent_prompt_at'] = now_ts
|
||
logger.info(f"💤 Asked user {user_id} whether to keep {username} (quiet for {days} days)")
|
||
event('silent_prompt', uid=user_id, gamer=username, days=days)
|
||
return False
|
||
|
||
def _stop_pair_blocked(self, user_id: int, gamer: Dict[str, Any], task_key: str) -> None:
|
||
"""
|
||
telegram.error.Forbidden: the user blocked the bot. Permanent, not worth
|
||
retrying: disable the pair's period and drop its task (the caller then
|
||
returns from periodic_check). Without this, consecutive_errors gets reset
|
||
to 0 right before the send, so the outer handler's backoff never grows
|
||
past 60s and the pair retries forever, wasting queue capacity that other
|
||
users' real checks need.
|
||
"""
|
||
logger.warning(f"🚫 User {user_id} blocked the bot; stopping periodic monitoring for {gamer['username']}")
|
||
event('blocked', uid=user_id, gamer=gamer['username'])
|
||
self.db.set_user_gamer_period(user_id, gamer['id'], 0)
|
||
self.periodic_tasks.pop(task_key, None)
|
||
self.period_start_times.pop(task_key, None)
|
||
|
||
async def periodic_check(self, gamer: Dict[str, Any], user_id: int, period_minutes: int):
|
||
"""Periodic check for gamer activity"""
|
||
task_key = f"{gamer['id']}_{user_id}"
|
||
username = gamer['username']
|
||
|
||
checkpoint_ts = self.db.get_period_checkpoint(user_id, gamer['id'])
|
||
if checkpoint_ts is not None:
|
||
restored_time = datetime.fromtimestamp(checkpoint_ts)
|
||
self.period_start_times[task_key] = restored_time
|
||
logger.info(f"♻️ Restored periodic checkpoint for {username} (user {user_id}) at {restored_time}")
|
||
|
||
logger.info(f"🔄 Started periodic monitoring for {username} (user {user_id}) with {period_minutes} minute intervals")
|
||
|
||
consecutive_errors = 0
|
||
max_consecutive_errors = 5
|
||
is_first_check = True # Флаг для первой проверки
|
||
|
||
while True:
|
||
try:
|
||
# Проверяем, что период все еще установлен в БД
|
||
current_gamers = self.db.get_user_gamers(user_id)
|
||
gamer_still_exists = False
|
||
current_period = 0
|
||
for g in current_gamers:
|
||
if g['id'] == gamer['id']:
|
||
gamer_still_exists = True
|
||
current_period = g.get('period_minutes', 0)
|
||
break
|
||
|
||
# Если игрок удален или период отключен, прекращаем мониторинг
|
||
if not gamer_still_exists or current_period == 0:
|
||
logger.info(f"Periodic monitoring stopped for {gamer['username']}: gamer removed or period disabled")
|
||
if task_key in self.periodic_tasks:
|
||
del self.periodic_tasks[task_key]
|
||
if task_key in self.period_start_times:
|
||
del self.period_start_times[task_key]
|
||
break
|
||
|
||
# Обновляем период на случай, если он был изменен
|
||
if current_period != period_minutes:
|
||
logger.info(f"Period changed for {gamer['username']} from {period_minutes} to {current_period} minutes")
|
||
period_minutes = current_period
|
||
|
||
# Получаем сохраненное время последней проверки для расчета следующего периода
|
||
# Используем флаг is_first_check для первой проверки вместо проверки наличия ключа
|
||
last_check_time = self.period_start_times.get(task_key)
|
||
if is_first_check and checkpoint_ts is None:
|
||
last_check_time = None # Принудительно делаем первую проверку
|
||
is_first_check = False
|
||
|
||
if last_check_time:
|
||
# Уже была хотя бы одна проверка
|
||
# Рассчитываем, когда должен начаться следующий период
|
||
next_period_start = last_check_time + timedelta(minutes=period_minutes)
|
||
now = datetime.now()
|
||
|
||
# Если следующий период еще не наступил, ждем
|
||
if next_period_start > now:
|
||
wait_seconds = (next_period_start - now).total_seconds()
|
||
logger.debug(f"⏳ Waiting {wait_seconds:.1f} seconds until next period start ({next_period_start}) for {username}")
|
||
await asyncio.sleep(wait_seconds)
|
||
# Используем сохраненное время как начало периода
|
||
since_time = last_check_time
|
||
# Конец периода - это момент, когда должен был начаться следующий период
|
||
period_end_approx = next_period_start
|
||
logger.debug(f"📌 Using saved period: from {since_time} to {period_end_approx}")
|
||
else:
|
||
# Мы отстаём от расписания (бэклог): если догонять по period_minutes
|
||
# за раз, при большом отставании (недели простоя, много отслеживаемых
|
||
# игроков через один общий лимитер stats-сервиса) чекпоинт никогда не догонит
|
||
# текущее время — отставание только растёт. Вместо этого закрываем
|
||
# весь пропущенный промежуток одним запросом и сразу прыгаем к "сейчас".
|
||
# Джиттер (см. _checkpoint_jitter_seconds) не даёт всем парам с
|
||
# одинаковым period_minutes зафиксироваться на один и тот же момент.
|
||
since_time = last_check_time
|
||
jitter = self._checkpoint_jitter_seconds(user_id, gamer['id'], period_minutes)
|
||
period_end_approx = now - timedelta(seconds=jitter)
|
||
if period_end_approx - next_period_start > timedelta(minutes=period_minutes):
|
||
logger.warning(
|
||
f"⏰ {username} is behind schedule by "
|
||
f"{(now - next_period_start).total_seconds():.0f}s; "
|
||
f"collapsing backlog into one request from {since_time} to {period_end_approx}"
|
||
)
|
||
logger.info(f"📌 Using saved period: from {since_time} to {period_end_approx}")
|
||
else:
|
||
# Первая проверка - ждем period_minutes минут от момента запуска
|
||
logger.info(f"⏳ First check: waiting {period_minutes} minutes before first check for {username}")
|
||
await asyncio.sleep(period_minutes * 60)
|
||
|
||
# Получаем текущее время (с джиттером, см. _checkpoint_jitter_seconds)
|
||
jitter = self._checkpoint_jitter_seconds(user_id, gamer['id'], period_minutes)
|
||
period_end_approx = datetime.now() - timedelta(seconds=jitter)
|
||
# Начало периода - текущее время минус period_minutes
|
||
since_time = period_end_approx - timedelta(minutes=period_minutes)
|
||
logger.info(f"📌 First check: period from {since_time} to {period_end_approx}")
|
||
|
||
# A collapsed backlog spanning way more than a normal check window isn't
|
||
# "recent activity" anymore — dumping a multi-week, game-by-game report
|
||
# on the user reads as spam, not a periodic update. Catch the checkpoint
|
||
# up silently in that case instead of sending the full notification.
|
||
# "Way more" is measured against the pair's own configured period
|
||
# (see _is_stale_backlog): an on-schedule 3h/6h/12h/24h window is
|
||
# normal for those pairs, not a stale backlog.
|
||
is_stale_backlog = self._is_stale_backlog(period_end_approx - since_time, period_minutes)
|
||
if is_stale_backlog:
|
||
logger.warning(
|
||
f"⏭️ {username}: collapsed window ({since_time} to {period_end_approx}) "
|
||
f"exceeds the configured period ({period_minutes} min) by more than "
|
||
f"{self.STALE_BACKLOG_THRESHOLD}; catching up checkpoint silently, "
|
||
f"no notification will be sent for this stale backlog"
|
||
)
|
||
|
||
# Bulk-status shortcut (see module docstring, _decide_skip, player_status.py):
|
||
# most windows on prod find 0 games, and an unchanged games total
|
||
# proves that without a games request.
|
||
status = self.db.get_gamer_status(gamer['id'])
|
||
pair_state = self.db.get_pair_check_state(user_id, gamer['id'])
|
||
|
||
# An account that was reported closed (or not found) and now
|
||
# shows as active again: tell the owner once and clear the flag.
|
||
# Done BEFORE the decision: with an unchanged games total the
|
||
# pair keeps skipping, and if this lived on the 'request' path
|
||
# the owner would only hear about it after the player's next
|
||
# game (tester observation).
|
||
if pair_state['closed_notice_sent'] and status \
|
||
and not status.get('disabled') and not status.get('not_found'):
|
||
try:
|
||
user_lang = self.db.get_user_language(user_id)
|
||
await self.application.bot.send_message(
|
||
chat_id=user_id,
|
||
text=t('gamer_account_reopened', user_lang, username=username)
|
||
)
|
||
except Forbidden:
|
||
self._stop_pair_blocked(user_id, gamer, task_key)
|
||
return
|
||
except Exception as notify_err:
|
||
logger.error(f"Failed to notify user {user_id} that {username} is active again: {notify_err}")
|
||
else:
|
||
logger.info(f"✅ {username} is active again on Lichess; notifications resumed for user {user_id}")
|
||
event('reopened_notice', uid=user_id, gamer=username)
|
||
self.db.set_pair_closed_notice_sent(user_id, gamer['id'], False)
|
||
pair_state['closed_notice_sent'] = False
|
||
|
||
# A player quiet for 30+ days: ask the owner once whether to keep
|
||
# them (see _maybe_silent_prompt). Before the decision for the same
|
||
# reason as the reopened notice: such a pair skips every window.
|
||
# Does not touch the checkpoint or the decision below.
|
||
if await self._maybe_silent_prompt(user_id, gamer, status, pair_state, task_key):
|
||
return
|
||
|
||
decision = self._decide_skip(
|
||
status, pair_state, time.time(), has_token=bool(gamer.get('token')),
|
||
since_ts=since_time.timestamp()
|
||
)
|
||
window_seconds = int((period_end_approx - since_time).total_seconds())
|
||
# Baseline candidate for this iteration, snapshotted NOW (before the
|
||
# games request) and stored only together with the checkpoint below.
|
||
# It is only valid if the status was refreshed no later than the
|
||
# checkpoint it will be stored with: a status refreshed after
|
||
# period_end_approx already counts games of the NEXT window, and an
|
||
# equal total at the next check would hide them. In that case the
|
||
# previous baseline is kept (it stays valid: checkpoints only grow).
|
||
games_total_snapshot = None
|
||
if status and status.get('games_total') is not None \
|
||
and status['checked_at'] <= period_end_approx.timestamp():
|
||
games_total_snapshot = status['games_total']
|
||
|
||
if decision in ('skip_unchanged', 'skip_closed'):
|
||
skip_end = self._skip_window_end(period_end_approx, status)
|
||
# Advance the checkpoint like a zero-activity check does (see the
|
||
# comment block at the end of the loop), but only as far as the
|
||
# status covers (_skip_window_end). Not counted as a notification.
|
||
self.period_start_times[task_key] = skip_end
|
||
self.db.set_period_checkpoint(user_id, gamer['id'], int(skip_end.timestamp()))
|
||
consecutive_errors = 0
|
||
# skip_closed covers two different things (see _decide_skip):
|
||
# a closed account and one Lichess no longer knows.
|
||
reason = None
|
||
if decision == 'skip_closed':
|
||
reason = 'not_found' if status.get('not_found') else 'closed'
|
||
event('check', uid=user_id, gamer=username, decision=decision, reason=reason,
|
||
window_s=window_seconds, stale=is_stale_backlog, games=None, puzzles=None,
|
||
notified=False, lag_s=int((datetime.now() - period_end_approx).total_seconds()))
|
||
if decision == 'skip_unchanged':
|
||
logger.info(f"⏭️ Skipped check for {username} (user {user_id}): no new games since last check (total={status['games_total']})")
|
||
continue
|
||
if reason == 'not_found':
|
||
logger.info(f"❓ {username} no longer exists on Lichess (deleted or renamed); check skipped for user {user_id}")
|
||
notice_key = 'gamer_account_not_found'
|
||
else:
|
||
logger.info(f"⛔ {username} is a closed Lichess account; check skipped for user {user_id}")
|
||
notice_key = 'gamer_account_closed'
|
||
if not pair_state['closed_notice_sent']:
|
||
try:
|
||
user_lang = self.db.get_user_language(user_id)
|
||
await self.application.bot.send_message(
|
||
chat_id=user_id,
|
||
text=t(notice_key, user_lang, username=username)
|
||
)
|
||
except Forbidden:
|
||
# Same handling as the notification path below: permanent, stop the pair.
|
||
self._stop_pair_blocked(user_id, gamer, task_key)
|
||
return
|
||
except Exception as notify_err:
|
||
# Not marked as sent: try again at the next skipped check.
|
||
logger.error(f"Failed to notify user {user_id} that {username} is {reason}: {notify_err}")
|
||
else:
|
||
event('closed_notice', uid=user_id, gamer=username, reason=reason)
|
||
self.db.set_pair_closed_notice_sent(user_id, gamer['id'], True)
|
||
continue
|
||
|
||
# 'request' path.
|
||
since_timestamp = int(since_time.timestamp() * 1000)
|
||
# Используем приблизительное время как until_timestamp
|
||
# После получения ответа пересчитаем фактическое время
|
||
until_timestamp_approx = int(period_end_approx.timestamp() * 1000)
|
||
|
||
logger.info(f"🔍 Checking activity for {username} (user {user_id}): period from {since_time} to {period_end_approx} (approx, last {period_minutes} minutes)")
|
||
logger.debug(f"📅 Unix timestamps: since={since_timestamp}, until_approx={until_timestamp_approx}")
|
||
|
||
# Делаем запросы к stats-сервису с обработкой ошибок
|
||
games_data = None
|
||
puzzles_data = None
|
||
|
||
try:
|
||
# Запрос к локальному stats-сервису; очередь и пейсинг общего
|
||
# Lichess-токена — на его стороне (SharedTokenGate), здесь только
|
||
# ограничиваем число одновременно открытых соединений.
|
||
#
|
||
# by_finish=True: a game is reported in the window in which it
|
||
# FINISHED (lastMoveAt in (since, until]), not the one in which
|
||
# it was created. Lichess's own since/until filter by createdAt
|
||
# and omit games still in progress, so a game created at 14:58
|
||
# and finished at 15:06 was in neither the 14:00-15:00 window
|
||
# (still running when checked) nor the 15:00-16:00 one (created
|
||
# before 15:00). The service looks back a few hours before
|
||
# `since` and filters by finish time itself. Consistent with the
|
||
# bulk-status skip: games_total also grows at game end.
|
||
logger.debug(f"📥 Requesting games for {gamer['username']}")
|
||
async with self._request_slots:
|
||
games_data = await self.lichess_api.get_games_period(
|
||
gamer['username'], since_timestamp, until_timestamp_approx,
|
||
include_games=True, by_finish=True
|
||
)
|
||
if games_data is None:
|
||
raise RuntimeError("Games period API returned no data")
|
||
# Фиксируем фактическое время получения ответа
|
||
request_end_time = datetime.now()
|
||
logger.debug(f"✅ Games API response received for {gamer['username']} at {request_end_time}")
|
||
except Exception as e:
|
||
logger.error(f"❌ Error getting games data for {gamer['username']}: {e}")
|
||
consecutive_errors += 1
|
||
event('check_error', uid=user_id, gamer=username, error=repr(e)[:80], consecutive=consecutive_errors)
|
||
backoff_seconds = min(300, 60 * consecutive_errors)
|
||
if consecutive_errors >= max_consecutive_errors:
|
||
logger.error(f"⚠️ {consecutive_errors} consecutive errors for {gamer['username']}; still retrying the same period (backoff {backoff_seconds}s)")
|
||
else:
|
||
logger.warning(f"⚠️ Games data unavailable for {gamer['username']}; retrying the same period in {backoff_seconds}s")
|
||
if consecutive_errors == self.ADMIN_NOTIFY_ERROR_THRESHOLD or (
|
||
consecutive_errors > self.ADMIN_NOTIFY_ERROR_THRESHOLD
|
||
and consecutive_errors % self.ADMIN_NOTIFY_ERROR_THRESHOLD == 0
|
||
):
|
||
await self.notifier.notify_periodic_check_failing(gamer['username'], user_id, consecutive_errors)
|
||
await asyncio.sleep(backoff_seconds)
|
||
continue
|
||
|
||
if gamer.get('token'):
|
||
# Транзитные ошибки получения пазлов обрабатываются так же, как ошибки игр:
|
||
# исключение всплывает во внешний обработчик, чекпоинт не продвигается,
|
||
# то же окно ретраится на следующей итерации (не считаем "пазлов не было").
|
||
# InvalidTokenError — отдельный случай: Lichess отклонил токен насовсем
|
||
# (401), ретраить бессмысленно — это раньше приводило к вечному циклу
|
||
# ретраев без продвижения чекпоинта (см. историю с Dor1zz). Вместо этого
|
||
# отключаем пазлы для этой пары и продолжаем отслеживать партии как обычно.
|
||
logger.debug(f"📥 Requesting puzzles for {gamer['username']}")
|
||
try:
|
||
async with self._request_slots:
|
||
puzzles_data = await self.lichess_api.get_puzzles_period(
|
||
gamer['token'], since_timestamp, until_timestamp_approx, 150
|
||
)
|
||
except InvalidTokenError:
|
||
logger.warning(f"🔑 Token rejected by Lichess for {gamer['username']} (user {user_id}); disabling puzzle tracking for this pair")
|
||
event('token_rejected', uid=user_id, gamer=username)
|
||
self.db.clear_user_gamer_token(user_id, gamer['id'])
|
||
gamer['token'] = None
|
||
puzzles_data = None
|
||
try:
|
||
user_lang = self.db.get_user_language(user_id)
|
||
await self.application.bot.send_message(
|
||
chat_id=user_id,
|
||
text=t('token_rejected_notice', user_lang, username=gamer['username'])
|
||
)
|
||
except Exception as notify_err:
|
||
logger.error(f"Failed to notify user {user_id} about rejected token: {notify_err}")
|
||
else:
|
||
if puzzles_data is None:
|
||
raise RuntimeError("Puzzles period API returned no data")
|
||
# Обновляем фактическое время после получения ответа по пазлам
|
||
request_end_time = datetime.now()
|
||
logger.debug(f"✅ Puzzles API response received for {gamer['username']} at {request_end_time}")
|
||
|
||
# Сбрасываем счетчик ошибок при успешном запросе
|
||
consecutive_errors = 0
|
||
|
||
# Проверяем наличие реальной активности
|
||
has_games = False
|
||
total_games = 0
|
||
if games_data:
|
||
# Логируем структуру ответа для отладки
|
||
logger.debug(f"📊 Games data structure for {username}: {games_data}")
|
||
|
||
# Проверяем games_count на верхнем уровне (приоритет)
|
||
top_level_count = games_data.get('games_count', 0)
|
||
logger.debug(f"🔍 Top-level games_count: {top_level_count}")
|
||
|
||
if top_level_count > 0:
|
||
total_games = top_level_count
|
||
has_games = True
|
||
logger.debug(f"✅ Found {total_games} games via games_count field")
|
||
else:
|
||
# Также проверяем data.total.games_played
|
||
games_data_dict = games_data.get('data')
|
||
if games_data_dict:
|
||
data_total = games_data_dict.get('total', {})
|
||
total_games_played = data_total.get('games_played', 0) if data_total else 0
|
||
else:
|
||
total_games_played = 0
|
||
logger.debug(f"🔍 data.total.games_played: {total_games_played}")
|
||
|
||
if total_games_played > 0:
|
||
total_games = total_games_played
|
||
has_games = True
|
||
logger.debug(f"✅ Found {total_games} games via data.total.games_played field")
|
||
else:
|
||
logger.debug(f"⚠️ No games found: games_count={top_level_count}, data.total.games_played={total_games_played}")
|
||
else:
|
||
logger.warning(f"⚠️ No games_data returned for {username}")
|
||
|
||
has_puzzles = False
|
||
total_puzzles = 0
|
||
if puzzles_data:
|
||
logger.debug(f"📊 Puzzles data structure for {username}: {puzzles_data}")
|
||
|
||
# Проверяем puzzles_in_period на верхнем уровне (приоритет)
|
||
if puzzles_data.get('puzzles_in_period', 0) > 0:
|
||
total_puzzles = puzzles_data.get('puzzles_in_period', 0)
|
||
has_puzzles = True
|
||
logger.debug(f"✅ Found {total_puzzles} puzzles via puzzles_in_period field")
|
||
# Также проверяем data.total_attempts
|
||
elif puzzles_data.get('data') and puzzles_data.get('data', {}).get('total_attempts', 0) > 0:
|
||
total_puzzles = puzzles_data.get('data', {}).get('total_attempts', 0)
|
||
has_puzzles = True
|
||
logger.debug(f"✅ Found {total_puzzles} puzzles via data.total_attempts field")
|
||
|
||
logger.debug(f"🔍 Activity check result for {username}: has_games={has_games} (total={total_games}), has_puzzles={has_puzzles} (total={total_puzzles})")
|
||
|
||
# Отправляем уведомление только если есть реальная активность и это не
|
||
# молчаливый догон устаревшего бэклога (is_stale_backlog, см. выше).
|
||
# Ошибки форматирования/отправки НЕ перехватываются здесь: они должны
|
||
# всплыть во внешний обработчик, чтобы чекпоинт не продвинулся и уже
|
||
# обнаруженная активность была отправлена повторно на следующей попытке,
|
||
# а не потеряна молча.
|
||
notified = False
|
||
if (has_games or has_puzzles) and not is_stale_backlog:
|
||
logger.info(f"📊 Activity detected for {gamer['username']}, preparing notification...")
|
||
user_lang = self.db.get_user_language(user_id)
|
||
# Label the notification with the actual queried window, not the
|
||
# configured period: after a backlog collapse (see above) they can
|
||
# differ by days/weeks, and showing "for 15 minutes" on activity
|
||
# that's actually from weeks ago is misleading.
|
||
actual_span_minutes = max(1, round((period_end_approx - since_time).total_seconds() / 60))
|
||
notification = StatsFormatter.format_report(
|
||
gamer['username'], games_data, puzzles_data, actual_span_minutes, lang=user_lang
|
||
)
|
||
|
||
if not self.application:
|
||
raise RuntimeError(f"Application not initialized, cannot send notification for {gamer['username']} to user {user_id}")
|
||
|
||
# Forbidden (user blocked the bot) is permanent, not worth retrying
|
||
# (see _stop_pair_blocked).
|
||
try:
|
||
await self.application.bot.send_message(
|
||
chat_id=user_id,
|
||
text=notification,
|
||
parse_mode='HTML'
|
||
)
|
||
except Forbidden:
|
||
self._stop_pair_blocked(user_id, gamer, task_key)
|
||
return
|
||
logger.info(f"✅ Sent periodic notification for {gamer['username']} to user {user_id}")
|
||
# Increment periodic notification counter (read by the admin /status)
|
||
self.counters.increment('periodic_notification')
|
||
by_mode = (games_data or {}).get('data') or {}
|
||
rows_total = sum(len((by_mode.get(m) or {}).get('games') or []) for m in ROW_MODES)
|
||
event('report_sent', uid=user_id, gamer=username, games=total_games, rows=rows_total,
|
||
puzzles=total_puzzles if puzzles_data is not None else None, span_min=actual_span_minutes)
|
||
notified = True
|
||
elif is_stale_backlog and (has_games or has_puzzles):
|
||
logger.info(f"⏭️ Suppressed stale backlog notification for {gamer['username']} (had activity, but window too old)")
|
||
else:
|
||
logger.debug(f"⏭️ No activity found for {gamer['username']} in the last {period_minutes} minutes")
|
||
|
||
# Обновляем время начала следующего периода на ПЛАНИРУЕМОЕ время окончания текущего периода
|
||
# (period_end_approx), а не на фактическое время завершения запроса (request_end_time).
|
||
# Это гарантирует непрерывность периодов без пропусков:
|
||
# - Проверяем период A-B
|
||
# - Следующая проверка будет периода B-C
|
||
# - Без пропусков между A-B и B-C
|
||
#
|
||
# Использование request_end_time приведет к пропуску диапазона между period_end_approx и request_end_time
|
||
#
|
||
# period_end_approx уже установлено в начале итерации
|
||
self.period_start_times[task_key] = period_end_approx
|
||
self.db.set_period_checkpoint(user_id, gamer['id'], int(period_end_approx.timestamp()))
|
||
# Baseline for the skip decision (see _decide_skip): the player's games
|
||
# total as snapshotted at decision time, i.e. BEFORE this request — a game
|
||
# finished in between shows up as a higher total at the next refresh and
|
||
# triggers a request. Stored here, together with the checkpoint, and not
|
||
# right after the games request: if the notification send had failed,
|
||
# this window is retried, and a baseline stored early would have turned
|
||
# that retry into a skip, losing the activity for good.
|
||
if games_total_snapshot is not None:
|
||
self.db.set_pair_last_games_total(user_id, gamer['id'], games_total_snapshot)
|
||
logger.debug(f"📌 Updated period_start_time for {username} to {period_end_approx} (planned period end, next period will start from here)")
|
||
if 'request_end_time' in locals():
|
||
delay = (request_end_time - period_end_approx).total_seconds()
|
||
if delay > 0:
|
||
logger.debug(f"⏱️ Request completed with {delay:.1f}s delay after planned period end")
|
||
event('check', uid=user_id, gamer=username, decision='request', reason=None, window_s=window_seconds,
|
||
stale=is_stale_backlog, games=total_games,
|
||
puzzles=total_puzzles if puzzles_data is not None else None, notified=notified,
|
||
lag_s=int((datetime.now() - period_end_approx).total_seconds()))
|
||
|
||
except asyncio.CancelledError:
|
||
logger.info(f"Periodic check cancelled for {gamer['username']}")
|
||
break
|
||
except Exception as e:
|
||
consecutive_errors += 1
|
||
logger.error(f"Error in periodic check for {gamer['username']}: {e}")
|
||
import traceback
|
||
logger.error(f"Full traceback: {traceback.format_exc()}")
|
||
event('check_error', uid=user_id, gamer=username, error=repr(e)[:80], consecutive=consecutive_errors)
|
||
|
||
# Не убиваем задачу навсегда: ретраим то же окно с растущим бэкоффом
|
||
# (капается на 300с), пока Lichess/Telegram не восстановятся.
|
||
backoff_seconds = min(300, 60 * consecutive_errors)
|
||
if consecutive_errors >= max_consecutive_errors:
|
||
logger.error(f"⚠️ {consecutive_errors} consecutive errors for {gamer['username']}; still retrying the same period (backoff {backoff_seconds}s)")
|
||
if consecutive_errors == self.ADMIN_NOTIFY_ERROR_THRESHOLD or (
|
||
consecutive_errors > self.ADMIN_NOTIFY_ERROR_THRESHOLD
|
||
and consecutive_errors % self.ADMIN_NOTIFY_ERROR_THRESHOLD == 0
|
||
):
|
||
await self.notifier.notify_periodic_check_failing(gamer['username'], user_id, consecutive_errors)
|
||
await asyncio.sleep(backoff_seconds)
|
||
continue
|
||
|
||
async def start_existing_periodic_tasks(self):
|
||
"""Start periodic tasks for all user-gamer pairs that have periods set"""
|
||
try:
|
||
# First bulk status refresh before any check runs, so the checks after a
|
||
# restart can already skip. Retried a few times (the stats service may
|
||
# still be booting, see PlayerStatusRefresher.INITIAL_REFRESH_ATTEMPTS).
|
||
# Final failure is fine: periodic checks work without status (they fall
|
||
# back to requesting every window).
|
||
if self.status_refresher is not None:
|
||
try:
|
||
result = await self.status_refresher.refresh_with_retries()
|
||
except Exception as e: # defensive: refresh_with_retries itself does not raise
|
||
result = None
|
||
logger.error(f"❌ Initial player status refresh raised: {e}")
|
||
if result is None:
|
||
logger.error("❌ Initial player status refresh failed; periodic checks will run without status until the next refresh")
|
||
|
||
gamers_with_periods = self.db.get_all_gamers_with_periods()
|
||
|
||
# Get statistics
|
||
counts = self.db.get_counts()
|
||
total_users, total_gamers = counts['users'], counts['gamers']
|
||
|
||
logger.info(f"📊 Statistics: {total_users} users, {total_gamers} tracked gamers")
|
||
logger.info(f"🔔 Found {len(gamers_with_periods)} user-gamer pairs with periodic notifications enabled")
|
||
|
||
if len(gamers_with_periods) == 0:
|
||
logger.warning("⚠️ No periodic notifications configured! Users need to set periods using /setperiod")
|
||
|
||
active_gamers = [g for g in gamers_with_periods if g['period_minutes'] > 0]
|
||
# Stagger task creation across a short startup window instead of firing all
|
||
# ~N tasks' first (blocking) sqlite checkpoint read in the same event loop
|
||
# tick. Small and one-off — the real anti-lockstep fix is the per-pair
|
||
# checkpoint jitter in periodic_check, this just smooths process boot.
|
||
stagger_step = config.PERIODIC_STARTUP_STAGGER_MAX_SECONDS / max(1, len(active_gamers))
|
||
|
||
for gamer in active_gamers:
|
||
user_id = gamer['user_id']
|
||
username = gamer['username']
|
||
period = gamer['period_minutes']
|
||
# Start periodic task with user_id and gamer
|
||
await self.start_periodic_task(gamer, user_id, period)
|
||
logger.info(f"✅ Started periodic task for {username} (user {user_id}) with period {period} minutes")
|
||
if stagger_step > 0:
|
||
await asyncio.sleep(stagger_step)
|
||
|
||
logger.info(f"✅ All periodic tasks started. Total: {len(active_gamers)}")
|
||
|
||
# Start daily counter reset task
|
||
asyncio.create_task(self.daily_counter_reset_task())
|
||
logger.info("✅ Started daily counter reset task")
|
||
|
||
if self.status_refresher is not None:
|
||
self._status_refresh_task = asyncio.create_task(self.status_refresher.run_forever())
|
||
logger.info(f"✅ Started player status refresh task (every {config.PLAYER_STATUS_REFRESH_MINUTES} min)")
|
||
|
||
except Exception as e:
|
||
logger.error(f"❌ Error starting existing periodic tasks: {e}")
|
||
import traceback
|
||
logger.error(traceback.format_exc())
|
||
|
||
async def write_daily_summary(self, for_date=None):
|
||
"""
|
||
One SUMMARY line for the day that just ended, computed from events.log
|
||
(events.summarize_day: checks, skipped, notifications, errors, users
|
||
started, new users, gamers added, commands) plus the DB counts (users,
|
||
gamers, pairs_active) and the stats service's 429 count of the last 24 h
|
||
(GET /health, '-' when the service does not answer). Never raises.
|
||
|
||
Which day: events.log timestamps are UTC, while daily_counter_reset_task
|
||
fires at LOCAL midnight. The day summarised is therefore the UTC date of
|
||
"now minus one minute": at a UTC midnight that is yesterday (the task
|
||
runs a few ms after 00:00), and on a host whose local midnight is not
|
||
UTC midnight it is whichever UTC day the moment belongs to — the line
|
||
is still a complete UTC day of events in both cases, provided the host
|
||
clock is UTC (prod containers are). `for_date` (a date) overrides it.
|
||
"""
|
||
try:
|
||
day = for_date or (datetime.now(timezone.utc) - timedelta(minutes=1)).date()
|
||
counted = summarize_day(day.isoformat())
|
||
counts = self.db.get_counts()
|
||
pairs_active = sum(1 for g in self.db.get_all_gamers_with_periods() if g['period_minutes'] > 0)
|
||
lichess_429 = None
|
||
try:
|
||
health = await self.lichess_api.get_service_health()
|
||
except Exception as e: # defensive: get_service_health itself does not raise
|
||
health = None
|
||
logger.warning(f"Stats service health unavailable for the daily summary: {e}")
|
||
if health and isinstance(health.get('lichess_429_24h'), int):
|
||
lichess_429 = health['lichess_429_24h']
|
||
summary(date=day.isoformat(), users=counts['users'], gamers=counts['gamers'], pairs_active=pairs_active,
|
||
checks=counted['checks'], skipped=counted['skipped'],
|
||
notifications=counted['notifications'], lichess_429=lichess_429, errors=counted['errors'],
|
||
users_started=counted['users_started'], new_users=counted['new_users'],
|
||
gamers_added=counted['gamers_added'], commands=counted['commands'])
|
||
except Exception as e:
|
||
logger.error(f"Failed to write daily summary: {e}")
|
||
|
||
async def daily_counter_reset_task(self):
|
||
"""Background task to reset daily counters at midnight"""
|
||
while True:
|
||
try:
|
||
# Calculate seconds until next midnight
|
||
now = datetime.now()
|
||
next_midnight = (now + timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
|
||
seconds_until_midnight = (next_midnight - now).total_seconds()
|
||
|
||
logger.info(f"Daily counter reset task: waiting {seconds_until_midnight} seconds until next midnight")
|
||
await asyncio.sleep(seconds_until_midnight)
|
||
|
||
# Daily SUMMARY line to events.log before the counters go (see events.py)
|
||
await self.write_daily_summary()
|
||
|
||
# Reset daily counters
|
||
self.counters._reset_daily_counters_if_needed()
|
||
logger.info("Daily counters reset at midnight")
|
||
|
||
except asyncio.CancelledError:
|
||
break
|
||
except Exception as e:
|
||
logger.error(f"Error in daily counter reset task: {e}")
|
||
import traceback
|
||
logger.error(traceback.format_exc())
|
||
# Wait 1 hour before retrying
|
||
await asyncio.sleep(3600)
|