Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
332 lines (267 loc) · 11.5 KB
/
Copy pathapp.py
File metadata and controls
332 lines (267 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
from __future__ import annotations
import csv
import io
import json
import os
import random
import secrets
import threading
import time
import tomllib
import uuid
from collections import defaultdict
from datetime import datetime, timezone
from pathlib import Path
from typing import Annotated
from fastapi import Depends, FastAPI, Header, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import Response
from pydantic import BaseModel, Field, field_validator
ADMIN_PASSWORD = os.environ.get("ADMIN_PASSWORD")
if not ADMIN_PASSWORD:
raise RuntimeError("ADMIN_PASSWORD must be set")
APP_VERSION = tomllib.loads(Path(__file__).with_name("pyproject.toml").read_text())["project"]["version"]
POINTS_RANGE = (1, 1000)
ID_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789" # no 0/O, 1/I/L
ID_LENGTH = 8
class Item(BaseModel):
course: str
seats: Annotated[int, Field(ge=0, le=100)] # % of available seats
points: Annotated[int, Field(ge=POINTS_RANGE[0], le=POINTS_RANGE[1])]
CONFIG_FILE = Path(os.environ.get("CONFIG_FILE", Path(__file__).with_name("config.json")))
COURSE_PAIRS = json.loads(CONFIG_FILE.read_text())
SEATS = {course: seats for course, seats in COURSE_PAIRS}
COURSES = list(SEATS)
if len(COURSES) != len(COURSE_PAIRS) or sum(SEATS.values()) != 100:
raise RuntimeError(f"{CONFIG_FILE}: courses must be unique and seats must sum to 100")
INITIAL_ORDER = sorted(COURSES, key=lambda course: SEATS[course])
class Submission(BaseModel):
session_id: str
items: list[Item]
@field_validator("items")
@classmethod
def items_are_each_course_once(cls, items: list[Item]) -> list[Item]:
if sorted(item.course for item in items) != sorted(COURSES):
raise ValueError(f"items must contain each of {COURSES} exactly once")
return items
DATA_DIR = Path(os.environ.get("DATA_DIR", "data"))
DATA_FILE = DATA_DIR / "data.jsonl"
SESSIONS_FILE = DATA_DIR / "sessions.json"
STATE_FILE = DATA_DIR / "state.json"
ASSIGNMENTS_FILE = DATA_DIR / "assignments.json"
ALGORITHMS = ["da", "ia"] # deferred acceptance, immediate acceptance
ARCHIVE_DIR = DATA_DIR / "archive"
DATA_DIR.mkdir(parents=True, exist_ok=True)
ARCHIVE_DIR.mkdir(parents=True, exist_ok=True)
DATA_FILE.touch(exist_ok=True)
if not SESSIONS_FILE.exists():
SESSIONS_FILE.write_text("{}")
if not STATE_FILE.exists():
STATE_FILE.write_text(json.dumps({"active": False}))
app = FastAPI(title="app-matching (minimal)", version=APP_VERSION)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["X-App-Version"],
)
@app.middleware("http")
async def add_version_header(request: Request, call_next):
response = await call_next(request)
response.headers["X-App-Version"] = APP_VERSION
return response
def read_json(path: Path):
return json.loads(path.read_text())
def write_json(path: Path, payload) -> None:
tmp = path.with_suffix(".tmp")
tmp.write_text(json.dumps(payload))
tmp.replace(path)
_lock = threading.Lock()
def new_session_id(taken) -> str:
while True:
session_id = "".join(secrets.choice(ID_ALPHABET) for _ in range(ID_LENGTH))
if session_id not in taken:
return session_id
def normalize_id(session_id: str) -> str:
return session_id.strip().upper()
def read_submissions() -> list[dict]:
return [json.loads(line) for line in DATA_FILE.read_text().splitlines() if line.strip()]
def is_active() -> bool:
return read_json(STATE_FILE)["active"]
# brute-force protection: N requests per IP per rolling window
RATE_LIMITS = {"admin": (10, 60), "session": (100, 60)} # (max hits, window seconds)
_hits: dict[tuple[str, str], list[float]] = defaultdict(list)
def rate_limit(bucket: str):
def check(request: Request) -> None:
limit, window = RATE_LIMITS[bucket]
key = (bucket, request.client.host if request.client else "unknown")
now = time.monotonic()
hits = [t for t in _hits[key] if now - t < window]
if len(hits) >= limit:
raise HTTPException(429, "Too many requests")
hits.append(now)
_hits[key] = hits
return check
# auth
def require_admin(x_admin_password: str = Header(...)) -> None:
if not secrets.compare_digest(x_admin_password, ADMIN_PASSWORD):
raise HTTPException(401, "Invalid admin password")
def require_active() -> None:
if not is_active():
raise HTTPException(403, "Server is not active")
# server
@app.post("/server/activate", dependencies=[Depends(rate_limit("admin")), Depends(require_admin)])
def activate() -> dict:
write_json(STATE_FILE, {"active": True})
return {"active": True}
@app.post("/server/deactivate", dependencies=[Depends(rate_limit("admin")), Depends(require_admin)])
def deactivate() -> dict:
write_json(STATE_FILE, {"active": False})
return {"active": False}
@app.post("/server/reset", dependencies=[Depends(rate_limit("admin")), Depends(require_admin)])
def reset() -> dict:
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
with _lock:
batch_dir = ARCHIVE_DIR / stamp
n = 1
while batch_dir.exists():
batch_dir = ARCHIVE_DIR / f"{stamp}-{n}"
n += 1
batch_dir.mkdir(parents=True)
DATA_FILE.rename(batch_dir / "data.jsonl")
SESSIONS_FILE.rename(batch_dir / "sessions.json")
if ASSIGNMENTS_FILE.exists():
ASSIGNMENTS_FILE.rename(batch_dir / "assignments.json")
DATA_FILE.touch()
write_json(SESSIONS_FILE, {})
return {"archived_to": str(batch_dir)}
@app.get("/server/statistics", dependencies=[Depends(rate_limit("admin")), Depends(require_admin)])
def statistics() -> dict:
submissions = read_submissions()
sessions = read_json(SESSIONS_FILE)
orders = [[item["course"] for item in r["items"]] for r in submissions]
n = len(submissions) or 1
return {
"version": APP_VERSION,
"active": is_active(),
"total_submissions": len(submissions),
"total_sessions": len(sessions),
"used_sessions": sum(1 for s in sessions.values() if s["used"]),
"average_rank_by_course": {
course: sum(order.index(course) + 1 for order in orders) / n for course in COURSES
},
"ranked_first_count": {
course: sum(1 for order in orders if order[0] == course) for course in COURSES
},
"kept_initial_order": sum(1 for order in orders if order == INITIAL_ORDER),
"assignments_uploaded": ASSIGNMENTS_FILE.exists(),
}
@app.get("/server/export", dependencies=[Depends(rate_limit("admin")), Depends(require_admin)])
def export() -> Response:
submissions = read_submissions()
out = io.StringIO()
writer = csv.writer(out)
writer.writerow([
"session_id", "submitted_at",
*(f"rank_{i}" for i in range(1, len(COURSES) + 1)),
*(f"{course} points" for course in COURSES),
])
for r in submissions:
points = {item["course"]: item["points"] for item in r["items"]}
writer.writerow([
r["session_id"], r["submitted_at"],
*(item["course"] for item in r["items"]),
*(points[course] for course in COURSES),
])
return Response(
out.getvalue(),
media_type="text/csv",
headers={"Content-Disposition": 'attachment; filename="submissions.csv"'},
)
@app.post("/server/assignments", dependencies=[Depends(rate_limit("admin")), Depends(require_admin)])
async def upload_assignments(request: Request) -> dict:
try:
text = (await request.body()).decode("utf-8-sig")
except UnicodeDecodeError:
raise HTTPException(422, "the file must be UTF-8 text")
rows = [row for row in csv.reader(io.StringIO(text)) if any(cell.strip() for cell in row)]
columns = ["session_id", *ALGORITHMS]
if rows and [cell.strip().lower() for cell in rows[0]] == columns:
rows = rows[1:]
if not rows:
raise HTTPException(422, "the file has no assignment rows")
sessions = read_json(SESSIONS_FILE)
assignments: dict[str, dict[str, str]] = {}
errors = []
for line, row in enumerate(rows, start=1):
if len(row) != len(columns):
errors.append(f"row {line}: expected {len(columns)} columns ({', '.join(columns)}), got {len(row)}")
continue
session_id, *courses = (cell.strip() for cell in row)
session_id = normalize_id(session_id)
if session_id not in sessions:
errors.append(f"row {line}: unknown session id {session_id!r}")
elif session_id in assignments:
errors.append(f"row {line}: session id {session_id!r} appears twice")
for algorithm, course in zip(ALGORITHMS, courses):
if course not in COURSES:
errors.append(f"row {line}: unknown {algorithm} course {course!r} (expected one of {COURSES})")
assignments[session_id] = dict(zip(ALGORITHMS, courses))
if errors:
raise HTTPException(422, errors[:20])
with _lock:
write_json(ASSIGNMENTS_FILE, assignments)
return {"assigned": len(assignments)}
# session
@app.post("/session/start", dependencies=[Depends(rate_limit("session")), Depends(require_active)])
def start() -> dict:
points = {course: random.randint(*POINTS_RANGE) for course in COURSES}
with _lock:
sessions = read_json(SESSIONS_FILE)
session_id = new_session_id(sessions)
sessions[session_id] = {
"created_at": datetime.now(timezone.utc).isoformat(),
"used": False,
"points": points,
}
write_json(SESSIONS_FILE, sessions)
items = [{"course": course, "seats": SEATS[course], "points": points[course]} for course in INITIAL_ORDER]
return {"session_id": session_id, "items": items}
@app.post("/session/submit", dependencies=[Depends(rate_limit("session")), Depends(require_active)])
def submit(payload: Submission) -> dict:
with _lock:
sessions = read_json(SESSIONS_FILE)
session = sessions.get(payload.session_id)
if session is None:
raise HTTPException(401, "Unknown session")
if session["used"]:
raise HTTPException(409, "Session already submitted")
expected = {course: (SEATS[course], session["points"][course]) for course in COURSES}
if {item.course: (item.seats, item.points) for item in payload.items} != expected:
raise HTTPException(422, "items must be the session's items, only reordered")
record = {
"id": uuid.uuid4().hex,
"submitted_at": datetime.now(timezone.utc).isoformat(),
"session_id": payload.session_id,
"items": [item.model_dump() for item in payload.items],
}
with DATA_FILE.open("a") as f:
f.write(json.dumps(record) + "\n")
session["used"] = True
write_json(SESSIONS_FILE, sessions)
return record
@app.get("/session/assignment/{session_id}", dependencies=[Depends(rate_limit("session"))])
def assignment(session_id: str) -> dict:
session_id = normalize_id(session_id)
submission = next((r for r in read_submissions() if r["session_id"] == session_id), None)
available = ASSIGNMENTS_FILE.exists()
matches = read_json(ASSIGNMENTS_FILE).get(session_id) if available else None
if submission is None and matches is None:
raise HTTPException(404, "No submission found for this session id")
return {
"session_id": session_id,
"items": submission["items"] if submission else None,
"results_available": available,
"matches": matches,
}