From 4afc4f7a04c6e5e71158690662aaf337772bcbe5 Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Wed, 2 Dec 2026 14:28:48 -0700 Subject: [PATCH] fix(dl): time elapsed lines, downloader and proxy waits with time.monotonic --- tests/core/test_download_archive_loop.py | 21 +++++++++++++++++ unshackle/commands/dl.py | 12 +++++----- unshackle/core/downloaders/requests.py | 30 ++++++++++++------------ unshackle/core/proxies/expressvpn.py | 4 ++-- unshackle/core/proxies/gluetun.py | 24 +++++++++---------- unshackle/core/utilities.py | 4 ++-- 6 files changed, 58 insertions(+), 37 deletions(-) diff --git a/tests/core/test_download_archive_loop.py b/tests/core/test_download_archive_loop.py index cf30027c..7dbc889d 100644 --- a/tests/core/test_download_archive_loop.py +++ b/tests/core/test_download_archive_loop.py @@ -2,6 +2,8 @@ import inspect import logging +import re +import time from pathlib import Path from types import SimpleNamespace @@ -10,6 +12,7 @@ import requests from unshackle.commands.dl import dl from unshackle.core.config import config +from unshackle.core.console import console from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS from unshackle.core.download_archive import DownloadArchive @@ -269,3 +272,21 @@ def test_partial_publication_of_multiple_variants_does_not_record(monkeypatch, r run(quality=[720, 1080]) assert len(published) == 1 and published[0].exists() assert not DownloadArchive(config.directories.cache).path.exists() + + +def test_wall_clock_step_back_prints_no_negative_elapsed_time(run, monkeypatch): + import unshackle.commands.dl as module + + download = module.download_tracks_in_passes + wall = time.time + + def download_then_step_back(*args, **kwargs): + download(*args, **kwargs) + monkeypatch.setattr(time, "time", lambda: wall() - 3) + + monkeypatch.setattr(module, "download_tracks_in_passes", download_then_step_back) + with console.capture() as captured: + run() + elapsed = re.findall(r"(?:finished|downloaded|titles) in (-?[\dhms]+)", captured.get()) + assert len(elapsed) == 3 + assert all(re.fullmatch(r"0m\d+s", value) for value in elapsed), elapsed diff --git a/unshackle/commands/dl.py b/unshackle/commands/dl.py index e39f67b8..c6adb1bc 100644 --- a/unshackle/commands/dl.py +++ b/unshackle/commands/dl.py @@ -1607,7 +1607,7 @@ class dl: if self.cdm_override and service.key_arrival is KeyArrival.EXPORT: self.log.warning("--cdm is ignored: an import uses the keys in the export") self._remote_service = service.key_source - start_time = time.time() + start_time = time.monotonic() lang, lang_excl = partition_exclusions(lang) v_lang, v_lang_excl = partition_exclusions(v_lang) @@ -1817,7 +1817,7 @@ class dl: if select_titles and isinstance(titles, Movies) and len(titles) > 1: console.print(Padding(Rule("[rule.text]Select Titles"), (1, 2))) - selection_start = time.time() + selection_start = time.monotonic() selected_idx = select_multiple( [str(movie) for movie in titles], minimal_count=1, @@ -1827,7 +1827,7 @@ class dl: if not selected_idx: console.print(Padding(":x: Selection Cancelled...", (0, 5, 1, 5))) return self.outcome() - start_time += time.time() - selection_start + start_time += time.monotonic() - selection_start keep = set(selected_idx) for i in range(len(titles) - 1, -1, -1): @@ -1874,7 +1874,7 @@ class dl: if current_season_header_idx != -1: dependencies[current_season_header_idx].append(current_ui_idx) - selection_start = time.time() + selection_start = time.monotonic() selected_ui_idx = select_multiple( selection_titles, @@ -1889,7 +1889,7 @@ class dl: console.print(Padding(":x: Selection Cancelled...", (0, 5, 1, 5))) return self.outcome() - selection_end = time.time() + selection_end = time.monotonic() start_time += selection_end - selection_start selected_idx = [] @@ -2317,7 +2317,7 @@ class dl: disk_check = None if skip_dl or sample else DiskCheck(title.tracks, self.log.warning) - dl_start_time = time.time() + dl_start_time = time.monotonic() try: with SyncLive(Padding(download_table, (1, 5)), console=console, refresh_per_second=20): diff --git a/unshackle/core/downloaders/requests.py b/unshackle/core/downloaders/requests.py index 287e6c5a..932d279e 100644 --- a/unshackle/core/downloaders/requests.py +++ b/unshackle/core/downloaders/requests.py @@ -703,7 +703,7 @@ def dispatch_parts( yield {"total": total_size} total_bytes = 0 - last_report = time.time() + last_report = time.monotonic() speed_window = SpeedWindow(last_report) completed = False worker_error = False @@ -723,7 +723,7 @@ def dispatch_parts( total_bytes += advance yield {"advance": advance} - now = time.time() + now = time.monotonic() if now - last_report > 0.5 and total_bytes > 0: rate = speed_window.rate(now, total_bytes) if rate: @@ -862,7 +862,7 @@ def download( elif tmp_file.exists(): resume_offset = tmp_file.stat().st_size - _time = time.time + _time = time.monotonic use_raw = is_requests_session(session) item_range = has_range_header(kwargs) @@ -1475,7 +1475,7 @@ def download_multiprocess( yield dict(advance=skipped) total_bytes = 0 - start_time = time.time() + start_time = time.monotonic() last_speed_report = start_time speed_window = SpeedWindow(start_time) done_count = 0 @@ -1535,7 +1535,7 @@ def download_multiprocess( yield dict(advance=1) yield event - now = time.time() + now = time.monotonic() if now - last_speed_report > 0.5 and total_bytes > 0: rate = speed_window.rate(now, total_bytes) if rate: @@ -1839,7 +1839,7 @@ def requests( raise else: total_bytes = 0 - start_time = time.time() + start_time = time.monotonic() last_speed_report = start_time speed_window = SpeedWindow(start_time) last_hedge_check = 0.0 @@ -1878,7 +1878,7 @@ def requests( # gain by starting low. error-burst backoff and AIMD recovery still apply from there. controller = AdaptiveWorkerController(cap=max_workers, start=max_workers) if adaptive else None # feed CDN error signals (429/timeout/reset) from each retrying segment into the controller - on_retry_cb = (lambda _exc: controller.record_error(time.time())) if controller else None + on_retry_cb = (lambda _exc: controller.record_error(time.monotonic())) if controller else None def download_worker(index: int, url_item: dict[str, Any], hedge: bool = False) -> None: item = dict(url_item) @@ -1898,7 +1898,7 @@ def requests( # under seg_lock: the hedge scan iterates seg_start.items() on the main # thread, and a first-time key insert during that iteration raises with seg_lock: - seg_start[index] = time.time() + seg_start[index] = time.monotonic() for event in download( session=session, segmented=segmented_batch, @@ -1920,7 +1920,7 @@ def requests( return seg_done.add(index) if not hedge: - seg_durations.append(time.time() - seg_start[index]) + seg_durations.append(time.monotonic() - seg_start[index]) os.replace(target, save_path) event = dict(event, file_downloaded=save_path) event_queue.put(event) @@ -2006,7 +2006,7 @@ def requests( part_target.unlink(missing_ok=True) return seg_done.add(index) - seg_durations.append(time.time() - seg_start[index]) + seg_durations.append(time.monotonic() - seg_start[index]) os.replace(part_target, save_path) event_queue.put(dict(file_downloaded=save_path, written=size)) event_queue.put(dict(advance=1)) @@ -2061,7 +2061,7 @@ def requests( part_target = save_path.with_name(f"{save_path.name}.tp.!dev") with open(part_target, "wb") as f: f.truncate(size) - seg_start[index] = time.time() + seg_start[index] = time.monotonic() tail_boosted.add(index) abort = threading.Event() part_aborts.append(abort) @@ -2089,7 +2089,7 @@ def requests( queue_depth = submission_window(max_workers) if controller: - submit(controller.update(time.time(), len(remaining))) + submit(controller.update(time.monotonic(), len(remaining))) else: submit(queue_depth) @@ -2110,7 +2110,7 @@ def requests( if written: total_bytes += written if controller: - controller.record_bytes(written, time.time()) + controller.record_bytes(written, time.monotonic()) yield event if pending_advance > 0: @@ -2120,7 +2120,7 @@ def requests( if DOWNLOAD_CANCELLED.is_set(): remaining.clear() - now = time.time() + now = time.monotonic() target = max_workers if controller: @@ -2249,7 +2249,7 @@ def requests( if pending_advance > 0: yield dict(advance=pending_advance) - elapsed = time.time() - start_time + elapsed = time.monotonic() - 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") diff --git a/unshackle/core/proxies/expressvpn.py b/unshackle/core/proxies/expressvpn.py index c61e8a44..1b9613b8 100644 --- a/unshackle/core/proxies/expressvpn.py +++ b/unshackle/core/proxies/expressvpn.py @@ -362,8 +362,8 @@ class ExpressVPN(Proxy): ) interval = int(data.get("interval") or 5) - deadline = time.time() + int(data.get("expires_in") or self.DEVICE_POLL_TIMEOUT) - while time.time() < deadline: + deadline = time.monotonic() + int(data.get("expires_in") or self.DEVICE_POLL_TIMEOUT) + while time.monotonic() < deadline: time.sleep(interval) poll = self.request( "POST", diff --git a/unshackle/core/proxies/gluetun.py b/unshackle/core/proxies/gluetun.py index a3b33517..e9ca896a 100644 --- a/unshackle/core/proxies/gluetun.py +++ b/unshackle/core/proxies/gluetun.py @@ -609,7 +609,7 @@ class Gluetun(Proxy): to Docker with --env-file, never as "-e KEY=VALUE" arguments, so the credentials stay out of process listings. unshackle overwrites and deletes the file once "docker run" returns. """ - start_time = time.time() + start_time = time.monotonic() log_event( "gluetun_container_create_start", @@ -764,7 +764,7 @@ class Gluetun(Proxy): message=f"Docker run timed out for {container_name}", context={"container_name": container_name}, success=False, - duration_ms=(time.time() - start_time) * 1000, + duration_ms=(time.monotonic() - start_time) * 1000, ) raise RuntimeError("Docker run command timed out") from None @@ -780,7 +780,7 @@ class Gluetun(Proxy): "stderr": error_msg, }, success=False, - duration_ms=(time.time() - start_time) * 1000, + duration_ms=(time.monotonic() - start_time) * 1000, ) raise RuntimeError(f"Docker run failed: {error_msg}") @@ -799,7 +799,7 @@ class Gluetun(Proxy): "container_id": result.stdout.strip()[:12] if result.stdout else None, }, success=True, - duration_ms=(time.time() - start_time) * 1000, + duration_ms=(time.monotonic() - start_time) * 1000, ) finally: if env_file_path: @@ -941,7 +941,7 @@ class Gluetun(Proxy): Returns: True if container is ready, False if it failed or timed out """ - start_time = time.time() + start_time = time.monotonic() last_error = None log_event( @@ -951,7 +951,7 @@ class Gluetun(Proxy): context={"container_name": container_name, "timeout": timeout}, ) - while time.time() - start_time < timeout: + while time.monotonic() - start_time < timeout: try: if not self.is_container_running(container_name): exit_info = self.get_container_exit_info(container_name) @@ -982,7 +982,7 @@ class Gluetun(Proxy): if proxy_ready and vpn_ready: # Give a brief moment for the proxy to fully initialize time.sleep(1) - duration_ms = (time.time() - start_time) * 1000 + duration_ms = (time.monotonic() - start_time) * 1000 log_event( "gluetun_container_ready", level="INFO", @@ -1023,7 +1023,7 @@ class Gluetun(Proxy): if last_error: self._last_wait_error = last_error - duration_ms = (time.time() - start_time) * 1000 + duration_ms = (time.monotonic() - start_time) * 1000 log_event( "gluetun_container_wait_timeout", level="ERROR", @@ -1090,7 +1090,7 @@ class Gluetun(Proxy): RuntimeError: If the IP resolves to a country other than the expected one, which aborts at once with no further retries, or if verification still fails after every retry """ - start_time = time.time() + start_time = time.monotonic() if query_key not in self.active_containers: return @@ -1134,7 +1134,7 @@ class Gluetun(Proxy): expected_code = expected_code.upper() if actual_country != expected_code: - duration_ms = (time.time() - start_time) * 1000 + duration_ms = (time.monotonic() - start_time) * 1000 log_event( "gluetun_verify_mismatch", level="ERROR", @@ -1162,7 +1162,7 @@ class Gluetun(Proxy): self.active_containers[query_key]["ip_city"] = ip_info.get("city") self.active_containers[query_key]["ip_org"] = ip_info.get("org") - duration_ms = (time.time() - start_time) * 1000 + duration_ms = (time.monotonic() - start_time) * 1000 log_event( "gluetun_verify_success", level="INFO", @@ -1206,7 +1206,7 @@ class Gluetun(Proxy): except Exception: pass - duration_ms = (time.time() - start_time) * 1000 + duration_ms = (time.monotonic() - start_time) * 1000 log_event( "gluetun_verify_failed", level="ERROR", diff --git a/unshackle/core/utilities.py b/unshackle/core/utilities.py index 2a4532d8..659b10a2 100644 --- a/unshackle/core/utilities.py +++ b/unshackle/core/utilities.py @@ -681,10 +681,10 @@ def get_country_code(name: str) -> str | None: def time_elapsed_since(start: float) -> str: """ - Get time elapsed since a timestamp as a string. + Get time elapsed since a `time.monotonic()` timestamp as a string. E.g., `1h56m2s`, `15m12s`, `0m55s`, e.t.c. """ - elapsed = int(time.time() - start) + elapsed = int(time.monotonic() - start) minutes, seconds = divmod(elapsed, 60) hours, minutes = divmod(minutes, 60)