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
+55 -15
View File
@@ -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)),