Files
iishko-public/bot/account_limits.py
T
reformandClaude Opus 5.5 0ee6fb843b
checks / pytest (push) Has been cancelled
checks / moderation (push) Has been cancelled
checks / node (push) Has been cancelled
IISHKO: Telegram bot, Mini App and gateway
Initial public release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 21:51:30 +03:00

77 lines
3.4 KiB
Python

"""Exact bot-account identity and read-only account-shared gateway usage."""
import os
from contextlib import closing
from pathlib import Path
import re
import sqlite3
DAILY_USD_CAP = {0: 100, 1: 100, 2: 200, 3: 500, 4: 1000}
QUOTA_PER_USD = 500_000
_owner_uid_raw = os.environ.get("IISHKO_OWNER_UID", "0").strip()
# Operator identity is configuration. 0 = nobody holds owner privileges.
OWNER_UID = int(_owner_uid_raw) if _owner_uid_raw.isdigit() else 0
_ACCOUNT_NAME = re.compile(r"(?:tg|pm|sol)([1-9][0-9]*)(?:-k[1-9][0-9]*)?\Z")
def account_uid(name: str) -> int | None:
"""Return the canonical Telegram UID, never a prefix/substring match."""
if not isinstance(name, str):
return None
match = _ACCOUNT_NAME.fullmatch(name)
if match is None:
return None
try:
uid = int(match[1])
except ValueError:
return None
return uid if uid <= 9223372036854775807 else None
def _name_scope(column, uid):
if type(uid) is not int or not 0 < uid <= 9223372036854775807:
raise ValueError("invalid account uid")
# GLOB is only an indexed candidate selection. Every returned name must also
# pass account_uid: '-k1foreign', Unicode digits and '-k01' are not credentials.
bases = [prefix + str(uid) for prefix in ("tg", "pm", "sol")]
terms, args = [], []
for name in bases:
terms.extend((column + "=?", column + " GLOB ?"))
args.extend((name, name + "-k[0-9]*"))
return "(" + " OR ".join(terms) + ")", args
def account_token_names(con: sqlite3.Connection, uid: int) -> list[str]:
"""Exact live names for this account; do not hide query/schema failures."""
scope, args = _name_scope("name", uid)
rows = con.execute("SELECT DISTINCT name FROM tokens WHERE deleted_at IS NULL AND " + scope,
args).fetchall()
return sorted(row[0] for row in rows if account_uid(row[0]) == uid)
def daily_spent_units(gw_db, uid: int, day_start: int, day_end: int | None = None) -> int:
scope, args = _name_scope("token_name", uid)
if type(day_start) is not int or (day_end is not None and type(day_end) is not int):
raise ValueError("invalid usage interval")
if day_end is not None and day_end < day_start:
raise ValueError("invalid usage interval")
time_scope = "created_at>=?"
times = [day_start]
if day_end is not None:
time_scope += " AND created_at<?"
times.append(day_end)
uri = Path(gw_db).resolve().as_uri() + "?mode=ro"
with closing(sqlite3.connect(uri, uri=True, timeout=8)) as con:
con.execute("PRAGMA query_only=ON")
# Prefer account-name lookups over scanning every account's daily logs.
# Keep the original plan on databases without the standard full index.
full_index = any(row[1] == "idx_logs_token_name" and not row[4]
for row in con.execute("PRAGMA index_list(logs)"))
columns = con.execute("PRAGMA index_info(idx_logs_token_name)").fetchall()
source = ("logs INDEXED BY idx_logs_token_name"
if full_index and [row[2] for row in columns] == ["token_name"] else "logs")
rows = con.execute(
"SELECT token_name,COALESCE(SUM(quota),0) FROM " + source + " WHERE type=2 AND "
+ time_scope + " AND " + scope + " GROUP BY token_name", times + args).fetchall()
return sum(int(units) for name, units in rows if account_uid(name) == uid)