refactor(downloader): build every progress speed string with format_speed

This commit is contained in:
imSp4rky
2026-12-04 15:50:22 -07:00
parent cc40deeb5c
commit a788f4d7b2
3 changed files with 23 additions and 9 deletions
@@ -1,9 +1,14 @@
import itertools
import math
import sys import sys
import threading import threading
import time
import types
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest import pytest
import requests as rq import requests as rq
from rich import filesize
from unshackle.core.constants import DOWNLOAD_CANCELLED from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.downloaders.requests import download from unshackle.core.downloaders.requests import download
@@ -91,3 +96,13 @@ def test_a_cut_body_bounds_the_following_requests(tmp_path, server):
assert spans and all(int(end) - int(start) + 1 <= CHUNK for start, end in spans) assert spans and all(int(end) - int(start) + 1 <= CHUNK for start, end in spans)
# the bounded requests are cheap because they share one pooled connection # the bounded requests are cheap because they share one pooled connection
assert server.connections < len(server.ranges) assert server.connections < len(server.ranges)
def test_each_speed_line_is_the_window_rate_rounded_up(tmp_path, server, monkeypatch):
clock = itertools.count(step=11.0)
monkeypatch.setattr(downloader, "time", types.SimpleNamespace(**{**vars(time), "monotonic": lambda: next(clock)}))
events = list(download(url=server.url, save_path=tmp_path / "0.mp4", session=rq.Session()))
pairs = [(events[i - 1]["advance"], e["downloaded"]) for i, e in enumerate(events) if "downloaded" in e]
assert any(n % 11 for n, _ in pairs)
assert all(text == f"{filesize.decimal(math.ceil(n / 11))}/s" for n, text in pairs)
+1
View File
@@ -56,6 +56,7 @@ def test_parse_speed_limit_rejects(value):
("rate", "expected"), ("rate", "expected"),
[ [
(500, "500 bytes/s"), (500, "500 bytes/s"),
(999.2, "1.0 kB/s"),
(512_000, "512.0 kB/s"), (512_000, "512.0 kB/s"),
(39 * 1024**2, "40.9 MB/s"), (39 * 1024**2, "40.9 MB/s"),
(1.5 * 1024**3, "1.6 GB/s"), (1.5 * 1024**3, "1.6 GB/s"),
+7 -9
View File
@@ -174,7 +174,7 @@ def parse_speed_limit(value: str | int | float | None) -> float | None:
def format_speed(bytes_per_sec: float) -> str: def format_speed(bytes_per_sec: float) -> str:
"""Format a byte rate in the same decimal units the progress bars show.""" """Format a byte rate in the same decimal units the progress bars show."""
return f"{filesize.decimal(int(bytes_per_sec))}/s" return f"{filesize.decimal(math.ceil(bytes_per_sec))}/s"
def set_speed_limit(bytes_per_sec: float | None) -> None: def set_speed_limit(bytes_per_sec: float | None) -> None:
@@ -807,7 +807,7 @@ def dispatch_parts(
if now - last_report > 0.5 and total_bytes > 0: if now - last_report > 0.5 and total_bytes > 0:
rate = speed_window.rate(now, total_bytes) rate = speed_window.rate(now, total_bytes)
if rate: if rate:
yield {"downloaded": f"{filesize.decimal(math.ceil(rate))}/s"} yield {"downloaded": format_speed(rate)}
last_report = now last_report = now
done, pending = wait(pending, timeout=0.1, return_when=FIRST_COMPLETED) done, pending = wait(pending, timeout=0.1, return_when=FIRST_COMPLETED)
@@ -1096,8 +1096,7 @@ def download(
yield dict(advance=_bytes_since_yield) yield dict(advance=_bytes_since_yield)
_bytes_since_yield = 0 _bytes_since_yield = 0
if not part_mode: if not part_mode:
download_speed = math.ceil(_data_accumulated / (time_since or 1)) yield dict(downloaded=format_speed(_data_accumulated / (time_since or 1)))
yield dict(downloaded=f"{filesize.decimal(download_speed)}/s")
last_speed_refresh = now last_speed_refresh = now
_data_accumulated = 0 _data_accumulated = 0
@@ -1489,7 +1488,7 @@ def download_multiprocess(
if now - last_speed_report > 0.5 and total_bytes > 0: if now - last_speed_report > 0.5 and total_bytes > 0:
rate = speed_window.rate(now, total_bytes) rate = speed_window.rate(now, total_bytes)
if rate: if rate:
yield dict(downloaded=f"{filesize.decimal(math.ceil(rate))}/s") yield dict(downloaded=format_speed(rate))
last_speed_report = now last_speed_report = now
except KeyboardInterrupt: except KeyboardInterrupt:
DOWNLOAD_CANCELLED.set() DOWNLOAD_CANCELLED.set()
@@ -2089,12 +2088,12 @@ def requests(
if controller: if controller:
rolling = controller.speed(now) rolling = controller.speed(now)
if rolling > 0: if rolling > 0:
yield dict(downloaded=f"{filesize.decimal(math.ceil(rolling))}/s") yield dict(downloaded=format_speed(rolling))
last_speed_report = now last_speed_report = now
elif total_bytes > 0: elif total_bytes > 0:
rate = speed_window.rate(now, total_bytes) rate = speed_window.rate(now, total_bytes)
if rate: if rate:
yield dict(downloaded=f"{filesize.decimal(math.ceil(rate))}/s") yield dict(downloaded=format_speed(rate))
last_speed_report = now last_speed_report = now
# hedge stuck segments once spare workers exist within the active target; # hedge stuck segments once spare workers exist within the active target;
@@ -2201,8 +2200,7 @@ def requests(
yield dict(advance=pending_advance) yield dict(advance=pending_advance)
elapsed = time.monotonic() - start_time elapsed = time.monotonic() - start_time
if elapsed > 0 and total_bytes > 0: if elapsed > 0 and total_bytes > 0:
download_speed = math.ceil(total_bytes / elapsed) yield dict(downloaded=format_speed(total_bytes / elapsed))
yield dict(downloaded=f"{filesize.decimal(download_speed)}/s")
if DOWNLOAD_CANCELLED.is_set(): if DOWNLOAD_CANCELLED.is_set():
raise DownloadCancelled() raise DownloadCancelled()