diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 155e567..ab9b1f7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,8 +28,12 @@ jobs: python-version: "3.11" cache: pip - run: pip install -r requirements-dev.txt + # For tests/test_nginx_conf.py, which runs nginx/viofosync.conf. + - run: command -v nginx || { sudo apt-get update && sudo apt-get install -y nginx; } - run: python -m ruff check . - run: python -m pytest -q + env: + VIOFOSYNC_REQUIRE_NGINX: "1" # Publishes to Docker Hub: :edge on main pushes, :X.Y + :latest on # version tags (v2.6 or 2.6 both work), and : on a diff --git a/CHANGELOG.md b/CHANGELOG.md index 98b6eaf..a22a40c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## Unreleased + +### Added + +#### Playback + +- **nginx can serve video.** Put nginx in front with the ready-made `nginx/viofosync.conf`, and playing or downloading a clip sends the browser to nginx, which serves the file itself, so playback no longer waits on the app. nginx checks the login with the app every 30 seconds or so, in the background, so logging out stops video within 30 seconds, and video keeps playing while the app restarts. Nothing to set on the app. See "Serving video through nginx" in the README. + +### Fixed + +- **Constant buffering in Safari.** Safari abandons and reopens its video request every half second or so, and the server kept reading each abandoned request to the end of the clip. Dozens of these at once swamped the disk, especially through Docker Desktop's file sharing. Clip and export playback now stop reading as soon as the browser hangs up. + ## v2.8 — 2026-11-17 ### Added diff --git a/README.md b/README.md index c37e136..d683abc 100644 --- a/README.md +++ b/README.md @@ -114,6 +114,43 @@ Confirm it engaged with `docker exec vainfo`, and check the startup > [!NOTE] > On arm64 hosts QuickSync won't probe-pass; exports degrade to VAAPI or software automatically. +### Serving video through nginx + +If playback buffers, put nginx in front and let it serve the video files. Browsers fetch a playing video as a stream of separate requests (Safari makes several a second), and with nginx none of them wait on the app, however busy it is syncing, making thumbnails or exporting. This made the biggest difference for Safari on Docker Desktop for Mac. + +When you play or download a clip, the app checks your login and sends the browser to the file's address on nginx, like `/media/2026-11-15/2026_1115_080000_0001F.MP4`. nginx sends the file from its own read-only mount of the recordings folder, and browsers keep using that address for every range request and seek. nginx asks the app whether the browser is logged in and remembers the answer for 30 seconds, so the app hears from it once in a while rather than on every request, and video never waits for it. Logging out, or changing the password with "log out other sessions", stops video within 30 seconds. While the app restarts (a new image, say), nginx goes on using the answers it has, so video that was playing keeps playing. + +**1.** Copy [`nginx/viofosync.conf`](nginx/viofosync.conf) next to your `docker-compose.yml`, in an `nginx` folder. + +**2.** Add the nginx service and move the published port from the app to nginx: + +```yaml +services: + viofosync: + # ...as before, but with no "ports:" section + + nginx: + image: nginx:1.27-alpine + container_name: viofosync-nginx + restart: unless-stopped + depends_on: + - viofosync + ports: + - "8080:8080" + volumes: + - ./nginx/viofosync.conf:/etc/nginx/conf.d/default.conf:ro + - /path/to/recordings:/recordings:ro # the same folder as the app's /recordings +``` + +**3.** `docker compose up -d`, then play a clip. `docker logs viofosync-nginx` should show one request to `/api/archive/clip/…/video` answered with `302`, then the `/media/…` requests answered with `206`. + +There's nothing to set on the app: nginx marks the requests it passes on, and the app only sends browsers to `/media/` for those. Reached directly on its own port, the app sends video itself as before, so publishing that port as well doesn't break anything; it's just the slow way in. + +- A `401` for `/media/…` means the browser isn't logged in (any more): log in again and reopen the clip. +- A `404` for `/media/…` means nginx's `/recordings` isn't the app's recordings folder. Mount the same folder at `/recordings` in both, or, if you've set `RECORDINGS` on the app to somewhere else, mount the folder it points to at `/recordings` in nginx. The app's log says which folder it links from. +- The config expects the service to be called `viofosync` and the app to listen on 8080, its default. Change `set $viofosync` in the config if yours differ. +- Behind nginx, every request reaches the app from nginx's address, so the login rate limit (5 tries a minute) is shared by all your devices. + ## Configuration The only Docker-level env vars are: diff --git a/docker-compose.yml b/docker-compose.yml index f7c7202..ffe071b 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -40,3 +40,20 @@ services: # Timezone for log timestamps and journey grouping. # https://en.wikipedia.org/wiki/List_of_tz_database_time_zones TZ: Europe/London + + # Optional: nginx in front, serving clip video itself so playback + # doesn't wait on the app. Uncomment, and remove the app's "ports" above + # so it's reached through nginx. See "Serving video through nginx" in + # the README. + # nginx: + # image: nginx:1.27-alpine + # container_name: viofosync-nginx + # restart: unless-stopped + # depends_on: + # - viofosync + # ports: + # - "8080:8080" + # volumes: + # - ./nginx/viofosync.conf:/etc/nginx/conf.d/default.conf:ro + # # The same recordings folder as above, read-only. + # - /path/to/recordings:/recordings:ro diff --git a/nginx/viofosync.conf b/nginx/viofosync.conf new file mode 100644 index 0000000..085f2cc --- /dev/null +++ b/nginx/viofosync.conf @@ -0,0 +1,107 @@ +# nginx in front of viofosync, serving clip video itself. +# +# Everything is proxied to the app. When you play a clip, the app sends +# the browser to the file's /media/ URL, and nginx sends the file from its +# own read-only mount of the recordings folder. Every range request and +# seek after that goes straight to nginx. nginx asks the app whether the +# browser is logged in, and remembers a yes for 30 seconds, so the app +# hears about it once in a while rather than on every request, and +# logging out (or "log out other sessions") takes effect within that. +# +# Mount at /etc/nginx/conf.d/default.conf in the official nginx image. See +# "Serving video through nginx" in the README. + +map $http_upgrade $connection_upgrade { + default upgrade; + '' close; +} + +# Downloads use the same URLs, with the name to save the file under in +# name=. The app percent-encodes it, which is the form filename*= takes, +# so it's passed through as it is; anything else in it is ignored, so a +# made-up link can't put odd things in the header. Browsers use +# filename*; filename= is for tools like curl and wget that don't. No +# name means inline playback, with no Content-Disposition. +map $arg_name $media_disposition { + "~^[A-Za-z0-9%._~-]+$" "attachment; filename=\"$arg_name\"; filename*=UTF-8''$arg_name"; + default ""; +} + +# The app's answers to "is this browser logged in?", by cookie. +proxy_cache_path /var/cache/nginx/viofosync_auth levels=1 keys_zone=viofosync_auth:1m + max_size=10m inactive=10m; + +server { + listen 8080; + + # Look the app up through Docker's DNS on every request, not just at + # startup, so recreating its container (a new image, say) doesn't leave + # nginx pointing at the old address. + resolver 127.0.0.11 valid=10s ipv6=off; + # Change "viofosync:8080" if the app's service name or port differs. + set $viofosync http://viofosync:8080; + + location / { + proxy_pass $viofosync; + proxy_http_version 1.1; + proxy_set_header Host $http_host; + # Tells the app nginx is here to serve /media/. Replaces any value + # the browser sent. + proxy_set_header X-Viofosync-Media 1; + # The live progress feed is a WebSocket. + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $connection_upgrade; + proxy_read_timeout 1h; + # Pass uploads (Import manually) straight through as they arrive. + # By default nginx would first write each one whole to a temp file + # in this container, multi-GB clips included, before the app saw + # a byte of it. + client_max_body_size 0; + proxy_request_buffering off; + } + + location /media/ { + auth_request /_viofosync_auth; + + # Must match the recordings mount on this container. + alias /recordings/; + add_header Content-Disposition $media_disposition; + sendfile on; + tcp_nopush on; + } + + location = /_viofosync_auth { + internal; + proxy_pass $viofosync/api/auth/check; + proxy_pass_request_body off; + proxy_set_header Content-Length ""; + proxy_set_header Range ""; + proxy_set_header Host $http_host; + # Send the app exactly what the answer is cached under, as one + # header (nginx joins repeated Cookie headers into this). + proxy_set_header Cookie $http_cookie; + + # Remember the answer for 30 seconds. A no is remembered too, so a + # logged-out tab that keeps retrying (Safari does, many times a + # second) doesn't ask the app every time. Logging in still works + # straight away: it comes with a new cookie, so a new question. + # + # Keyed on the whole Cookie header, not just the session cookie: + # with the session cookie sent twice nginx would pick the first and + # the app the last, and a logged-in browser could then file a yes + # under a cookie the app never checked (even under no cookie). + proxy_cache viofosync_auth; + proxy_cache_key $http_cookie; + proxy_cache_valid 204 401 30s; + proxy_cache_lock on; + proxy_ignore_headers Cache-Control Expires Vary; + + # When an answer runs out, keep using it while nginx asks again in + # the background, so playback never waits on the app. + proxy_cache_background_update on; + # And keep using it while the app can't answer (restarting, say), + # rather than failing every video. Answers are kept for up to 10 + # minutes after they were last used (inactive= above). + proxy_cache_use_stale updating error timeout http_500 http_502 http_503 http_504; + } +} diff --git a/tests/test_nginx_conf.py b/tests/test_nginx_conf.py new file mode 100644 index 0000000..4ae21a1 --- /dev/null +++ b/tests/test_nginx_conf.py @@ -0,0 +1,410 @@ +"""nginx/viofosync.conf, run for real in front of the app. + +The rules that keep recordings private live in the nginx config, not the +app: /media/ asks the app about the login, answers are cached by the +whole Cookie header, a no is cached too, download names are filtered, +requests to the app are marked, uploads pass straight through. These +tests start nginx with the shipped config (pointed at a temp folder and +an in-process app, with a 1-second cache) and check each from outside. + +Skipped where nginx isn't installed, unless VIOFOSYNC_REQUIRE_NGINX is +set, as CI does, so they can't be skipped there without anyone noticing. +""" +from __future__ import annotations + +import json +import os +import shutil +import socket +import subprocess +import threading +import time +from pathlib import Path +from types import SimpleNamespace + +import httpx +import pytest + +from tests.test_video_nginx import PASSWORD, _add_clip, _add_export, _FakeMqttService +from web import settings as settings_mod +from web.auth import SESSION_COOKIE + +CONF = Path(__file__).resolve().parent.parent / "nginx" / "viofosync.conf" +CACHE_SECONDS = 1 + + +def _outlast_the_cache() -> None: + # nginx counts in whole seconds, so a 1-second answer can last nearly 3. + time.sleep(CACHE_SECONDS + 2.1) + + +def _nginx_binary() -> str | None: + found = shutil.which("nginx") + if found: + return found + for path in ("/usr/sbin/nginx", "/usr/local/sbin/nginx"): + if os.access(path, os.X_OK): + return path + return None + + +NGINX_BIN = _nginx_binary() +if NGINX_BIN is None: + if os.environ.get("VIOFOSYNC_REQUIRE_NGINX"): + raise RuntimeError("VIOFOSYNC_REQUIRE_NGINX is set but nginx isn't installed") + pytest.skip("nginx isn't installed", allow_module_level=True) + + +def _free_port() -> int: + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def _wait_for_port(port: int, what: str) -> None: + deadline = time.monotonic() + 15 + while time.monotonic() < deadline: + with socket.socket() as s: + if s.connect_ex(("127.0.0.1", port)) == 0: + return + time.sleep(0.05) + raise RuntimeError(f"{what} didn't start listening on {port}") + + +def _swap(conf: str, old: str, new: str) -> str: + # Exactly once, so a change to the shipped config that these tests + # don't follow fails here rather than testing something else. + assert conf.count(old) == 1, f"expected {old!r} once in {CONF.name}" + return conf.replace(old, new) + + +def _write_nginx_conf(tmp: Path, nginx_port: int, app_port: int, recordings: Path) -> Path: + conf = CONF.read_text() + conf = _swap(conf, "listen 8080;", f"listen 127.0.0.1:{nginx_port};") + # An address needs no resolver; Docker's isn't here anyway. + conf = _swap(conf, "resolver 127.0.0.11 valid=10s ipv6=off;", "") + conf = _swap(conf, "set $viofosync http://viofosync:8080;", + f"set $viofosync http://127.0.0.1:{app_port};") + conf = _swap(conf, "alias /recordings/;", f"alias {recordings}/;") + conf = _swap(conf, "/var/cache/nginx/viofosync_auth", str(tmp / "auth_cache")) + conf = _swap(conf, "proxy_cache_valid 204 401 30s;", + f"proxy_cache_valid 204 401 {CACHE_SECONDS}s;") + (tmp / "viofosync.conf").write_text(conf) + + temp_paths = "\n".join( + f" {kind}_temp_path {tmp / kind};" + for kind in ("client_body", "proxy", "fastcgi", "uwsgi", "scgi") + ) + main = tmp / "nginx.conf" + # One process as the current user: no worker switching to a user that + # can't read the temp folders. + main.write_text( + f"daemon off;\nmaster_process off;\npid {tmp / 'nginx.pid'};\n" + f"error_log {tmp / 'error.log'} warn;\n" + "events {}\n" + "http {\n" + f" access_log {tmp / 'access.log'};\n" + f"{temp_paths}\n" + f" include {tmp / 'viofosync.conf'};\n" + "}\n" + ) + return main + + +class _App: + """The app on a real port, in a thread, so it can be stopped.""" + + def __init__(self, app, port: int): + import uvicorn + + self.app = app + self.server = uvicorn.Server(uvicorn.Config( + app, host="127.0.0.1", port=port, log_level="warning", + loop="asyncio", http="h11", ws="none", lifespan="on", + )) + self.thread = threading.Thread(target=self.server.run, daemon=True) + self.thread.start() + deadline = time.monotonic() + 30 + while not self.server.started: + if not self.thread.is_alive() or time.monotonic() > deadline: + raise RuntimeError("the app didn't start") + time.sleep(0.05) + + def stop(self) -> None: + if self.thread.is_alive(): + self.server.should_exit = True + self.thread.join(15) + + +@pytest.fixture +def stack(tmp_config_dir, tmp_recordings_dir, tmp_path, monkeypatch): + import bcrypt + + from web.app import create_app + from web.services.sync_worker import SyncWorker + + monkeypatch.setattr(SyncWorker, "start", lambda self: None) + monkeypatch.setattr("web.app.MqttService", _FakeMqttService) + digest = bcrypt.hashpw(PASSWORD.encode(), bcrypt.gensalt()).decode() + (tmp_config_dir / "config.json").write_text( + json.dumps({"WEB_PASSWORD_HASH": digest}) + ) + settings_mod.reset_for_tests() + + app_port, nginx_port = _free_port(), _free_port() + app = _App(create_app(), app_port) + main = _write_nginx_conf(tmp_path, nginx_port, app_port, tmp_recordings_dir) + for kind in ("client_body", "proxy", "fastcgi", "uwsgi", "scgi"): + (tmp_path / kind).mkdir() + nginx = subprocess.Popen( + [NGINX_BIN, "-p", str(tmp_path), "-c", str(main), "-e", str(tmp_path / "error.log")], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + try: + _wait_for_port(nginx_port, "nginx") + except RuntimeError as e: + nginx.kill() + nginx.wait(10) + app.stop() + log = tmp_path / "error.log" + raise RuntimeError(log.read_text() if log.exists() else str(e)) from e + + clip_id, data = _add_clip(SimpleNamespace(app=app.app), tmp_recordings_dir) + export_id = _add_export(SimpleNamespace(app=app.app), tmp_recordings_dir) + client = httpx.Client(base_url=f"http://127.0.0.1:{nginx_port}") + try: + yield SimpleNamespace( + app=app, client=client, recordings=tmp_recordings_dir, + clip_id=clip_id, data=data, export_id=export_id, + direct=f"http://127.0.0.1:{app_port}", + ) + finally: + client.close() + nginx.terminate() + nginx.wait(10) + app.stop() + settings_mod.reset_for_tests() + + +def _login(s) -> str: + r = s.client.post("/api/auth/login", json={"password": PASSWORD}) + assert r.status_code == 200 + # Every request says which cookie it sends, or none. + s.client.cookies.clear() + return r.cookies[SESSION_COOKIE] + + +def _as(session: str) -> dict: + return {"Cookie": f"{SESSION_COOKIE}={session}"} + + +def _media(s) -> str: + r = s.client.get(f"/api/archive/clip/{s.clip_id}/video", + headers=_as(_login(s))) + assert r.status_code == 302 + return r.headers["location"].split("?")[0] + + +def _get(s, url: str, cookie: str | None) -> int: + headers = {"Range": "bytes=0-0"} + if cookie is not None: + headers["Cookie"] = cookie + return s.client.get(url, headers=headers).status_code + + +def test_media_is_served_by_nginx_only_when_logged_in(stack): + s = stack + url = _media(s) + assert url == "/media/2026-11-15/2026_1115_080000_0001F.MP4" + cookie = f"{SESSION_COOKIE}={_login(s)}" + + r = s.client.get(url, headers={"Cookie": cookie, "Range": "bytes=100-299"}) + assert r.status_code == 206 + assert r.content == s.data[100:300] + + assert _get(s, url, None) == 401 + assert _get(s, url, f"{SESSION_COOKIE}=made-up") == 401 + + +def test_a_session_cookie_sent_twice_files_nothing_for_others(stack): + """nginx would read the first, the app the last; the answer must be + filed under exactly what the app was asked about.""" + s = stack + url = _media(s) + real = _login(s) + + _get(s, url, f"{SESSION_COOKIE}=; {SESSION_COOKIE}={real}") + _get(s, url, f"{SESSION_COOKIE}=junk; {SESSION_COOKIE}={real}") + assert _get(s, url, None) == 401 + assert _get(s, url, f"{SESSION_COOKIE}=") == 401 + assert _get(s, url, f"{SESSION_COOKIE}=junk") == 401 + + +def test_the_app_is_asked_about_the_cookies_as_cached(stack, monkeypatch): + """Cookies sent as two headers are cached joined into one, so the app + must be sent that one header too, not the two, which it could read + differently.""" + from web.routers import auth as auth_router + + s = stack + url = _media(s) + real = _login(s) + asked: list[list[str]] = [] + check = auth_router.require_session + + def recording(request, *args, **kwargs): + asked.append(request.headers.getlist("cookie")) + return check(request, *args, **kwargs) + + monkeypatch.setattr(auth_router, "require_session", recording) + r = s.client.get(url, headers=[ + ("Range", "bytes=0-0"), + ("Cookie", f"{SESSION_COOKIE}=junk"), + ("Cookie", f"{SESSION_COOKIE}={real}"), + ]) + assert r.status_code == 206 + assert asked == [[f"{SESSION_COOKIE}=junk; {SESSION_COOKIE}={real}"]] + + +def test_playback_does_not_wait_for_a_slow_app(stack, monkeypatch): + """Once the answer runs out, nginx keeps using it while it asks the app + again in the background.""" + from web.routers import auth as auth_router + + s = stack + url = _media(s) + cookie = f"{SESSION_COOKIE}={_login(s)}" + assert _get(s, url, cookie) == 206 + + real = auth_router.require_session + + def stalled(*args, **kwargs): + time.sleep(3) # the app's event loop held up, as by a slow disk + return real(*args, **kwargs) + + monkeypatch.setattr(auth_router, "require_session", stalled) + _outlast_the_cache() + started = time.monotonic() + assert _get(s, url, cookie) == 206 + assert time.monotonic() - started < 1.5 + + +def test_logging_others_out_stops_their_video_within_the_cache_time(stack): + s = stack + url = _media(s) + other = f"{SESSION_COOKIE}={_login(s)}" + assert _get(s, url, other) == 206 + + me = _login(s) + csrf = s.client.get("/api/auth/csrf", headers=_as(me)).json()["csrf"] + r = s.client.post( + "/api/settings/password", + headers={**_as(me), "X-CSRF-Token": csrf}, + json={"current": PASSWORD, "new_password": PASSWORD + "2", + "logout_others": True}, + ) + assert r.status_code == 200 + + # Once the remembered yes runs out, one more request may still get it + # while nginx asks again in the background; after that, no. + deadline = time.monotonic() + CACHE_SECONDS + 5 + while _get(s, url, other) == 206: + assert time.monotonic() < deadline, "still playing after logout" + time.sleep(0.2) + assert _get(s, url, other) == 401 + assert _get(s, url, f"{SESSION_COOKIE}={r.cookies[SESSION_COOKIE]}") == 206 + + +def test_video_keeps_playing_while_the_app_is_down(stack): + s = stack + url = _media(s) + cookie = f"{SESSION_COOKIE}={_login(s)}" + assert _get(s, url, cookie) == 206 + + s.app.stop() + _outlast_the_cache() + for _ in range(3): + assert _get(s, url, cookie) == 206 + # With nothing remembered there's nothing to go on: still no. + assert _get(s, url, None) not in (200, 206) + assert _get(s, url, f"{SESSION_COOKIE}=made-up") not in (200, 206) + + +def test_downloads_are_named_and_odd_names_are_dropped(stack): + s = stack + me = _as(_login(s)) + r = s.client.get(f"/api/exports/{s.export_id}/download", headers=me) + assert r.status_code == 302 + r = s.client.get(r.headers["location"], headers=me) + assert r.status_code == 200 + assert r.content == b"\0" * 1024 + disposition = r.headers["content-disposition"] + assert disposition.startswith("attachment; filename=") + assert "filename*=UTF-8''" in disposition + + r = s.client.get(f"/api/exports/{s.export_id}/video", headers=me) + r = s.client.get(r.headers["location"], headers=me) + assert r.status_code == 200 + assert "content-disposition" not in r.headers + + # Kept as they are by httpx, and each has something the name filter + # turns away. + for name in ("evil%22%0d%0aX-Bad:%20y", "a;b", "a=b", "a,b"): + r = s.client.get(f"/media/.exports/5.mp4?name={name}", headers=me) + assert r.status_code == 200 + assert "content-disposition" not in r.headers + assert "x-bad" not in r.headers + + +def test_only_requests_through_nginx_are_sent_to_media(stack): + s = stack + me = _as(_login(s)) + video = f"/api/archive/clip/{s.clip_id}/video" + # nginx replaces whatever the browser sent. + r = s.client.get(video, headers={**me, "X-Viofosync-Media": ""}) + assert r.status_code == 302 + # Straight at the app, it sends the video itself. + r = httpx.get(s.direct + video, headers=me) + assert r.status_code == 200 + assert r.content == s.data + + +def test_uploads_reach_the_app_while_still_being_sent(stack): + s = stack + me = _as(_login(s)) + csrf = s.client.get("/api/auth/csrf", headers=me).json()["csrf"] + name = "2026_1116_100000_0005F.MP4" + part = s.recordings / ".import_tmp" / (name + ".part") + chunk, chunks = b"\0" * (1 << 20), 8 + seen: list[int] = [] + + def body(): + for i in range(chunks): + if i == chunks - 2: + # 6 of 8 MB sent: passed straight through, the app has + # been writing it down all along. + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + size = part.stat().st_size if part.exists() else 0 + if size >= len(chunk): + break + time.sleep(0.05) + seen.append(size) + yield chunk + + r = s.client.post( + "/api/import/upload", + headers={ + **me, + "X-CSRF-Token": csrf, + "X-Import-Path": name, + "Content-Type": "application/octet-stream", + "Content-Length": str(len(chunk) * chunks), + }, + content=body(), + timeout=30, + ) + assert r.status_code == 200 + assert seen and seen[0] >= len(chunk), ( + f"the app had {seen} bytes with 6 MB sent: nginx is holding uploads back" + ) diff --git a/tests/test_video_file_response.py b/tests/test_video_file_response.py new file mode 100644 index 0000000..66e9095 --- /dev/null +++ b/tests/test_video_file_response.py @@ -0,0 +1,96 @@ +"""VideoFileResponse stops reading when the client hangs up. + +Starlette's FileResponse kept reading an abandoned range to its end. Safari +abandons an open-ended ``Range: bytes=N-`` request roughly every 0.6 s during +playback, so each one read the rest of a multi-GB clip and the disk was +swamped with reads nobody would receive. +""" +from __future__ import annotations + +import os + +import anyio + +from web.responses import VideoFileResponse + +_SIZE = 4 * 1024 * 1024 # 64 chunks of FileResponse's 64 KiB + + +def _scope(range_header: bytes | None = b"bytes=0-") -> dict: + headers = [(b"range", range_header)] if range_header else [] + return {"type": "http", "method": "GET", "path": "/", "headers": headers} + + +def _clip(tmp_path) -> str: + path = tmp_path / "clip.mp4" + path.write_bytes(os.urandom(_SIZE)) + return str(path) + + +async def test_stops_reading_after_client_disconnects(tmp_path): + hung_up = anyio.Event() + body = bytearray() + + async def receive(): + await hung_up.wait() + return {"type": "http.disconnect"} + + async def send(message): + if message["type"] == "http.response.body": + body.extend(message.get("body", b"")) + if len(body) >= 256 * 1024: + hung_up.set() + + with anyio.fail_after(5): + await VideoFileResponse(_clip(tmp_path), media_type="video/mp4")( + _scope(), receive, send + ) + assert 256 * 1024 <= len(body) < _SIZE + + +async def test_sends_everything_while_client_stays(tmp_path): + path = _clip(tmp_path) + messages: list[dict] = [] + first = True + + async def receive(): + nonlocal first + if first: + first = False + return {"type": "http.request", "body": b"", "more_body": False} + await anyio.sleep_forever() + + async def send(message): + messages.append(message) + + with anyio.fail_after(5): + await VideoFileResponse(path, media_type="video/mp4")(_scope(), receive, send) + + assert messages[0]["status"] == 206 + body = b"".join(m.get("body", b"") for m in messages[1:]) + with open(path, "rb") as f: + assert body == f.read() + assert messages[-1].get("more_body", False) is False + + +async def test_small_range_is_exact(tmp_path): + path = _clip(tmp_path) + messages: list[dict] = [] + + async def receive(): + await anyio.sleep_forever() + + async def send(message): + messages.append(message) + + with anyio.fail_after(5): + await VideoFileResponse(path, media_type="video/mp4")( + _scope(b"bytes=100-199"), receive, send + ) + + headers = dict(messages[0]["headers"]) + assert headers[b"content-range"] == f"bytes 100-199/{_SIZE}".encode() + body = b"".join(m.get("body", b"") for m in messages[1:]) + with open(path, "rb") as f: + f.seek(100) + assert body == f.read(100) diff --git a/tests/test_video_nginx.py b/tests/test_video_nginx.py new file mode 100644 index 0000000..4d7cb19 --- /dev/null +++ b/tests/test_video_nginx.py @@ -0,0 +1,311 @@ +"""nginx in front serves video: the app redirects to /media/ and answers +nginx's login checks. + +nginx/viofosync.conf marks the requests it passes on with +X-Viofosync-Media. With it, the video endpoints check the session and look +the file up as before, then redirect to the file's /media/ URL. nginx +checks each /media/ request with GET /api/auth/check (caching a yes for a +short while) and serves the file itself. Without the header the endpoints +stream the file. +""" +from __future__ import annotations + +import json +import re +from pathlib import Path +from urllib.parse import quote, unquote, urlsplit + +import bcrypt +import pytest +from fastapi.testclient import TestClient + +from web import responses +from web import settings as settings_mod +from web.auth import SESSION_COOKIE +from web.responses import media_link + +PASSWORD = "pwpwpwpwpwpwpwpw" +NGINX = {"X-Viofosync-Media": "1"} + +# The pattern nginx/viofosync.conf's $media_disposition map accepts. +NGINX_NAME = re.compile(r"[A-Za-z0-9%._~-]+") + + +def _name_arg(url: str) -> str: + """name= as nginx's $arg_name sees it: still percent-encoded.""" + for arg in urlsplit(url).query.split("&"): + if arg.startswith("name="): + return arg[len("name="):] + return "" + + +def test_conf_name_pattern_matches_this_test(): + conf = (Path(__file__).resolve().parent.parent / "nginx" / "viofosync.conf").read_text() + assert '"~^' + NGINX_NAME.pattern + '$"' in conf + + +# --- media_link --- + + +def test_media_link_escapes_the_path(): + assert media_link("2026-11-15/2026_1115_080000_0001F.MP4") == ( + "/media/2026-11-15/2026_1115_080000_0001F.MP4" + ) + assert media_link("Road trip/clip #1?.MP4") == ( + "/media/Road%20trip/clip%20%231%3F.MP4" + ) + + +def test_download_name_is_encoded_for_nginx(): + url = media_link(".exports/5.mp4", 'Café "trip" 2026/11/15 a&b=c;.mp4') + assert url == ( + "/media/.exports/5.mp4?name=Caf%C3%A9%20%22trip%22%202026%2F11%2F15" + "%20a%26b%3Dc%3B.mp4" + ) + # nginx puts it into the header as it is, so it must hold nothing + # that would need quoting there, and nginx must accept it. + assert NGINX_NAME.fullmatch(_name_arg(url)) + + +# --- endpoints --- + + +class _FakeMqttService: + def __init__(self, **kwargs): + self._last_node_id = "" + self._last_discovery_prefix = "" + + def start(self): pass + async def stop(self): pass + async def on_settings_changed(self, keys, snap): pass + def get_status(self): + return {"state": "idle", "detail": None, "last_published_at": None} + + +@pytest.fixture +def make_client(tmp_config_dir, tmp_recordings_dir, monkeypatch): + from web.app import create_app + from web.services.sync_worker import SyncWorker + + monkeypatch.setattr(SyncWorker, "start", lambda self: None) + monkeypatch.setattr("web.app.MqttService", _FakeMqttService) + monkeypatch.setattr(responses, "_warned_outside", False) + monkeypatch.setattr(responses, "_noted_root", False) + opened: list[TestClient] = [] + + def _make(**config) -> TestClient: + digest = bcrypt.hashpw(PASSWORD.encode(), bcrypt.gensalt()).decode() + (tmp_config_dir / "config.json").write_text( + json.dumps({"WEB_PASSWORD_HASH": digest, **config}) + ) + settings_mod.reset_for_tests() + c = TestClient(create_app()) + c.__enter__() + opened.append(c) + return c + + yield _make + for c in opened: + c.__exit__(None, None, None) + settings_mod.reset_for_tests() + + +def _add_clip(client, recordings) -> tuple[int, bytes]: + day = recordings / "2026-11-15" + day.mkdir(exist_ok=True) + clip = day / "2026_1115_080000_0001F.MP4" + data = bytes(range(256)) * 4 + clip.write_bytes(data) + with client.app.state.db.write() as c: + c.execute( + "INSERT INTO clip_index " + "(id, path, basename, group_name, timestamp, camera, " + " sequence, event_type, has_gpx, gps_examined, scanned_at) " + "VALUES (7,?,?,?,1,'F',1,'normal',0,0,1)", + (str(clip), clip.name, "2026-11-15"), + ) + return 7, data + + +def _add_export(client, recordings) -> int: + out = recordings / ".exports" / "5.mp4" + out.parent.mkdir(exist_ok=True) + out.write_bytes(b"\0" * 1024) + with client.app.state.db.write() as c: + return c.execute( + "INSERT INTO export_jobs " + "(type, clip_ids, state, output_path, created_at, finished_at) " + "VALUES ('join_front', ?, 'done', ?, 1, 2)", + (json.dumps({"clip_ids": [], "encoder": "software"}), str(out)), + ).lastrowid + + +def _login(client) -> str: + client.post("/api/auth/login", json={"password": PASSWORD}) + return client.cookies[SESSION_COOKIE] + + +def test_clip_video_redirects_to_media_behind_nginx(make_client, tmp_recordings_dir): + c = make_client() + clip_id, _ = _add_clip(c, tmp_recordings_dir) + _login(c) + + r = c.get(f"/api/archive/clip/{clip_id}/video", headers=NGINX, + follow_redirects=False) + assert r.status_code == 302 + assert r.headers["cache-control"] == "no-store" + # Also the archive's download link: named as the app would name it. + assert r.headers["location"] == ( + "/media/2026-11-15/2026_1115_080000_0001F.MP4" + "?name=2026_1115_080000_0001F.MP4" + ) + + +def test_clip_video_still_needs_login(make_client, tmp_recordings_dir): + c = make_client() + clip_id, _ = _add_clip(c, tmp_recordings_dir) + r = c.get(f"/api/archive/clip/{clip_id}/video", headers=NGINX, + follow_redirects=False) + assert r.status_code == 401 + assert "location" not in r.headers + + +def test_export_video_plays_inline_and_download_keeps_its_name( + make_client, tmp_recordings_dir +): + c = make_client() + job_id = _add_export(c, tmp_recordings_dir) + _login(c) + + r = c.get(f"/api/exports/{job_id}/video", headers=NGINX, + follow_redirects=False) + assert r.status_code == 302 + assert r.headers["location"] == "/media/.exports/5.mp4" + + r = c.get(f"/api/exports/{job_id}/download", headers=NGINX, + follow_redirects=False) + assert r.status_code == 302 + url = r.headers["location"] + assert url.startswith("/media/.exports/5.mp4?name=") + name = unquote(_name_arg(url)) + assert name != "5.mp4" + assert NGINX_NAME.fullmatch(_name_arg(url)) + + # The same name the app gives the download without nginx. + r = c.get(f"/api/exports/{job_id}/download", follow_redirects=False) + assert r.status_code == 200 + assert r.content == b"\0" * 1024 + want = r.headers["content-disposition"] + assert f'filename="{name}"' in want or quote(name) in want + + +def test_without_nginx_the_app_streams_it(make_client, tmp_recordings_dir): + c = make_client() + clip_id, data = _add_clip(c, tmp_recordings_dir) + _login(c) + r = c.get(f"/api/archive/clip/{clip_id}/video", follow_redirects=False) + assert r.status_code == 200 + assert r.content == data + assert "2026_1115_080000_0001F.MP4" in r.headers["content-disposition"] + + +def test_file_outside_recordings_is_streamed_and_warned_once( + make_client, tmp_recordings_dir, tmp_path, monkeypatch +): + c = make_client() + _login(c) + outside = tmp_path / "elsewhere.mp4" + outside.write_bytes(b"x" * 100) + with c.app.state.db.write() as db: + db.execute( + "INSERT INTO clip_index " + "(id, path, basename, group_name, timestamp, camera, " + " sequence, event_type, has_gpx, gps_examined, scanned_at) " + "VALUES (8,?,?,?,1,'F',1,'normal',0,0,1)", + (str(outside), outside.name, "2026-11-15"), + ) + warnings: list[str] = [] + monkeypatch.setattr( + responses.log, "warning", lambda msg, *a: warnings.append(msg % a) + ) + for _ in range(3): + r = c.get("/api/archive/clip/8/video", headers=NGINX, + follow_redirects=False) + assert r.status_code == 200 + assert r.content == b"x" * 100 + assert len(warnings) == 1 + assert str(outside) in warnings[0] + + +def test_a_recordings_folder_other_than_nginxs_is_noted_once( + make_client, tmp_recordings_dir, monkeypatch +): + """nginx serves /media/ from its /recordings, and the app links + relative to its own recordings folder: with a different one (as here) + say which folder nginx must have there.""" + c = make_client() + clip_id, _ = _add_clip(c, tmp_recordings_dir) + _login(c) + notes: list[str] = [] + monkeypatch.setattr(responses.log, "info", lambda msg, *a: notes.append(msg % a)) + for _ in range(3): + r = c.get(f"/api/archive/clip/{clip_id}/video", headers=NGINX, + follow_redirects=False) + assert r.status_code == 302 + assert len(notes) == 1 + assert str(tmp_recordings_dir) in notes[0] + + +# --- nginx's login check --- + + +def test_check_needs_a_login(make_client): + c = make_client() + r = c.get("/api/auth/check") + assert r.status_code == 401 + + _login(c) + r = c.get("/api/auth/check") + assert r.status_code == 204 + assert r.content == b"" + # nginx caches the answer by cookie: nothing here may stop that or + # change the cookie. + assert "set-cookie" not in r.headers + assert "cache-control" not in r.headers + + +def test_check_fails_once_other_sessions_are_logged_out(make_client): + c = make_client() + old = _login(c) + csrf = c.get("/api/auth/csrf").json()["csrf"] + r = c.post( + "/api/settings/password", + headers={"X-CSRF-Token": csrf}, + json={"current": PASSWORD, "new_password": PASSWORD + "2", + "logout_others": True}, + ) + assert r.status_code == 200 + new = c.cookies[SESSION_COOKIE] + assert new != old + + c.cookies.set(SESSION_COOKIE, old) + assert c.get("/api/auth/check").status_code == 401 + c.cookies.set(SESSION_COOKIE, new) + assert c.get("/api/auth/check").status_code == 204 + + +def test_check_with_password_login_off(make_client): + c = make_client(WEB_PASSWORD_DISABLED=True) + r = c.get("/api/auth/check") + assert r.status_code == 204 + assert "set-cookie" not in r.headers + + +def test_check_does_not_wait_for_a_worker_thread(): + """It's async so it answers straight away while sync endpoints have + every worker thread busy.""" + import asyncio + + from web.routers.auth import check + + assert asyncio.iscoroutinefunction(check) diff --git a/web/responses.py b/web/responses.py new file mode 100644 index 0000000..1bf49eb --- /dev/null +++ b/web/responses.py @@ -0,0 +1,126 @@ +"""Response classes shared by the routers.""" +from __future__ import annotations + +import logging +import os +from urllib.parse import quote + +import anyio +from fastapi import Request +from starlette.responses import FileResponse, RedirectResponse, Response +from starlette.types import Receive, Scope, Send + +log = logging.getLogger("viofosync.responses") + +# Both must match nginx/viofosync.conf: the header it sets on requests it +# passes to the app, and where it serves the recordings folder. +MEDIA_HEADER = "X-Viofosync-Media" +MEDIA_PREFIX = "/media/" + + +class VideoFileResponse(FileResponse): + """A ``FileResponse`` that stops reading the file when the client hangs up. + + Starlette's ``FileResponse`` streams the whole requested range to the end + even after the client has disconnected: uvicorn quietly discards the + writes, but every chunk is still read from disk. Browsers abandon video + requests constantly, and Safari above all: during playback it opens a + fresh open-ended ``Range: bytes=N-`` request roughly every 0.6 s and drops + the previous one after reading a few MB. Each abandoned request then kept + reading the rest of a multi-GB dashcam clip, so dozens of them ended up + competing for the disk (a slow one on Docker Desktop's file sharing) with + the reads playback actually needed, and Safari buffered constantly. + + This listens for ``http.disconnect`` alongside the transfer, the same way + Starlette's ``StreamingResponse`` does, and cancels the transfer when it + arrives. + """ + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + async with anyio.create_task_group() as tg: + + async def transfer() -> None: + await FileResponse.__call__(self, scope, receive, send) + tg.cancel_scope.cancel() + + tg.start_soon(transfer) + while (await receive())["type"] != "http.disconnect": + pass + tg.cancel_scope.cancel() + + +def media_link(rel_path: str, filename: str | None = None) -> str: + """The /media/ URL nginx serves ``rel_path`` (relative to the + recordings folder) at. + + With ``filename``, nginx sends the file as a download with that name. + It travels percent-encoded in ``name=``, which is exactly the form + ``Content-Disposition: attachment; filename*=UTF-8''…`` wants, so + nginx passes it through without decoding it. nginx ignores a name + with anything but those characters in it. + """ + url = MEDIA_PREFIX + quote(rel_path) + if filename: + url += "?name=" + quote(filename, safe="") + return url + + +# Where nginx/viofosync.conf serves /media/ from, in nginx's container. +NGINX_ROOT = "/recordings" + +_warned_outside = False +_noted_root = False + + +def video_response( + request: Request, + path: str, + recordings: str, + filename: str | None = None, +) -> Response: + """Serve a video, or send the browser to nginx for it. + + nginx/viofosync.conf marks every request it passes on with the + ``X-Viofosync-Media`` header, overwriting any the browser sent. Then + the reply is a redirect to the file's /media/ URL. Browsers keep + using the URL they were redirected to for every following range + request and seek, so after this one request nginx serves the whole + clip itself, checking the login with the app now and then rather + than on every request. With ``filename`` it's a download under that + name, from either. + + The caller has already checked the session and that the file exists. + Without nginx, or for a file outside the recordings folder, the app + serves it. + """ + if request.headers.get(MEDIA_HEADER): + root = os.path.abspath(recordings) + target = os.path.abspath(path) + if os.path.commonpath([root, target]) == root and target != root: + rel = os.path.relpath(target, root).replace(os.sep, "/") + global _noted_root + if not _noted_root: + _noted_root = True + if root != NGINX_ROOT: + log.info( + "Sending video to nginx under /media/, relative to " + "the recordings folder %s. nginx/viofosync.conf " + "serves /media/ from %s in its own container, so " + "mount that same folder there. (Logged once.)", + root, NGINX_ROOT, + ) + return RedirectResponse( + media_link(rel, filename), + status_code=302, + headers={"Cache-Control": "no-store"}, + ) + global _warned_outside + if not _warned_outside: + _warned_outside = True + log.warning( + "%s is outside the recordings folder %s, so nginx can't " + "serve it and the app is sending it instead. Videos like " + "it will play more slowly. (Logged once.)", + path, recordings, + ) + return VideoFileResponse(path, media_type="video/mp4", filename=filename) diff --git a/web/routers/archive.py b/web/routers/archive.py index cc2fe61..6d2ffd5 100644 --- a/web/routers/archive.py +++ b/web/routers/archive.py @@ -21,6 +21,7 @@ from fastapi.responses import FileResponse, JSONResponse, Response from ..auth import require_csrf, require_session +from ..responses import video_response from ..services import durations, filmstrip, route_cache, scanner, thumbs from ..services import tasks as _tasks from ..services import gps as gps_service @@ -1160,12 +1161,16 @@ async def clip_filmstrip_jpg(request: Request, clip_id: int): @router.get("/clip/{clip_id}/video") def clip_video(request: Request, clip_id: int): - """Stream the MP4. ``FileResponse`` handles HTTP Range - out of the box so