forked from kenzuya/unshackle
Merge branch 'dev' into feat/downloader-speed
Catch the branch up with dev (45 commits) so testers can run the perf work against current dev. Conflict resolutions: - downloaders/requests.py: keep the branch's racing-gated read1, adaptive controller speed reporting and byte-range slice guards; take dev's content-encoding checks (raw reads are skipped on an encoded body) and its rolling SpeedWindow for the no-controller speed fallback. The single-URL ranged-parallel gate now requires no speed limit and no caller Range. - service.py / session.py: keep the branch's TimeoutHTTPAdapter and retry config, raise POOL_MAX_SIZE to 64 so dev's pool-starvation fix survives (pool_block=True stalls threads on a pool smaller than the in-flight count). - docs: dev split configuration.md into per-area pages, so the branch's rnet network option rows moved to reference/configuration/network.md.
This commit is contained in:
@@ -1,3 +1,3 @@
|
||||
from .requests import requests
|
||||
from .requests import format_speed, parse_speed_limit, requests, set_speed_limit
|
||||
|
||||
__all__ = ("requests",)
|
||||
__all__ = ("requests", "format_speed", "parse_speed_limit", "set_speed_limit")
|
||||
|
||||
@@ -2,6 +2,7 @@ import math
|
||||
import multiprocessing
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import socket
|
||||
import statistics
|
||||
import sys
|
||||
@@ -60,6 +61,104 @@ TAIL_BOOST_MIN_SEGMENT_SIZE = 8 * 1024 * 1024 # don't probe+split segments smal
|
||||
TAIL_BOOST_PART_SIZE = 4 * 1024 * 1024 # target size per tail part (smaller than the whole-file part size)
|
||||
|
||||
|
||||
class SpeedWindow:
|
||||
"""Rolling-window download rate over the last SPEED_ROLLING_WINDOW seconds."""
|
||||
|
||||
def __init__(self, start: float) -> None:
|
||||
# zero-byte seed keeps early readings from exceeding the true rate
|
||||
self.samples: deque[tuple[float, int]] = deque([(start, 0)])
|
||||
|
||||
def rate(self, now: float, total: int) -> Optional[float]:
|
||||
self.samples.append((now, total))
|
||||
while now - self.samples[0][0] > SPEED_ROLLING_WINDOW:
|
||||
self.samples.popleft()
|
||||
span = now - self.samples[0][0]
|
||||
delta = total - self.samples[0][1]
|
||||
if span <= 0 or delta <= 0:
|
||||
return None
|
||||
return delta / span
|
||||
|
||||
|
||||
class TokenBucket:
|
||||
"""Aggregate byte-rate limiter shared by every download thread."""
|
||||
|
||||
def __init__(self, rate: float) -> None:
|
||||
self.rate = rate
|
||||
self.capacity = rate
|
||||
self.tokens = 0.0
|
||||
self.ts = time.monotonic()
|
||||
self.lock = threading.Lock()
|
||||
|
||||
def consume(self, n: int) -> None:
|
||||
# tokens may go negative; waiting for n > capacity would deadlock
|
||||
with self.lock:
|
||||
now = time.monotonic()
|
||||
self.tokens = min(self.capacity, self.tokens + (now - self.ts) * self.rate)
|
||||
self.ts = now
|
||||
self.tokens -= n
|
||||
wait = -self.tokens / self.rate if self.tokens < 0 else 0.0
|
||||
if wait > 0:
|
||||
DOWNLOAD_CANCELLED.wait(wait)
|
||||
|
||||
|
||||
_speed_limiter: Optional[TokenBucket] = None
|
||||
_speed_limit_locked = False
|
||||
|
||||
SPEED_UNITS = {
|
||||
"": 1,
|
||||
"b": 1,
|
||||
"k": 1_000,
|
||||
"kb": 1_000,
|
||||
"m": 1_000_000,
|
||||
"mb": 1_000_000,
|
||||
"g": 1_000_000_000,
|
||||
"gb": 1_000_000_000,
|
||||
}
|
||||
|
||||
|
||||
def parse_speed_limit(value: Union[str, int, float, None]) -> Optional[float]:
|
||||
"""
|
||||
Parse a human-readable speed limit into bytes/sec, or None for unlimited.
|
||||
|
||||
Accepts plain numbers (exact bytes/sec) or a decimal suffix with optional
|
||||
/s, case-insensitive: "500k", "5M", "10MB/s", "1.5G", 5000000. Suffixes
|
||||
match the displayed speeds (5M = 5.0 MB/s); values are bytes, not bits.
|
||||
"", 0, "off", "none" and "unlimited" mean no limit.
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, (int, float)):
|
||||
if not math.isfinite(value) or value < 0:
|
||||
raise ValueError(f"Invalid speed limit {value!r}: must be a positive number of bytes/sec.")
|
||||
return float(value) or None
|
||||
text = value.strip().lower().removesuffix("/s")
|
||||
if text in ("", "0", "off", "none", "unlimited"):
|
||||
return None
|
||||
match = re.fullmatch(r"(\d*\.?\d+)\s*([kmg]b?|b)?", text)
|
||||
if not match:
|
||||
raise ValueError(f"Invalid speed limit {value!r}: use e.g. 500k, 5M, 1.5G, plain bytes/sec, or 'off'.")
|
||||
return float(match.group(1)) * SPEED_UNITS[match.group(2) or ""]
|
||||
|
||||
|
||||
def format_speed(bytes_per_sec: float) -> str:
|
||||
"""Format a byte rate in the same decimal units the progress bars show."""
|
||||
return f"{filesize.decimal(int(bytes_per_sec))}/s"
|
||||
|
||||
|
||||
def set_speed_limit(bytes_per_sec: Optional[float], lock: bool = False) -> None:
|
||||
"""
|
||||
Set (or clear) the global download speed limit shared by all threads.
|
||||
|
||||
A locked limit (serve's global_speed_limit) wins: later unlocked calls,
|
||||
like the per-job one in dl.result(), become no-ops for the process.
|
||||
"""
|
||||
global _speed_limiter, _speed_limit_locked
|
||||
if _speed_limit_locked and not lock:
|
||||
return
|
||||
_speed_limit_locked = lock
|
||||
_speed_limiter = TokenBucket(bytes_per_sec) if bytes_per_sec else None
|
||||
|
||||
|
||||
def _adaptive_chunk_size(content_length: int) -> int:
|
||||
"""Pick chunk size based on content length. Benchmarked sweet spot: 512KB-4MB."""
|
||||
if content_length <= 0:
|
||||
@@ -257,6 +356,18 @@ def _is_rnet_session(session: Any) -> bool:
|
||||
return isinstance(session, RnetSession)
|
||||
|
||||
|
||||
def _is_content_encoded(value: Optional[str]) -> bool:
|
||||
"""
|
||||
Check a Content-Encoding value for any coding other than absent or `identity`.
|
||||
|
||||
Reading .raw skips urllib3's decoding, so an encoded body has to go through
|
||||
iter_content or the compressed bytes land on disk as the payload. Codings
|
||||
urllib3 cannot decode still count: an allowlist fails open on whatever token
|
||||
a server sends next, and the cost of guessing wrong is a corrupt file.
|
||||
"""
|
||||
return any(coding.strip() not in ("", "identity") for coding in (value or "").lower().split(","))
|
||||
|
||||
|
||||
def _probe_ranged(url: str, session: Any, **kwargs: Any) -> tuple[int, bool]:
|
||||
headers = {**(kwargs.get("headers") or {}), "Range": "bytes=0-0"}
|
||||
rest = {k: v for k, v in kwargs.items() if k != "headers"}
|
||||
@@ -273,8 +384,7 @@ def _probe_ranged(url: str, session: Any, **kwargs: Any) -> tuple[int, bool]:
|
||||
try:
|
||||
if resp.status_code != 206:
|
||||
return 0, False
|
||||
ce = (resp.headers.get("Content-Encoding") or resp.headers.get("content-encoding") or "").lower()
|
||||
if ce in ("gzip", "deflate", "br"):
|
||||
if _is_content_encoded(resp.headers.get("Content-Encoding") or resp.headers.get("content-encoding")):
|
||||
return 0, False
|
||||
content_range = resp.headers.get("Content-Range") or resp.headers.get("content-range") or ""
|
||||
total = content_range.rsplit("/", 1)[-1].strip()
|
||||
@@ -389,7 +499,8 @@ def _dispatch_parts(
|
||||
yield {"total": total_size}
|
||||
|
||||
total_bytes = 0
|
||||
start_time = last_report = time.time()
|
||||
last_report = time.time()
|
||||
speed_window = SpeedWindow(last_report)
|
||||
completed = False
|
||||
worker_error = False
|
||||
|
||||
@@ -410,7 +521,9 @@ def _dispatch_parts(
|
||||
|
||||
now = time.time()
|
||||
if now - last_report > 0.5 and total_bytes > 0:
|
||||
yield {"downloaded": f"{filesize.decimal(math.ceil(total_bytes / (now - start_time)))}/s"}
|
||||
rate = speed_window.rate(now, total_bytes)
|
||||
if rate:
|
||||
yield {"downloaded": f"{filesize.decimal(math.ceil(rate))}/s"}
|
||||
last_report = now
|
||||
|
||||
done, pending = wait(pending, timeout=0.1, return_when=FIRST_COMPLETED)
|
||||
@@ -469,7 +582,8 @@ def download(
|
||||
Download a file with optimized I/O.
|
||||
|
||||
Supports both requests.Session and RnetSession for TLS fingerprinting.
|
||||
Uses raw socket reads for requests.Session and native rnet streaming for RnetSession.
|
||||
RnetSession streams natively; requests.Session reads the raw socket, except
|
||||
on a content-encoded body, which has to go through iter_content to be decoded.
|
||||
|
||||
Yields the following download status updates while chunks are downloading:
|
||||
|
||||
@@ -600,20 +714,34 @@ def download(
|
||||
# server ignored the slice's Range and sent the whole parent; writing that
|
||||
# as the segment would silently corrupt the merge, so fail the attempt
|
||||
raise IOError(f"expected 206 for byte-range segment, got {stream.status_code}")
|
||||
content_encoded = False
|
||||
if use_rnet:
|
||||
content_length = stream.content_length or 0
|
||||
ce = (stream.headers.get("Content-Encoding") or stream.headers.get("content-encoding") or "").lower()
|
||||
if ce in ("gzip", "deflate", "br"):
|
||||
content_length = 0
|
||||
else:
|
||||
content_encoded = _is_content_encoded(stream.headers.get("Content-Encoding"))
|
||||
try:
|
||||
content_length = int(stream.headers.get("Content-Length", "0"))
|
||||
if stream.headers.get("Content-Encoding", "").lower() in ["gzip", "deflate", "br"]:
|
||||
if content_encoded:
|
||||
content_length = 0
|
||||
except ValueError:
|
||||
content_length = 0
|
||||
|
||||
if resumed and content_encoded:
|
||||
try:
|
||||
stream.close()
|
||||
except Exception:
|
||||
pass
|
||||
tmp_file.unlink(missing_ok=True)
|
||||
resume_offset = 0
|
||||
continue
|
||||
|
||||
limiter = _speed_limiter
|
||||
chunk_size = _adaptive_chunk_size(content_length)
|
||||
if limiter:
|
||||
chunk_size = min(chunk_size, max(8192, int(limiter.rate / 4)))
|
||||
total_size = (resume_offset + content_length) if resumed and content_length > 0 else content_length
|
||||
|
||||
if not segmented and not part_mode:
|
||||
@@ -643,7 +771,7 @@ def download(
|
||||
|
||||
if use_rnet:
|
||||
chunks = stream.stream()
|
||||
elif use_raw:
|
||||
elif use_raw and not content_encoded:
|
||||
_read1 = getattr(stream.raw, "read1", None) if claimed is not None else None
|
||||
if _read1 is not None and racing is not None:
|
||||
# only pay the per-arrival read1 tax while this segment is actually
|
||||
@@ -672,6 +800,8 @@ def download(
|
||||
except Exception:
|
||||
pass
|
||||
return
|
||||
if limiter is not None:
|
||||
limiter.consume(len(chunk))
|
||||
_write(chunk)
|
||||
download_size = len(chunk)
|
||||
written += download_size
|
||||
@@ -1136,9 +1266,8 @@ def requests(
|
||||
# once per batch; download() skips it for segments
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Use provided session or create a new optimized requests.Session
|
||||
# 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.
|
||||
# Provided sessions may be shared across tracks: don't mutate or remount them. Remounting
|
||||
# drops the service's 429/5xx Retry config and races get_adapter() in other track threads.
|
||||
if session is None:
|
||||
session = Session()
|
||||
if headers:
|
||||
@@ -1148,10 +1277,6 @@ def requests(
|
||||
session.cookies.update(cookies)
|
||||
if proxy:
|
||||
session.proxies.update({"all": proxy})
|
||||
|
||||
# Mount HTTPAdapter with connection pooling sized to worker count.
|
||||
# Safe to do on any requests.Session — improves connection reuse for parallel downloads.
|
||||
if _is_requests_session(session):
|
||||
adapter = HTTPAdapter(pool_connections=max_workers, pool_maxsize=max_workers, pool_block=True)
|
||||
session.mount("https://", adapter)
|
||||
session.mount("http://", adapter)
|
||||
@@ -1181,7 +1306,7 @@ def requests(
|
||||
url_item = urls[0]
|
||||
try:
|
||||
ranged_used = False
|
||||
if max_workers > 1 and not _has_range_header(url_item):
|
||||
if max_workers > 1 and _speed_limiter is None and not _has_range_header(url_item):
|
||||
total_size, supports_ranges = _probe_ranged(url_item["url"], session)
|
||||
if supports_ranges and total_size >= RANGE_PARALLEL_MIN_SIZE:
|
||||
try:
|
||||
@@ -1219,6 +1344,7 @@ def requests(
|
||||
total_bytes = 0
|
||||
start_time = time.time()
|
||||
last_speed_report = start_time
|
||||
speed_window = SpeedWindow(start_time)
|
||||
last_hedge_check = 0.0
|
||||
hedge_median = 0.0 # cached; recomputed only when seg_durations grows
|
||||
hedge_median_len = 0
|
||||
@@ -1512,10 +1638,9 @@ def requests(
|
||||
yield dict(downloaded=f"{filesize.decimal(math.ceil(rolling))}/s")
|
||||
last_speed_report = now
|
||||
elif 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")
|
||||
rate = speed_window.rate(now, total_bytes)
|
||||
if rate:
|
||||
yield dict(downloaded=f"{filesize.decimal(math.ceil(rate))}/s")
|
||||
last_speed_report = now
|
||||
|
||||
# hedge stuck segments once spare workers exist within the active target;
|
||||
@@ -1523,6 +1648,7 @@ def requests(
|
||||
if (
|
||||
len(pending) < target
|
||||
and seg_durations
|
||||
and _speed_limiter is None
|
||||
and now - last_hedge_check > 0.5
|
||||
and not DOWNLOAD_CANCELLED.is_set()
|
||||
):
|
||||
@@ -1630,4 +1756,4 @@ def requests(
|
||||
)
|
||||
|
||||
|
||||
__all__ = ("requests",)
|
||||
__all__ = ("requests", "format_speed", "parse_speed_limit", "set_speed_limit")
|
||||
|
||||
Reference in New Issue
Block a user