vpstream 0.3.0__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. {vpstream-0.3.0 → vpstream-0.4.0}/CHANGELOG.md +9 -0
  2. {vpstream-0.3.0 → vpstream-0.4.0}/PKG-INFO +14 -1
  3. {vpstream-0.3.0 → vpstream-0.4.0}/README.md +12 -0
  4. {vpstream-0.3.0 → vpstream-0.4.0}/pyproject.toml +2 -2
  5. vpstream-0.4.0/src/vpstream/api.py +39 -0
  6. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/cli.py +66 -0
  7. vpstream-0.4.0/src/vpstream/client.py +70 -0
  8. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/config.py +10 -0
  9. vpstream-0.4.0/src/vpstream/daemon.py +157 -0
  10. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/tests/conftest.py +11 -0
  11. vpstream-0.4.0/src/vpstream/tests/test_daemon.py +263 -0
  12. {vpstream-0.3.0 → vpstream-0.4.0}/.gitignore +0 -0
  13. {vpstream-0.3.0 → vpstream-0.4.0}/LICENSE +0 -0
  14. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/__init__.py +0 -0
  15. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/__main__.py +0 -0
  16. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/assets/__init__.py +0 -0
  17. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/assets/caps.html +0 -0
  18. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/assets/caps.js +0 -0
  19. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/assets/hls.js.LICENSE +0 -0
  20. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/assets/hls.js.version +0 -0
  21. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/assets/hls.min.js +0 -0
  22. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/bench.py +0 -0
  23. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/caps/__init__.py +0 -0
  24. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/caps/clips.py +0 -0
  25. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/caps/server.py +0 -0
  26. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/doctor.py +0 -0
  27. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/ffargs.py +0 -0
  28. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/ffmpeg_install.py +0 -0
  29. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/probe.py +0 -0
  30. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/selftest.py +0 -0
  31. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/subtitles.py +0 -0
  32. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/tailscale.py +0 -0
  33. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/tests/__init__.py +0 -0
  34. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/tests/data/three-cues.sup +0 -0
  35. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/tests/fakes.py +0 -0
  36. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/tests/test_assets.py +0 -0
  37. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/tests/test_bench.py +0 -0
  38. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/tests/test_caps.py +0 -0
  39. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/tests/test_cli.py +0 -0
  40. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/tests/test_config.py +0 -0
  41. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/tests/test_doctor.py +0 -0
  42. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/tests/test_ffargs.py +0 -0
  43. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/tests/test_ffmpeg_install.py +0 -0
  44. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/tests/test_integration.py +0 -0
  45. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/tests/test_probe.py +0 -0
  46. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/tests/test_subtitles.py +0 -0
  47. {vpstream-0.3.0 → vpstream-0.4.0}/src/vpstream/tools.py +0 -0
@@ -2,6 +2,15 @@
2
2
 
3
3
  <!-- version list -->
4
4
 
