Bandwidth test: fix repeat tests failing, add a duration (1-60 s)

The server kept streaming (and holding the one-test lock) after the browser stopped reading, so the
next test got a 409. The server now ends the stream at the chosen duration, the browser reads to the
end, and a new test ends any earlier stream instead of being refused. Errors show in the cell.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
neil 2026-10-26 20:29:42 -07:00
parent 169a6154ab
commit 87b92f8332
No known key found for this signature in database
4 changed files with 58 additions and 23 deletions

View file

@ -20,7 +20,7 @@ from pathlib import Path
import docker
from starlette.concurrency import run_in_threadpool
from docker.errors import NotFound
from fastapi import Depends, FastAPI, File, Form, HTTPException, Request, UploadFile
from fastapi import Depends, FastAPI, File, Form, HTTPException, Query, Request, UploadFile
from fastapi.responses import FileResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from starlette.middleware.sessions import SessionMiddleware
@ -421,31 +421,32 @@ def get_stats():
# ---------- bandwidth test ----------
# The browser downloads random bytes for BANDWIDTH_TEST_S and measures the rate, so the result is the
# The browser downloads random bytes for `seconds` and measures the rate, so the result is the
# VPS -> browser path (the VPS's upload, what players receive), capped by the viewer's own connection.
# One test at a time, and none while anyone is playing: a test saturates the uplink and would lag them.
BANDWIDTH_TEST_S = 5
# None while anyone is playing: a test saturates the uplink and would lag them. A new test ends the
# previous stream, which a proxy may still be reading after the browser gave up on it.
BANDWIDTH_TEST_MAX_S = 60
_bw_chunk = os.urandom(1024 * 1024) # random, so a compressing proxy can't shrink it
_bw_lock = threading.Lock()
_bw_run = 0 # id of the newest test
@app.get("/api/bandwidth-test", dependencies=[Depends(require_auth)])
def bandwidth_test():
def bandwidth_test(seconds: int = Query(5, ge=1, le=BANDWIDTH_TEST_MAX_S)):
global _bw_run
with stats_lock:
online = sum(len(s.get("players") or []) for s in server_stats.values())
if online:
raise HTTPException(409, f"{online} player{'s are' if online != 1 else ' is'} connected. The test would "
"use all of the VPS's bandwidth and lag them, so it's disabled until everyone has left.")
if not _bw_lock.acquire(blocking=False):
raise HTTPException(409, "A bandwidth test is already running.")
with _bw_lock:
_bw_run += 1
run = _bw_run
def stream():
try:
end = time.monotonic() + BANDWIDTH_TEST_S + 1 # the browser stops at BANDWIDTH_TEST_S
while time.monotonic() < end:
yield _bw_chunk
finally:
_bw_lock.release()
end = time.monotonic() + seconds
while time.monotonic() < end and _bw_run == run:
yield _bw_chunk
return StreamingResponse(stream(), media_type="application/octet-stream",
headers={"Cache-Control": "no-store", "Content-Encoding": "identity"})