feat(session): replace curl_cffi with rnet for TLS-fingerprinted HTTP

Replace CurlSession (curl_cffi) with RnetSession powered by rnet (Rust/BoringSSL). Benchmarks show 3.5x faster segmented downloads (1.06 GB/s vs 304 MB/s) and 16% faster single-file downloads with near-zero TLS fingerprinting overhead.

- Add RnetSession wrapper with requests-compatible API (headers, cookies, proxies, retry logic, prepared requests)
- Add RnetResponse wrapper normalizing rnet quirks (status_code as int, text as property, bytes-to-str headers, iter_content re-chunking)
- Replace CurlSession isinstance checks across manifests, tracks, DRM
- Update downloader with rnet native streaming path and byte-based progress tracking for accurate Rich progress bars
- Add speed display column to Rich progress bar (DASH/HLS/URL prefix)
- Add rnet dependency, services use exact preset names (e.g. OkHttp4_12)
This commit is contained in:
Andy
2026-03-24 10:08:17 -06:00
parent 6840944738
commit 99be88dc08
11 changed files with 790 additions and 424 deletions
+162 -110
View File
@@ -1,7 +1,6 @@
import math
import os
import time
from collections import deque
from concurrent.futures import FIRST_COMPLETED, wait
from concurrent.futures.thread import ThreadPoolExecutor
from http.cookiejar import CookieJar
@@ -39,19 +38,24 @@ def _is_requests_session(session: Any) -> bool:
return isinstance(session, Session)
def _is_rnet_session(session: Any) -> bool:
"""Check if the session is an RnetSession (uses resp.stream())."""
from unshackle.core.session import RnetSession
return isinstance(session, RnetSession)
def download(
url: str,
save_path: Path,
session: Optional[Any] = None,
segmented: bool = False,
_speed_tracker: Optional[dict] = None,
**kwargs: Any,
) -> Generator[dict[str, Any], None, None]:
"""
Download a file with optimized I/O.
Supports both requests.Session and curl_cffi CurlSession for TLS fingerprinting.
Uses raw socket reads for requests.Session (30-35% faster) and iter_content for CurlSession.
Supports both requests.Session and RnetSession for TLS fingerprinting.
Uses raw socket reads for requests.Session and native rnet streaming for RnetSession.
Yields the following download status updates while chunks are downloading:
@@ -65,19 +69,15 @@ def download(
url: Web URL of a file to download.
save_path: The path to save the file to. If the save path's directory does not
exist then it will be made automatically.
session: A requests.Session or curl_cffi CurlSession to make HTTP requests with.
CurlSession preserves TLS fingerprinting for services that need it.
session: A requests.Session or RnetSession to make HTTP requests with.
RnetSession preserves TLS fingerprinting for services that need it.
segmented: If downloads are segments or parts of one bigger file.
_speed_tracker: Shared speed tracking state for this download batch (per-call, not global).
kwargs: Any extra keyword arguments to pass to the session.get() call. Use this
for one-time request changes like a header, cookie, or proxy. For example,
to request Byte-ranges use e.g., `headers={"Range": "bytes=0-128"}`.
"""
session = session or Session()
if _speed_tracker is None:
_speed_tracker = {"sizes": deque(), "last_refresh": time.time()}
save_dir = save_path.parent
control_file = save_path.with_name(f"{save_path.name}.!dev")
@@ -100,22 +100,26 @@ def download(
last_speed_refresh = _time()
try:
use_rnet = _is_rnet_session(session)
stream = session.get(url, stream=True, **kwargs)
stream.raise_for_status()
# Determine content length and adaptive chunk size
try:
content_length = int(stream.headers.get("Content-Length", "0"))
if stream.headers.get("Content-Encoding", "").lower() in ["gzip", "deflate", "br"]:
if use_rnet:
content_length = stream.content_length or 0
else:
try:
content_length = int(stream.headers.get("Content-Length", "0"))
if stream.headers.get("Content-Encoding", "").lower() in ["gzip", "deflate", "br"]:
content_length = 0
except ValueError:
content_length = 0
except ValueError:
content_length = 0
chunk_size = _adaptive_chunk_size(content_length)
if not segmented:
if content_length > 0:
yield dict(total=math.ceil(content_length / chunk_size))
yield dict(total=content_length)
else:
yield dict(total=None)
@@ -128,8 +132,12 @@ def download(
# Cache f.write for hot loop
_write = f.write
# Build chunk iterator — raw reads for requests.Session, iter_content for CurlSession
if use_raw:
# Build chunk iterator based on session type
if use_rnet:
# rnet: native Rust streaming — 3.5x faster than curl_cffi (benchmarked)
chunks = stream.stream()
elif use_raw:
# requests.Session: raw socket read — 30-35% faster than iter_content
stream.raw.decode_content = False
_read = stream.raw.read
@@ -143,6 +151,7 @@ def download(
chunks = _chunks()
else:
# Fallback: iter_content
def _chunks_iter() -> Generator[bytes, None, None]:
yield from stream.iter_content(chunk_size=chunk_size)
stream.close()
@@ -151,22 +160,31 @@ def download(
# Unified write + progress loop
_data_accumulated = 0
_bytes_since_yield = 0
for chunk in chunks:
if DOWNLOAD_CANCELLED.is_set():
break
_write(chunk)
download_size = len(chunk)
written += download_size
if not segmented:
yield dict(advance=1)
_bytes_since_yield += download_size
_data_accumulated += download_size
now = _time()
time_since = now - last_speed_refresh
_data_accumulated += download_size
if time_since > PROGRESS_WINDOW or download_size < chunk_size:
if time_since > PROGRESS_WINDOW:
yield dict(advance=_bytes_since_yield)
_bytes_since_yield = 0
download_speed = math.ceil(_data_accumulated / (time_since or 1))
yield dict(downloaded=f"{filesize.decimal(download_speed)}/s")
last_speed_refresh = now
_data_accumulated = 0
# Flush any remaining bytes
if not segmented and _bytes_since_yield > 0:
yield dict(advance=_bytes_since_yield)
# Truncate to actual written size in case pre-allocation overshot
if content_length > 0 and written != content_length:
f.truncate(written)
@@ -178,21 +196,6 @@ def download(
if segmented:
yield dict(advance=1)
now = _time()
sizes = _speed_tracker["sizes"]
if written:
sizes.append((now, written))
cutoff = now - SPEED_ROLLING_WINDOW
while sizes and sizes[0][0] < cutoff:
sizes.popleft()
time_since = now - _speed_tracker["last_refresh"]
if sizes and time_since > PROGRESS_WINDOW:
window_start = sizes[0][0]
window_duration = now - window_start
data_size = sum(size for _, size in sizes)
download_speed = math.ceil(data_size / (window_duration or 1))
yield dict(downloaded=f"{filesize.decimal(download_speed)}/s")
_speed_tracker["last_refresh"] = now
break
except Exception as e:
save_path.unlink(missing_ok=True)
@@ -217,7 +220,7 @@ def requests(
"""
Download files with optimized I/O and adaptive chunk sizing.
Supports both requests.Session and curl_cffi CurlSession. When a CurlSession is
Supports both requests.Session and RnetSession. When a RnetSession is
provided (e.g. from a service's get_session()), TLS fingerprinting is preserved
on all segment downloads.
@@ -245,7 +248,7 @@ def requests(
proxy: An optional proxy URI to route connections through for all downloads.
max_workers: The maximum amount of threads to use for downloads. Defaults to
min(12,(cpu_count+4)).
session: An optional requests.Session or curl_cffi CurlSession to use. If provided,
session: An optional requests.Session or RnetSession to use. If provided,
it will be used directly (preserving TLS fingerprinting). If None, a new
requests.Session with HTTPAdapter connection pooling will be created.
"""
@@ -293,7 +296,7 @@ def requests(
]
# Use provided session or create a new optimized requests.Session
# When a session is provided (e.g., service's CurlSession), don't mutate headers/cookies/proxy —
# When a session is provided (e.g., service's RnetSession), don't mutate headers/cookies/proxy —
# they're already set and the session may be shared across tracks.
if session is None:
session = Session()
@@ -331,93 +334,142 @@ def requests(
)
segmented_batch = len(urls) > 1
if segmented_batch:
yield dict(total=len(urls))
# Per-call speed tracker — shared across threads within this call only
speed_tracker: dict[str, Any] = {"sizes": deque(), "last_refresh": time.time()}
try:
# Fast path: single URL — no thread pool overhead
if len(urls) == 1:
# Fast path: single URL — no thread pool overhead
if len(urls) == 1:
try:
yield from download(
session=session,
segmented=segmented_batch,
_speed_tracker=speed_tracker,
**urls[0],
)
else:
with ThreadPoolExecutor(max_workers=max_workers) as pool:
event_queue: Queue[dict[str, Any]] = Queue()
except KeyboardInterrupt:
DOWNLOAD_CANCELLED.set()
yield dict(downloaded="[yellow]CANCELLED")
raise
else:
# Segmented download with thread pool
# Speed is tracked here on the main thread, not in workers
total_bytes = 0
start_time = time.time()
last_speed_report = start_time
def _download_worker(url_item: dict[str, Any]) -> None:
for event in download(
session=session,
segmented=segmented_batch,
_speed_tracker=speed_tracker,
**url_item,
):
event_queue.put(event)
pool = ThreadPoolExecutor(max_workers=max_workers)
event_queue: Queue[dict[str, Any]] = Queue()
futures = [pool.submit(_download_worker, url) for url in urls]
pending = set(futures)
def _download_worker(url_item: dict[str, Any]) -> None:
for event in download(
session=session,
segmented=segmented_batch,
**url_item,
):
event_queue.put(event)
while pending:
# Drain queued progress updates for responsive UI
while True:
try:
yield event_queue.get_nowait()
except Empty:
break
futures = [pool.submit(_download_worker, url) for url in urls]
pending = set(futures)
# Wait efficiently for next future completion (OS condition variable)
completed, pending = wait(pending, timeout=0.1, return_when=FIRST_COMPLETED)
for future in completed:
exc = future.exception()
if isinstance(exc, KeyboardInterrupt):
DOWNLOAD_CANCELLED.set()
yield dict(downloaded="[yellow]CANCELLING")
pool.shutdown(wait=True, cancel_futures=True)
yield dict(downloaded="[yellow]CANCELLED")
raise exc
elif exc:
DOWNLOAD_CANCELLED.set()
yield dict(downloaded="[red]FAILING")
pool.shutdown(wait=True, cancel_futures=True)
yield dict(downloaded="[red]FAILED")
if debug_logger:
debug_logger.log(
level="ERROR",
operation="downloader_failed",
message=f"Download failed: {exc}",
error=exc,
context={
"url_count": len(urls),
"output_dir": str(output_dir),
},
)
raise exc
pending_advance = 0
# Drain any remaining events from workers that just finished
try:
while pending:
# Drain queued events — batch advances, track bytes for speed
while True:
try:
yield event_queue.get_nowait()
event = event_queue.get_nowait()
except Empty:
break
# Accumulate advance events for batched yield
advance = event.get("advance")
if advance:
pending_advance += advance
continue
# Track bytes from completed segments for speed calculation
written = event.get("written")
if written:
total_bytes += written
# Pass through other events (file_downloaded, total, etc.)
yield event
if debug_logger:
debug_logger.log(
level="DEBUG",
operation="downloader_complete",
message="Download completed successfully",
context={
"url_count": len(urls),
"output_dir": str(output_dir),
"filename": filename,
},
)
finally:
speed_tracker["sizes"].clear()
# Yield batched advances every drain cycle for responsive progress bar
if pending_advance > 0:
yield dict(advance=pending_advance)
pending_advance = 0
# Yield speed every 0.5s (throttled to avoid spamming Rich)
now = time.time()
if now - last_speed_report > 0.5 and total_bytes > 0:
elapsed = now - start_time
if elapsed > 0:
download_speed = math.ceil(total_bytes / elapsed)
yield dict(downloaded=f"{filesize.decimal(download_speed)}/s")
last_speed_report = now
# Wait efficiently for next future completion (OS condition variable)
completed, pending = wait(pending, timeout=0.1, return_when=FIRST_COMPLETED)
for future in completed:
exc = future.exception()
if isinstance(exc, KeyboardInterrupt):
raise KeyboardInterrupt()
elif exc:
DOWNLOAD_CANCELLED.set()
yield dict(downloaded="[red]FAILING")
pool.shutdown(wait=False, cancel_futures=True)
yield dict(downloaded="[red]FAILED")
if debug_logger:
debug_logger.log(
level="ERROR",
operation="downloader_failed",
message=f"Download failed: {exc}",
error=exc,
context={
"url_count": len(urls),
"output_dir": str(output_dir),
},
)
raise exc
except KeyboardInterrupt:
DOWNLOAD_CANCELLED.set()
yield dict(downloaded="[yellow]CANCELLING")
pool.shutdown(wait=False, cancel_futures=True)
yield dict(downloaded="[yellow]CANCELLED")
raise
finally:
pool.shutdown(wait=False, cancel_futures=True)
# Drain remaining events
while True:
try:
event = event_queue.get_nowait()
except Empty:
break
advance = event.get("advance")
if advance:
pending_advance += advance
continue
written = event.get("written")
if written:
total_bytes += written
yield event
# Flush remaining advances and final speed
if pending_advance > 0:
yield dict(advance=pending_advance)
elapsed = time.time() - start_time
if elapsed > 0 and total_bytes > 0:
download_speed = math.ceil(total_bytes / elapsed)
yield dict(downloaded=f"{filesize.decimal(download_speed)}/s")
if debug_logger:
debug_logger.log(
level="DEBUG",
operation="downloader_complete",
message="Download completed successfully",
context={
"url_count": len(urls),
"output_dir": str(output_dir),
"filename": filename,
},
)
__all__ = ("requests",)