diff --git a/downloads.py b/downloads.py index 8bfa7f7..0b14190 100644 --- a/downloads.py +++ b/downloads.py @@ -55,6 +55,20 @@ _MODEL_EXTS = (".safetensors", ".pt", ".ckpt", ".bin", ".pth") # Record progress at most every this many bytes. _PROGRESS_STEP = 512 * 1024 +# Per-file concurrency for the Range-parted downloader. Saturating a fast NIC +# (RunPod boxes typically have 1–10 Gbps) requires multiple parallel TCP +# streams — a single HTTP/1.1 connection caps at ~200–400 MB/s after TLS + +# CivitAI's per-connection throttling. The default of 8 has been a good +# tradeoff in testing; bump via env if you're on a 10 Gbps host. +_CONNECTIONS = max(1, int(os.environ.get("IMAGELAB_DOWNLOAD_CONNECTIONS", "8") or "8")) +# Minimum size before we even try to part the download — parting a 1 MB file +# adds latency for no throughput win. CivitAI files of interest are all 100s +# of MB or GBs anyway. +_PART_THRESHOLD = 16 * 1024 * 1024 +# Per-connection read chunk. 1 MB strikes a balance between syscall overhead +# and how quickly we react to cancellation. +_CHUNK = 1024 * 1024 + class CivitaiError(Exception): """A CivitAI/download failure carrying an HTTP status for the API layer.""" @@ -217,37 +231,28 @@ async def _run_download(version_id: int, folder: Optional[str], filename: Option download_url += ("&" if "?" in download_url else "?") + f"token={token}" os.makedirs(target_dir, exist_ok=True) - last_mark = 0 - async with aiohttp.ClientSession() as session: - async with session.get( - download_url, - timeout=aiohttp.ClientTimeout(total=None, connect=30), - allow_redirects=True, - ) as res: - if res.status in (401, 403): - raise CivitaiError("Download requires a valid CIVITAI_TOKEN", "AUTH_ERROR", 401) - if res.status != 200: - raise CivitaiError(f"Download failed: HTTP {res.status}", "DOWNLOAD_FAILED", 502) + # Decide single-stream vs. Range-parted up front. CivitAI typically + # 302s to a CloudFront URL which does support Range, but the first + # response we get is from civitai.com — follow redirects with a HEAD + # so we read the final origin's headers (Accept-Ranges, Content-Length). + connector = aiohttp.TCPConnector(limit=_CONNECTIONS * 2, ttl_dns_cache=300) + timeout = aiohttp.ClientTimeout(total=None, connect=30, sock_read=120) + async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session: + head_total, supports_range = await _probe_url(session, download_url) + if head_total > 0: + progress.total_bytes = head_total - content_length = res.headers.get("Content-Length") - if content_length: - progress.total_bytes = int(content_length) + if supports_range and head_total >= _PART_THRESHOLD and _CONNECTIONS > 1: + await _download_parted(session, download_url, temp_path, head_total, version_id, progress) + else: + await _download_single(session, download_url, temp_path, version_id, progress) - with open(temp_path, "wb") as fh: - async for chunk in res.content.iter_chunked(65536): - if version_id in _cancelled: - progress.status = "cancelled" - progress.updated_at = time.time() - fh.close() - if os.path.exists(temp_path): - os.remove(temp_path) - return - fh.write(chunk) - progress.downloaded_bytes += len(chunk) - if progress.downloaded_bytes - last_mark >= _PROGRESS_STEP: - last_mark = progress.downloaded_bytes - progress.updated_at = time.time() + # Caller's cancel-during-download path: bail out before atomic swap. + if progress.status == "cancelled": + if os.path.exists(temp_path): + os.remove(temp_path) + return # Atomically swap the completed file into place. if os.path.exists(target_path): @@ -284,6 +289,140 @@ async def _run_download(version_id: int, folder: Optional[str], filename: Option _tasks.pop(version_id, None) +async def _probe_url(session: aiohttp.ClientSession, url: str) -> tuple[int, bool]: + """HEAD the final-redirect URL to learn total size + Range support. + Returns (total_bytes, supports_range). 0 / False on any uncertainty — + callers fall back to a plain GET stream.""" + try: + async with session.head(url, allow_redirects=True) as res: + if res.status >= 400: + return 0, False + length = res.headers.get("Content-Length") + accept = (res.headers.get("Accept-Ranges") or "").lower() + total = int(length) if length and length.isdigit() else 0 + return total, accept == "bytes" + except Exception: + return 0, False + + +async def _download_single( + session: aiohttp.ClientSession, + url: str, + temp_path: str, + version_id: int, + progress: "DownloadProgress", +) -> None: + """Fallback path — one connection, stream into the temp file. Used when + the origin doesn't advertise Range support or the file's too small to + benefit from parting.""" + last_mark = 0 + async with session.get(url, allow_redirects=True) as res: + if res.status in (401, 403): + raise CivitaiError("Download requires a valid CIVITAI_TOKEN", "AUTH_ERROR", 401) + if res.status != 200: + raise CivitaiError(f"Download failed: HTTP {res.status}", "DOWNLOAD_FAILED", 502) + if progress.total_bytes == 0: + cl = res.headers.get("Content-Length") + if cl and cl.isdigit(): + progress.total_bytes = int(cl) + + with open(temp_path, "wb") as fh: + async for chunk in res.content.iter_chunked(_CHUNK): + if version_id in _cancelled: + progress.status = "cancelled" + progress.updated_at = time.time() + return + fh.write(chunk) + progress.downloaded_bytes += len(chunk) + if progress.downloaded_bytes - last_mark >= _PROGRESS_STEP: + last_mark = progress.downloaded_bytes + progress.updated_at = time.time() + + +async def _download_parted( + session: aiohttp.ClientSession, + url: str, + temp_path: str, + total: int, + version_id: int, + progress: "DownloadProgress", +) -> None: + """Multi-connection downloader. Pre-allocates the temp file at full size, + then fires N concurrent Range requests writing to disjoint offsets. Speeds + are tracked via the shared progress object — every part advances the same + counter, so the popover's MB/s reflects total throughput across parts. + + Cancellation: each part checks `_cancelled` between chunks and returns + early; the gather() below propagates the first error, after which we + leave the .downloading file in place for `_cleanup_temp` to remove.""" + parts = _CONNECTIONS + part_size = (total + parts - 1) // parts # ceil-divide + ranges: list[tuple[int, int]] = [] + for i in range(parts): + start = i * part_size + end = min(start + part_size - 1, total - 1) + if start <= end: + ranges.append((start, end)) + + # Pre-allocate the temp file so parallel pwrites land at the right place. + with open(temp_path, "wb") as fh: + fh.truncate(total) + + # We open one file descriptor per part — pwrite (via os.pwrite) is + # threadsafe and the kernel orders the writes correctly. fd is closed + # below regardless of which part failed. + fd = os.open(temp_path, os.O_WRONLY) + try: + last_mark_lock = asyncio.Lock() + last_mark = [0] + + async def _fetch_range(start: int, end: int) -> None: + headers = {"Range": f"bytes={start}-{end}"} + offset = start + async with session.get(url, headers=headers, allow_redirects=True) as res: + if res.status in (401, 403): + raise CivitaiError("Download requires a valid CIVITAI_TOKEN", "AUTH_ERROR", 401) + # 206 = Partial Content (good); 200 = the origin ignored our + # Range and is sending the whole file → bail and let single + # stream retry handle it. + if res.status == 200: + raise CivitaiError("Server ignored Range header", "NO_RANGE", 502) + if res.status != 206: + raise CivitaiError(f"Range request failed: HTTP {res.status}", "DOWNLOAD_FAILED", 502) + + async for chunk in res.content.iter_chunked(_CHUNK): + if version_id in _cancelled: + progress.status = "cancelled" + progress.updated_at = time.time() + return + # pwrite is blocking — small writes, but keep them off the loop. + await asyncio.to_thread(os.pwrite, fd, chunk, offset) + offset += len(chunk) + progress.downloaded_bytes += len(chunk) + if progress.downloaded_bytes - last_mark[0] >= _PROGRESS_STEP: + async with last_mark_lock: + if progress.downloaded_bytes - last_mark[0] >= _PROGRESS_STEP: + last_mark[0] = progress.downloaded_bytes + progress.updated_at = time.time() + + try: + await asyncio.gather(*(_fetch_range(s, e) for s, e in ranges)) + except CivitaiError as e: + # If the server lied about Range support, retry once with the + # single-stream path so the user still gets the file. + if e.code == "NO_RANGE": + print(f"[ImageLab] Parted download fell back to single-stream for {progress.filename}") + progress.downloaded_bytes = 0 + await _download_single(session, url, temp_path, version_id, progress) + return + raise + finally: + try: + os.close(fd) + except OSError: + pass + + def _cleanup_temp(target_dir: Optional[str], filename: str) -> None: if not target_dir: return