mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-05 15:35:06 +00:00
fix(remote): end a remote session from before its create to after its DELETE
This commit is contained in:
@@ -7,7 +7,6 @@ Everything else (track selection, download, decrypt, mux) runs locally.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import atexit
|
||||
import base64
|
||||
import contextlib
|
||||
import hashlib
|
||||
@@ -78,7 +77,6 @@ from unshackle.core.remote_protocol import (
|
||||
SegmentFilterReply,
|
||||
SegmentFilterRequest,
|
||||
SegmentsRequest,
|
||||
SessionClosed,
|
||||
SessionCreate,
|
||||
SessionCreated,
|
||||
TitlesReply,
|
||||
@@ -106,6 +104,7 @@ from unshackle.core.wire import apply_tracks_reply, build_chapters, build_music,
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from unshackle.core.remote_channel import Channel
|
||||
from unshackle.core.remote_lifetime import RemoteSessionLifetime
|
||||
|
||||
log = logging.getLogger("remote_service")
|
||||
|
||||
@@ -135,7 +134,7 @@ class _Mute(local):
|
||||
"""This thread's RemoteError log state: inside ``session_call`` (``recovering``) and under ``quiet()``."""
|
||||
|
||||
recovering = False
|
||||
quiet = False
|
||||
quiet: Callable[[], bool] = staticmethod(lambda: False)
|
||||
|
||||
|
||||
_mute = _Mute()
|
||||
@@ -163,10 +162,10 @@ def malformed_answer(what: str) -> Iterator[None]:
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def quiet() -> Iterator[None]:
|
||||
"""Log this thread's RemoteErrors at debug level, because the caller reports them."""
|
||||
def quiet(when: Callable[[], bool] = lambda: True) -> Iterator[None]:
|
||||
"""Log this thread's RemoteErrors at debug level, because the caller reports them; only while ``when`` is true."""
|
||||
before = _mute.quiet
|
||||
_mute.quiet = True
|
||||
_mute.quiet = lambda: before() or when()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
@@ -210,7 +209,7 @@ class RemoteError(SystemExit):
|
||||
super().__init__(1)
|
||||
self.message = sanitize_log(message)
|
||||
self.kind = kind
|
||||
muted = _mute.quiet or (_mute.recovering and kind in RECOVERABLE)
|
||||
muted = _mute.quiet() or (_mute.recovering and kind in RECOVERABLE)
|
||||
(log.debug if muted else log.error)(self.message)
|
||||
|
||||
def __str__(self) -> str:
|
||||
@@ -411,9 +410,6 @@ class RemoteClient:
|
||||
"""GET an endpoint that an older server may not have. Empty dict when the route is missing."""
|
||||
return self.request("get", endpoint, optional=True)
|
||||
|
||||
def delete(self, endpoint: str) -> dict[str, Any]:
|
||||
return self.request("delete", endpoint)
|
||||
|
||||
|
||||
def sample_batches(samples: list[bytes]) -> Iterator[list[bytes]]:
|
||||
"""Split samples into consecutive batches of at most cbcs.SAMPLE_BATCH_BYTES (a larger sample goes alone)."""
|
||||
@@ -672,7 +668,7 @@ def start_tunnel(client: RemoteClient, proxy: str | None = None) -> TunnelClient
|
||||
slot_deadline = time.monotonic() + RETRY_AFTER_MAX
|
||||
rate_waits = 0
|
||||
while True:
|
||||
tunnel = TunnelClient(client.server_url, headers, proxy)
|
||||
tunnel = client.tunnel = TunnelClient(client.server_url, headers, proxy)
|
||||
try:
|
||||
tunnel.start()
|
||||
break
|
||||
@@ -684,7 +680,6 @@ def start_tunnel(client: RemoteClient, proxy: str | None = None) -> TunnelClient
|
||||
wait_retry_after(TUNNEL_SLOT_POLL, "Every tunnel of this API key is in use")
|
||||
else:
|
||||
raise click.ClickException(f"--local-proxy could not open a tunnel to the server: {e}") from None
|
||||
client.tunnel = tunnel
|
||||
return tunnel
|
||||
|
||||
|
||||
@@ -810,7 +805,7 @@ class RemoteService(TitleSource):
|
||||
"""
|
||||
|
||||
server_cdm_type: str = "widevine"
|
||||
channel: Channel | None = None
|
||||
lifetime: RemoteSessionLifetime
|
||||
licensing: LicensingMode | None = None
|
||||
"""The server's answer to who licenses this remote session; an older server gives it in the tracks reply."""
|
||||
_server_cdm_request: bool | None = None
|
||||
@@ -826,6 +821,8 @@ class RemoteService(TitleSource):
|
||||
services_config: dict,
|
||||
service_params: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
from unshackle.core.remote_lifetime import RemoteSessionLifetime
|
||||
|
||||
self.__class__.__name__ = service_tag
|
||||
console.print(Padding(Rule(f"[rule.text]Service: {service_tag} (Remote)"), (1, 2)))
|
||||
|
||||
@@ -840,7 +837,7 @@ class RemoteService(TitleSource):
|
||||
self._titles: Titles_T | None = None
|
||||
self._tracks_by_title: dict[str, Tracks] = {}
|
||||
self._chapters_by_title: dict[str, list] = {}
|
||||
self._session_id: str | None = None
|
||||
self.lifetime = RemoteSessionLifetime(self.client, self.save_session_cache)
|
||||
self.client_licensed: set[str] = set() # track ids this machine's device licenses by challenge relay
|
||||
self.deferred_refusals: dict[str, str] = {}
|
||||
self.server_vault_keys: dict[UUID, str] = {}
|
||||
@@ -917,6 +914,14 @@ class RemoteService(TitleSource):
|
||||
def title(self) -> str:
|
||||
return self.title_id
|
||||
|
||||
@property
|
||||
def _session_id(self) -> str | None:
|
||||
return self.lifetime.session_id
|
||||
|
||||
@property
|
||||
def channel(self) -> Channel | None:
|
||||
return self.lifetime.channel
|
||||
|
||||
def search(self) -> Iterator[SearchResult]:
|
||||
"""Search on the server, which logs in to the service itself with the login material sent here."""
|
||||
params = self.ctx.parent.params if self.ctx.parent else {}
|
||||
@@ -926,15 +931,15 @@ class RemoteService(TitleSource):
|
||||
data["profile"] = profile
|
||||
if not self._anonymous_search:
|
||||
data.update(self.client_login(profile))
|
||||
if params.get("no_proxy"):
|
||||
data["no_proxy"] = True
|
||||
elif params.get("local_proxy"):
|
||||
data["proxy"] = self.tunnel()
|
||||
elif params.get("proxy"):
|
||||
providers = getattr(self.ctx.obj, "proxy_providers", None)
|
||||
data["proxy"] = resolve_remote_proxy_arg(server_proxy_arg(params), providers)
|
||||
self.require_reachable_proxy(data["proxy"])
|
||||
try:
|
||||
if params.get("no_proxy"):
|
||||
data["no_proxy"] = True
|
||||
elif params.get("local_proxy"):
|
||||
data["proxy"] = self.tunnel()
|
||||
elif params.get("proxy"):
|
||||
providers = getattr(self.ctx.obj, "proxy_providers", None)
|
||||
data["proxy"] = resolve_remote_proxy_arg(server_proxy_arg(params), providers)
|
||||
self.require_reachable_proxy(data["proxy"])
|
||||
response = self.client.post(SEARCH_ROUTE, data)
|
||||
finally:
|
||||
if self.client.tunnel: # a search is one request, so its tunnel ends with it
|
||||
@@ -983,6 +988,11 @@ class RemoteService(TitleSource):
|
||||
return f"tunnel:{tunnel.id}"
|
||||
|
||||
def authenticate(self, cookies: CookieJar | None = None, credential: Credential | None = None) -> None:
|
||||
with self.lifetime.opening():
|
||||
self.open_session(credential)
|
||||
|
||||
def open_session(self, credential: Credential | None) -> None:
|
||||
"""Make the remote session and wait for its login; what it opens belongs to ``lifetime``."""
|
||||
self.credential = credential
|
||||
profile = self.ctx.parent.params.get("profile") if self.ctx.parent else None
|
||||
proxy = self.ctx.parent.params.get("proxy") if self.ctx.parent else None
|
||||
@@ -1121,16 +1131,11 @@ class RemoteService(TitleSource):
|
||||
"argv": argv,
|
||||
}
|
||||
|
||||
try:
|
||||
result = cast(SessionCreated, self.client.post(SESSION_CREATE_ROUTE, create_data))
|
||||
if not isinstance(result.get("session_id"), str):
|
||||
raise RemoteError("The remote server sent malformed session: no session_id", ClientErrorKind.UNKNOWN)
|
||||
except BaseException:
|
||||
if local and self.client.tunnel: # no session, so close() never runs: free the tunnel now
|
||||
self.client.tunnel.stop()
|
||||
raise
|
||||
self._session_id = result["session_id"]
|
||||
atexit.register(self.close)
|
||||
create_data["session_id"] = self.lifetime.name()
|
||||
result = cast(SessionCreated, self.client.post(SESSION_CREATE_ROUTE, create_data))
|
||||
if not isinstance(result.get("session_id"), str):
|
||||
raise RemoteError("The remote server sent malformed session: no session_id", ClientErrorKind.UNKNOWN)
|
||||
self.lifetime.adopt(create_data["session_id"], result["session_id"])
|
||||
# an older server omits the field, and the tracks response settles it
|
||||
if "server_cdm" in result:
|
||||
answer = LicensingMode.from_created(result)
|
||||
@@ -1151,13 +1156,13 @@ class RemoteService(TitleSource):
|
||||
|
||||
from unshackle.core.remote_channel import open_channel
|
||||
|
||||
self.channel = open_channel(self)
|
||||
channel = self.lifetime.channel = open_channel(self)
|
||||
if result.get("status", AuthStatus.AUTHENTICATED) == AuthStatus.AUTHENTICATING:
|
||||
self.channel.wait_auth()
|
||||
channel.wait_auth()
|
||||
if create_data.get("cdm_relay"):
|
||||
self.client.in_flight = self.channel.in_flight
|
||||
self.client.in_flight = channel.in_flight
|
||||
self.drain_server_logs()
|
||||
self.channel.keep_alive()
|
||||
channel.keep_alive()
|
||||
|
||||
@property
|
||||
def local_cdm(self) -> Any:
|
||||
@@ -1223,7 +1228,7 @@ class RemoteService(TitleSource):
|
||||
raise
|
||||
lost = e
|
||||
if not self.recover(session_id, lost.kind):
|
||||
if not _mute.quiet:
|
||||
if not _mute.quiet():
|
||||
log.error(lost.message)
|
||||
raise lost
|
||||
return call(self._session_id)
|
||||
@@ -1245,14 +1250,18 @@ class RemoteService(TitleSource):
|
||||
if alive:
|
||||
return kind == ClientErrorKind.CONNECT
|
||||
self.log.warning("The remote session was lost, opening a new one")
|
||||
self.lifetime.release(gone=kind == APIErrorCode.SESSION_NOT_FOUND)
|
||||
return self.reopen()
|
||||
|
||||
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."""
|
||||
"""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.
|
||||
"""
|
||||
deadline = time.monotonic() + REOPEN_WAIT
|
||||
delay = 1.0
|
||||
warned = False
|
||||
while True:
|
||||
while not self.lifetime.ended:
|
||||
health = self.client.probe(HEALTH_ROUTE)
|
||||
if health.get("status") == "ok" and not (accepting and health.get("draining")):
|
||||
return True
|
||||
@@ -1264,6 +1273,7 @@ class RemoteService(TitleSource):
|
||||
# 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
|
||||
delay = min(delay * 2, 30.0)
|
||||
return False
|
||||
|
||||
def licence_path(self) -> object:
|
||||
"""Where this remote session takes its keys from, which a reopened session must keep.
|
||||
@@ -1274,16 +1284,11 @@ class RemoteService(TitleSource):
|
||||
return (licensing.licensor, licensing.vault_first) if licensing else self._server_cdm_request
|
||||
|
||||
def reopen(self) -> bool:
|
||||
"""Open a new remote session after the server lost this one, and load the current title's tracks on it again.
|
||||
"""Open a new remote session after the release of the last one, and load the current title's tracks on it again.
|
||||
|
||||
A track the new remote session gives another id keeps its old one here, and calls translate it.
|
||||
"""
|
||||
grants = self.licence_path()
|
||||
self.close_channel()
|
||||
self._session_id = None
|
||||
if self.client.tunnel: # the server forgot the tunnel too
|
||||
self.client.tunnel.stop()
|
||||
self.client.tunnel = None
|
||||
self._segment_filters.clear()
|
||||
if not self.wait_for_server(accepting=True):
|
||||
return False
|
||||
@@ -1322,10 +1327,10 @@ class RemoteService(TitleSource):
|
||||
return True
|
||||
|
||||
def reopen_after_drain(self) -> None:
|
||||
"""Close the remote session before the server's announced restart, so its drain can end, then open a new one."""
|
||||
"""Release the remote session before the server's announced restart, so its drain can end, then open a new one."""
|
||||
with self._reopen_lock:
|
||||
self.log.info("The remote server restarts for an update, reopening the session after it")
|
||||
self.close()
|
||||
self.lifetime.release()
|
||||
self._current_title = None
|
||||
if not self.reopen():
|
||||
raise RemoteError(
|
||||
@@ -1345,11 +1350,6 @@ class RemoteService(TitleSource):
|
||||
if self.channel:
|
||||
self.channel.drain_logs()
|
||||
|
||||
def close_channel(self) -> None:
|
||||
channel, self.channel = self.channel, None
|
||||
if channel:
|
||||
channel.close()
|
||||
|
||||
def get_titles(self) -> Titles_T:
|
||||
if self._titles is not None:
|
||||
return self._titles
|
||||
@@ -1851,22 +1851,12 @@ class RemoteService(TitleSource):
|
||||
) from None
|
||||
|
||||
def close(self) -> None:
|
||||
# a long-lived serve opens many of these; the atexit hook would keep every one alive
|
||||
atexit.unregister(self.close)
|
||||
self.close_channel()
|
||||
session_id, self._session_id = self._session_id, None
|
||||
if session_id:
|
||||
try:
|
||||
with quiet():
|
||||
result = cast(SessionClosed, self.client.delete(SESSION_ROUTE.format(session_id=session_id)))
|
||||
profile = self.ctx.parent.params.get("profile") if self.ctx.parent else None
|
||||
self.save_returned_cache(result.get("cache", {}), profile)
|
||||
except SystemExit:
|
||||
pass
|
||||
except Exception as e:
|
||||
self.log.warning(f"Failed to clean up remote session: {e}")
|
||||
if self.client.tunnel:
|
||||
self.client.tunnel.stop()
|
||||
"""End the remote session for good. dl, the job worker and the relay pool all end it here."""
|
||||
self.lifetime.end()
|
||||
|
||||
def save_session_cache(self, cache_data: dict[str, str]) -> None:
|
||||
"""Save the cache files that the DELETE of the remote session returns."""
|
||||
self.save_returned_cache(cache_data, self.ctx.parent.params.get("profile") if self.ctx.parent else None)
|
||||
|
||||
def save_returned_cache(self, cache_data: dict[str, str], profile: str | None = None) -> None:
|
||||
"""Save cache files returned by the server to the local cache directory.
|
||||
|
||||
Reference in New Issue
Block a user