"""Durable, bounded local history and pairings. No game calls run under this lock.""" import hashlib import json import secrets import sqlite3 import threading import time import zlib from pathlib import Path MAX_FRAMES = 3600 MAX_FRAME_DISTANCE_TICKS = 100 MAX_EVENTS = 30000 MAX_RAIDS = 400 MAX_TIMELINE_MARKERS = 480 SESSION_AGE = 30 * 24 * 60 * 60 TIMELINE_LABELS = { "Попадание по объекту": "impact", "Попадание по комплексу": "impact", "Комплекс уничтожен": "impact", "Промах перехватчика": "miss", "Промах очереди": "miss", "Огонь запрещён": "refusal", "Комплекс на марше": "refusal", "Перезарядка": "refusal", "Ожидает пополнения": "refusal", "Ожидает данных о рельефе": "refusal", "Траектория перекрыта": "refusal", "Орудие недоступно": "refusal", "Пусковая недоступна": "refusal", "Нет свежего захвата": "refusal", "Вне дальности орудия": "refusal", } def compact(value): return json.dumps(value, ensure_ascii=False, separators=(",", ":"), allow_nan=False) def digest(token): return hashlib.sha256(token.encode("ascii")).hexdigest() class Store: def __init__(self, path: Path): self.lock = threading.RLock() self.db = sqlite3.connect(path, check_same_thread=False) self.db.row_factory = sqlite3.Row self.db.executescript(""" PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; CREATE TABLE IF NOT EXISTS frames ( session TEXT, tick INTEGER, world TEXT, time REAL, data BLOB, PRIMARY KEY(session, tick) ); CREATE TABLE IF NOT EXISTS raids ( session TEXT, raid INTEGER, world TEXT, time REAL, start INTEGER, length INTEGER, active INTEGER, gap INTEGER, PRIMARY KEY(session, raid) ); CREATE TABLE IF NOT EXISTS events ( id INTEGER PRIMARY KEY AUTOINCREMENT, session TEXT, raid INTEGER, kind TEXT, seq INTEGER, tick INTEGER, unit INTEGER, target INTEGER, label TEXT, payload TEXT, object INTEGER, UNIQUE(session, raid, kind, seq) ); CREATE INDEX IF NOT EXISTS events_filter ON events(session, raid, tick); CREATE INDEX IF NOT EXISTS frames_retention ON frames(time); CREATE INDEX IF NOT EXISTS raids_retention ON raids(time); CREATE TABLE IF NOT EXISTS pairings (token TEXT PRIMARY KEY, role TEXT, expires REAL); CREATE TABLE IF NOT EXISTS launches ( id TEXT PRIMARY KEY, owner TEXT, session TEXT, data TEXT, time REAL, state TEXT, message TEXT ); CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY, value TEXT); """) if not any(row["name"] == "object" for row in self.db.execute("PRAGMA table_info(events)")): self.db.execute("ALTER TABLE events ADD COLUMN object INTEGER") with self.db: self.db.execute("""UPDATE launches SET state='unknown', message=? WHERE state IN ('queued', 'dispatching')""", ("Ответ предыдущего запуска неизвестен. Игра могла принять сценарий.",)) def pair(self, role): value = secrets.token_urlsafe(32) now = time.time() with self.lock, self.db: self.db.execute("DELETE FROM pairings WHERE expires < ?", (now,)) self.db.execute("INSERT INTO pairings VALUES (?, ?, ?)", (digest(value), role, now + SESSION_AGE)) return value def role(self, value): if not value or len(value) != 43 or not value.isascii(): return None key = digest(value) with self.lock: row = self.db.execute("SELECT role FROM pairings WHERE token=? AND expires>?", (key, time.time())).fetchone() return (key, row["role"]) if row else None def revoke(self, key): with self.lock, self.db: self.db.execute("DELETE FROM pairings WHERE token=?", (key,)) def revoke_all(self): with self.lock, self.db: self.db.execute("DELETE FROM pairings") def append(self, snapshot, public, *, capture_frame=True): session, world, tick = snapshot["session"], snapshot["world"], snapshot["tick"] active = next((raid["id"] for raid in snapshot["raids"] if raid["active"]), 0) now = time.time() frame = zlib.compress(compact(public).encode("utf-8"), level=1) if capture_frame else None with self.lock, self.db: if frame is not None: self.db.execute("INSERT OR IGNORE INTO frames VALUES (?, ?, ?, ?, ?)", (session, tick, world, now, frame)) for raid in snapshot["raids"]: fields = (session, raid["id"], world, now, raid["start"], raid["length"], int(raid["active"]), int(raid["gap"] or raid["limited"])) self.db.execute("""INSERT INTO raids VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(session,raid) DO UPDATE SET length=excluded.length, active=excluded.active, gap=max(raids.gap,excluded.gap)""", fields) for kind in ("events", "decisions", "observations"): self.db.executemany("""INSERT OR IGNORE INTO events (session,raid,kind,seq,tick,unit,target,label,payload,object) VALUES (?,?,?,?,?,?,?,?,?,?)""", ((session, raid["id"], kind, e["seq"], raid["start"] + e["at"], e["unit"], e["target"], e["label"], compact(e), e.get("object")) for e in raid.get(kind, ()))) self.db.execute("""UPDATE raids SET active=0, gap=1 WHERE active=1 AND (session<>? OR raid<>?)""", (session, active)) # Keep only the most recent bounded window. Tell clients when history has aged out. removed = self.db.execute("""DELETE FROM events WHERE id < coalesce( (SELECT id FROM events ORDER BY id DESC LIMIT 1 OFFSET ?),0)""", (MAX_EVENTS - 1,)).rowcount gone = self.db.execute("""DELETE FROM raids WHERE rowid IN (SELECT rowid FROM raids ORDER BY time DESC LIMIT -1 OFFSET ?)""", (MAX_RAIDS,)).rowcount if removed or gone: self.db.execute("INSERT OR REPLACE INTO metadata VALUES ('history_limited','1')") if frame is not None: self.db.execute("""DELETE FROM frames WHERE rowid IN (SELECT rowid FROM frames ORDER BY time DESC LIMIT -1 OFFSET ?)""", (MAX_FRAMES,)) def raids(self): with self.lock: rows = self.db.execute("SELECT * FROM raids ORDER BY time DESC, raid DESC LIMIT ?", (MAX_RAIDS,)).fetchall() limited = self.db.execute("SELECT value FROM metadata WHERE key='history_limited'").fetchone() return {"raids": [dict(row) for row in rows], "limited": limited is not None} def events(self, *, session=None, raid=None, unit=None, target=None, object=None, kind=None, after=None, before=None, since=None, until=None, query="", limit=100): conditions = [] values = [] for field, value in (("session", session), ("raid", raid), ("unit", unit), ("target", target), ("object", object), ("kind", kind)): if value is not None: conditions.append(f"{field}=?") values.append(value) for clause, value in (("id>?", after), ("id=?", since), ("tick<=?", until)): if value is not None: conditions.append(clause) values.append(value) statement = "SELECT * FROM events" if conditions: statement += " WHERE " + " AND ".join(conditions) statement += " ORDER BY id " + ("ASC" if after is not None else "DESC") if not query: statement += " LIMIT ?" values.append(limit + 1) with self.lock: rows = self.db.execute(statement, values) if query: wanted = query.casefold() selected = [] for row in rows: if wanted in row["label"].casefold() or wanted in row["payload"].casefold(): selected.append(row) if len(selected) > limit: break rows = selected else: rows = rows.fetchall() output = [event_row(row) for row in rows[:limit]] first = output[0]["id"] if output else None last = output[-1]["id"] if output else None return {"events": output, "first": first, "last": last, "more": len(rows) > limit} def chain(self, event_id): with self.lock: event = self.db.execute("SELECT * FROM events WHERE id=?", (event_id,)).fetchone() if not event: return None context = event["target"] is None if context and event["unit"] is None: return {"events": [], "context": True} base = "SELECT * FROM events WHERE session=? AND raid=?" args = [event["session"], event["raid"]] if context: base += " AND unit=? AND tick BETWEEN ? AND ?" args.extend([event["unit"], max(0, event["tick"] - 200), event["tick"] + 200]) else: base += " AND target=?" args.append(event["target"]) rows = self.db.execute(base + " ORDER BY id<>?, abs(tick - ?), id LIMIT 41", [*args, event_id, event["tick"]]).fetchall() kinds = {"observations": 0, "decisions": 1, "events": 2} return { "events": [event_row(row) for row in sorted(rows[:40], key=lambda row: (row["tick"], kinds[row["kind"]], row["id"]))], "context": context, "limited": len(rows) > 40, } def timeline(self, session, raid, after=None): placeholders = ",".join("?" for _ in TIMELINE_LABELS) matching = f"FROM events WHERE session=? AND raid=? AND label IN ({placeholders})" args = (session, raid, *TIMELINE_LABELS) with self.lock: count, last = self.db.execute(f"SELECT count(*), coalesce(max(id), 0) {matching}", args).fetchone() revision = f"{count}:{last}" if after == revision: return None rows = self.db.execute(f"SELECT * {matching} ORDER BY tick, id", args).fetchall() markers = [] for marker in ("impact", "miss", "refusal"): candidates = [row for row in rows if TIMELINE_LABELS[row["label"]] == marker] available = MAX_TIMELINE_MARKERS - len(markers) if not available: break if len(candidates) > available: if available == 1: candidates = candidates[-1:] else: candidates = [candidates[i * (len(candidates) - 1) // (available - 1)] for i in range(available)] markers.extend(dict(event_row(row), marker=marker) for row in candidates) markers.sort(key=lambda event: (event["tick"], event["id"])) return {"events": markers, "limited": len(markers) < len(rows), "revision": revision} def frame(self, session, tick): with self.lock: before = self.db.execute("""SELECT data, tick FROM frames WHERE session=? AND tick<=? ORDER BY tick DESC LIMIT 1""", (session, tick)).fetchone() after = self.db.execute("""SELECT data, tick FROM frames WHERE session=? AND tick>=? ORDER BY tick ASC LIMIT 1""", (session, tick)).fetchone() candidates = [row for row in (before, after) if row is not None] if not candidates: return None nearest = min(candidates, key=lambda row: abs(tick - row["tick"])) if abs(tick - nearest["tick"]) > MAX_FRAME_DISTANCE_TICKS: return None data = nearest["data"] return {"requested": tick, "frame": json.loads(zlib.decompress(data) if isinstance(data, bytes) else data)} def reserve_launch(self, key, owner, session, data): with self.lock, self.db: previous = self.db.execute("SELECT * FROM launches WHERE id=?", (key,)).fetchone() if previous: if (previous["owner"], previous["session"], previous["data"]) != (owner, session, data): raise ValueError("ID уже связан с другим запросом") return self.launch_result(previous), False self.db.execute("INSERT INTO launches VALUES (?, ?, ?, ?, ?, 'queued', ?)", (key, owner, session, data, time.time(), "Ожидает ответа игры")) return {"id": key, "state": "queued", "message": "Ожидает ответа игры"}, True @staticmethod def launch_result(row): return {key: row[key] for key in ("id", "state", "message")} def launch(self, key, owner): with self.lock: row = self.db.execute("SELECT * FROM launches WHERE id=? AND owner=?", (key, owner)).fetchone() return self.launch_result(row) if row else None def previous_launch(self, key, owner, session, data): with self.lock: row = self.db.execute("SELECT * FROM launches WHERE id=?", (key,)).fetchone() if row is None: return None if (row["owner"], row["session"], row["data"]) != (owner, session, data): raise ValueError("ID уже связан с другим запросом") return self.launch_result(row) def complete_launch(self, key, state, message): with self.lock, self.db: self.db.execute("UPDATE launches SET state=?, message=? WHERE id=?", (state, message, key)) def event_row(row): row = dict(row) row["data"] = json.loads(row.pop("payload")) return row