diff --git a/docs/dev/rest-api/remote-sessions.md b/docs/dev/rest-api/remote-sessions.md index 7283caca..1d4332e9 100644 --- a/docs/dev/rest-api/remote-sessions.md +++ b/docs/dev/rest-api/remote-sessions.md @@ -794,8 +794,8 @@ the error codes and the request and reply shapes that it shares with the server gives another ID keeps its old ID on the client, and the client sends the new ID. The client matches a title by season and episode number, and a track by its attributes. - The client waits up to 30 minutes for the server, which covers a deploy's drain. It - stops with an error if the new remote session licenses differently from the old one, + The client waits up to 30 minutes for the server, which covers a deploy's drain. A Ctrl+C + ends this wait. The client stops with an error if the new remote session licenses differently from the old one, for example after a change to the API key's `server_cdm` grant. An interactive login asks for its input again. - **Server resolution.** `resolve_server()` reads `config.remote_services.` @@ -819,8 +819,14 @@ saves the returned cache and then stops the tunnel. It does so: - when a serve that relays for a REST client closes its pooled remote session The `DELETE` has a connect and read timeout of 15s each. The client sends it again only once, when a gateway answers with -an error page or asks for the API key in the other header. It does not wait for a rate limit. A Ctrl+C waits for the -download threads before it ends the remote session. +an error page or asks for the API key in the other header. It does not wait for a rate limit. + +A Ctrl+C during the downloads cancels the run. The client waits for the download threads and for the content keys that +still go to the vaults, and then ends the remote session. The cancel ends each wait of a download thread within 0.5s: +the wait for a server that restarts, for a rate limit and for a login. A cancelled thread opens no new remote session, +and the client deletes a remote session that a thread opens at that moment. The cancel does not stop a request that the +server already has: the client waits for its answer. A failed track is no cancel, so the next title can open +a new remote session. While the client ends a remote session, it ignores the first Ctrl+C, so it does not lose the returned cache. The next Ctrl+C stops the wait at once, and the process then waits for no other end. The count of Ctrl+C is one for the process. diff --git a/tests/conftest.py b/tests/conftest.py index 8c2ba9dc..3a834dde 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -14,6 +14,7 @@ import pytest from unshackle.core import binaries, process_exit from unshackle.core import session as http_session from unshackle.core.config import config +from unshackle.core.constants import RunCancel from unshackle.core.providers import anilist from unshackle.core.proxies.proxy import CATALOGUES from unshackle.core.update_checker import UpdateChecker @@ -61,9 +62,10 @@ def client_process(monkeypatch: pytest.MonkeyPatch) -> None: @pytest.fixture(autouse=True) def keep_signal_handlers(monkeypatch: pytest.MonkeyPatch) -> None: - """Keep the signal handlers of a command or a job worker out of the pytest process.""" + """Keep the signal handlers and the cancel of a command or a job worker out of the pytest process.""" monkeypatch.setattr(process_exit, "listen", lambda *args: None) monkeypatch.setattr(process_exit.Stop, "raised", False) + monkeypatch.setattr(RunCancel, "pressed", False) monkeypatch.setattr(process_exit, "ends", set()) diff --git a/tests/core/test_licence_turns.py b/tests/core/test_licence_turns.py index c2e04bec..90fb9c7f 100644 --- a/tests/core/test_licence_turns.py +++ b/tests/core/test_licence_turns.py @@ -197,6 +197,26 @@ def test_a_refused_licence_without_the_track_key_reports_the_licence_error( assert "Licence request failed" in str(tree.children[-1].label) +@pytest.mark.parametrize("all_drm", [False, True]) +def test_a_licence_that_the_user_cancelled_shows_no_error( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, all_drm: bool +) -> None: + def cancel(self: Widevine, **_: Any) -> None: + raise DownloadCancelled + + monkeypatch.setattr(Widevine, "get_content_keys", cancel) + keys = resolver(best_available=True) + keys.all_drm_warned.add("PlayReady") + ContentKeyResolver.LICENSE_KEY_CACHE[KID_B] = KEYS[KID_B] + table = key_table() + + with pytest.raises(DownloadCancelled): + prepare(keys, widevine(KID_A, KID_B), None, table, all_drm) + + assert not [r for r in caplog.records if r.levelname == "WARNING"] + assert list(table.columns[0].cells) == [""] + + def test_a_held_track_key_needs_no_licence(licences: Licences) -> None: keys = resolver() ContentKeyResolver.LICENSE_KEY_CACHE[KID_A] = KEYS[KID_A] diff --git a/tests/core/test_playready_multi_header.py b/tests/core/test_playready_multi_header.py index b7f9a87d..ebbeb3ce 100644 --- a/tests/core/test_playready_multi_header.py +++ b/tests/core/test_playready_multi_header.py @@ -13,6 +13,7 @@ from pyplayready.system.wrmheader import WRMHeader from pywidevine.key import Key as WidevineKey from unshackle.core.cdm.http_cdm import HttpCdm +from unshackle.core.constants import DownloadCancelled from unshackle.core.drm import PlayReady KID_A = UUID("00112233-4455-6677-8899-aabbccddeeff") @@ -196,6 +197,18 @@ def test_a_refused_header_does_not_lose_the_keys_of_the_others() -> None: assert drm.content_keys == {KID_B: KEY_B} +def test_a_licence_that_the_user_cancelled_is_no_refusal() -> None: + drm = _drm(_wrm_header(KID_A), _wrm_header(KID_B)) + cdm = FakeCdm({KID_B: KEY_B}) + + def cancel(**_: Any) -> str: + raise DownloadCancelled + + with pytest.raises(DownloadCancelled): + drm.get_content_keys(cdm=cdm, certificate=_cert, licence=cancel) + assert cdm.attempted == [[KID_A]] + + def test_every_header_refused_raises() -> None: drm = _drm(_wrm_header(KID_A), _wrm_header(KID_B)) cdm = FakeCdm({}, fail_on={KID_A, KID_B}) diff --git a/tests/remote/unit/test_run_cancel.py b/tests/remote/unit/test_run_cancel.py new file mode 100644 index 00000000..920ceb8a --- /dev/null +++ b/tests/remote/unit/test_run_cancel.py @@ -0,0 +1,669 @@ +"""Ctrl+C in the download pool ends every wait of a track for the remote server, and a failed track ends none.""" + +from __future__ import annotations + +import asyncio +import contextlib +import json +import signal +import socket +import subprocess +import time +from collections.abc import Callable, Iterator +from pathlib import Path +from threading import Event, Thread, Timer +from types import SimpleNamespace +from typing import Any, cast +from urllib.parse import urlsplit + +import pytest +from aiohttp import web + +from tests.remote.unit.test_process_exit import ( # noqa: F401 + COMMAND, + DEADLINE, + HeldDelete, + held_delete, + lasting_sessions, + logins, + posix, + run, + saved, + sessions, + settings, + store_cache, + wait_line, +) +from tests.remote.unit.test_remote_loopback import StubService, count, forget, server # noqa: F401 +from tests.remote.unit.test_tunnel import wait_until +from unshackle.core import remote_channel +from unshackle.core.api import routes, session_store +from unshackle.core.constants import RunCancel +from unshackle.core.proxies.controld import relay +from unshackle.core.remote_channel import ServerMessages +from unshackle.core.remote_protocol import ( + LOGS_ROUTE, + PROMPT_ROUTE, + SESSION_CREATE_ROUTE, + SESSION_ROUTE, + TITLES_ROUTE, + TRACKS_ROUTE, + AuthStatus, +) +from unshackle.core.tracks import Audio, Tracks + +pytestmark = [pytest.mark.unit, posix] + +BOUND = 8.0 +WAITING = "Waiting for the remote server" +LIMITED = "Rate limited by the server" + +CLIENT = """ +import contextlib, logging, sys +from threading import Event +from types import SimpleNamespace +from uuid import UUID +import click +from unshackle.core import process_exit, remote_channel, remote_service +from unshackle.core.config import config +config.__init__(directories={"cache": sys.argv[2], "cookies": sys.argv[2] + "/cookies"}) +logging.basicConfig(level=logging.INFO, stream=sys.stdout, format="%(message)s") +from tests.core.key_resolver import resolver +from tests.remote.unit.test_remote_loopback import make_client +from unshackle.commands.dl import download_tracks_in_passes +from unshackle.core.constants import DOWNLOAD_CANCELLED, RunCancel +from unshackle.core.tracks.track import Track + +phase = sys.argv[3] +service = make_client(sys.argv[1]) +keys = resolver() +if phase == "push": + remote_service.KEYS_TIMEOUT = 60 +if "polling" in sys.argv[4:]: + remote_channel.WebSocketChannel.open = lambda self, timeout=0: False + +def say(line): + print(line, flush=True) + +def set_and_say(real=DOWNLOAD_CANCELLED.set): + real() + if RunCancel.pressed: + say("cancelled") + +def hold(line): + say(line) + while not RunCancel.pressed: + Event().wait(0.01) + +def drain_logs(real=service.drain_server_logs): + real() + if phase == "login-done" and service._tracks_by_title: + hold("login done") + +service.drain_server_logs = drain_logs + +def login_material(profile, real=service.client_login): + if phase == "login-material" and service._titles: + hold("login material") + return real(profile) + +DOWNLOAD_CANCELLED.set = set_and_say +service.client_login = login_material + +def titles(sid): + return service.client.get(f"/api/session/{sid}/titles") + +def push(): + track = SimpleNamespace(id="example-1-login1") + return keys.VAULT_WRITER.submit(service.server_vault.add_keys, "EXAMPLE", {UUID(int=1): "ab" * 16}, track) + +calls = { + "url": service.track_url, + "licence": lambda track: service.license_track( + track, type("Widevine", (), {"pssh": SimpleNamespace(dumps=lambda: "AAAA")})() + ), + "file": service.license_file, + "relay": lambda track: service.proxy_license(b"c", track, "widevine"), + "certificate": lambda track: service.get_widevine_service_certificate(challenge=b"c", title=None, track=track), + "filter": lambda track: service.remote_segment_filter(track.id)(None), + "samples": lambda track: service.get_sample_decrypter(track, 0), +} + +def run_one(track, index): + if phase == "fails" and index == 1: + sys.stdin.readline() + DOWNLOAD_CANCELLED.set() + say("failed") + raise ValueError("EXAMPLE failed") + if phase == "push": + push() + if phase in calls: + service._server_cdm_request = phase == "file" + try: + calls[phase](track) + except Exception as e: + say(type(e).__name__) + raise + service.session_call(titles) + say("called") + +def download(count): + tracks = [SimpleNamespace(id=str(n)) for n in range(count)] + download_tracks_in_passes(tracks, count, run_one, skip_subtitle_errors=False, on_subtitle_skipped=None) + +@click.command() +@click.pass_context +def main(ctx): + ctx.with_resource(process_exit.unwinding(linger="job" not in sys.argv[4:])) + service.authenticate() + remote_channel.AUTH_POLL_INTERVAL = 600 + say("ready") + sys.stdin.readline() + if phase == "main": + service.session_call(titles) + if phase in ("tracks", "login-material", "login-done"): + service.get_tracks(service.get_titles()[0]) + say("tracks") + sys.stdin.readline() + try: + download(2 if phase in ("pool", "fails") else 1) + except ValueError: + say("title failed") + service.session_call(titles) + say("next title") + except KeyboardInterrupt: + say("Download Cancelled") + if phase == "lost-push": + push() + keys.wait_vault_writes() + say("vault writes done") + +main(args=[]) +""" + + +class Gate: + """A port in front of the server. ``close`` takes it away as a dead server does, and lets no other process have it.""" + + def __init__(self, url: str) -> None: + self.server = (urlsplit(url).hostname, urlsplit(url).port) + self.port = 0 + self.held = socket.socket() + self.open() + self.url = f"http://127.0.0.1:{self.port}" + + def open(self) -> None: + self.links: list[socket.socket] = [] + self.held.close() + self.listener = socket.create_server(("127.0.0.1", self.port), backlog=32) + self.port = self.listener.getsockname()[1] + Thread(target=self.accept, args=[self.listener], daemon=True).start() + + def accept(self, listener: socket.socket) -> None: + with contextlib.suppress(OSError): + while True: + near = listener.accept()[0] + far = socket.create_connection(self.server) + self.links += [near, far] + for source, sink in ((near, far), (far, near)): + Thread(target=relay, args=[source, sink], daemon=True).start() + + def close(self) -> None: + for end in (self.listener, *self.links): + with contextlib.suppress(OSError): + end.shutdown(socket.SHUT_RDWR) + end.close() + self.held.close() + self.held = socket.socket() + self.held.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self.held.bind(("127.0.0.1", self.port)) + + +@pytest.fixture +def gate(server: SimpleNamespace, logins: list[Any]) -> Iterator[Gate]: # noqa: F811 + gate = Gate(server.url) + yield gate + gate.close() + gate.held.close() + + +def go(process: subprocess.Popen[str]) -> None: + assert process.stdin is not None + process.stdin.write("\n") + process.stdin.flush() + + +def creates(server: SimpleNamespace) -> int: # noqa: F811 + return len([seen for seen in server.seen if seen == ("POST", SESSION_CREATE_ROUTE, 200)]) + + +@pytest.fixture +def launch(run: Callable[..., Any]) -> Iterator[Callable[..., subprocess.Popen[str]]]: # noqa: F811 + """Start a process that does not outlive twice the deadline, so a client that waits on fails its test.""" + timers: list[Timer] = [] + + def start(*argv: str) -> subprocess.Popen[str]: + process = run("-c", *argv, stdin=subprocess.PIPE) + timers.append(Timer(2 * DEADLINE, process.kill)) + timers[-1].start() + return process + + yield start + for timer in timers: + timer.cancel() + + +@pytest.fixture +def client(gate: Gate, launch: Callable[..., Any], tmp_path: Path) -> Callable[..., subprocess.Popen[str]]: + """Start a client with a remote session, which calls the server when the test says so.""" + + def start(*argv: str) -> subprocess.Popen[str]: + process = launch(CLIENT, gate.url, str(tmp_path / "client"), *argv) + wait_line(process, "ready") + return process + + return start + + +def press(process: subprocess.Popen[str]) -> str: + """Send Ctrl+C, and return what the client prints before it ends in time.""" + sent = time.monotonic() + process.send_signal(signal.SIGINT) + output, _ = process.communicate(timeout=DEADLINE) + assert time.monotonic() - sent < BOUND, output + assert "Traceback" not in output + return output + + +def limit(monkeypatch: pytest.MonkeyPatch, handler: str) -> None: + """Answer one route of the server with a 429 that asks for an hour, before its first heartbeat sends a 200.""" + + async def refuse(*args: Any) -> web.Response: + return web.json_response({"error_code": "RATE_LIMITED"}, status=429, headers={"Retry-After": "3600"}) + + monkeypatch.setattr(routes, "HEARTBEAT_INTERVAL", 30.0) + monkeypatch.setattr(routes, handler, refuse) + + +class Held: + """A handler of the server that waits for ``release`` before it does its work, from the first call that ``when`` takes.""" + + def __init__(self, monkeypatch: pytest.MonkeyPatch, name: str, when: Callable[[], bool] = lambda: True) -> None: + self.started, self.release = Event(), Event() + handler = getattr(routes, name) + + async def held(*args: Any) -> Any: + if when(): + self.started.set() + while not self.release.is_set(): + await asyncio.sleep(0.01) + return await handler(*args) + + monkeypatch.setattr(routes, name, held) + + def __enter__(self) -> Held: + return self + + def __exit__(self, *_: object) -> None: + self.release.set() + + +def lose(server: SimpleNamespace, gate: Gate, monkeypatch: pytest.MonkeyPatch, wait: str) -> str: # noqa: F811 + """Make the next call of the client wait, and return the line that the client prints for it.""" + if wait == "dead": + gate.close() + elif wait == "draining": + store = session_store.get_session_store() + monkeypatch.setattr(store, "draining", True) + forget(server, sessions()[0].session_id) + else: + limit(monkeypatch, "session_titles_handler") + return LIMITED + return WAITING + + +@pytest.mark.parametrize("wait", ["dead", "draining", "limited"]) +def test_a_ctrl_c_ends_the_wait_of_each_track( + server: SimpleNamespace, # noqa: F811 + gate: Gate, + client: Callable[..., Any], + monkeypatch: pytest.MonkeyPatch, + wait: str, +) -> None: + """Two tracks wait: one in its wait and one for the lock of that wait.""" + process = client("pool") + line = lose(server, gate, monkeypatch, wait) + go(process) + wait_line(process, line) + if wait != "dead": + assert wait_until(lambda: count(server, "GET", TITLES_ROUTE) == 2, DEADLINE) + seen = len(server.seen) + + output = press(process) + assert output.split("\n")[:-1] == ["cancelled", "Download Cancelled", "vault writes done"] + assert {(method, status) for method, _, status in server.seen[seen:]} <= {("DELETE", 200), ("GET", 101)} + assert wait == "dead" or sessions() == [] + + +@pytest.mark.parametrize("wait", ["dead", "limited", "login"]) +def test_a_ctrl_c_in_the_main_thread_ends_its_wait( + server: SimpleNamespace, # noqa: F811 + gate: Gate, + client: Callable[..., Any], + monkeypatch: pytest.MonkeyPatch, + wait: str, +) -> None: + process = client("main") + if wait == "login": + login = hold_login(monkeypatch) + forget(server, sessions()[0].session_id) + go(process) + assert login.started.wait(DEADLINE) + assert wait_until(lambda: sessions() and sessions()[0].channel.attached, DEADLINE) + try: + output = press(process) + finally: + login.release.set() + else: + line = lose(server, gate, monkeypatch, wait) + go(process) + wait_line(process, line) + output = press(process) + assert "Aborted" in output + + +def hold_login(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace: + login = SimpleNamespace(started=Event(), release=Event()) + + def hold(stub: StubService, cookies: Any, credential: Any) -> None: + login.started.set() + login.release.wait(DEADLINE) + + monkeypatch.setattr(StubService, "authenticate", hold) + return login + + +@pytest.mark.parametrize("channel", ["socket", "polling"]) +def test_a_ctrl_c_in_the_login_of_a_reopen_deletes_the_new_session( + server: SimpleNamespace, # noqa: F811 + client: Callable[..., Any], + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + channel: str, +) -> None: + """The client of the polling channel does not know yet that its login succeeded, so the DELETE returns a cache.""" + process = client("pool", channel) + login = hold_login(monkeypatch) + forget(server, sessions()[0].session_id) + polls = count(server, "GET", PROMPT_ROUTE) + go(process) + try: + assert login.started.wait(DEADLINE) + if channel == "socket": + assert wait_until(lambda: sessions()[0].channel.attached, DEADLINE) + else: + assert wait_until(lambda: count(server, "GET", PROMPT_ROUTE) > polls, DEADLINE) + login.release.set() + assert wait_until(lambda: sessions()[0].auth_status == AuthStatus.AUTHENTICATED, DEADLINE) + store_cache() + created, (entry,) = count(server, "POST", SESSION_CREATE_ROUTE), sessions() + output = press(process) + finally: + login.release.set() + + assert "Download Cancelled" in output and "called" not in output and "error" not in output.lower() + assert sessions() == [] and count(server, "POST", SESSION_CREATE_ROUTE) == created + assert count(server, "DELETE", SESSION_ROUTE, entry.session_id) == 1 + assert channel == "socket" or saved(tmp_path / "client") + + +def test_a_failed_track_does_not_stop_the_reopen_of_the_others( + server: SimpleNamespace, # noqa: F811 + gate: Gate, + client: Callable[..., Any], +) -> None: + """The failed track cancels the downloads while the server restarts, and the next title has a remote session.""" + process = client("fails") + gate.close() + forget(server, sessions()[0].session_id) + go(process) + wait_line(process, WAITING) + go(process) + wait_line(process, "failed") + gate.open() + output, _ = process.communicate(timeout=DEADLINE) + + assert output.split("\n")[-4:-1] == ["called", "title failed", "next title"], output + assert creates(server) == 2 + + +def test_a_ctrl_c_after_a_failed_track_ends_the_wait_of_the_others(gate: Gate, client: Callable[..., Any]) -> None: + process = client("fails") + gate.close() + go(process) + wait_line(process, WAITING) + go(process) + wait_line(process, "failed") + assert press(process).split("\n")[:-1] == ["cancelled", "Download Cancelled", "vault writes done"] + + +def test_a_push_in_flight_reaches_the_server_before_the_end( + server: SimpleNamespace, # noqa: F811 + client: Callable[..., Any], + monkeypatch: pytest.MonkeyPatch, +) -> None: + held = Held(monkeypatch, "session_keys_handler") + limit(monkeypatch, "session_titles_handler") + process = client("push") + go(process) + wait_line(process, LIMITED) + with held: + assert held.started.wait(DEADLINE) + process.send_signal(signal.SIGINT) + wait_line(process, "Download Cancelled") + assert count(server, "DELETE", SESSION_ROUTE) == 0 + output, _ = process.communicate(timeout=DEADLINE) + + assert "vault writes done" in output + (push,) = [seen for seen in server.seen if seen[0] == "POST" and seen[1].endswith("/keys")] + assert [seen for seen in server.seen[server.seen.index(push) :] if seen[0] == "DELETE"] and sessions() == [] + + +def test_a_push_to_a_lost_server_gives_up(gate: Gate, client: Callable[..., Any]) -> None: + process = client("lost-push") + gate.close() + go(process) + wait_line(process, WAITING) + assert "vault writes done" in press(process) + + +@pytest.mark.parametrize( + ("phase", "handler"), + [ + ("url", "session_segments_handler"), + ("licence", "session_license_handler"), + ("file", "session_license_handler"), + ("relay", "session_license_handler"), + ("certificate", "session_license_handler"), + ("filter", "session_segment_filter_handler"), + ("samples", "session_samples_handler"), + ], +) +def test_a_track_whose_wait_was_cancelled_did_not_fail( + client: Callable[..., Any], monkeypatch: pytest.MonkeyPatch, phase: str, handler: str +) -> None: + limit(monkeypatch, handler) + process = client(phase) + go(process) + wait_line(process, LIMITED) + lines = press(process).split("\n")[:-1] + assert sorted(lines) == ["Download Cancelled", "DownloadCancelled", "cancelled", "vault writes done"] + + +def test_a_cancelled_call_of_the_polling_channel_fetches_no_server_log( + server: SimpleNamespace, # noqa: F811 + client: Callable[..., Any], + monkeypatch: pytest.MonkeyPatch, +) -> None: + limit(monkeypatch, "session_segments_handler") + process = client("url", "polling") + fetched = count(server, "GET", LOGS_ROUTE) + go(process) + wait_line(process, LIMITED) + press(process) + assert count(server, "GET", LOGS_ROUTE) == fetched > 0 + + +@pytest.mark.parametrize("cancelled", [False, True]) +def test_a_cancelled_login_shows_no_notice(monkeypatch: pytest.MonkeyPatch, cancelled: bool) -> None: + shown: list[Any] = [] + monkeypatch.setattr(remote_channel, "show_notice", lambda *args: shown.append(args)) + monkeypatch.setattr(RunCancel, "pressed", cancelled) + messages = ServerMessages(cast(Any, SimpleNamespace(auth_notice=None, auth_qr=None))) + messages.recent_logs.append("Approve at example.com") + messages.note_waiting(0) + assert bool(shown) is not cancelled + + +def test_a_stop_of_a_job_cancels_its_tracks_too( + client: Callable[..., Any], + held_delete: HeldDelete, # noqa: F811 + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A job worker gets no KeyboardInterrupt, and its cancelled track must not look like a failed or a finished one.""" + limit(monkeypatch, "session_segments_handler") + process = client("url", "job") + go(process) + wait_line(process, LIMITED) + process.send_signal(signal.SIGTERM) + assert held_delete.started.wait(DEADLINE) + lines = [wait_line(process, "Download").strip() for _ in range(2)] + held_delete.release.set() + assert lines == ["DownloadCancelled", "Download Cancelled"] + assert process.wait(DEADLINE) == 128 + signal.SIGTERM + + +def cancel_in(process: subprocess.Popen[str], held: Held, then: Callable[[], None] = lambda: None) -> str: + """Send Ctrl+C while the server holds a request of the pool, which no cancel can reach, and then let it answer.""" + with held: + assert held.started.wait(DEADLINE) + process.send_signal(signal.SIGINT) + wait_line(process, "cancelled") + then() + output, _ = process.communicate(timeout=DEADLINE) + assert "Download Cancelled" in output + return output + + +@pytest.mark.parametrize( + ("name", "line"), [("latest_release", WAITING), ("session_info_handler", "The remote session was lost")] +) +def test_a_request_of_the_recovery_that_ends_after_the_ctrl_c_is_silent( + server: SimpleNamespace, # noqa: F811 + gate: Gate, + client: Callable[..., Any], + monkeypatch: pytest.MonkeyPatch, + name: str, + line: str, +) -> None: + process = client("call") + held = Held(monkeypatch, name) + forget(server, sessions()[0].session_id) + go(process) + output = cancel_in(process, held, gate.close if line == WAITING else lambda: None) + assert line not in output and creates(server) == 1 + + +def test_a_session_that_is_alive_after_the_ctrl_c_gets_no_second_call( + server: SimpleNamespace, # noqa: F811 + gate: Gate, + client: Callable[..., Any], + monkeypatch: pytest.MonkeyPatch, +) -> None: + process = client("call") + gate.close() + go(process) + wait_line(process, WAITING) + held = Held(monkeypatch, "session_info_handler") + gate.open() + cancel_in(process, held) + assert count(server, "GET", TITLES_ROUTE) == 0 and sessions() == [] + + +@pytest.mark.parametrize(("name", "tracks"), [("session_titles_handler", 1), ("session_tracks_handler", 2)]) +def test_a_reopen_stops_after_the_request_of_the_ctrl_c( + server: SimpleNamespace, # noqa: F811 + client: Callable[..., Any], + monkeypatch: pytest.MonkeyPatch, + name: str, + tracks: int, +) -> None: + process = client("tracks") + go(process) + wait_line(process, "tracks") + held = Held(monkeypatch, name, lambda: creates(server) == 2) + forget(server, sessions()[0].session_id) + go(process) + cancel_in(process, held) + assert count(server, "GET", TITLES_ROUTE) == 3 + assert count(server, "POST", TRACKS_ROUTE) == tracks and sessions() == [] + + +@pytest.mark.parametrize(("phase", "created"), [("login-material", 1), ("login-done", 2)]) +def test_a_ctrl_c_in_a_reopen_stops_it_at_its_next_step( + server: SimpleNamespace, # noqa: F811 + client: Callable[..., Any], + phase: str, + created: int, +) -> None: + process = client(phase) + go(process) + wait_line(process, "tracks") + forget(server, sessions()[0].session_id) + titles = count(server, "GET", TITLES_ROUTE) + go(process) + wait_line(process, phase.replace("-", " ")) + press(process) + assert creates(server) == created and sessions() == [] + assert count(server, "GET", TITLES_ROUTE) == titles + 1 + + +def test_a_ctrl_c_ends_the_wait_for_the_channel_of_a_reopen( + server: SimpleNamespace, # noqa: F811 + client: Callable[..., Any], + monkeypatch: pytest.MonkeyPatch, +) -> None: + process = client("call") + held = Held(monkeypatch, "session_channel_handler", lambda: creates(server) == 2) + forget(server, sessions()[0].session_id) + go(process) + with held: + assert held.started.wait(DEADLINE) + press(process) + assert sessions() == [] + + +def test_the_command_prints_one_line_and_starts_with_no_cancel( + server: SimpleNamespace, # noqa: F811 + logins: list[Any], # noqa: F811 + example_service: None, + launch: Callable[..., Any], + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + def tracks(stub: StubService, title: Any) -> Tracks: + audio = Audio(url="", language="en", codec=Audio.Codec.AAC, bitrate=128_000, channels=2, id_="a1") + audio.resolve_url = lambda: "https://cdn.example/a1.m4a" + return Tracks([audio]) + + monkeypatch.setattr(StubService, "get_tracks", tracks) + limit(monkeypatch, "session_segments_handler") + script = "from unshackle.core.constants import RunCancel\nRunCancel.pressed = True\n" + COMMAND + argv = ["dl", "--remote", "--no-proxy", "--audio-only", "-l", "en", "-w", "1", "EXAMPLE", "example-1"] + process = launch(script, json.dumps(settings(server.url, tmp_path)), *argv) + wait_line(process, LIMITED) + output = press(process) + + assert process.returncode == 0 and sessions() == [] + after = output[output.index("Download Cancelled") :] + assert after.strip() == "Download Cancelled..." and "FAILED" not in output and "ERROR" not in output diff --git a/tests/tracks/test_subtitle_skip.py b/tests/tracks/test_subtitle_skip.py index 2438e2fe..ed1e85b1 100644 --- a/tests/tracks/test_subtitle_skip.py +++ b/tests/tracks/test_subtitle_skip.py @@ -13,7 +13,8 @@ from __future__ import annotations import pytest from unshackle.commands.dl import SkippedSubtitle, download_tracks_in_passes -from unshackle.core.constants import DOWNLOAD_CANCELLED +from unshackle.core import process_exit +from unshackle.core.constants import DOWNLOAD_CANCELLED, RunCancel from unshackle.core.tracks import Audio, Subtitle, Video @@ -95,7 +96,37 @@ def test_ctrl_c_cancels_the_tracks_still_downloading(): ) assert seen == {"v": True} - assert DOWNLOAD_CANCELLED.is_set() + assert DOWNLOAD_CANCELLED.is_set() and RunCancel.pressed + + +def test_a_failed_track_is_not_a_cancel_of_the_user(): + """A child process that the cancel of the failed track ends can look like Ctrl+C.""" + + def run_one(track, _index): + raise KeyboardInterrupt if track.id == "a" else ValueError("EXAMPLE failed") + + with pytest.raises(ValueError): + download_tracks_in_passes( + [make_video(), make_audio()], + 1, + run_one, + skip_subtitle_errors=False, + on_subtitle_skipped=lambda track: None, + ) + + assert not RunCancel.pressed and not DOWNLOAD_CANCELLED.is_set() + + +@pytest.mark.parametrize("tracks", [[make_video()], [make_subtitle("s-en", "en")]], ids=["pool", "subtitle"]) +def test_a_track_that_ends_while_the_process_stops_is_not_finished(monkeypatch, tracks): + with pytest.raises(KeyboardInterrupt): + download_tracks_in_passes( + tracks, + 1, + lambda track, _index: monkeypatch.setattr(process_exit.Stop, "signum", 15), + skip_subtitle_errors=True, + on_subtitle_skipped=lambda track: None, + ) @pytest.fixture(autouse=True) diff --git a/unshackle/commands/dl.py b/unshackle/commands/dl.py index f88c04fb..5773f917 100644 --- a/unshackle/commands/dl.py +++ b/unshackle/commands/dl.py @@ -1,5 +1,6 @@ from __future__ import annotations +import contextlib import logging import os import random @@ -8,11 +9,11 @@ import subprocess import sys import time from collections.abc import Callable, Collection, Iterable, Sequence -from concurrent import futures from concurrent.futures import ThreadPoolExecutor from copy import deepcopy from functools import partial from pathlib import Path +from queue import Empty, SimpleQueue from threading import Lock from typing import TYPE_CHECKING, Any, TypedDict @@ -44,6 +45,7 @@ from unshackle.core.constants import ( DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, AnyTrack, + RunCancel, context_settings, ) from unshackle.core.dl_options import DL_OPTION_ALIASES @@ -343,7 +345,11 @@ def download_tracks_in_passes( failure's cancel silently drop the others, unrecorded), with the event cleared before each. Video/audio failures stay fatal. This function clears the event on entry (stale cancel from a prior title) and on exit (never leave it set for later code). A Ctrl+C leaves it set: a second - Ctrl+C while the pool waits must not let the tracks that still run carry on. + Ctrl+C while the pool waits must not let the tracks that still run carry on. It also sets ``RunCancel``, + which ends each wait of a track for a remote server, so a lost remote session opens no new one. + + The pool reports through a queue: Ctrl+C in ``futures.wait`` can leave the lock of a future held, and its track + then never ends. ``run_one(track, index)`` downloads a single track. ``on_subtitle_skipped(track)`` records a subtitle whose download raised (handled here). @@ -356,30 +362,56 @@ def download_tracks_in_passes( else: primary, skippable = indexed, [] - interrupted = False + outcomes: SimpleQueue[BaseException | None] = SimpleQueue() + error: BaseException | None = None + + def run(track: AnyTrack, i: int) -> None: + """A track that ends in a process that stops did not finish, and a job worker gets no KeyboardInterrupt for it.""" + try: + run_one(track, i) + finally: + if process_exit.stopping(): + raise KeyboardInterrupt + + def download(track: AnyTrack, i: int) -> None: + try: + run(track, i) + except BaseException as e: + outcomes.put(e) + else: + outcomes.put(None) + try: with ThreadPoolExecutor(max_concurrent) as pool: - pending = {pool.submit(run_one, track, i) for i, track in primary} try: - # timed: on Windows an untimed wait holds Ctrl+C back until a track ends - while pending: - done, pending = futures.wait(pending, timeout=0.5, return_when=futures.FIRST_COMPLETED) - for download in done: - download.result() # a video/audio failure is fatal + for i, track in primary: + pool.submit(download, track, i) + left = len(primary) + while left: + # timed: on Windows an untimed wait holds Ctrl+C back until a track ends + with contextlib.suppress(Empty): + failure = outcomes.get(timeout=0.5) + left -= 1 + error = error or failure + if isinstance(error, KeyboardInterrupt): + raise error except KeyboardInterrupt: # Ctrl+C reaches only this thread; the pool exit waits for the tracks unless they see the cancel - interrupted = True + RunCancel.pressed = True DOWNLOAD_CANCELLED.set() raise + if error: + raise error # a video/audio failure is fatal + for i, track in skippable: DOWNLOAD_CANCELLED.clear() try: - run_one(track, i) + run(track, i) except Exception: on_subtitle_skipped(track) finally: - if not interrupted: + if not RunCancel.pressed: DOWNLOAD_CANCELLED.clear() # never leave a failed track's cancel set for later code @@ -1536,6 +1568,7 @@ class dl: *_: Any, **__: Any, ) -> RunOutcome: + RunCancel.pressed = False if all_drm: DOWNLOAD_ALL_DRM.set() else: diff --git a/unshackle/core/constants.py b/unshackle/core/constants.py index efe01ce7..6d7057d0 100644 --- a/unshackle/core/constants.py +++ b/unshackle/core/constants.py @@ -12,6 +12,15 @@ HTTP_LOGGERS = ("urllib3", "urllib3.connectionpool", "requests", "rnet", "httpx" DOWNLOAD_ALL_DRM = Event() +class RunCancel: + """The user's Ctrl+C in a download pool. A failed track never sets it, and each run starts with it clear. + + Not an Event: a second Ctrl+C in its ``set`` can leave its lock held, and each thread that waits on it then hangs. + """ + + pressed = False + + class DownloadCancelled(Exception): """A track stopped because ``DOWNLOAD_CANCELLED`` was set, not because it itself failed. diff --git a/unshackle/core/drm/key_resolution.py b/unshackle/core/drm/key_resolution.py index d0be09a2..ebe8f595 100644 --- a/unshackle/core/drm/key_resolution.py +++ b/unshackle/core/drm/key_resolution.py @@ -629,6 +629,8 @@ class ContentKeyResolver: ) try: get_keys() + except DownloadCancelled: + raise except Exception as e: if drm.content_keys and (not track_kid or track_kid in drm.content_keys): self.log.warning( @@ -785,6 +787,8 @@ class ContentKeyResolver: self._licence_one_drm(prepare, target, kid) else: prepare(target, track_kid=kid) + except DownloadCancelled: + raise except Exception as e: if not tolerate: raise diff --git a/unshackle/core/drm/playready.py b/unshackle/core/drm/playready.py index 0ddf3af6..e33dad8e 100644 --- a/unshackle/core/drm/playready.py +++ b/unshackle/core/drm/playready.py @@ -16,6 +16,7 @@ from pyplayready.system.pssh import PSSH from pyplayready.system.wrmheader import WRMHeader from unshackle.core.cdm.http_cdm import HttpCdm +from unshackle.core.constants import DownloadCancelled from unshackle.core.drm.cenc import PLAYREADY_ID, CencDrm, as_kid from unshackle.core.remote_protocol import APIErrorCode from unshackle.core.utilities import call_licence, log_event @@ -199,7 +200,7 @@ class PlayReady(CencDrm): pssh_b64, required = self.pro_b64_for(header), header_kids or self.kids try: keys = self._license_header(cdm, header, pssh_b64, required, licence) - except PlayReady.Exceptions.DeviceRevoked: + except (PlayReady.Exceptions.DeviceRevoked, DownloadCancelled): raise except Exception as e: self._refused_headers.add(header.dumps()) diff --git a/unshackle/core/remote_channel.py b/unshackle/core/remote_channel.py index 4e150607..c5c810b7 100644 --- a/unshackle/core/remote_channel.py +++ b/unshackle/core/remote_channel.py @@ -41,7 +41,7 @@ from unshackle.core.remote_protocol import ( PromptReply, SessionInfo, ) -from unshackle.core.remote_service import RemoteError, quiet, ws_headers +from unshackle.core.remote_service import RemoteError, cancelled, pause, quiet, require_run, ws_headers from unshackle.core.tunnel import HEARTBEAT, retry_after, run_loop if TYPE_CHECKING: @@ -127,7 +127,7 @@ class ServerMessages: def note_waiting(self, seen: int) -> None: """Show the last service log lines while the login waits on the user (a pair code, an approval link).""" - if self.log_seq == seen and self.recent_logs: + if self.log_seq == seen and self.recent_logs and not cancelled(): notice = "\n".join(self.recent_logs) if notice != self.service.auth_notice: self.service.auth_notice = notice @@ -179,6 +179,7 @@ class PollingChannel: deadline = time.monotonic() + timeout try: while time.monotonic() < deadline: + require_run() if (step or self.auth_step)(): return raise RemoteError("Remote authentication timed out", ClientErrorKind.AUTH) @@ -204,7 +205,7 @@ class PollingChannel: elif status == AuthStatus.PENDING_INPUT: self.answer(self.messages.ask_user(resp.get("prompt") or "Enter input: ", resp.get("qr"))) else: - time.sleep(AUTH_POLL_INTERVAL) + pause(AUTH_POLL_INTERVAL) return False def answer(self, response: str) -> None: @@ -288,7 +289,7 @@ class PollingChannel: A relay failure must never break the operation itself, so this method swallows every error. """ - if not self.service._session_id: + if not self.service._session_id or cancelled(): return with self.drain_lock: try: @@ -339,7 +340,7 @@ class WebSocketChannel: def open(self, timeout: float = CONNECT_TIMEOUT) -> bool: """Connect once; False when the server or a gateway refuses the channel, or the connection fails.""" self.thread.start() - self.attempted.wait(timeout) + pause(timeout, self.attempted) if not self.connected.is_set(): self.close() return False @@ -472,7 +473,7 @@ class WebSocketChannel: f"Remote auth failed: {self.error or 'Authentication failed on server'}", ClientErrorKind.AUTH ) seen = self.messages.log_seq - if not self.changed.wait(AUTH_POLL_INTERVAL) and self.status == AuthStatus.AUTHENTICATING: + if not pause(AUTH_POLL_INTERVAL, self.changed) and self.status == AuthStatus.AUTHENTICATING: self.messages.note_waiting(seen) return False diff --git a/unshackle/core/remote_lifetime.py b/unshackle/core/remote_lifetime.py index 8afaae9b..a57bddbb 100644 --- a/unshackle/core/remote_lifetime.py +++ b/unshackle/core/remote_lifetime.py @@ -13,7 +13,7 @@ from typing import TYPE_CHECKING from unshackle.core import process_exit from unshackle.core.remote_protocol import SESSION_ROUTE, APIErrorCode, SessionClosed -from unshackle.core.remote_service import RemoteClient, RemoteError, quiet +from unshackle.core.remote_service import RemoteClient, RemoteError, quiet, require_run if TYPE_CHECKING: from unshackle.core.remote_channel import Channel @@ -75,6 +75,7 @@ class RemoteSessionLifetime: process_exit.ends.add(self.end_at_exit) yield self.require_open() + require_run() except BaseException: if self.ended: self.end_at_exit() @@ -88,6 +89,7 @@ class RemoteSessionLifetime: named = str(uuid.uuid4()) with self._lock: self.require_open() + require_run() self._held.add(named) return named diff --git a/unshackle/core/remote_service.py b/unshackle/core/remote_service.py index 0d38a1c2..6329875c 100644 --- a/unshackle/core/remote_service.py +++ b/unshackle/core/remote_service.py @@ -21,7 +21,7 @@ from collections.abc import Callable, Iterable, Iterator, Mapping from dataclasses import replace from functools import partial from http.cookiejar import CookieJar -from threading import Lock, local +from threading import Event, Lock, local from typing import ( TYPE_CHECKING, Any, @@ -42,7 +42,7 @@ from rich.spinner import Spinner from unshackle.core import login, process_exit from unshackle.core.config import config from unshackle.core.console import SyncLive, console -from unshackle.core.constants import AnyTrack +from unshackle.core.constants import AnyTrack, DownloadCancelled, RunCancel from unshackle.core.credential import Credential from unshackle.core.dl_options import remote_dl_params from unshackle.core.drm import cbcs, real_kids, whole_file_cipher @@ -128,13 +128,34 @@ TUNNEL_SLOT_POLL = 15 PROBE_TIMEOUT = 30.0 KEYS_TIMEOUT = 5.0 REOPEN_WAIT = 1800.0 # seconds a lost session waits for its server to come back; covers a deploy's whole drain +CANCEL_POLL = 0.5 + + +def cancelled() -> bool: + """Whether Ctrl+C or a stop of the process cancelled the run, so that no thread waits for the server or opens a remote session.""" + return RunCancel.pressed or process_exit.stopping() + + +def require_run() -> None: + """Raise the error of a lost remote session when the run is cancelled.""" + if cancelled(): + raise RemoteError("The run was cancelled", APIErrorCode.SESSION_NOT_FOUND) + + +def pause(seconds: float, until: Event | None = None) -> bool: + """Wait until ``until`` is set, the time ends or the run is cancelled. Return whether ``until`` is set.""" + deadline = time.monotonic() + seconds + wait = until.wait if until else time.sleep + while not (until and until.is_set()) and not cancelled() and (left := deadline - time.monotonic()) > 0: + wait(min(CANCEL_POLL, left)) + return bool(until and until.is_set()) class _Mute(local): """This thread's RemoteError log state: inside ``session_call`` (``recovering``) and under ``quiet()``.""" recovering = False - quiet: Callable[[], bool] = staticmethod(process_exit.stopping) + quiet: Callable[[], bool] = staticmethod(cancelled) _mute = _Mute() @@ -181,10 +202,11 @@ def redact_secrets(text: str, data: Mapping[str, Any] | None = None) -> str: def wait_retry_after(seconds: int, reason: str = "Rate limited by the server") -> None: """Count down a wait on the console, as ``--slow`` does, so the caller can retry; one hour at most, the rate-limit window. - Threads refused together share one countdown, each still waits out its own deadline. + Threads refused together share one countdown, each still waits out its own deadline. A cancel of the run ends every wait. """ deadline = time.monotonic() + min(seconds, RETRY_AFTER_MAX) with RETRY_AFTER_LOCK: + require_run() if deadline <= time.monotonic(): return log.info(f"{reason}, retrying in {math.ceil(deadline - time.monotonic())}s") @@ -192,7 +214,8 @@ def wait_retry_after(seconds: int, reason: str = "Rate limited by the server") - with SyncLive(Padding(spinner, (0, 5)), console=console, refresh_per_second=12.5, transient=True): while (left := deadline - time.monotonic()) > 0: spinner.update(text=f"{reason}, retrying in {math.ceil(left)} seconds...") - time.sleep(min(1.0, left)) + time.sleep(min(CANCEL_POLL, left)) + require_run() class RemoteError(SystemExit): @@ -1231,8 +1254,18 @@ class RemoteService(TitleSource): if not _mute.quiet(): log.error(lost.message) raise lost + require_run() return call(self._session_id) + def track_call(self, call: Callable[[str | None], T]) -> T: + """:meth:`session_call` for a track: in a cancelled run the track did not fail, so it ends without an error line.""" + try: + return self.session_call(call) + except RemoteError: + if cancelled(): + raise DownloadCancelled() from None + raise + def recover(self, session_id: str | None, kind: str) -> bool: """Whether a call that failed with ``kind`` can run again, on the same session or on a new one. @@ -1247,6 +1280,8 @@ class RemoteService(TitleSource): alive = kind != ClientErrorKind.TUNNEL_CLOSED and bool( self.client.probe(SESSION_ROUTE.format(session_id=session_id), background=False) ) + if cancelled(): + return False if alive: return kind == ClientErrorKind.CONNECT self.log.warning("The remote session was lost, opening a new one") @@ -1256,13 +1291,15 @@ class RemoteService(TitleSource): def wait_for_server(self, accepting: bool) -> bool: """Wait until the server answers, and with ``accepting`` until it also takes new sessions. - False on timeout, and when the owner of the remote session has ended. + False on timeout, on a cancel of the run, and when the owner of the remote session has ended. """ deadline = time.monotonic() + REOPEN_WAIT delay = 1.0 warned = False - while not self.lifetime.ended: + while not (self.lifetime.ended or cancelled()): health = self.client.probe(HEALTH_ROUTE) + if cancelled(): + break if health.get("status") == "ok" and not (accepting and health.get("draining")): return True if time.monotonic() >= deadline: @@ -1271,7 +1308,7 @@ class RemoteService(TitleSource): self.log.warning(f"Waiting for the remote server at {safe_display_url(self.client.server_url)}") warned = True # jittered, so the clients of a restarted server do not all log in again at the same moment - time.sleep(random.uniform(delay / 2, delay)) # nosec B311 + pause(random.uniform(delay / 2, delay)) # nosec B311 delay = min(delay * 2, 30.0) return False @@ -1305,6 +1342,7 @@ class RemoteService(TitleSource): if len(same) == 1 and str(same[0].id) != str(old.id): self._title_alias[str(old.id)] = str(same[0].id) title = self._current_title + require_run() if title is not None: held = self._tracks_by_title.pop(str(title.id), None) try: @@ -1434,7 +1472,7 @@ class RemoteService(TitleSource): query = urlencode({"track_id": self.server_track_id(track.id), "entry": entry}) return self.client.request("post", SAMPLES_ROUTE.format(session_id=sid) + f"?{query}", body=body) - return self.session_call(call) + return self.track_call(call) answer = samples(b"") if answer.get("key"): @@ -1463,7 +1501,7 @@ class RemoteService(TitleSource): with quiet(): result = cast( SegmentFilterReply, - self.session_call( + self.track_call( lambda sid: self.client.post_optional( SEGMENT_FILTER_ROUTE.format(session_id=sid), SegmentFilterRequest(track_id=self.server_track_id(track_id)), @@ -1711,7 +1749,7 @@ class RemoteService(TitleSource): with quiet(): resp = cast( LicenseReply, - self.session_call( + self.track_call( lambda sid: self.client.post( LICENSE_ROUTE.format(session_id=sid), LicenseRequest( @@ -1756,7 +1794,7 @@ class RemoteService(TitleSource): request["kid"] = kid.hex try: with quiet(): - resp = self.session_call( + resp = self.track_call( lambda sid: self.client.post( LICENSE_ROUTE.format(session_id=sid), LicenseRequest(**request, track_id=self.server_track_id(track.id)), @@ -1768,6 +1806,8 @@ class RemoteService(TitleSource): keys = resp.get("keys", {}) self.note_vault_keys(keys, set(resp.get("vault_keys", []))) return {UUID(hex=kid_hex): key for kid_hex, key in keys.items()} + except DownloadCancelled: + raise except (Exception, RemoteError) as e: self.log.warning("server_cdm license failed: %s", e) return {} @@ -1783,7 +1823,7 @@ class RemoteService(TitleSource): ) try: with quiet(): - resp = self.session_call( + resp = self.track_call( lambda sid: self.client.post( LICENSE_ROUTE.format(session_id=sid), LicenseRequest( @@ -1805,7 +1845,7 @@ class RemoteService(TitleSource): """The URL that the server looks up for a track it sent with ``resolve_url``, or raise ClickException.""" try: with quiet(): - resp = self.session_call( + resp = self.track_call( lambda sid: self.client.post( SEGMENTS_ROUTE.format(session_id=sid), SegmentsRequest(track_ids=[self.server_track_id(track.id)]), @@ -1832,7 +1872,7 @@ class RemoteService(TitleSource): try: with quiet(): - resp = self.session_call( + resp = self.track_call( lambda sid: self.client.post( LICENSE_ROUTE.format(session_id=sid), LicenseRequest(**payload, track_id=self.server_track_id(track.id)),