import argparse import asyncio from contextlib import closing import datetime import json import logging import math import os from pathlib import Path import secrets import sqlite3 import time from urllib.parse import urlsplit, urlunsplit log = logging.getLogger("key-notifications") KINDS = ("policy", "elapsed") STATES = ("pending", "sending", "sent", "covered", "uncertain", "terminal", "suppressed") ENABLE_ENV = "IISHKO_KEY_NOTIFICATIONS_ENABLED" def ledger_path(bot_db): return os.environ.get("IISHKO_KEY_NOTIFICATIONS_DB") or str(Path(bot_db).with_name("key_notifications.sqlite3")) def enable_path(bot_db): return os.environ.get("IISHKO_KEY_NOTIFICATIONS_ENABLE_FILE") or str(Path(bot_db).with_name("key_notifications.enabled")) def delivery_enabled(bot_db): if ENABLE_ENV in os.environ: return os.environ[ENABLE_ENV] == "1" try: with open(enable_path(bot_db), encoding="ascii") as marker: content = marker.read(17) return len(content) <= 16 and content.strip() == "1" except (OSError, UnicodeError): return False def keys_url(url): parts = urlsplit(url) if parts.scheme != "https" or not parts.netloc: raise ValueError("invalid_webapp_url") return urlunsplit(parts._replace(fragment="keys")) def wait_duration(wait_seconds, lang="ru"): if wait_seconds % 3600 == 0: return "%d %s" % (wait_seconds // 3600, "h" if lang == "en" else "ч") return "%d %s" % (wait_seconds, "s" if lang == "en" else "с") def policy_summary(wait_seconds, lang="ru"): duration = wait_duration(wait_seconds, lang) if lang == "en": return ("Create your first API key after %s from registration. " "The timer is in Mini App → Keys. The key is not sent automatically." % duration) return ("Первый API-ключ можно создать через %s после регистрации. " "Таймер — в Mini App → «Ключи». Ключ не придёт автоматически: создай его там." % duration) def notification_text(claim, wait_seconds, now): en = claim["lang"] == "en" elapsed = now >= claim["deadline"] if claim["kind"] == "elapsed" or elapsed: heading = "Your first-key waiting period has elapsed" if en else "Период ожидания первого ключа истёк" timing = ("Your waiting period has already elapsed; no new waiting period starts with this notice." if en else "Твой период ожидания уже истёк; новое ожидание с этого сообщения не начинается.") else: heading = "First API key: waiting period" if en else "Первый API-ключ: период ожидания" deadline = datetime.datetime.fromtimestamp(claim["deadline"], datetime.timezone.utc).strftime("%d.%m.%Y %H:%M:%S UTC") timing = ("Your registration-based deadline is %s." if en else "Твой срок по дате регистрации закончится %s.") % deadline summary = policy_summary(wait_seconds, claim["lang"]) + "\n\n" if claim["kind"] == "policy" else "" ending = ("Open Mini App → Keys to check your account conditions and create a main key if you still need one. " "No key has been issued automatically. Elapsed waiting time does not guarantee model or provider availability." if en else "Открой Mini App → «Ключи», чтобы проверить условия аккаунта и создать основной ключ, если он ещё нужен. " "Ключ автоматически не выдан. Истечение срока не гарантирует доступность моделей или провайдеров.") return "%s\n\n%s%s\n\n%s" % (heading, summary, timing, ending), elapsed def _readonly(path): con = sqlite3.connect(Path(path).resolve().as_uri() + "?mode=ro", uri=True, timeout=2) con.row_factory = sqlite3.Row con.execute("PRAGMA query_only=ON") return con def _eligible(row, now): return (row is not None and type(row["tg_id"]) is int and row["tg_id"] > 0 and type(row["created"]) in (int, float) and math.isfinite(row["created"]) and 0 < row["created"] <= now and row["privacy_ok"] == 1 and not row["banned"]) class LostClaim(RuntimeError): pass class DeliveryRejected(Exception): """Telegram explicitly rejected the request; retry only an explicit flood delay.""" def __init__(self, code, *, retry_after=None): super().__init__(code) self.code, self.retry_after = code, retry_after class DeliveryUncertain(Exception): pass class KeyNotificationStore: def __init__(self, bot_db, path=None, *, wait_seconds, clock=time.time, max_attempts=5, lease_seconds=90, pace_seconds=0.2): if type(wait_seconds) is not int or wait_seconds < 0: raise ValueError("invalid_wait_seconds") self.bot_db, self.path = str(bot_db), str(path or ledger_path(bot_db)) if Path(self.path).resolve() == Path(self.bot_db).resolve(): raise ValueError("notification_ledger_must_be_separate") self.wait_seconds, self.clock = wait_seconds, clock self.max_attempts, self.lease_seconds, self.pace_seconds = max_attempts, lease_seconds, pace_seconds def connect(self): con = sqlite3.connect(self.path, timeout=2) con.row_factory = sqlite3.Row con.execute("PRAGMA synchronous=FULL") return con def init_db(self): with closing(self.connect()) as con: con.execute("PRAGMA journal_mode=WAL") con.executescript(""" CREATE TABLE IF NOT EXISTS key_notifications ( uid INTEGER NOT NULL, kind TEXT NOT NULL CHECK(kind IN ('policy','elapsed')), registered_at REAL NOT NULL, deadline REAL NOT NULL, state TEXT NOT NULL DEFAULT 'pending' CHECK(state IN ('pending','sending','sent','covered','uncertain','terminal','suppressed')), attempts INTEGER NOT NULL DEFAULT 0, next_attempt REAL NOT NULL DEFAULT 0, claim_token TEXT, lease_until REAL NOT NULL DEFAULT 0, sent_at REAL, error_code TEXT, PRIMARY KEY(uid,kind) ); CREATE INDEX IF NOT EXISTS key_notifications_due ON key_notifications(state,next_attempt,deadline); CREATE TABLE IF NOT EXISTS key_notification_meta (name TEXT PRIMARY KEY, value REAL NOT NULL); """) con.commit() @staticmethod def _meta(con, name): row = con.execute("SELECT value FROM key_notification_meta WHERE name=?", (name,)).fetchone() return row[0] if row else 0 @staticmethod def _set_meta(con, name, value): con.execute("INSERT INTO key_notification_meta(name,value) VALUES(?,?) " "ON CONFLICT(name) DO UPDATE SET value=excluded.value", (name, value)) def discover(self, limit=250): """A wrapping keyset scan includes old users and newly consented registrations.""" limit, now = max(1, min(int(limit), 1000)), self.clock() with closing(self.connect()) as con, closing(_readonly(self.bot_db)) as source: con.execute("BEGIN IMMEDIATE") cursor = int(self._meta(con, "scan_cursor")) query = "SELECT tg_id,created,privacy_ok,banned,lang FROM users WHERE tg_id>? ORDER BY tg_id LIMIT ?" rows = source.execute(query, (cursor, limit)).fetchall() wrapped = len(rows) < limit if not rows and cursor: rows = source.execute(query, (0, limit)).fetchall() wrapped = True accepted = 0 for row in rows: if not _eligible(row, now): continue accepted += 1 for kind in KINDS: con.execute("INSERT OR IGNORE INTO key_notifications(uid,kind,registered_at,deadline) VALUES(?,?,?,?)", (row["tg_id"], kind, row["created"], row["created"] + self.wait_seconds)) con.execute("UPDATE key_notifications SET registered_at=?,deadline=?,state='pending',error_code=NULL " "WHERE uid=? AND kind=? AND state IN ('pending','suppressed')", (row["created"], row["created"] + self.wait_seconds, row["tg_id"], kind)) self._set_meta(con, "scan_cursor", rows[-1]["tg_id"] if rows and not wrapped else 0) con.commit() return {"scanned": len(rows), "eligible": accepted, "scan_pending": not wrapped} def _live(self, source, uid, now): row = source.execute("SELECT tg_id,created,privacy_ok,banned,lang FROM users WHERE tg_id=?", (uid,)).fetchone() return dict(row) if _eligible(row, now) else None @staticmethod def _suppress(con, uid): con.execute("UPDATE key_notifications SET state='suppressed',claim_token=NULL,lease_until=0,error_code='ineligible' " "WHERE uid=? AND state IN ('pending','sending')", (uid,)) def claim(self): now = self.clock() with closing(self.connect()) as con, closing(_readonly(self.bot_db)) as source: con.execute("BEGIN IMMEDIATE") # An expired claim is an unknown outcome, not permission to resend. con.execute("UPDATE key_notifications SET state='uncertain',error_code='expired_claim' " "WHERE state='sending' AND lease_until<=?", (now,)) if max(self._meta(con, "pause_until"), self._meta(con, "send_after")) > now: con.commit() return None rows = con.execute("""SELECT n.* FROM key_notifications n WHERE n.state='pending' AND n.attempts now: continue token = secrets.token_hex(16) con.execute("UPDATE key_notifications SET state='sending',attempts=attempts+1,claim_token=?,lease_until=? " "WHERE uid=? AND kind=? AND state='pending'", (token, now + self.lease_seconds, row["uid"], row["kind"])) self._set_meta(con, "send_after", now + self.pace_seconds) con.commit() return {**dict(row), "deadline": deadline, "lang": "en" if live["lang"] == "en" else "ru", "claim_token": token, "attempts": row["attempts"] + 1} con.commit() return None def prepare(self, claim): """Recheck consent/ban/deadline immediately before the one transport call.""" now = self.clock() with closing(self.connect()) as con, closing(_readonly(self.bot_db)) as source: con.execute("BEGIN IMMEDIATE") row = con.execute("SELECT * FROM key_notifications WHERE uid=? AND kind=? AND state='sending' " "AND claim_token=? AND lease_until>?", (claim["uid"], claim["kind"], claim["claim_token"], now)).fetchone() if row is None: con.commit() return None live = self._live(source, claim["uid"], now) if not live: self._suppress(con, claim["uid"]) con.commit() return None deadline = live["created"] + self.wait_seconds if claim["kind"] == "elapsed" and deadline > now: self._release(con, claim) con.commit() return None con.execute("UPDATE key_notifications SET registered_at=?,deadline=?,lease_until=? WHERE uid=? AND kind=?", (live["created"], deadline, now + self.lease_seconds, claim["uid"], claim["kind"])) con.commit() return {**claim, "deadline": deadline, "lang": "en" if live["lang"] == "en" else "ru"} @staticmethod def _release(con, claim): con.execute("UPDATE key_notifications SET state='pending',attempts=MAX(0,attempts-1),claim_token=NULL,lease_until=0 " "WHERE uid=? AND kind=? AND state='sending' AND claim_token=?", (claim["uid"], claim["kind"], claim["claim_token"])) def release_unsent(self, claim): with closing(self.connect()) as con: con.execute("BEGIN IMMEDIATE") self._release(con, claim) con.commit() def finish(self, claim, state, *, covers_elapsed=False, error_code=None, retry_after=None): if state not in ("sent", "pending", "terminal", "uncertain"): raise ValueError("invalid_delivery_state") now = self.clock() if state == "pending": if retry_after is None or not math.isfinite(retry_after) or retry_after < 0: raise ValueError("retry_requires_known_rejection_delay") if claim["attempts"] >= self.max_attempts: state = "terminal" delay = max(1, retry_after) if retry_after is not None else 0 with closing(self.connect()) as con: con.execute("BEGIN IMMEDIATE") changed = con.execute("UPDATE key_notifications SET state=?,next_attempt=?,lease_until=0,sent_at=?,error_code=? " "WHERE uid=? AND kind=? AND claim_token=? AND attempts=? AND state IN ('sending','uncertain')", (state, now + delay, now if state == "sent" else None, error_code, claim["uid"], claim["kind"], claim["claim_token"], claim["attempts"])) if changed.rowcount != 1: raise LostClaim("notification_claim_lost") if retry_after is not None: self._set_meta(con, "pause_until", max(self._meta(con, "pause_until"), now + delay)) if state == "sent" and claim["kind"] == "policy" and covers_elapsed: con.execute("UPDATE key_notifications SET state='covered',sent_at=?,error_code=NULL " "WHERE uid=? AND kind='elapsed' AND state IN ('pending','suppressed')", (now, claim["uid"])) if state == "terminal" and (error_code == "unreachable" or claim["kind"] == "policy"): con.execute("UPDATE key_notifications SET state='terminal',error_code=? " "WHERE uid=? AND state IN ('pending','suppressed')", (error_code, claim["uid"])) con.commit() def status(self): result = {"enabled": delivery_enabled(self.bot_db), "counts": {kind: {state: 0 for state in STATES} for kind in KINDS}, "pause_until": 0, "send_after": 0} if not Path(self.path).exists(): return result with closing(_readonly(self.path)) as con: for row in con.execute("SELECT kind,state,COUNT(*) AS n FROM key_notifications GROUP BY kind,state"): result["counts"][row["kind"]][row["state"]] = row["n"] result["pause_until"] = self._meta(con, "pause_until") result["send_after"] = self._meta(con, "send_after") return result def dry_run(self): """Read-only aggregate plan; never creates a ledger, changes claims or lists IDs.""" now, cursor = self.clock(), 0 plan = {key: 0 for key in ("eligible", "waiting", "elapsed", "policy_waiting_due", "policy_combined_due", "elapsed_due", "elapsed_scheduled", "held", "ineligible")} ledger = _readonly(self.path) if Path(self.path).exists() else None try: with closing(_readonly(self.bot_db)) as source: plan["ineligible"] = source.execute("SELECT COUNT(*) FROM users WHERE tg_id<=0").fetchone()[0] while True: rows = source.execute("SELECT tg_id,created,privacy_ok,banned,lang FROM users " "WHERE tg_id>? ORDER BY tg_id LIMIT 500", (cursor,)).fetchall() if not rows: break for row in rows: if not _eligible(row, now): plan["ineligible"] += 1 continue plan["eligible"] += 1 elapsed = row["created"] + self.wait_seconds <= now plan["elapsed" if elapsed else "waiting"] += 1 states = {item["kind"]: dict(item) for item in ledger.execute( "SELECT kind,state,next_attempt FROM key_notifications WHERE uid=?", (row["tg_id"],))} if ledger else {} policy, notice = states.get("policy", {}), states.get("elapsed", {}) if policy.get("state", "pending") in ("pending", "suppressed"): if policy.get("next_attempt", 0) <= now: plan["policy_combined_due" if elapsed else "policy_waiting_due"] += 1 else: plan["held"] += 1 elif policy["state"] == "sent" and notice.get("state", "pending") in ("pending", "suppressed"): plan["elapsed_due" if elapsed and notice.get("next_attempt", 0) <= now else "elapsed_scheduled"] += 1 elif policy["state"] in ("sending", "uncertain", "terminal"): plan["held"] += 1 cursor = rows[-1]["tg_id"] finally: if ledger: ledger.close() return {"now": now, "wait_seconds": self.wait_seconds, "plan": plan, "status": self.status()} def cleanup_orphans(self, limit=250): """Bounded reconciliation of an existing ledger; live leases defer deletion.""" empty = {"scanned": 0, "removed": 0, "scan_pending": False} if not Path(self.path).is_file(): return empty limit, now = max(1, min(int(limit), 500)), self.clock() # mode=rw cannot create a ledger if it disappears after the existence check. uri = Path(self.path).resolve().as_uri() + "?mode=rw" with closing(sqlite3.connect(uri, uri=True, timeout=2)) as con, closing(_readonly(self.bot_db)) as source: con.row_factory = sqlite3.Row tables = {row["name"] for row in con.execute("SELECT name FROM sqlite_master WHERE type='table'")} if not {"key_notifications", "key_notification_meta"}.issubset(tables): return empty con.execute("PRAGMA synchronous=FULL") con.execute("BEGIN IMMEDIATE") cursor = int(self._meta(con, "cleanup_cursor")) query = "SELECT DISTINCT uid FROM key_notifications WHERE uid>? ORDER BY uid LIMIT ?" rows = con.execute(query, (cursor, limit)).fetchall() wrapped = len(rows) < limit if not rows and cursor: rows = con.execute(query, (0, limit)).fetchall() wrapped = True removed = 0 if rows: recipients = [row["uid"] for row in rows] slots = ",".join("?" for _ in recipients) existing = {row["tg_id"] for row in source.execute( "SELECT tg_id FROM users WHERE tg_id IN (" + slots + ")", recipients)} for uid in recipients: if uid in existing: continue deleted = con.execute( "DELETE FROM key_notifications WHERE uid=? AND NOT EXISTS(" "SELECT 1 FROM key_notifications live WHERE live.uid=? " "AND live.state='sending' AND live.lease_until>?)", (uid, uid, now)) removed += deleted.rowcount self._set_meta(con, "cleanup_cursor", rows[-1]["uid"] if rows and not wrapped else 0) con.commit() return {"scanned": len(rows), "removed": removed, "scan_pending": not wrapped} async def telegram_send(bot, claim, text, url): from aiogram.exceptions import (TelegramBadRequest, TelegramForbiddenError, TelegramNetworkError, TelegramRetryAfter, TelegramServerError) from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup, WebAppInfo label = "Keys in Mini App" if claim["lang"] == "en" else "Ключи в Mini App" keyboard = InlineKeyboardMarkup(inline_keyboard=[[ InlineKeyboardButton(text=label, web_app=WebAppInfo(url=url))]]) try: await bot.send_message(claim["uid"], text, parse_mode="HTML", reply_markup=keyboard, request_timeout=20) except TelegramRetryAfter as error: raise DeliveryRejected("rate_limited", retry_after=error.retry_after) from None except TelegramForbiddenError: raise DeliveryRejected("unreachable") from None except TelegramBadRequest as error: unreachable = any(part in str(error).lower() for part in ("chat not found", "user is deactivated", "chat_id is empty", "chat_id is invalid")) raise DeliveryRejected("unreachable" if unreachable else "bad_request") from None except (TelegramNetworkError, TelegramServerError): raise DeliveryUncertain("telegram_transport") from None class KeyNotificationWorker: def __init__(self, store, sender, webapp_url, *, enabled=None, batch=25, scan_batch=250, interval=30, timeout=25, sleep=asyncio.sleep): self.store, self.sender, self.url = store, sender, keys_url(webapp_url) self.enabled = enabled or (lambda: delivery_enabled(store.bot_db)) self.batch, self.scan_batch, self.interval = batch, scan_batch, interval self.timeout, self.sleep, self.initialized = timeout, sleep, False async def run_once(self): counts = {"sent": 0, "uncertain": 0, "rejected": 0, "scan_pending": 0} cleanup = await asyncio.to_thread(self.store.cleanup_orphans, self.scan_batch) counts["orphan_removed"] = cleanup["removed"] counts["cleanup_pending"] = int(cleanup["scan_pending"]) if not await asyncio.to_thread(self.enabled): return counts if not self.initialized: await asyncio.to_thread(self.store.init_db) self.initialized = True scan = await asyncio.to_thread(self.store.discover, self.scan_batch) counts["scan_pending"] = int(scan["scan_pending"]) for _ in range(self.batch): if not await asyncio.to_thread(self.enabled): break claim = await asyncio.to_thread(self.store.claim) if claim is None: break claim = await asyncio.to_thread(self.store.prepare, claim) if claim is None: continue if not await asyncio.to_thread(self.enabled): await asyncio.to_thread(self.store.release_unsent, claim) break text, covers_elapsed = notification_text(claim, self.store.wait_seconds, self.store.clock()) try: await asyncio.wait_for(self.sender(claim, text, self.url), timeout=self.timeout) except asyncio.CancelledError: try: await asyncio.shield(asyncio.to_thread(self.store.finish, claim, "uncertain", error_code="cancelled")) except (sqlite3.Error, OSError): log.error("key notification cancellation state unavailable; claim remains quarantinable") raise except DeliveryRejected as error: await asyncio.to_thread(self.store.finish, claim, "pending" if error.retry_after is not None else "terminal", error_code=error.code, retry_after=error.retry_after) counts["rejected"] += 1 if error.retry_after is not None: break except (DeliveryUncertain, TimeoutError, OSError) as error: await asyncio.to_thread(self.store.finish, claim, "uncertain", error_code=type(error).__name__) counts["uncertain"] += 1 except Exception: # Preserve the original programming failure; the attempted delivery must not be replayed. await asyncio.to_thread(self.store.finish, claim, "uncertain", error_code="unexpected_failure") raise else: await asyncio.to_thread(self.store.finish, claim, "sent", covers_elapsed=covers_elapsed) counts["sent"] += 1 await self.sleep(self.store.pace_seconds) return counts async def run(self): while True: try: counts = await self.run_once() except (sqlite3.Error, OSError) as error: counts = {"storage_error": 0} # Do not log exception text, recipient IDs, SQL values or token-bearing URLs. log.error("key notification worker storage failure: %s", type(error).__name__) await self.sleep(0 if sum(counts.values()) else self.interval) def main(): parser = argparse.ArgumentParser(description="Read-only first-key notification aggregates; this CLI never sends.") parser.add_argument("action", choices=("dry-run", "status")) parser.add_argument("--bot-db", default=os.environ.get("GROK_BOT_DB", "/opt/grok-bot/bot.db")) parser.add_argument("--ledger") parser.add_argument("--config", default=os.environ.get("GROK_BOT_CFG", "/opt/grok-bot/config.json")) args = parser.parse_args() with open(args.config, encoding="utf-8") as config: wait_seconds = int(json.load(config).get("key_wait_hours", 24)) * 3600 store = KeyNotificationStore(args.bot_db, args.ledger, wait_seconds=wait_seconds) print(json.dumps(store.dry_run() if args.action == "dry-run" else store.status(), ensure_ascii=False, sort_keys=True)) if __name__ == "__main__": main()