mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-24 18:05:07 +00:00
perf(dl): parallelise mux, licensing, and vault lookups; size the shared pool
Grow the service session pool to downloads * workers before track downloads, run mkvmerge jobs concurrently (muxing.concurrency, default 4), lock DRM preparation per key set instead of globally, and query local vaults first then remote vaults together.
This commit is contained in:
@@ -1,3 +1,3 @@
|
||||
from .requests import format_speed, parse_speed_limit, requests, set_speed_limit
|
||||
from .requests import default_max_workers, format_speed, parse_speed_limit, requests, set_speed_limit
|
||||
|
||||
__all__ = ("requests", "format_speed", "parse_speed_limit", "set_speed_limit")
|
||||
__all__ = ("requests", "default_max_workers", "format_speed", "parse_speed_limit", "set_speed_limit")
|
||||
|
||||
@@ -1019,6 +1019,11 @@ def build_session_spec(session: Optional[Any]) -> Optional[dict[str, Any]]:
|
||||
return None
|
||||
|
||||
|
||||
def default_max_workers() -> int:
|
||||
"""Return the per-track worker count to use when the caller gives none."""
|
||||
return min(16, (os.cpu_count() or 1) + 4)
|
||||
|
||||
|
||||
def rebuild_session(spec: dict[str, Any], max_workers: int) -> Optional[Any]:
|
||||
"""Reconstruct an HTTP session inside a child process from a spec built by ``build_session_spec``.
|
||||
|
||||
@@ -1343,7 +1348,7 @@ def requests(
|
||||
urls = [urls]
|
||||
|
||||
if not max_workers:
|
||||
max_workers = min(16, (os.cpu_count() or 1) + 4)
|
||||
max_workers = default_max_workers()
|
||||
|
||||
# A spawned child re-imports this module and would start with no TokenBucket, so the
|
||||
# configured cap would silently stop applying; the cap wins over the fan-out, matching
|
||||
|
||||
@@ -82,6 +82,31 @@ class TimeoutHTTPAdapter(HTTPAdapter):
|
||||
return super().send(request, **kwargs)
|
||||
|
||||
|
||||
def grow_session_pool(session: Any, size: int) -> None:
|
||||
"""Grow a shared requests session's connection pool to ``size`` before track downloads start.
|
||||
|
||||
The worker threads of every track draw on this one pool, because the downloader never
|
||||
remounts an HTTP session the caller passes in (see downloaders/requests.py). The pool must hold
|
||||
``downloads * workers`` connections, or threads queue for a slot instead of reading.
|
||||
Call this before any download thread exists: a remount races with other threads that call
|
||||
``get_adapter``. RnetSession does not block on its idle-pool cap, so this function skips it.
|
||||
"""
|
||||
if not isinstance(session, requests.Session):
|
||||
return
|
||||
adapter = session.get_adapter("https://")
|
||||
if not isinstance(adapter, HTTPAdapter) or getattr(adapter, "_pool_maxsize", 0) >= size:
|
||||
return
|
||||
grown = TimeoutHTTPAdapter(
|
||||
max_retries=adapter.max_retries,
|
||||
pool_connections=size,
|
||||
pool_maxsize=size,
|
||||
pool_block=True,
|
||||
timeout=getattr(adapter, "default_timeout", DEFAULT_TIMEOUT),
|
||||
)
|
||||
session.mount("https://", grown)
|
||||
session.mount("http://", grown)
|
||||
|
||||
|
||||
@dataclass
|
||||
class TrackRequest:
|
||||
"""Holds what the user requested for video codec and range selection.
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import threading
|
||||
from abc import ABC
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterable, Optional, Union
|
||||
@@ -120,7 +122,10 @@ class Chapters(SortedKeyList, ABC):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
ogm_text = self.dumps(*args, **kwargs)
|
||||
return path.write_text(ogm_text, encoding="utf8")
|
||||
tmp = path.with_name(f"{path.name}.{os.getpid()}.{threading.get_ident()}.tmp")
|
||||
written = tmp.write_text(ogm_text, encoding="utf8")
|
||||
os.replace(tmp, path)
|
||||
return written
|
||||
|
||||
def add(self, value: Chapter) -> None:
|
||||
if not isinstance(value, Chapter):
|
||||
|
||||
@@ -4,6 +4,9 @@ from uuid import UUID
|
||||
|
||||
|
||||
class Vault(metaclass=ABCMeta):
|
||||
# a vault on this machine; Vaults.get_key tries these first, before the network ones
|
||||
local: bool = False
|
||||
|
||||
def __init__(self, name: str, no_push: bool = False):
|
||||
self.name = name
|
||||
self.no_push = no_push
|
||||
|
||||
+49
-25
@@ -1,6 +1,7 @@
|
||||
import inspect
|
||||
import logging
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from typing import Any, Iterator, Optional, Union
|
||||
from uuid import UUID
|
||||
|
||||
@@ -56,39 +57,62 @@ class Vaults:
|
||||
self.vaults.append(vault)
|
||||
|
||||
def get_key(self, kid: Union[UUID, str]) -> tuple[Optional[str], Optional[Vault]]:
|
||||
"""Get Key from the first Vault it can by KID (Key ID) and Service."""
|
||||
"""Get Key from the first Vault it can by KID (Key ID) and Service.
|
||||
|
||||
Local vaults go first, one at a time: a hit there costs nothing and skips the network.
|
||||
The remaining vaults run at the same time, 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]
|
||||
for vault in local:
|
||||
key = self.query_vault(vault, kid)
|
||||
if key:
|
||||
return key, vault
|
||||
if not remote:
|
||||
return None, None
|
||||
pool = ThreadPoolExecutor(len(remote))
|
||||
try:
|
||||
futures = {pool.submit(self.query_vault, vault, kid): vault for vault in remote}
|
||||
for future in as_completed(futures):
|
||||
key = future.result()
|
||||
if key:
|
||||
return key, futures[future]
|
||||
return None, None
|
||||
finally:
|
||||
# a slow vault must not hold up a content key another vault already returned
|
||||
pool.shutdown(wait=False, cancel_futures=True)
|
||||
|
||||
def query_vault(self, vault: Vault, kid: Union[UUID, str]) -> Optional[str]:
|
||||
"""Ask one vault for a content key. A failure logs a warning and returns None."""
|
||||
dl = get_debug_logger()
|
||||
for vault in self.vaults:
|
||||
start = time.monotonic()
|
||||
try:
|
||||
key = vault.get_key(kid, self.service)
|
||||
except (PermissionError, NotImplementedError):
|
||||
continue
|
||||
except Exception as e:
|
||||
log.warning(f"Failed to get key from Vault '{vault.name}': {e}")
|
||||
if dl:
|
||||
dl.log_vault_query(
|
||||
vault.name,
|
||||
"get_key",
|
||||
kid=str(kid),
|
||||
reachable=False,
|
||||
error=e,
|
||||
duration_ms=round((time.monotonic() - start) * 1000, 1),
|
||||
)
|
||||
continue
|
||||
found = bool(key and key.count("0") != len(key))
|
||||
start = time.monotonic()
|
||||
try:
|
||||
key = vault.get_key(kid, self.service)
|
||||
except (PermissionError, NotImplementedError):
|
||||
return None
|
||||
except Exception as e:
|
||||
log.warning(f"Failed to get key from Vault '{vault.name}': {e}")
|
||||
if dl:
|
||||
dl.log_vault_query(
|
||||
vault.name,
|
||||
"get_key",
|
||||
kid=str(kid),
|
||||
key_found=found,
|
||||
reachable=True,
|
||||
reachable=False,
|
||||
error=e,
|
||||
duration_ms=round((time.monotonic() - start) * 1000, 1),
|
||||
)
|
||||
if found:
|
||||
return key, vault
|
||||
return None, None
|
||||
return None
|
||||
found = bool(key and key.count("0") != len(key))
|
||||
if dl:
|
||||
dl.log_vault_query(
|
||||
vault.name,
|
||||
"get_key",
|
||||
kid=str(kid),
|
||||
key_found=found,
|
||||
reachable=True,
|
||||
duration_ms=round((time.monotonic() - start) * 1000, 1),
|
||||
)
|
||||
return key if found else None
|
||||
|
||||
def add_key(self, kid: Union[UUID, str], key: str, excluding: Optional[Vault] = None) -> int:
|
||||
"""Add a KID:KEY to all Vaults, optionally with an exclusion."""
|
||||
|
||||
Reference in New Issue
Block a user