fix(remote): end every remote wait of a run when the user cancels it

This commit is contained in:
imSp4rky
2026-11-30 19:59:26 -07:00
parent b826eccb86
commit b907069eb5
13 changed files with 873 additions and 42 deletions
+10 -4
View File
@@ -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 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. attributes.
The client waits up to 30 minutes for the server, which covers a deploy's drain. It The client waits up to 30 minutes for the server, which covers a deploy's drain. A Ctrl+C
stops with an error if the new remote session licenses differently from the old one, 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 for example after a change to the API key's `server_cdm` grant. An interactive login
asks for its input again. asks for its input again.
- **Server resolution.** `resolve_server()` reads `config.remote_services.<name>` - **Server resolution.** `resolve_server()` reads `config.remote_services.<name>`
@@ -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 - 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 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 an error page or asks for the API key in the other header. It does not wait for a rate limit.
download threads before it ends the remote session.
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 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. 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.
+3 -1
View File
@@ -14,6 +14,7 @@ import pytest
from unshackle.core import binaries, process_exit from unshackle.core import binaries, process_exit
from unshackle.core import session as http_session from unshackle.core import session as http_session
from unshackle.core.config import config from unshackle.core.config import config
from unshackle.core.constants import RunCancel
from unshackle.core.providers import anilist from unshackle.core.providers import anilist
from unshackle.core.proxies.proxy import CATALOGUES from unshackle.core.proxies.proxy import CATALOGUES
from unshackle.core.update_checker import UpdateChecker from unshackle.core.update_checker import UpdateChecker
@@ -61,9 +62,10 @@ def client_process(monkeypatch: pytest.MonkeyPatch) -> None:
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def keep_signal_handlers(monkeypatch: pytest.MonkeyPatch) -> None: 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, "listen", lambda *args: None)
monkeypatch.setattr(process_exit.Stop, "raised", False) monkeypatch.setattr(process_exit.Stop, "raised", False)
monkeypatch.setattr(RunCancel, "pressed", False)
monkeypatch.setattr(process_exit, "ends", set()) monkeypatch.setattr(process_exit, "ends", set())
+20
View File
@@ -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) 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: def test_a_held_track_key_needs_no_licence(licences: Licences) -> None:
keys = resolver() keys = resolver()
ContentKeyResolver.LICENSE_KEY_CACHE[KID_A] = KEYS[KID_A] ContentKeyResolver.LICENSE_KEY_CACHE[KID_A] = KEYS[KID_A]
+13
View File
@@ -13,6 +13,7 @@ from pyplayready.system.wrmheader import WRMHeader
from pywidevine.key import Key as WidevineKey from pywidevine.key import Key as WidevineKey
from unshackle.core.cdm.http_cdm import HttpCdm from unshackle.core.cdm.http_cdm import HttpCdm
from unshackle.core.constants import DownloadCancelled
from unshackle.core.drm import PlayReady from unshackle.core.drm import PlayReady
KID_A = UUID("00112233-4455-6677-8899-aabbccddeeff") 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} 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: def test_every_header_refused_raises() -> None:
drm = _drm(_wrm_header(KID_A), _wrm_header(KID_B)) drm = _drm(_wrm_header(KID_A), _wrm_header(KID_B))
cdm = FakeCdm({}, fail_on={KID_A, KID_B}) cdm = FakeCdm({}, fail_on={KID_A, KID_B})
+669
View File
@@ -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
+33 -2
View File
@@ -13,7 +13,8 @@ from __future__ import annotations
import pytest import pytest
from unshackle.commands.dl import SkippedSubtitle, download_tracks_in_passes 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 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 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) @pytest.fixture(autouse=True)
+45 -12
View File
@@ -1,5 +1,6 @@
from __future__ import annotations from __future__ import annotations
import contextlib
import logging import logging
import os import os
import random import random
@@ -8,11 +9,11 @@ import subprocess
import sys import sys
import time import time
from collections.abc import Callable, Collection, Iterable, Sequence from collections.abc import Callable, Collection, Iterable, Sequence
from concurrent import futures
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor
from copy import deepcopy from copy import deepcopy
from functools import partial from functools import partial
from pathlib import Path from pathlib import Path
from queue import Empty, SimpleQueue
from threading import Lock from threading import Lock
from typing import TYPE_CHECKING, Any, TypedDict from typing import TYPE_CHECKING, Any, TypedDict
@@ -44,6 +45,7 @@ from unshackle.core.constants import (
DOWNLOAD_CANCELLED, DOWNLOAD_CANCELLED,
DOWNLOAD_LICENCE_ONLY, DOWNLOAD_LICENCE_ONLY,
AnyTrack, AnyTrack,
RunCancel,
context_settings, context_settings,
) )
from unshackle.core.dl_options import DL_OPTION_ALIASES 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. 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 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 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 ``run_one(track, index)`` downloads a single track. ``on_subtitle_skipped(track)`` records a
subtitle whose download raised (handled here). subtitle whose download raised (handled here).
@@ -356,30 +362,56 @@ def download_tracks_in_passes(
else: else:
primary, skippable = indexed, [] 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: try:
with ThreadPoolExecutor(max_concurrent) as pool: with ThreadPoolExecutor(max_concurrent) as pool:
pending = {pool.submit(run_one, track, i) for i, track in primary}
try: try:
# timed: on Windows an untimed wait holds Ctrl+C back until a track ends for i, track in primary:
while pending: pool.submit(download, track, i)
done, pending = futures.wait(pending, timeout=0.5, return_when=futures.FIRST_COMPLETED) left = len(primary)
for download in done: while left:
download.result() # a video/audio failure is fatal # 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: except KeyboardInterrupt:
# Ctrl+C reaches only this thread; the pool exit waits for the tracks unless they see the cancel # 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() DOWNLOAD_CANCELLED.set()
raise raise
if error:
raise error # a video/audio failure is fatal
for i, track in skippable: for i, track in skippable:
DOWNLOAD_CANCELLED.clear() DOWNLOAD_CANCELLED.clear()
try: try:
run_one(track, i) run(track, i)
except Exception: except Exception:
on_subtitle_skipped(track) on_subtitle_skipped(track)
finally: finally:
if not interrupted: if not RunCancel.pressed:
DOWNLOAD_CANCELLED.clear() # never leave a failed track's cancel set for later code DOWNLOAD_CANCELLED.clear() # never leave a failed track's cancel set for later code
@@ -1536,6 +1568,7 @@ class dl:
*_: Any, *_: Any,
**__: Any, **__: Any,
) -> RunOutcome: ) -> RunOutcome:
RunCancel.pressed = False
if all_drm: if all_drm:
DOWNLOAD_ALL_DRM.set() DOWNLOAD_ALL_DRM.set()
else: else:
+9
View File
@@ -12,6 +12,15 @@ HTTP_LOGGERS = ("urllib3", "urllib3.connectionpool", "requests", "rnet", "httpx"
DOWNLOAD_ALL_DRM = Event() 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): class DownloadCancelled(Exception):
"""A track stopped because ``DOWNLOAD_CANCELLED`` was set, not because it itself failed. """A track stopped because ``DOWNLOAD_CANCELLED`` was set, not because it itself failed.
+4
View File
@@ -629,6 +629,8 @@ class ContentKeyResolver:
) )
try: try:
get_keys() get_keys()
except DownloadCancelled:
raise
except Exception as e: except Exception as e:
if drm.content_keys and (not track_kid or track_kid in drm.content_keys): if drm.content_keys and (not track_kid or track_kid in drm.content_keys):
self.log.warning( self.log.warning(
@@ -785,6 +787,8 @@ class ContentKeyResolver:
self._licence_one_drm(prepare, target, kid) self._licence_one_drm(prepare, target, kid)
else: else:
prepare(target, track_kid=kid) prepare(target, track_kid=kid)
except DownloadCancelled:
raise
except Exception as e: except Exception as e:
if not tolerate: if not tolerate:
raise raise
+2 -1
View File
@@ -16,6 +16,7 @@ from pyplayready.system.pssh import PSSH
from pyplayready.system.wrmheader import WRMHeader from pyplayready.system.wrmheader import WRMHeader
from unshackle.core.cdm.http_cdm import HttpCdm 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.drm.cenc import PLAYREADY_ID, CencDrm, as_kid
from unshackle.core.remote_protocol import APIErrorCode from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.utilities import call_licence, log_event 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 pssh_b64, required = self.pro_b64_for(header), header_kids or self.kids
try: try:
keys = self._license_header(cdm, header, pssh_b64, required, licence) keys = self._license_header(cdm, header, pssh_b64, required, licence)
except PlayReady.Exceptions.DeviceRevoked: except (PlayReady.Exceptions.DeviceRevoked, DownloadCancelled):
raise raise
except Exception as e: except Exception as e:
self._refused_headers.add(header.dumps()) self._refused_headers.add(header.dumps())
+7 -6
View File
@@ -41,7 +41,7 @@ from unshackle.core.remote_protocol import (
PromptReply, PromptReply,
SessionInfo, 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 from unshackle.core.tunnel import HEARTBEAT, retry_after, run_loop
if TYPE_CHECKING: if TYPE_CHECKING:
@@ -127,7 +127,7 @@ class ServerMessages:
def note_waiting(self, seen: int) -> None: 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).""" """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) notice = "\n".join(self.recent_logs)
if notice != self.service.auth_notice: if notice != self.service.auth_notice:
self.service.auth_notice = notice self.service.auth_notice = notice
@@ -179,6 +179,7 @@ class PollingChannel:
deadline = time.monotonic() + timeout deadline = time.monotonic() + timeout
try: try:
while time.monotonic() < deadline: while time.monotonic() < deadline:
require_run()
if (step or self.auth_step)(): if (step or self.auth_step)():
return return
raise RemoteError("Remote authentication timed out", ClientErrorKind.AUTH) raise RemoteError("Remote authentication timed out", ClientErrorKind.AUTH)
@@ -204,7 +205,7 @@ class PollingChannel:
elif status == AuthStatus.PENDING_INPUT: elif status == AuthStatus.PENDING_INPUT:
self.answer(self.messages.ask_user(resp.get("prompt") or "Enter input: ", resp.get("qr"))) self.answer(self.messages.ask_user(resp.get("prompt") or "Enter input: ", resp.get("qr")))
else: else:
time.sleep(AUTH_POLL_INTERVAL) pause(AUTH_POLL_INTERVAL)
return False return False
def answer(self, response: str) -> None: 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. 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 return
with self.drain_lock: with self.drain_lock:
try: try:
@@ -339,7 +340,7 @@ class WebSocketChannel:
def open(self, timeout: float = CONNECT_TIMEOUT) -> bool: def open(self, timeout: float = CONNECT_TIMEOUT) -> bool:
"""Connect once; False when the server or a gateway refuses the channel, or the connection fails.""" """Connect once; False when the server or a gateway refuses the channel, or the connection fails."""
self.thread.start() self.thread.start()
self.attempted.wait(timeout) pause(timeout, self.attempted)
if not self.connected.is_set(): if not self.connected.is_set():
self.close() self.close()
return False return False
@@ -472,7 +473,7 @@ class WebSocketChannel:
f"Remote auth failed: {self.error or 'Authentication failed on server'}", ClientErrorKind.AUTH f"Remote auth failed: {self.error or 'Authentication failed on server'}", ClientErrorKind.AUTH
) )
seen = self.messages.log_seq 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) self.messages.note_waiting(seen)
return False return False
+3 -1
View File
@@ -13,7 +13,7 @@ from typing import TYPE_CHECKING
from unshackle.core import process_exit from unshackle.core import process_exit
from unshackle.core.remote_protocol import SESSION_ROUTE, APIErrorCode, SessionClosed 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: if TYPE_CHECKING:
from unshackle.core.remote_channel import Channel from unshackle.core.remote_channel import Channel
@@ -75,6 +75,7 @@ class RemoteSessionLifetime:
process_exit.ends.add(self.end_at_exit) process_exit.ends.add(self.end_at_exit)
yield yield
self.require_open() self.require_open()
require_run()
except BaseException: except BaseException:
if self.ended: if self.ended:
self.end_at_exit() self.end_at_exit()
@@ -88,6 +89,7 @@ class RemoteSessionLifetime:
named = str(uuid.uuid4()) named = str(uuid.uuid4())
with self._lock: with self._lock:
self.require_open() self.require_open()
require_run()
self._held.add(named) self._held.add(named)
return named return named
+55 -15
View File
@@ -21,7 +21,7 @@ from collections.abc import Callable, Iterable, Iterator, Mapping
from dataclasses import replace from dataclasses import replace
from functools import partial from functools import partial
from http.cookiejar import CookieJar from http.cookiejar import CookieJar
from threading import Lock, local from threading import Event, Lock, local
from typing import ( from typing import (
TYPE_CHECKING, TYPE_CHECKING,
Any, Any,
@@ -42,7 +42,7 @@ from rich.spinner import Spinner
from unshackle.core import login, process_exit from unshackle.core import login, process_exit
from unshackle.core.config import config from unshackle.core.config import config
from unshackle.core.console import SyncLive, console 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.credential import Credential
from unshackle.core.dl_options import remote_dl_params from unshackle.core.dl_options import remote_dl_params
from unshackle.core.drm import cbcs, real_kids, whole_file_cipher from unshackle.core.drm import cbcs, real_kids, whole_file_cipher
@@ -128,13 +128,34 @@ TUNNEL_SLOT_POLL = 15
PROBE_TIMEOUT = 30.0 PROBE_TIMEOUT = 30.0
KEYS_TIMEOUT = 5.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 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): class _Mute(local):
"""This thread's RemoteError log state: inside ``session_call`` (``recovering``) and under ``quiet()``.""" """This thread's RemoteError log state: inside ``session_call`` (``recovering``) and under ``quiet()``."""
recovering = False recovering = False
quiet: Callable[[], bool] = staticmethod(process_exit.stopping) quiet: Callable[[], bool] = staticmethod(cancelled)
_mute = _Mute() _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: 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. """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) deadline = time.monotonic() + min(seconds, RETRY_AFTER_MAX)
with RETRY_AFTER_LOCK: with RETRY_AFTER_LOCK:
require_run()
if deadline <= time.monotonic(): if deadline <= time.monotonic():
return return
log.info(f"{reason}, retrying in {math.ceil(deadline - time.monotonic())}s") 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): with SyncLive(Padding(spinner, (0, 5)), console=console, refresh_per_second=12.5, transient=True):
while (left := deadline - time.monotonic()) > 0: while (left := deadline - time.monotonic()) > 0:
spinner.update(text=f"{reason}, retrying in {math.ceil(left)} seconds...") 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): class RemoteError(SystemExit):
@@ -1231,8 +1254,18 @@ class RemoteService(TitleSource):
if not _mute.quiet(): if not _mute.quiet():
log.error(lost.message) log.error(lost.message)
raise lost raise lost
require_run()
return call(self._session_id) 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: 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. """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( alive = kind != ClientErrorKind.TUNNEL_CLOSED and bool(
self.client.probe(SESSION_ROUTE.format(session_id=session_id), background=False) self.client.probe(SESSION_ROUTE.format(session_id=session_id), background=False)
) )
if cancelled():
return False
if alive: if alive:
return kind == ClientErrorKind.CONNECT return kind == ClientErrorKind.CONNECT
self.log.warning("The remote session was lost, opening a new one") 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: def wait_for_server(self, accepting: bool) -> bool:
"""Wait until the server answers, and with ``accepting`` until it also takes new sessions. """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 deadline = time.monotonic() + REOPEN_WAIT
delay = 1.0 delay = 1.0
warned = False warned = False
while not self.lifetime.ended: while not (self.lifetime.ended or cancelled()):
health = self.client.probe(HEALTH_ROUTE) health = self.client.probe(HEALTH_ROUTE)
if cancelled():
break
if health.get("status") == "ok" and not (accepting and health.get("draining")): if health.get("status") == "ok" and not (accepting and health.get("draining")):
return True return True
if time.monotonic() >= deadline: 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)}") self.log.warning(f"Waiting for the remote server at {safe_display_url(self.client.server_url)}")
warned = True warned = True
# jittered, so the clients of a restarted server do not all log in again at the same moment # 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) delay = min(delay * 2, 30.0)
return False return False
@@ -1305,6 +1342,7 @@ class RemoteService(TitleSource):
if len(same) == 1 and str(same[0].id) != str(old.id): if len(same) == 1 and str(same[0].id) != str(old.id):
self._title_alias[str(old.id)] = str(same[0].id) self._title_alias[str(old.id)] = str(same[0].id)
title = self._current_title title = self._current_title
require_run()
if title is not None: if title is not None:
held = self._tracks_by_title.pop(str(title.id), None) held = self._tracks_by_title.pop(str(title.id), None)
try: try:
@@ -1434,7 +1472,7 @@ class RemoteService(TitleSource):
query = urlencode({"track_id": self.server_track_id(track.id), "entry": entry}) 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.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"") answer = samples(b"")
if answer.get("key"): if answer.get("key"):
@@ -1463,7 +1501,7 @@ class RemoteService(TitleSource):
with quiet(): with quiet():
result = cast( result = cast(
SegmentFilterReply, SegmentFilterReply,
self.session_call( self.track_call(
lambda sid: self.client.post_optional( lambda sid: self.client.post_optional(
SEGMENT_FILTER_ROUTE.format(session_id=sid), SEGMENT_FILTER_ROUTE.format(session_id=sid),
SegmentFilterRequest(track_id=self.server_track_id(track_id)), SegmentFilterRequest(track_id=self.server_track_id(track_id)),
@@ -1711,7 +1749,7 @@ class RemoteService(TitleSource):
with quiet(): with quiet():
resp = cast( resp = cast(
LicenseReply, LicenseReply,
self.session_call( self.track_call(
lambda sid: self.client.post( lambda sid: self.client.post(
LICENSE_ROUTE.format(session_id=sid), LICENSE_ROUTE.format(session_id=sid),
LicenseRequest( LicenseRequest(
@@ -1756,7 +1794,7 @@ class RemoteService(TitleSource):
request["kid"] = kid.hex request["kid"] = kid.hex
try: try:
with quiet(): with quiet():
resp = self.session_call( resp = self.track_call(
lambda sid: self.client.post( lambda sid: self.client.post(
LICENSE_ROUTE.format(session_id=sid), LICENSE_ROUTE.format(session_id=sid),
LicenseRequest(**request, track_id=self.server_track_id(track.id)), LicenseRequest(**request, track_id=self.server_track_id(track.id)),
@@ -1768,6 +1806,8 @@ class RemoteService(TitleSource):
keys = resp.get("keys", {}) keys = resp.get("keys", {})
self.note_vault_keys(keys, set(resp.get("vault_keys", []))) self.note_vault_keys(keys, set(resp.get("vault_keys", [])))
return {UUID(hex=kid_hex): key for kid_hex, key in keys.items()} return {UUID(hex=kid_hex): key for kid_hex, key in keys.items()}
except DownloadCancelled:
raise
except (Exception, RemoteError) as e: except (Exception, RemoteError) as e:
self.log.warning("server_cdm license failed: %s", e) self.log.warning("server_cdm license failed: %s", e)
return {} return {}
@@ -1783,7 +1823,7 @@ class RemoteService(TitleSource):
) )
try: try:
with quiet(): with quiet():
resp = self.session_call( resp = self.track_call(
lambda sid: self.client.post( lambda sid: self.client.post(
LICENSE_ROUTE.format(session_id=sid), LICENSE_ROUTE.format(session_id=sid),
LicenseRequest( 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.""" """The URL that the server looks up for a track it sent with ``resolve_url``, or raise ClickException."""
try: try:
with quiet(): with quiet():
resp = self.session_call( resp = self.track_call(
lambda sid: self.client.post( lambda sid: self.client.post(
SEGMENTS_ROUTE.format(session_id=sid), SEGMENTS_ROUTE.format(session_id=sid),
SegmentsRequest(track_ids=[self.server_track_id(track.id)]), SegmentsRequest(track_ids=[self.server_track_id(track.id)]),
@@ -1832,7 +1872,7 @@ class RemoteService(TitleSource):
try: try:
with quiet(): with quiet():
resp = self.session_call( resp = self.track_call(
lambda sid: self.client.post( lambda sid: self.client.post(
LICENSE_ROUTE.format(session_id=sid), LICENSE_ROUTE.format(session_id=sid),
LicenseRequest(**payload, track_id=self.server_track_id(track.id)), LicenseRequest(**payload, track_id=self.server_track_id(track.id)),