Initial
This commit is contained in:
commit
2ca7a264b3
53 files changed
+7113
No files matched your search
+478
@@ -0,0 +1,478 @@
|
||||
import asyncio
|
||||
import gzip
|
||||
from functools import lru_cache
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import secrets
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from urllib.request import Request as UrlRequest, urlopen
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Query, Request, Response
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from . import engine as e
|
||||
from .store import Database, pack, unpack
|
||||
|
||||
db = Database()
|
||||
logger = logging.getLogger("dispatch")
|
||||
COOKIE = "dispatch_owner"
|
||||
WORKER = os.getenv("BOT_URL", "http://127.0.0.1:8081").rstrip("/")
|
||||
|
||||
|
||||
def now():
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def owner(request, response=None):
|
||||
token = request.cookies.get(COOKIE)
|
||||
if not token or len(token) != 64:
|
||||
if response is None:
|
||||
raise HTTPException(404, "Партия не найдена")
|
||||
token = secrets.token_hex(32)
|
||||
response.set_cookie(
|
||||
COOKIE,
|
||||
token,
|
||||
httponly=True,
|
||||
samesite="strict",
|
||||
secure=os.getenv("COOKIE_SECURE") == "1",
|
||||
max_age=365 * 86400,
|
||||
)
|
||||
return hashlib.sha256(token.encode()).hexdigest()
|
||||
|
||||
|
||||
def require(row):
|
||||
if row is None:
|
||||
raise HTTPException(404, "Партия не найдена")
|
||||
return row
|
||||
|
||||
|
||||
def recorder(run, gid, start):
|
||||
seq = start
|
||||
|
||||
def emit(s, kind, data):
|
||||
nonlocal seq
|
||||
seq += 1
|
||||
data.setdefault("seat", s["active"])
|
||||
run(
|
||||
"INSERT INTO events VALUES (?,?,?,?,?,?,?)",
|
||||
(gid, seq, s["turn"], kind, now(), json.dumps(data), pack(s)),
|
||||
)
|
||||
|
||||
return emit, lambda: seq
|
||||
|
||||
|
||||
def filtered(kind, data, seat):
|
||||
if seat != "full":
|
||||
if kind == "draw" and data["seat"] != seat:
|
||||
return {"seat": data["seat"]}
|
||||
if kind == "decision" and data["seat"] != seat:
|
||||
return {"seat": data["seat"]}
|
||||
return data
|
||||
|
||||
|
||||
def events(run, gid, seat, after=0, end=2147483647):
|
||||
rows = run(
|
||||
"SELECT seq,turn,kind,at,data FROM events WHERE game_id=? AND seq>? AND seq<=? ORDER BY seq",
|
||||
(gid, after, end),
|
||||
)
|
||||
return [
|
||||
dict(seq=n, turn=t, kind=k, at=a, data=filtered(k, json.loads(d), seat))
|
||||
for n, t, k, a, d in rows
|
||||
]
|
||||
|
||||
|
||||
def commit(gid, account, rev, cid, cmd, trace=None, bot=False):
|
||||
payload = json.dumps([rev, cmd], sort_keys=True)
|
||||
with db.transaction(True) as run:
|
||||
row = require(db.row(run, gid, account, True))
|
||||
old = run(
|
||||
"SELECT payload,result FROM commands WHERE game_id=? AND command_id=?",
|
||||
(gid, cid),
|
||||
).fetchone()
|
||||
if old:
|
||||
if old[0] != payload:
|
||||
raise HTTPException(409, "Ключ команды уже использован")
|
||||
return json.loads(old[1])
|
||||
_, version, blob, seq = row
|
||||
if rev != version:
|
||||
raise HTTPException(409, f"Текущая версия {version}")
|
||||
s = unpack(blob)
|
||||
if s["catalog"] != e.DIGEST:
|
||||
raise HTTPException(409, "Требуется исходная версия каталога")
|
||||
if s["winner"] is not None or ((e.actor(s) != 0) != bot):
|
||||
raise HTTPException(409, "Сейчас ход другого участника или игра окончена")
|
||||
emit, last = recorder(run, gid, seq)
|
||||
if trace:
|
||||
emit(s, "decision", dict(seat=e.actor(s), observed_seq=seq, **trace))
|
||||
try:
|
||||
e.Turn(s, emit).apply(cmd)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(422, str(exc)) from exc
|
||||
result = dict(version=version + 1, seq=last())
|
||||
run(
|
||||
"UPDATE games SET version=?,seq=?,state=?,next_actor=?,winner=?,turn=?,updated=? WHERE id=?",
|
||||
(
|
||||
version + 1,
|
||||
last(),
|
||||
pack(s),
|
||||
e.actor(s) if s["winner"] is None else None,
|
||||
s["winner"],
|
||||
s["turn"],
|
||||
now(),
|
||||
gid,
|
||||
),
|
||||
)
|
||||
run(
|
||||
"INSERT INTO commands VALUES (?,?,?,?)",
|
||||
(gid, cid, payload, json.dumps(result)),
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def tick():
|
||||
with db.transaction() as run:
|
||||
item = run(
|
||||
"SELECT id,version,state,seq FROM games WHERE next_actor>0 ORDER BY updated LIMIT 1"
|
||||
).fetchone()
|
||||
if not item:
|
||||
return False
|
||||
gid, rev, raw, seq = item
|
||||
s = unpack(raw)
|
||||
seat = e.actor(s)
|
||||
choices = e.actions(s)
|
||||
body = dict(
|
||||
view=e.observation(s, seat),
|
||||
actions=choices,
|
||||
history=events(run, gid, seat, end=seq),
|
||||
)
|
||||
encoded = json.dumps(body).encode()
|
||||
for _ in range(2):
|
||||
try:
|
||||
req = UrlRequest(
|
||||
WORKER + "/decide",
|
||||
data=encoded,
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
with urlopen(req, timeout=4) as answer:
|
||||
trace = json.load(answer)
|
||||
cmd = trace["command"]
|
||||
if not isinstance(trace["alternatives"], list):
|
||||
raise ValueError("worker protocol")
|
||||
break
|
||||
except (OSError, ValueError, KeyError):
|
||||
trace = None
|
||||
if not trace:
|
||||
cmd = choices[0]
|
||||
if cmd["kind"] == "exchange":
|
||||
cmd = dict(kind="exchange", cards=[body["view"]["hand"][0]])
|
||||
trace = dict(
|
||||
command=cmd, alternatives=[], reason="Резервное решение: воркер недоступен"
|
||||
)
|
||||
try:
|
||||
commit(gid, None, rev, "bot-" + str(rev), cmd, trace, True)
|
||||
except HTTPException as exc:
|
||||
if exc.status_code not in (404, 409):
|
||||
raise
|
||||
return True
|
||||
|
||||
|
||||
async def loop():
|
||||
while True:
|
||||
try:
|
||||
worked = await asyncio.to_thread(tick)
|
||||
except Exception:
|
||||
logger.exception("Не удалось обработать очередь ботов")
|
||||
worked = False
|
||||
await asyncio.sleep(0.08 if worked else 0.4)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app):
|
||||
db.init()
|
||||
task = asyncio.create_task(loop())
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
task.cancel()
|
||||
try:
|
||||
await task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
|
||||
app = FastAPI(title="Взлёт разрешён!", lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def privacy(request, call_next):
|
||||
response = await call_next(request)
|
||||
if request.url.path.startswith("/api/"):
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
return response
|
||||
|
||||
|
||||
class Setup(BaseModel):
|
||||
bots: int = Field(ge=3, le=5)
|
||||
color: str | None = None
|
||||
|
||||
|
||||
class Move(BaseModel):
|
||||
command_id: uuid.UUID
|
||||
expected_version: int = Field(ge=0)
|
||||
command: dict
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
def health():
|
||||
with db.transaction() as run:
|
||||
run("SELECT 1")
|
||||
return {"ready": True}
|
||||
|
||||
|
||||
@app.get("/api/catalog")
|
||||
def catalog():
|
||||
return e.CAT
|
||||
|
||||
|
||||
@app.post("/api/games", status_code=201)
|
||||
def create(data: Setup, request: Request, response: Response):
|
||||
if data.color and data.color not in e.CAT["fleets"]:
|
||||
raise HTTPException(422, "Неизвестная авиакомпания")
|
||||
account = owner(request, response)
|
||||
gid = uuid.uuid4().hex
|
||||
s = e.new_game(data.bots, data.color)
|
||||
ts = now()
|
||||
with db.transaction(True) as run:
|
||||
run(
|
||||
"INSERT INTO catalogs VALUES (?,?) ON CONFLICT (digest) DO NOTHING",
|
||||
(e.DIGEST, json.dumps(e.CAT)),
|
||||
)
|
||||
run(
|
||||
"INSERT INTO games VALUES (?,?,?,?,?,?,?,?,?,?,?)",
|
||||
(
|
||||
gid,
|
||||
account,
|
||||
ts,
|
||||
ts,
|
||||
0,
|
||||
1,
|
||||
pack(s),
|
||||
e.actor(s),
|
||||
None,
|
||||
json.dumps(s["colors"]),
|
||||
1,
|
||||
),
|
||||
)
|
||||
emit, _ = recorder(run, gid, 0)
|
||||
emit(s, "start", dict(seat=s["active"]))
|
||||
return dict(
|
||||
id=gid,
|
||||
version=0,
|
||||
seq=1,
|
||||
view=e.observation(s, 0),
|
||||
actions=e.actions(s) if e.actor(s) == 0 else [],
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/games")
|
||||
def archive(request: Request, response: Response):
|
||||
account = owner(request, response)
|
||||
with db.transaction() as run:
|
||||
rows = run(
|
||||
"SELECT id,created,updated,turn,winner,colors,state FROM games WHERE owner=? ORDER BY created DESC",
|
||||
(account,),
|
||||
)
|
||||
return [
|
||||
dict(
|
||||
id=k,
|
||||
created=a,
|
||||
updated=b,
|
||||
turn=t,
|
||||
winner=w,
|
||||
colors=json.loads(c),
|
||||
rules=unpack(blob)["catalog"],
|
||||
strategy=unpack(blob)["strategy"],
|
||||
)
|
||||
for k, a, b, t, w, c, blob in rows
|
||||
]
|
||||
|
||||
|
||||
class ArchiveRemoval(BaseModel):
|
||||
ids: list[uuid.UUID] = Field(min_length=1)
|
||||
allow_active: bool = False
|
||||
|
||||
|
||||
@app.post("/api/archive/remove")
|
||||
def remove_games(data: ArchiveRemoval, request: Request):
|
||||
account = owner(request)
|
||||
ids = sorted({gid.hex for gid in data.ids})
|
||||
if data.allow_active and len(ids) != 1:
|
||||
raise HTTPException(422, "Текущие партии удаляются только по одной")
|
||||
removed = 0
|
||||
with db.transaction(True) as run:
|
||||
for offset in range(0, len(ids), 300):
|
||||
chunk = ids[offset:offset+300]
|
||||
marks = ",".join("?" for _ in chunk)
|
||||
lookup = f"SELECT id FROM games WHERE owner=? AND id IN ({marks})"
|
||||
if not data.allow_active:
|
||||
lookup += " AND winner IS NOT NULL"
|
||||
lookup += " ORDER BY id"
|
||||
if db.dsn:
|
||||
lookup += " FOR UPDATE"
|
||||
matched = [row[0] for row in run(lookup, [account, *chunk])]
|
||||
if not matched:
|
||||
continue
|
||||
marks = ",".join("?" for _ in matched)
|
||||
for table in ("commands", "events"):
|
||||
run(f"DELETE FROM {table} WHERE game_id IN ({marks})", matched)
|
||||
run(f"DELETE FROM games WHERE id IN ({marks})", matched)
|
||||
removed += len(matched)
|
||||
return {"removed": removed}
|
||||
|
||||
|
||||
@app.get("/api/games/{gid}")
|
||||
def state(gid: str, request: Request):
|
||||
with db.transaction() as run:
|
||||
_, rev, blob, seq = require(db.row(run, gid, owner(request)))
|
||||
s = unpack(blob)
|
||||
return dict(
|
||||
view=e.observation(s, 0),
|
||||
version=rev,
|
||||
seq=seq,
|
||||
actions=e.actions(s) if e.actor(s) == 0 else [],
|
||||
recent=events(run, gid, 0, max(0, seq - 8), seq),
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/games/{gid}/commands")
|
||||
def command(gid: str, data: Move, request: Request):
|
||||
return commit(
|
||||
gid, owner(request), data.expected_version, str(data.command_id), data.command
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/games/{gid}/events")
|
||||
def stream(gid: str, request: Request, after: int = Query(0, ge=0)):
|
||||
with db.transaction() as run:
|
||||
row = require(db.row(run, gid, owner(request)))
|
||||
return events(run, gid, 0, after, row[3])
|
||||
|
||||
|
||||
def perspective_seat(s, perspective):
|
||||
if perspective not in ["full", *map(str, range(len(s["colors"])))]:
|
||||
raise HTTPException(422, "Неизвестная перспектива")
|
||||
if perspective != "0" and s["winner"] is None:
|
||||
raise HTTPException(403, "Доступно после окончания партии")
|
||||
seat = perspective if perspective == "full" else int(perspective)
|
||||
return seat
|
||||
|
||||
|
||||
def replay_frame(point, seat, seq, timeline, finished):
|
||||
v = e.observation(point, 0 if seat == "full" else seat)
|
||||
if seat == "full":
|
||||
v.update(hands=point["hands"], deck=list(reversed(point["deck"])))
|
||||
for later in timeline[seq:]:
|
||||
later["data"] = {}
|
||||
later["kind"] = "future"
|
||||
return dict(
|
||||
view=v, seq=seq, last=len(timeline), finished=finished, timeline=timeline
|
||||
)
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def reference():
|
||||
with gzip.open(
|
||||
Path(__file__).with_name("fixtures") / "reference.json.gz",
|
||||
"rt",
|
||||
encoding="utf8",
|
||||
) as f:
|
||||
return json.load(f)
|
||||
|
||||
|
||||
@app.get("/api/reference/replay")
|
||||
def reference_replay(seq: int = Query(1, ge=1), perspective: str = "0"):
|
||||
records = reference()["events"]
|
||||
seat = perspective_seat(records[-1]["state"], perspective)
|
||||
seq = min(seq, len(records))
|
||||
timeline = [
|
||||
dict(
|
||||
seq=r["seq"],
|
||||
turn=r["turn"],
|
||||
kind=r["kind"],
|
||||
at=r["at"],
|
||||
data=filtered(r["kind"], r["data"], seat),
|
||||
)
|
||||
for r in records
|
||||
]
|
||||
return replay_frame(records[seq - 1]["state"], seat, seq, timeline, True)
|
||||
|
||||
|
||||
@app.get("/api/reference/export")
|
||||
def reference_export():
|
||||
return Response(
|
||||
json.dumps(reference(), ensure_ascii=False),
|
||||
media_type="application/json",
|
||||
headers={"Content-Disposition": 'attachment; filename="reference.json"'},
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/games/{gid}/replay")
|
||||
def replay(
|
||||
gid: str, request: Request, seq: int = Query(1, ge=1), perspective: str = "0"
|
||||
):
|
||||
with db.transaction() as run:
|
||||
_, _, current, last = require(db.row(run, gid, owner(request)))
|
||||
s = unpack(current)
|
||||
seat = perspective_seat(s, perspective)
|
||||
seq = min(seq, last)
|
||||
raw = run(
|
||||
"SELECT snapshot FROM events WHERE game_id=? AND seq=?", (gid, seq)
|
||||
).fetchone()[0]
|
||||
point = unpack(raw)
|
||||
return replay_frame(
|
||||
point, seat, seq, events(run, gid, seat, end=last), s["winner"] is not None
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/games/{gid}/export")
|
||||
def export(gid: str, request: Request):
|
||||
with db.transaction() as run:
|
||||
_, _, blob, _ = require(db.row(run, gid, owner(request)))
|
||||
s = unpack(blob)
|
||||
if s["winner"] is None:
|
||||
raise HTTPException(403, "Экспорт доступен после окончания")
|
||||
rows = run(
|
||||
"SELECT seq,turn,kind,at,data,snapshot FROM events WHERE game_id=? ORDER BY seq",
|
||||
(gid,),
|
||||
)
|
||||
data = dict(
|
||||
schema=1,
|
||||
id=gid,
|
||||
rules=s["catalog"],
|
||||
catalog=json.loads(
|
||||
run(
|
||||
"SELECT content FROM catalogs WHERE digest=?", (s["catalog"],)
|
||||
).fetchone()[0]
|
||||
),
|
||||
strategy=s["strategy"],
|
||||
events=[
|
||||
dict(seq=n, turn=t, kind=k, at=a, data=json.loads(d), state=unpack(b))
|
||||
for n, t, k, a, d, b in rows
|
||||
],
|
||||
)
|
||||
return Response(
|
||||
json.dumps(data, ensure_ascii=False),
|
||||
media_type="application/json",
|
||||
headers={"Content-Disposition": f'attachment; filename="dispatch-{gid}.json"'},
|
||||
)
|
||||
|
||||
|
||||
app.mount(
|
||||
"/", StaticFiles(directory=Path(__file__).with_name("static"), html=True), name="ui"
|
||||
)
|
||||
Reference in new issue
Block a user