5
+ ## v0.4.0 (2026-11-10)
6
+
7
+ ### Features
8
+
9
+ - Add the daemon with its unix-socket CLI and Tailscale-only dashboard port
10
+ ([#6](https://github.com/skj-skj/vpstream/pull/6),
11
+ [`acdef5e`](https://github.com/skj-skj/vpstream/commit/acdef5ec4f27005cf00c419e22040d34b297c2a8))
12
+
13
+
5
14
  ## v0.3.0 (2026-11-10)
6
15
 
7
16
  ### Features
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: vpstream
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: On-demand video streaming from a VPS, controlled over SSH or a private dashboard
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -13,6 +13,7 @@ Classifier: Programming Language :: Python :: 3.13
13
13
  Classifier: Programming Language :: Python :: 3.14
14
14
  Classifier: Topic :: Multimedia :: Video
15
15
  Requires-Python: >=3.12
16
+ Requires-Dist: flask>=3.0
16
17
  Provides-Extra: dev
17
18
  Requires-Dist: pytest>=8; extra == 'dev'
18
19
  Description-Content-Type: text/markdown
@@ -68,6 +69,18 @@ pipx uninstall vpstream # the per-user copy, if there is one
68
69
  Settings are read from `/etc/vpstream/config.toml` when it exists: `port` under `[stream]`
69
70
  (default 1337) and `port` under `[dashboard]` (default 1338).
70
71
 
72
+ ## `vpstream daemon` and `vpstream status`
73
+
74
+ One daemon does the work, and the command line and the dashboard both talk to it.
75
+ `vpstream daemon` runs it in the foreground; normally the service does that.
76
+
77
+ - **Command line:** `vpstream status` asks the daemon over a unix socket,
78
+ `/run/vpstream/daemon.sock`, which only the service user and its group can use.
79
+ `--json` prints the raw answer.
80
+ - **Dashboard port:** bound to this host's Tailscale address only (from `tailscale ip -4`),
81
+ never to every interface. While Tailscale has no address the daemon keeps running and tries
82
+ again every 10 seconds; `vpstream status` says why the dashboard is not available.
83
+
71
84
  ## `vpstream install ffmpeg` and `vpstream update ffmpeg`
72
85
 
73
86
  Distribution packages of ffmpeg are often several versions old. `vpstream install ffmpeg`
@@ -49,6 +49,18 @@ pipx uninstall vpstream # the per-user copy, if there is one
49
49
  Settings are read from `/etc/vpstream/config.toml` when it exists: `port` under `[stream]`
50
50
  (default 1337) and `port` under `[dashboard]` (default 1338).
51
51
 
52
+ ## `vpstream daemon` and `vpstream status`
53
+
54
+ One daemon does the work, and the command line and the dashboard both talk to it.
55
+ `vpstream daemon` runs it in the foreground; normally the service does that.
56
+
57
+ - **Command line:** `vpstream status` asks the daemon over a unix socket,
58
+ `/run/vpstream/daemon.sock`, which only the service user and its group can use.
59
+ `--json` prints the raw answer.
60
+ - **Dashboard port:** bound to this host's Tailscale address only (from `tailscale ip -4`),
61
+ never to every interface. While Tailscale has no address the daemon keeps running and tries
62
+ again every 10 seconds; `vpstream status` says why the dashboard is not available.
63
+
52
64
  ## `vpstream install ffmpeg` and `vpstream update ffmpeg`
53
65
 
54
66
  Distribution packages of ffmpeg are often several versions old. `vpstream install ffmpeg`
@@ -4,13 +4,13 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "vpstream"
7
- version = "0.3.0"
7
+ version = "0.4.0"
8
8
  description = "On-demand video streaming from a VPS, controlled over SSH or a private dashboard"
9
9
  readme = "README.md"
10
10
  license = "MIT"
11
11
  license-files = ["LICENSE", "src/vpstream/assets/hls.js.LICENSE"]
12
12
  requires-python = ">=3.12"
13
- dependencies = []
13
+ dependencies = ["flask>=3.0"]
14
14
  classifiers = [
15
15
  "Programming Language :: Python :: 3",
16
16
  "Programming Language :: Python :: 3.12",
@@ -0,0 +1,39 @@
1
+ """The daemon's HTTP API: one Flask app, served on the unix socket and on the dashboard port.
2
+
3
+ The CLI and the dashboard call the same routes, so either can act on what the other started.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from collections.abc import Callable
9
+ from typing import Any
10
+
11
+ from flask import Flask, Response, jsonify
12
+ from markupsafe import escape
13
+ from werkzeug.exceptions import HTTPException
14
+
15
+ API = "/api/v1"
16
+
17
+
18
+ def create_app(status: Callable[[], dict[str, Any]]) -> Flask:
19
+ """Build the app. `status` returns the daemon's current state as plain data."""
20
+ app = Flask("vpstream", static_folder=None, template_folder=None)
21
+
22
+ @app.get(f"{API}/status")
23
+ def api_status() -> Response:
24
+ return jsonify(status())
25
+
26
+ @app.get("/")
27
+ def index() -> str:
28
+ info = status()
29
+ stream = "a stream is running" if info.get("stream") else "no stream is running"
30
+ return (
31
+ "<!doctype html><meta charset=utf-8><title>vpstream</title>"
32
+ f"<h1>vpstream {escape(info.get('version', ''))}</h1><p>The daemon is up; {stream}.</p>"
33
+ )
34
+
35
+ @app.errorhandler(HTTPException)
36
+ def http_error(exc: HTTPException) -> tuple[Response, int]:
37
+ return jsonify(error=exc.description or exc.name), exc.code or 500
38
+
39
+ return app
@@ -9,6 +9,7 @@ import tarfile
9
9
  import time
10
10
  from collections.abc import Sequence
11
11
  from pathlib import Path
12
+ from typing import Any
12
13
 
13
14
  from vpstream import __version__
14
15
 
@@ -143,6 +144,64 @@ def cmd_doctor(args: argparse.Namespace) -> int:
143
144
  return doctor.exit_code(checks)
144
145
 
145
146
 
147
+ def _duration(seconds: float) -> str:
148
+ """A short human duration: 45s, 3m 12s, 2h 05m, 3d 4h."""
149
+ total = int(seconds)
150
+ days, rest = divmod(total, 86400)
151
+ hours, rest = divmod(rest, 3600)
152
+ minutes, secs = divmod(rest, 60)
153
+ if days:
154
+ return f"{days}d {hours}h"
155
+ if hours:
156
+ return f"{hours}h {minutes:02d}m"
157
+ if minutes:
158
+ return f"{minutes}m {secs:02d}s"
159
+ return f"{secs}s"
160
+
161
+
162
+ def format_status(info: dict[str, Any], cli_version: str) -> str:
163
+ """The daemon's status as text for `vpstream status`."""
164
+ dash = info.get("dashboard") or {}
165
+ lines = [
166
+ f"vpstream daemon {info.get('version')}, "
167
+ f"up {_duration(float(info.get('uptime_seconds') or 0))} (pid {info.get('pid')})",
168
+ f"Stream: {'running' if info.get('stream') else 'none'}",
169
+ f"Stream port: {info.get('stream_port')}",
170
+ "Dashboard: "
171
+ + (f"http://{dash['address']}/" if dash.get("address") else str(dash.get("problem"))),
172
+ ]
173
+ if info.get("version") != cli_version:
174
+ lines.append(
175
+ f"note: the daemon runs {info.get('version')} but this command is {cli_version}; "
176
+ "restart it with: sudo systemctl restart vpstream"
177
+ )
178
+ return "\n".join(lines)
179
+
180
+
181
+ def cmd_status(args: argparse.Namespace) -> int:
182
+ import json
183
+
184
+ from vpstream import client, config
185
+
186
+ try:
187
+ info = client.call(config.default_paths().socket, "GET", "status")
188
+ except (client.DaemonUnavailable, client.DaemonRefused) as exc:
189
+ return _error(str(exc))
190
+ print(json.dumps(info, indent=2) if args.json else format_status(info, __version__))
191
+ return 0
192
+
193
+
194
+ def cmd_daemon(args: argparse.Namespace) -> int:
195
+ from vpstream import config, daemon
196
+ from vpstream.tools import SystemRunner
197
+
198
+ paths = config.default_paths()
199
+ try:
200
+ return daemon.run(config.load(paths.config_file), paths, SystemRunner())
201
+ except (config.ConfigError, daemon.DaemonError) as exc:
202
+ return _error(str(exc))
203
+
204
+
146
205
  def _ask(question: str) -> bool:
147
206
  try:
148
207
  answer = input(f"{question} [y/N] ")
@@ -206,6 +265,13 @@ def build_parser() -> argparse.ArgumentParser:
206
265
  d = sub.add_parser("doctor", help="check this host for the programs vpstream needs")
207
266
  d.set_defaults(func=cmd_doctor)
208
267
 
268
+ s = sub.add_parser("status", help="show what the running daemon is doing")
269
+ s.add_argument("--json", action="store_true", help="print the daemon's answer as JSON")
270
+ s.set_defaults(func=cmd_status)
271
+
272
+ dm = sub.add_parser("daemon", help="run the daemon in the foreground (the service does this)")
273
+ dm.set_defaults(func=cmd_daemon)
274
+
209
275
  b = sub.add_parser("bench", help="measure how fast this host prepares a file")
210
276
  b.add_argument("file")
211
277
  b.add_argument(
@@ -0,0 +1,70 @@
1
+ """Talk to the running daemon over its unix socket."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import http.client
6
+ import json
7
+ import socket
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from vpstream import api
12
+
13
+ TIMEOUT = 10.0
14
+
15
+
16
+ class DaemonUnavailable(RuntimeError):
17
+ """The daemon cannot be reached; the message says why and what to do."""
18
+
19
+
20
+ class DaemonRefused(RuntimeError):
21
+ """The daemon answered with an error."""
22
+
23
+
24
+ class _UnixConnection(http.client.HTTPConnection):
25
+ def __init__(self, path: Path, timeout: float) -> None:
26
+ super().__init__("localhost", timeout=timeout)
27
+ self._path = path
28
+
29
+ def connect(self) -> None:
30
+ sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
31
+ sock.settimeout(self.timeout)
32
+ try:
33
+ sock.connect(str(self._path))
34
+ except OSError:
35
+ sock.close()
36
+ raise
37
+ self.sock = sock
38
+
39
+
40
+ def call(socket_path: Path, method: str, route: str, timeout: float = TIMEOUT) -> Any:
41
+ """Send one request to the daemon and return the decoded JSON answer."""
42
+ conn = _UnixConnection(socket_path, timeout)
43
+ try:
44
+ conn.request(method, f"{api.API}/{route}", headers={"Connection": "close"})
45
+ response = conn.getresponse()
46
+ body = response.read()
47
+ except (FileNotFoundError, ConnectionRefusedError) as exc:
48
+ raise DaemonUnavailable(
49
+ f"the vpstream daemon is not running (no answer on {socket_path}). "
50
+ "Start it with: sudo systemctl start vpstream"
51
+ ) from exc
52
+ except PermissionError as exc:
53
+ raise DaemonUnavailable(
54
+ f"no permission to use {socket_path}. Your user must be in the vpstream group: "
55
+ "log out and in again if it was just added, or run the command with sudo"
56
+ ) from exc
57
+ except (OSError, http.client.HTTPException) as exc:
58
+ raise DaemonUnavailable(f"the vpstream daemon did not answer: {exc}") from exc
59
+ finally:
60
+ conn.close()
61
+ try:
62
+ data = json.loads(body)
63
+ except ValueError as exc:
64
+ raise DaemonRefused(
65
+ f"the daemon sent an answer that is not JSON ({response.status})"
66
+ ) from exc
67
+ if response.status >= 400:
68
+ message = data.get("error") if isinstance(data, dict) else None
69
+ raise DaemonRefused(f"the daemon refused: {message or response.status}")
70
+ return data
@@ -2,6 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import os
5
6
  import tomllib
6
7
  from dataclasses import dataclass
7
8
  from pathlib import Path
@@ -38,6 +39,15 @@ class Paths:
38
39
  )
39
40
 
40
41
 
42
+ ROOT_ENV = "VPSTREAM_ROOT"
43
+
44
+
45
+ def default_paths() -> Paths:
46
+ """The real paths, or the same layout under $VPSTREAM_ROOT for trying things out."""
47
+ root = os.environ.get(ROOT_ENV)
48
+ return Paths.under(Path(root)) if root else Paths()
49
+
50
+
41
51
  @dataclass(frozen=True)
42
52
  class Config:
43
53
  stream_port: int = 1337
@@ -0,0 +1,157 @@
1
+ """The always-on daemon: serves the API on a unix socket and on the dashboard port.
2
+
3
+ The dashboard port is bound to the Tailscale address only, never to every interface. While
4
+ Tailscale has no address the daemon keeps running, so the CLI works, and tries again.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import socket
11
+ import threading
12
+ import time
13
+ from collections.abc import Callable
14
+ from dataclasses import dataclass, field
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from vpstream import __version__, api, tailscale
19
+ from vpstream.config import Config, Paths
20
+ from vpstream.tools import Runner
21
+
22
+ SOCKET_MODE = 0o660 # the service user and its group; the folder keeps everyone else out
23
+ RETRY_SECONDS = 10.0
24
+
25
+
26
+ class DaemonError(RuntimeError):
27
+ pass
28
+
29
+
30
+ def bind_unix(path: Path, mode: int = SOCKET_MODE) -> socket.socket:
31
+ """Listen on a unix socket at `path`, replacing a socket file left by an earlier run."""
32
+ try:
33
+ if path.is_socket():
34
+ path.unlink()
35
+ sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
36
+ # The mask applies from the moment the file exists, so it is never open to others.
37
+ old = os.umask(0o777 & ~mode)
38
+ try:
39
+ sock.bind(str(path))
40
+ finally:
41
+ os.umask(old)
42
+ sock.listen(16)
43
+ except OSError as exc:
44
+ raise DaemonError(f"cannot listen on the socket {path}: {exc}") from exc
45
+ return sock
46
+
47
+
48
+ def bind_tcp(host: str, port: int) -> socket.socket:
49
+ """Listen on one address. Raises OSError when the address or port cannot be used."""
50
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
51
+ try:
52
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
53
+ sock.bind((host, port))
54
+ sock.listen(16)
55
+ except OSError:
56
+ sock.close()
57
+ raise
58
+ return sock
59
+
60
+
61
+ @dataclass
62
+ class Daemon:
63
+ config: Config
64
+ paths: Paths
65
+ runner: Runner
66
+ log: Callable[[str], None] = print
67
+ retry_seconds: float = RETRY_SECONDS
68
+ started: float = field(default_factory=time.time)
69
+ dashboard_address: str | None = None
70
+ dashboard_problem: str = "starting"
71
+ ready: threading.Event = field(default_factory=threading.Event)
72
+
73
+ def status(self) -> dict[str, Any]:
74
+ return {
75
+ "version": __version__,
76
+ "pid": os.getpid(),
77
+ "uptime_seconds": round(time.time() - self.started, 1),
78
+ "stream": None,
79
+ "stream_port": self.config.stream_port,
80
+ "dashboard": {
81
+ "port": self.config.dashboard_port,
82
+ "address": self.dashboard_address,
83
+ "problem": None if self.dashboard_address else self.dashboard_problem,
84
+ },
85
+ }
86
+
87
+ def serve(self, stop: threading.Event) -> None:
88
+ """Serve until `stop` is set. The socket file is removed on the way out."""
89
+ from werkzeug.serving import make_server
90
+
91
+ app = api.create_app(self.status)
92
+ self.paths.run_dir.mkdir(parents=True, exist_ok=True)
93
+ listener = bind_unix(self.paths.socket)
94
+ server = make_server(
95
+ f"unix://{self.paths.socket}", 0, app, threaded=True, fd=listener.fileno()
96
+ )
97
+ threads = [
98
+ threading.Thread(target=server.serve_forever, name="socket", daemon=True),
99
+ threading.Thread(target=self._dashboard, args=(app, stop), name="dash", daemon=True),
100
+ ]
101
+ for thread in threads:
102
+ thread.start()
103
+ self.log(f"vpstream {__version__} daemon listening on {self.paths.socket}")
104
+ self.ready.set()
105
+ try:
106
+ stop.wait()
107
+ finally:
108
+ server.shutdown()
109
+ for thread in threads:
110
+ thread.join(timeout=5)
111
+ server.server_close()
112
+ listener.close()
113
+ self.paths.socket.unlink(missing_ok=True)
114
+ self.log("vpstream daemon stopped")
115
+
116
+ def _dashboard(self, app: Any, stop: threading.Event) -> None:
117
+ """Keep the dashboard up on the Tailscale address; wait and retry while it has none."""
118
+ from werkzeug.serving import make_server
119
+
120
+ port = self.config.dashboard_port
121
+ while not stop.is_set():
122
+ try:
123
+ host = tailscale.ipv4(self.runner)
124
+ listener = bind_tcp(host, port)
125
+ except (tailscale.TailscaleDown, OSError) as exc:
126
+ problem = f"the dashboard is not available: {exc}"
127
+ if problem != self.dashboard_problem:
128
+ self.log(f"{problem}; trying again every {self.retry_seconds:g} seconds")
129
+ self.dashboard_problem = problem
130
+ stop.wait(self.retry_seconds)
131
+ continue
132
+ bound_port = listener.getsockname()[1]
133
+ server = make_server(host, bound_port, app, threaded=True, fd=listener.fileno())
134
+ self.dashboard_address = f"{host}:{bound_port}"
135
+ self.log(f"dashboard on http://{self.dashboard_address}/ (Tailscale only)")
136
+ closer = threading.Thread(
137
+ target=lambda s=server: (stop.wait(), s.shutdown()), daemon=True
138
+ )
139
+ closer.start()
140
+ try:
141
+ server.serve_forever()
142
+ finally:
143
+ self.dashboard_address = None
144
+ self.dashboard_problem = "stopped"
145
+ server.server_close()
146
+ listener.close()
147
+
148
+
149
+ def run(config: Config, paths: Paths, runner: Runner) -> int:
150
+ """Run the daemon in the foreground until SIGTERM or Ctrl+C."""
151
+ import signal
152
+
153
+ stop = threading.Event()
154
+ for signum in (signal.SIGTERM, signal.SIGINT):
155
+ signal.signal(signum, lambda *_: stop.set())
156
+ Daemon(config, paths, runner, log=lambda m: print(m, flush=True)).serve(stop)
157
+ return 0
@@ -1,6 +1,9 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import shutil
4
+ import tempfile
5
+ from collections.abc import Iterator
6
+ from pathlib import Path
4
7
 
5
8
  import pytest
6
9
 
@@ -32,3 +35,11 @@ def need_ffmpeg() -> None:
32
35
  for tool in ("ffmpeg", "ffprobe"):
33
36
  if not shutil.which(tool):
34
37
  pytest.fail(f"{tool} is required for integration tests")
38
+
39
+
40
+ @pytest.fixture
41
+ def short_tmp() -> Iterator[Path]:
42
+ """A temporary folder with a short path: a unix socket path may be at most 107 bytes."""
43
+ path = Path(tempfile.mkdtemp(prefix="vp"))
44
+ yield path
45
+ shutil.rmtree(path, ignore_errors=True)
@@ -0,0 +1,263 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import socket
5
+ import stat
6
+ import threading
7
+ import urllib.request
8
+ from collections.abc import Iterator
9
+ from pathlib import Path
10
+
11
+ import pytest
12
+
13
+ from vpstream import __version__, api, cli, client, config, daemon
14
+ from vpstream.tests.fakes import FakeRunner
15
+
16
+
17
+ def _free_port() -> int:
18
+ with socket.socket() as s:
19
+ s.bind(("127.0.0.1", 0))
20
+ return int(s.getsockname()[1])
21
+
22
+
23
+ class Running:
24
+ """A daemon serving in a background thread, stopped when the test ends."""
25
+
26
+ def __init__(self, root: Path, runner: FakeRunner, cfg: config.Config) -> None:
27
+ self.paths = config.Paths.under(root)
28
+ self.log: list[str] = []
29
+ self.daemon = daemon.Daemon(
30
+ cfg, self.paths, runner, log=self.log.append, retry_seconds=0.05
31
+ )
32
+ self.stop = threading.Event()
33
+ self.thread = threading.Thread(target=self.daemon.serve, args=(self.stop,), daemon=True)
34
+
35
+ def start(self) -> Running:
36
+ self.thread.start()
37
+ assert self.daemon.ready.wait(5)
38
+ return self
39
+
40
+ def wait_for_dashboard(self) -> str:
41
+ for _ in range(100):
42
+ if self.daemon.dashboard_address:
43
+ return self.daemon.dashboard_address
44
+ self.stop.wait(0.05)
45
+ raise AssertionError(f"no dashboard: {self.log}")
46
+
47
+ def close(self) -> None:
48
+ self.stop.set()
49
+ self.thread.join(5)
50
+ assert not self.thread.is_alive()
51
+
52
+
53
+ @pytest.fixture
54
+ def tailnet() -> FakeRunner:
55
+ """A host whose "Tailscale address" is the loopback address, so tests can bind it."""
56
+ runner = FakeRunner(("tailscale",))
57
+ runner.on("tailscale", "ip", "-4", stdout="127.0.0.1\n")
58
+ return runner
59
+
60
+
61
+ @pytest.fixture
62
+ def running(short_tmp: Path, tailnet: FakeRunner) -> Iterator[Running]:
63
+ cfg = config.Config(stream_port=_free_port(), dashboard_port=_free_port())
64
+ run = Running(short_tmp, tailnet, cfg).start()
65
+ yield run
66
+ run.close()
67
+
68
+
69
+ # --- the API
70
+
71
+
72
+ def test_status_route() -> None:
73
+ app = api.create_app(lambda: {"version": "1.2.3", "stream": None})
74
+ http = app.test_client()
75
+ assert http.get("/api/v1/status").get_json() == {"version": "1.2.3", "stream": None}
76
+ page = http.get("/").get_data(as_text=True)
77
+ assert "vpstream 1.2.3" in page and "no stream is running" in page
78
+
79
+
80
+ def test_errors_are_json() -> None:
81
+ http = api.create_app(dict).test_client()
82
+ answer = http.get("/api/v1/nope")
83
+ assert answer.status_code == 404 and "error" in answer.get_json()
84
+ assert http.post("/api/v1/status").status_code == 405
85
+
86
+
87
+ def test_index_escapes_what_it_shows() -> None:
88
+ app = api.create_app(lambda: {"version": "<b>x</b>"})
89
+ assert "<b>x</b>" not in app.test_client().get("/").get_data(as_text=True)
90
+
91
+
92
+ # --- the socket and the CLI
93
+
94
+
95
+ def test_cli_talks_to_the_daemon_over_the_socket(running: Running) -> None:
96
+ info = client.call(running.paths.socket, "GET", "status")
97
+ assert info["version"] == __version__
98
+ assert info["stream"] is None
99
+ assert info["stream_port"] == running.daemon.config.stream_port
100
+
101
+
102
+ def test_socket_is_for_the_owner_and_group_only(running: Running) -> None:
103
+ mode = running.paths.socket.stat().st_mode
104
+ assert stat.S_ISSOCK(mode)
105
+ assert stat.S_IMODE(mode) == 0o660
106
+
107
+
108
+ def test_socket_file_is_removed_on_stop(short_tmp: Path, tailnet: FakeRunner) -> None:
109
+ run = Running(short_tmp, tailnet, config.Config(dashboard_port=_free_port())).start()
110
+ assert run.paths.socket.exists()
111
+ run.close()
112
+ assert not run.paths.socket.exists()
113
+ assert run.log[-1] == "vpstream daemon stopped"
114
+
115
+
116
+ def test_a_leftover_socket_file_is_replaced(short_tmp: Path, tailnet: FakeRunner) -> None:
117
+ paths = config.Paths.under(short_tmp)
118
+ paths.run_dir.mkdir(parents=True)
119
+ stale = socket.socket(socket.AF_UNIX)
120
+ stale.bind(str(paths.socket))
121
+ stale.close() # the file stays, as after a crash
122
+ run = Running(short_tmp, tailnet, config.Config(dashboard_port=_free_port())).start()
123
+ try:
124
+ assert client.call(paths.socket, "GET", "status")["pid"]
125
+ finally:
126
+ run.close()
127
+
128
+
129
+ def test_a_file_that_is_not_a_socket_is_not_removed(short_tmp: Path) -> None:
130
+ path = short_tmp / "daemon.sock"
131
+ path.write_text("mine")
132
+ with pytest.raises(daemon.DaemonError, match="cannot listen"):
133
+ daemon.bind_unix(path)
134
+ assert path.read_text() == "mine"
135
+
136
+
137
+ def test_client_says_when_the_daemon_is_not_running(short_tmp: Path) -> None:
138
+ with pytest.raises(client.DaemonUnavailable, match="not running"):
139
+ client.call(short_tmp / "nope.sock", "GET", "status")
140
+
141
+
142
+ def test_client_says_when_the_user_lacks_the_group(
143
+ short_tmp: Path, monkeypatch: pytest.MonkeyPatch
144
+ ) -> None:
145
+ def refuse(self: socket.socket, address: str) -> None:
146
+ raise PermissionError(13, "Permission denied")
147
+
148
+ monkeypatch.setattr(socket.socket, "connect", refuse)
149
+ with pytest.raises(client.DaemonUnavailable, match="vpstream group"):
150
+ client.call(short_tmp / "daemon.sock", "GET", "status")
151
+
152
+
153
+ def test_client_reports_a_refusal(running: Running) -> None:
154
+ with pytest.raises(client.DaemonRefused, match="refused"):
155
+ client.call(running.paths.socket, "GET", "nope")
156
+
157
+
158
+ def test_cli_status(
159
+ running: Running, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
160
+ ) -> None:
161
+ address = running.wait_for_dashboard()
162
+ monkeypatch.setenv(config.ROOT_ENV, str(running.paths.run_dir.parent.parent))
163
+ assert cli.main(["status"]) == 0
164
+ out = capsys.readouterr().out
165
+ assert f"vpstream daemon {__version__}" in out
166
+ assert "Stream: none" in out
167
+ assert f"Dashboard: http://{address}/" in out
168
+ assert cli.main(["status", "--json"]) == 0
169
+ assert json.loads(capsys.readouterr().out)["dashboard"]["address"] == address
170
+
171
+
172
+ def test_cli_status_without_a_daemon(
173
+ short_tmp: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
174
+ ) -> None:
175
+ monkeypatch.setenv(config.ROOT_ENV, str(short_tmp))
176
+ assert cli.main(["status"]) == 1
177
+ assert "not running" in capsys.readouterr().err
178
+
179
+
180
+ def test_status_notes_a_version_mismatch() -> None:
181
+ info = {"version": "0.3.0", "uptime_seconds": 3725, "pid": 7, "stream_port": 1337}
182
+ info["dashboard"] = {"address": None, "problem": "the dashboard is not available: x"}
183
+ text = cli.format_status(info, "0.4.0")
184
+ assert "up 1h 02m (pid 7)" in text
185
+ assert "Dashboard: the dashboard is not available: x" in text
186
+ assert "sudo systemctl restart vpstream" in text
187
+ assert "restart" not in cli.format_status(info, "0.3.0")
188
+
189
+
190
+ @pytest.mark.parametrize(
191
+ ("seconds", "text"), [(5, "5s"), (192, "3m 12s"), (7500, "2h 05m"), (273600, "3d 4h")]
192
+ )
193
+ def test_duration(seconds: float, text: str) -> None:
194
+ assert cli._duration(seconds) == text
195
+
196
+
197
+ # --- the dashboard port
198
+
199
+
200
+ def test_dashboard_listens_on_the_tailscale_address_only(running: Running) -> None:
201
+ address = running.wait_for_dashboard()
202
+ host, _, port = address.partition(":")
203
+ assert host == "127.0.0.1" and int(port) == running.daemon.config.dashboard_port
204
+ with urllib.request.urlopen(f"http://{address}/api/v1/status", timeout=5) as answer:
205
+ assert json.load(answer)["dashboard"]["address"] == address
206
+ assert "tailscale ip -4" in [" ".join(c) for c in running.daemon.runner.calls] # type: ignore[attr-defined]
207
+
208
+
209
+ def test_dashboard_is_never_bound_to_every_interface(
210
+ short_tmp: Path, monkeypatch: pytest.MonkeyPatch, tailnet: FakeRunner
211
+ ) -> None:
212
+ bound: list[str] = []
213
+ real = daemon.bind_tcp
214
+
215
+ def spy(host: str, port: int) -> socket.socket:
216
+ bound.append(host)
217
+ return real(host, port)
218
+
219
+ monkeypatch.setattr(daemon, "bind_tcp", spy)
220
+ run = Running(short_tmp, tailnet, config.Config(dashboard_port=_free_port())).start()
221
+ try:
222
+ run.wait_for_dashboard()
223
+ finally:
224
+ run.close()
225
+ assert bound == ["127.0.0.1"]
226
+
227
+
228
+ def test_without_tailscale_the_socket_works_and_the_dashboard_waits(short_tmp: Path) -> None:
229
+ runner = FakeRunner(("tailscale",))
230
+ runner.on("tailscale", "ip", "-4", returncode=1, stdout="Tailscale is stopped.\n")
231
+ run = Running(short_tmp, runner, config.Config(dashboard_port=_free_port())).start()
232
+ try:
233
+ for _ in range(100):
234
+ if "Tailscale is stopped" in run.daemon.dashboard_problem:
235
+ break
236
+ run.stop.wait(0.05)
237
+ dash = client.call(run.paths.socket, "GET", "status")["dashboard"]
238
+ assert dash["address"] is None and "Tailscale is stopped" in dash["problem"]
239
+ # The same problem is logged once, not on every retry.
240
+ run.stop.wait(0.3)
241
+ assert sum("Tailscale is stopped" in line for line in run.log) == 1
242
+
243
+ # Tailscale comes up: the dashboard starts without a restart.
244
+ runner.on("tailscale", "ip", "-4", stdout="127.0.0.1\n")
245
+ assert run.wait_for_dashboard().startswith("127.0.0.1:")
246
+ finally:
247
+ run.close()
248
+
249
+
250
+ def test_a_busy_dashboard_port_is_reported(short_tmp: Path, tailnet: FakeRunner) -> None:
251
+ with socket.socket() as busy:
252
+ busy.bind(("127.0.0.1", 0))
253
+ busy.listen()
254
+ cfg = config.Config(dashboard_port=busy.getsockname()[1])
255
+ run = Running(short_tmp, tailnet, cfg).start()
256
+ try:
257
+ for _ in range(100):
258
+ if "not available" in run.daemon.dashboard_problem:
259
+ break
260
+ run.stop.wait(0.05)
261
+ assert "not available" in run.daemon.status()["dashboard"]["problem"]
262
+ finally:
263
+ run.close()
File without changes
File without changes
File without changes
File without changes
File without changes