mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-24 18:05:07 +00:00
fix(vaults): stop querying sibling KIDs and skip unavailable vaults
The server CDM stub names only the manifest's KIDs; sibling keys stay content keys. API and HTTP vaults retry a 429, and a vault that is down or still rate limited costs one timeout per run.
This commit is contained in:
@@ -38,7 +38,7 @@ from unshackle.core.config import config
|
||||
from unshackle.core.console import console, prompt_user
|
||||
from unshackle.core.constants import AnyTrack
|
||||
from unshackle.core.credential import Credential
|
||||
from unshackle.core.drm import cbcs
|
||||
from unshackle.core.drm import cbcs, real_kids
|
||||
from unshackle.core.proxies.resolve import is_loopback
|
||||
from unshackle.core.session import MAX_BACKOFF
|
||||
from unshackle.core.titles import Title_T, Titles_T, remap_titles
|
||||
@@ -303,7 +303,8 @@ def reconstruct_drm(drm_list: Optional[list]) -> list:
|
||||
from unshackle.core.drm import Widevine
|
||||
|
||||
wv_pssh = WidevinePSSH(pssh_str)
|
||||
result.append(Widevine(pssh=wv_pssh))
|
||||
kids = drm_info.get("kids")
|
||||
result.append(Widevine(pssh=wv_pssh, kid=kids[0] if kids and not wv_pssh.key_ids else None))
|
||||
elif drm_type == "playready":
|
||||
import base64 as b64
|
||||
|
||||
@@ -1542,9 +1543,9 @@ class RemoteService:
|
||||
self.log.warning(f"Server CDM returned no content keys for track {track.id}")
|
||||
continue
|
||||
|
||||
kid_list = list(track_keys.keys())
|
||||
named = {kid.hex for drm in track.drm or [] for kid in real_kids(drm)} & track_keys.keys()
|
||||
track_drm_type = drm_types_by_track.get(str(track.id), server_drm_type)
|
||||
drm_obj = self.create_drm_stub(track_drm_type, kid_list)
|
||||
drm_obj = self.create_drm_stub(track_drm_type, sorted(named) or list(track_keys))
|
||||
for kid_hex, key_hex in track_keys.items():
|
||||
drm_obj.content_keys[UUID(hex=kid_hex)] = key_hex
|
||||
track.drm = [drm_obj]
|
||||
|
||||
@@ -2,6 +2,46 @@ from abc import ABCMeta, abstractmethod
|
||||
from typing import Iterator, Optional, Union
|
||||
from uuid import UUID
|
||||
|
||||
from requests import ConnectionError as RequestsConnectionError
|
||||
from requests import Session, Timeout
|
||||
from requests.adapters import HTTPAdapter
|
||||
from urllib3.util.retry import Retry
|
||||
|
||||
from unshackle.core import __version__
|
||||
from unshackle.core.session import POOL_MAX_SIZE
|
||||
|
||||
|
||||
class RateLimited(Exception):
|
||||
"""The vault still answered 429 after the retries."""
|
||||
|
||||
|
||||
UNREACHABLE = (RequestsConnectionError, Timeout, ConnectionError, TimeoutError)
|
||||
|
||||
|
||||
def vault_session(timeout: float) -> Session:
|
||||
"""An HTTP session for a remote vault that retries a 429 and nothing else.
|
||||
|
||||
A 429 means the request was not processed, so a POST is safe to send again. A connect or read
|
||||
failure is not retried: a lookup waits on every remote vault, so a retry multiplies the timeout.
|
||||
"""
|
||||
retry = Retry(
|
||||
total=3,
|
||||
connect=0,
|
||||
read=0,
|
||||
other=0,
|
||||
backoff_factor=0.5,
|
||||
status_forcelist=[429],
|
||||
allowed_methods=None,
|
||||
retry_after_max=int(timeout),
|
||||
raise_on_status=False,
|
||||
)
|
||||
session = Session()
|
||||
adapter = HTTPAdapter(pool_connections=POOL_MAX_SIZE, pool_maxsize=POOL_MAX_SIZE, max_retries=retry)
|
||||
session.mount("https://", adapter)
|
||||
session.mount("http://", adapter)
|
||||
session.headers.update({"User-Agent": f"unshackle v{__version__}"})
|
||||
return session
|
||||
|
||||
|
||||
class Vault(metaclass=ABCMeta):
|
||||
# a vault on this machine; Vaults.get_key tries these first, before the network ones
|
||||
|
||||
@@ -8,7 +8,7 @@ from uuid import UUID
|
||||
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.utilities import get_debug_logger, import_module_by_path
|
||||
from unshackle.core.vault import Vault
|
||||
from unshackle.core.vault import UNREACHABLE, RateLimited, Vault
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
@@ -29,6 +29,7 @@ class Vaults:
|
||||
self.flagged: set[tuple[Union[UUID, str], str]] = set()
|
||||
self.candidates: dict[Union[UUID, str], list[tuple[str, Vault]]] = {}
|
||||
self.warned: set[tuple[str, Union[UUID, str], str]] = set()
|
||||
self.unreachable: set[Vault] = set()
|
||||
|
||||
def __iter__(self) -> Iterator[Vault]:
|
||||
return iter(self.vaults)
|
||||
@@ -70,7 +71,7 @@ class Vaults:
|
||||
and the first one with the content key wins.
|
||||
"""
|
||||
local = [v for v in self.vaults if v.local]
|
||||
remote = [v for v in self.vaults if not v.local]
|
||||
remote = [v for v in self.live() if not v.local]
|
||||
for vault in local:
|
||||
key = self.query_vault(vault, kid)
|
||||
if key:
|
||||
@@ -123,6 +124,7 @@ class Vaults:
|
||||
return None
|
||||
except Exception as e:
|
||||
log.warning(f"Failed to get key from Vault '{vault.name}': {e}")
|
||||
self.mark_unreachable(vault, e)
|
||||
if dl:
|
||||
dl.log_vault_query(
|
||||
vault.name,
|
||||
@@ -160,7 +162,7 @@ class Vaults:
|
||||
"""
|
||||
self.flagged.add((kid, key))
|
||||
source = self.sources.pop(kid, None)
|
||||
for vault in self.vaults:
|
||||
for vault in self.live():
|
||||
if not vault.local and (source is None or vault is not source[1]):
|
||||
continue
|
||||
try:
|
||||
@@ -171,7 +173,7 @@ class Vaults:
|
||||
def unflag_bad_key(self, kid: Union[UUID, str], key: str) -> None:
|
||||
"""Remove a flag from every Vault."""
|
||||
self.flagged.discard((kid, key))
|
||||
for vault in self.vaults:
|
||||
for vault in self.live():
|
||||
try:
|
||||
vault.unflag_bad_key(kid, key)
|
||||
except Exception as e:
|
||||
@@ -183,7 +185,7 @@ class Vaults:
|
||||
This method pushes to all Vaults at the same time, so one unreachable Vault costs only its
|
||||
own timeout and does not delay the others.
|
||||
"""
|
||||
vaults = [vault for vault in self.vaults if vault != excluding and not vault.no_push]
|
||||
vaults = [v for v in self.live() if v != excluding and not v.no_push]
|
||||
if not vaults:
|
||||
return 0
|
||||
with ThreadPoolExecutor(len(vaults), thread_name_prefix="vault-push") as pool:
|
||||
@@ -201,6 +203,7 @@ class Vaults:
|
||||
return 0
|
||||
except Exception as e:
|
||||
log.warning(f"Failed to add key to Vault '{vault.name}': {e}")
|
||||
self.mark_unreachable(vault, e)
|
||||
if dl:
|
||||
dl.log_vault_query(vault.name, "add_key", kid=str(kid), success=False, error=e)
|
||||
return 0
|
||||
@@ -214,7 +217,7 @@ class Vaults:
|
||||
This method pushes to all Vaults at the same time, so one unreachable Vault costs only its
|
||||
own timeout and does not delay the others.
|
||||
"""
|
||||
vaults = [vault for vault in self.vaults if not vault.no_push]
|
||||
vaults = [vault for vault in self.live() if not vault.no_push]
|
||||
if not vaults:
|
||||
return 0
|
||||
with ThreadPoolExecutor(len(vaults), thread_name_prefix="vault-push") as pool:
|
||||
@@ -229,7 +232,23 @@ class Vaults:
|
||||
return 0
|
||||
except Exception as e:
|
||||
log.warning(f"Failed to add keys to Vault '{vault.name}': {e}")
|
||||
self.mark_unreachable(vault, e)
|
||||
return 0
|
||||
|
||||
def live(self) -> list[Vault]:
|
||||
"""The vaults this run still uses."""
|
||||
return [vault for vault in self.vaults if vault not in self.unreachable]
|
||||
|
||||
def held_locally(self, kid: Union[UUID, str], key: str) -> bool:
|
||||
"""True when a local vault already holds this KID:KEY."""
|
||||
return any(self.query_vault(vault, kid) == key for vault in self.vaults if vault.local)
|
||||
|
||||
def mark_unreachable(self, vault: Vault, error: Exception) -> None:
|
||||
"""Skip a vault that is down or still rate limited for the rest of the run, so it costs one
|
||||
timeout, not one per KID."""
|
||||
if isinstance(error, (RateLimited, *UNREACHABLE)) and vault not in self.unreachable:
|
||||
self.unreachable.add(vault)
|
||||
log.warning(f"Vault '{vault.name}' is unavailable, so this run does not use it again")
|
||||
|
||||
|
||||
__all__ = ("Vaults",)
|
||||
|
||||
Reference in New Issue
Block a user