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:
parent
169a6154ab
commit
87b92f8332
4 changed files with 58 additions and 23 deletions
25
app/app.py
25
app/app.py
|
|
@ -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:
|
||||
end = time.monotonic() + seconds
|
||||
while time.monotonic() < end and _bw_run == run:
|
||||
yield _bw_chunk
|
||||
finally:
|
||||
_bw_lock.release()
|
||||
|
||||
return StreamingResponse(stream(), media_type="application/octet-stream",
|
||||
headers={"Cache-Control": "no-store", "Content-Encoding": "identity"})
|
||||
|
|
|
|||
|
|
@ -124,54 +124,79 @@ function setResourcesOpen(open) {
|
|||
try { setResourcesOpen(!!localStorage.getItem('resources-open')); } catch { /* private mode */ }
|
||||
$('#resources-toggle').addEventListener('click', () => setResourcesOpen($('#resources-more').classList.contains('hidden')));
|
||||
|
||||
// Bandwidth test: download random bytes from the VPS for BW_TEST_S and report the fastest half second,
|
||||
// i.e. the VPS's upload as seen by this browser. app.py refuses it while players are connected.
|
||||
const BW_TEST_S = 5;
|
||||
// Bandwidth test: download random bytes from the VPS for the chosen number of seconds (1-60) and report
|
||||
// the fastest half second, i.e. the VPS's upload as seen by this browser. app.py refuses it while
|
||||
// players are connected.
|
||||
const BW_MAX_S = 60;
|
||||
const fmtMbps = (bytesPerSec) => `${((bytesPerSec * 8) / 1e6).toFixed(bytesPerSec < 125000 ? 2 : 0)} Mbit/s`;
|
||||
let bwRunning = false;
|
||||
|
||||
function bwSeconds() {
|
||||
const n = Math.round(+$('#bw-seconds').value);
|
||||
return Number.isFinite(n) ? Math.min(BW_MAX_S, Math.max(1, n)) : 5;
|
||||
}
|
||||
try { const saved = localStorage.getItem('bw-seconds'); if (saved) $('#bw-seconds').value = saved; } catch { /* private mode */ }
|
||||
$('#bw-seconds').addEventListener('change', () => {
|
||||
$('#bw-seconds').value = bwSeconds();
|
||||
try { localStorage.setItem('bw-seconds', bwSeconds()); } catch { /* private mode */ }
|
||||
});
|
||||
|
||||
function applyBandwidthGuard() {
|
||||
const online = Object.values(stats.servers).reduce((n, st) => n + (st.players?.length || 0), 0);
|
||||
const why = online ? `${online} player${online === 1 ? ' is' : 's are'} connected. The test uses all of the VPS's `
|
||||
+ 'bandwidth and would lag them, so it\'s disabled until everyone has left.' : '';
|
||||
$('#bw-btn').disabled = bwRunning || !!why;
|
||||
$('#bw-seconds').disabled = bwRunning;
|
||||
$('#bw-tip').title = why;
|
||||
}
|
||||
|
||||
$('#bw-btn').addEventListener('click', async () => {
|
||||
const seconds = bwSeconds();
|
||||
$('#bw-seconds').value = seconds;
|
||||
bwRunning = true;
|
||||
applyBandwidthGuard();
|
||||
$('#bw-btn').textContent = 'Testing…';
|
||||
const out = $('#bw-result');
|
||||
const detail = $('#bw-detail');
|
||||
detail.textContent = '';
|
||||
detail.classList.remove('error');
|
||||
out.title = '';
|
||||
const ctrl = new AbortController();
|
||||
const failsafe = setTimeout(() => ctrl.abort(), (seconds + 15) * 1000); // the server ends the stream itself
|
||||
let total = 0;
|
||||
let peak = 0;
|
||||
let elapsed = 0;
|
||||
const samples = []; // [time, total bytes]
|
||||
try {
|
||||
const res = await fetch('/api/bandwidth-test', { signal: ctrl.signal, cache: 'no-store' });
|
||||
const res = await fetch(`/api/bandwidth-test?seconds=${seconds}`, { signal: ctrl.signal, cache: 'no-store' });
|
||||
if (!res.ok) throw new Error((await res.json().catch(() => ({}))).detail || `Request failed (${res.status})`);
|
||||
const reader = res.body.getReader();
|
||||
const start = performance.now();
|
||||
setTimeout(() => ctrl.abort(), BW_TEST_S * 1000);
|
||||
samples.push([start, 0]);
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
total += value.length;
|
||||
const now = performance.now();
|
||||
elapsed = (now - start) / 1000;
|
||||
samples.push([now, total]);
|
||||
while (samples.length > 2 && now - samples[1][0] >= 500) samples.shift(); // keep a 0.5 s window
|
||||
const [t0, b0] = samples[0];
|
||||
if (now - t0 >= 500) peak = Math.max(peak, ((total - b0) * 1000) / (now - t0));
|
||||
out.textContent = `Testing… ${fmtMbps((total * 1000) / (now - start))}`;
|
||||
out.textContent = `Testing… ${fmtMbps(total / elapsed)}`;
|
||||
}
|
||||
} catch (err) {
|
||||
if (err.name !== 'AbortError') { out.textContent = 'Test failed'; out.title = err.message; }
|
||||
if (err.name !== 'AbortError' || !peak) {
|
||||
out.textContent = 'Test failed';
|
||||
detail.textContent = err.name === 'AbortError' ? 'The VPS stopped responding.' : err.message;
|
||||
detail.classList.add('error');
|
||||
}
|
||||
}
|
||||
clearTimeout(failsafe);
|
||||
if (peak) {
|
||||
out.textContent = `Peak ${fmtMbps(peak)}`;
|
||||
out.title = `Fastest half second of a ${BW_TEST_S} s download from the VPS (${fmtRate(peak)}); `
|
||||
+ `${fmtBytes(total)} transferred. Limited by your own connection too.`;
|
||||
detail.textContent = `Average ${fmtMbps(total / elapsed)} · ${fmtBytes(total)} in ${elapsed.toFixed(1)} s`;
|
||||
out.title = `Fastest half second (${fmtRate(peak)}) of a download from the VPS. Limited by your own connection too.`;
|
||||
}
|
||||
bwRunning = false;
|
||||
$('#bw-btn').textContent = 'Test bandwidth';
|
||||
|
|
|
|||
|
|
@ -51,7 +51,11 @@
|
|||
<div class="meter"><div class="meter-label"><span>Disk</span><span id="m-disk">–</span></div><div class="bar"><div id="b-disk"></div></div></div>
|
||||
<div class="meter">
|
||||
<div class="meter-label"><span>Bandwidth</span><span id="bw-result">Not tested</span></div>
|
||||
<div class="bw-controls">
|
||||
<span class="tip" id="bw-tip"><button class="small" id="bw-btn">Test bandwidth</button></span>
|
||||
<label class="bw-seconds">for <input type="number" id="bw-seconds" min="1" max="60" step="1" value="5"> s</label>
|
||||
</div>
|
||||
<div class="bw-detail" id="bw-detail"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="more-toggle"><button class="ghost small" id="resources-toggle" aria-expanded="false" aria-controls="resources-more">More ▾</button></div>
|
||||
|
|
|
|||
|
|
@ -81,6 +81,11 @@ a { color: var(--accent); }
|
|||
.more-toggle { display: flex; justify-content: center; margin: 10px 0 -8px; }
|
||||
#resources-toggle { border: 0; color: var(--muted); }
|
||||
#resources-toggle:hover { color: var(--text); }
|
||||
.bw-controls { display: flex; align-items: center; gap: 8px; }
|
||||
.bw-seconds { display: flex; align-items: center; gap: 6px; margin: 0; font-size: 13px; font-weight: normal; color: var(--muted); }
|
||||
#bw-seconds { width: 56px; margin: 0; padding: 3px 6px; font-size: 13px; }
|
||||
.bw-detail { font-size: 12px; color: var(--muted); margin-top: 4px; min-height: 1em; }
|
||||
.bw-detail.error { color: var(--bad); }
|
||||
.meter-label { display: flex; justify-content: space-between; gap: 8px; white-space: nowrap; font-size: 13px; margin-bottom: 4px; }
|
||||
.meter-label span:last-child { color: var(--muted); font-variant-numeric: tabular-nums; }
|
||||
.bar { height: 8px; background: var(--bar); border-radius: 4px; overflow: hidden; }
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue