205 lines
9.1 KiB
Python
205 lines
9.1 KiB
Python
"""Single local game bridge. HTTP clients only see cached projections and the archive."""
|
|
import json
|
|
import os
|
|
import queue
|
|
import re
|
|
import secrets
|
|
import socket
|
|
import threading
|
|
import time
|
|
from pathlib import Path
|
|
|
|
TOKEN = re.compile(r"[0-9a-f]{16,32}\Z")
|
|
MAX_PACKET = 1 << 20
|
|
MAX_REPLY = 1 << 18
|
|
|
|
|
|
def local_chat(endpoint: Path, text: str):
|
|
"""Use Horizon's local transport, with no arbitrary commands from HTTP."""
|
|
if not text.startswith("chat /airdef panel ") or "\n" in text or "\r" in text:
|
|
raise ValueError("Invalid local bridge command")
|
|
if os.name == "nt" or endpoint.suffix == ".json":
|
|
config = read_json(endpoint, 4096)
|
|
port, token = config["port"], config["token"]
|
|
if type(port) is not int or not 1 <= port <= 65535 or not re.fullmatch(r"[a-zA-Z0-9_-]{16,256}", token):
|
|
raise ValueError("Invalid local control endpoint")
|
|
connection = socket.create_connection(("127.0.0.1", port), timeout=2.5)
|
|
auth = f"auth {token}\n"
|
|
else:
|
|
connection = socket.socket(socket.AF_UNIX)
|
|
connection.settimeout(2.5)
|
|
try:
|
|
connection.connect(str(endpoint))
|
|
except OSError:
|
|
connection.close()
|
|
raise
|
|
auth = None
|
|
with connection, connection.makefile("rb") as lines:
|
|
if auth:
|
|
connection.sendall(auth.encode("ascii"))
|
|
if not read_line(lines).get("ok"):
|
|
raise OSError("Horizon rejected the local pairing")
|
|
connection.sendall((text + "\n").encode("ascii"))
|
|
result = read_line(lines)
|
|
if result.get("error"):
|
|
raise OSError(str(result["error"]))
|
|
return result
|
|
|
|
|
|
def read_line(stream):
|
|
raw = stream.readline(MAX_REPLY + 1)
|
|
if len(raw) > MAX_REPLY or not raw.endswith(b"\n"):
|
|
raise ValueError("Invalid reply from Horizon")
|
|
return json.loads(raw)
|
|
|
|
|
|
def read_json(path, limit=MAX_PACKET):
|
|
with path.open("rb") as stream:
|
|
data = stream.read(limit + 1)
|
|
if len(data) > limit:
|
|
raise ValueError("Bridge packet exceeds its size limit")
|
|
return json.loads(data)
|
|
|
|
|
|
def validate_wave(payload, catalog):
|
|
if type(payload) is not dict or set(payload) != {"counts", "distance", "approach", "aim"}:
|
|
raise ValueError("Укажите состав, дальность, подход и цель сценария")
|
|
counts = payload["counts"]
|
|
distance, approach, aim = (payload[key] for key in ("distance", "approach", "aim"))
|
|
if (type(counts) is not list or len(counts) != len(catalog["kinds"]) or
|
|
any(type(n) is not int or not 0 <= n <= 80 for n in counts) or not any(counts)):
|
|
raise ValueError("Укажите от 0 до 80 аппаратов каждого типа, хотя бы один суммарно")
|
|
low, high = catalog["distance"]
|
|
if type(distance) is not int or not low <= distance <= high:
|
|
raise ValueError(f"Дальность должна быть целым числом от {low:.0f} до {high:.0f}")
|
|
if type(approach) is not int or not 0 <= approach < len(catalog["approaches"]):
|
|
raise ValueError("Неизвестный подход")
|
|
if type(aim) is not int or not 0 <= aim < len(catalog["aims"]):
|
|
raise ValueError("Неизвестная цель сценария")
|
|
return f"{approach}:{distance}:{aim}:" + ",".join(map(str, counts))
|
|
|
|
|
|
def public_view(raw):
|
|
return {
|
|
"version": 1, "session": raw["session"], "world": raw["world"], "tick": raw["tick"],
|
|
"frame": raw["live"], "catalog": raw["catalog"],
|
|
"selected": raw.get("selected"), "canLaunch": raw["canLaunch"],
|
|
}
|
|
|
|
|
|
class Bridge:
|
|
def __init__(self, endpoint, data, store, *, debug=False, interval=1.0, transport=local_chat):
|
|
self.endpoint, self.data, self.store = endpoint, data, store
|
|
self.debug, self.interval, self.transport = debug, interval, transport
|
|
self.lock = threading.Lock()
|
|
self.stop = threading.Event()
|
|
self.queue = queue.Queue(maxsize=8)
|
|
self.snapshot = None
|
|
self.raw_enemy, self.raw_truth = None, None
|
|
self.connected = False
|
|
self.updated = None
|
|
self.revision = 0
|
|
self.epoch = secrets.token_hex(8)
|
|
self.cursors = {}
|
|
self.thread = threading.Thread(target=self.worker, name="airdef-local-bridge", daemon=True)
|
|
|
|
def begin(self):
|
|
self.thread.start()
|
|
|
|
def close(self):
|
|
self.stop.set()
|
|
if self.thread.is_alive():
|
|
self.thread.join(timeout=8)
|
|
|
|
def worker(self):
|
|
next_poll = time.monotonic()
|
|
backoff = self.interval
|
|
while not self.stop.is_set():
|
|
now = time.monotonic()
|
|
if now >= next_poll:
|
|
try:
|
|
self.poll()
|
|
backoff = self.interval
|
|
except (OSError, ValueError, TypeError, KeyError):
|
|
backoff = min(4.0, backoff * 1.5)
|
|
with self.lock:
|
|
if self.connected:
|
|
self.connected = False
|
|
self.revision += 1
|
|
next_poll = time.monotonic() + backoff
|
|
try:
|
|
job = self.queue.get(timeout=min(0.25, self.interval))
|
|
except queue.Empty:
|
|
continue
|
|
self.dispatch(*job)
|
|
|
|
def poll(self):
|
|
nonce = secrets.token_hex(12)
|
|
mode = "debug" if self.debug else "public"
|
|
epoch = self.snapshot["session"] if self.snapshot else "-"
|
|
cursor = epoch + ":" + ",".join(".".join(map(str, [raid, *indices])) for raid, indices in self.cursors.items())
|
|
self.transport(self.endpoint, f"chat /airdef panel snapshot {nonce} {mode} {cursor}")
|
|
raw = read_json(self.data / "panel-snapshot-v1.json")
|
|
if raw.get("nonce") != nonce or raw.get("version") != 1 or not TOKEN.fullmatch(raw["session"]):
|
|
raise ValueError("Snapshot does not belong to this request")
|
|
public = public_view(raw)
|
|
self.store.append(raw, public)
|
|
self.cursors = {raid["id"]: raid["next"] for raid in raw["raids"]}
|
|
with self.lock:
|
|
self.snapshot = public
|
|
self.raw_enemy, self.raw_truth = raw.get("enemy"), raw.get("truth")
|
|
self.connected = True
|
|
self.updated = time.time()
|
|
self.revision += 1
|
|
|
|
def view(self, mode):
|
|
with self.lock:
|
|
result = dict(self.snapshot or {})
|
|
connected = self.connected
|
|
result.update({
|
|
"revision": f"{self.epoch}-{self.revision}", "connected": connected,
|
|
"updated": self.updated, "perspective": mode,
|
|
"canLaunch": connected and mode == "network" and result.get("canLaunch", False),
|
|
})
|
|
if mode == "enemy":
|
|
result["frame"] = self.raw_enemy
|
|
result.pop("selected", None)
|
|
if mode == "truth":
|
|
result["frame"] = dict(result.get("frame") or {}, contacts=self.raw_truth or [])
|
|
return result
|
|
|
|
def submit(self, key, owner, session, payload):
|
|
state = self.view("network")
|
|
# A retry obtains the stored receipt even if the game went away meanwhile.
|
|
if "catalog" not in state:
|
|
raise ValueError("Игра ещё не передала каталог. Статус принятого запроса доступен по его ID.")
|
|
encoded = validate_wave(payload, state["catalog"])
|
|
prior = self.store.previous_launch(key, owner, session, encoded)
|
|
if prior:
|
|
return prior
|
|
if not state["canLaunch"] or session != state.get("session"):
|
|
raise ValueError("Игра недоступна для запуска. Вернитесь к текущему бою.")
|
|
receipt, created = self.store.reserve_launch(key, owner, session, encoded)
|
|
if created:
|
|
try:
|
|
self.queue.put_nowait((key, session, encoded))
|
|
except queue.Full:
|
|
self.store.complete_launch(key, "rejected", "Очередь занята. Проверьте состояние игры.")
|
|
return self.store.launch(key, owner)
|
|
return receipt
|
|
|
|
def dispatch(self, key, session, encoded):
|
|
state = self.view("network")
|
|
if not state["canLaunch"] or state.get("session") != session:
|
|
self.store.complete_launch(key, "rejected", "Игровая сессия или режим сменились")
|
|
return
|
|
self.store.complete_launch(key, "dispatching", "Запрос передан игре")
|
|
try:
|
|
self.transport(self.endpoint, f"chat /airdef panel launch {key} {session} {encoded}")
|
|
receipt = read_json(self.data / "panel-receipt-v1.json", 4096)
|
|
if receipt["id"] != key or type(receipt["accepted"]) is not bool:
|
|
raise ValueError("Receipt does not belong to this request")
|
|
self.store.complete_launch(key, "accepted" if receipt["accepted"] else "rejected", str(receipt["message"]))
|
|
except (OSError, ValueError, TypeError, KeyError):
|
|
self.store.complete_launch(key, "unknown", "Игра могла принять сценарий. Проверьте состояние карты.")
|