fix(dl): time elapsed lines, downloader and proxy waits with time.monotonic

This commit is contained in:
imSp4rky
2026-12-02 15:23:59 -07:00
parent ac4425cdca
commit 4afc4f7a04
6 changed files with 58 additions and 37 deletions
+21
View File
@@ -2,6 +2,8 @@
import inspect import inspect
import logging import logging
import re
import time
from pathlib import Path from pathlib import Path
from types import SimpleNamespace from types import SimpleNamespace
@@ -10,6 +12,7 @@ import requests
from unshackle.commands.dl import dl from unshackle.commands.dl import dl
from unshackle.core.config import config 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.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY
from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS
from unshackle.core.download_archive import DownloadArchive 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]) run(quality=[720, 1080])
assert len(published) == 1 and published[0].exists() assert len(published) == 1 and published[0].exists()
assert not DownloadArchive(config.directories.cache).path.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
+6 -6
View File
@@ -1607,7 +1607,7 @@ class dl:
if self.cdm_override and service.key_arrival is KeyArrival.EXPORT: 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.log.warning("--cdm is ignored: an import uses the keys in the export")
self._remote_service = service.key_source self._remote_service = service.key_source
start_time = time.time() start_time = time.monotonic()
lang, lang_excl = partition_exclusions(lang) lang, lang_excl = partition_exclusions(lang)
v_lang, v_lang_excl = partition_exclusions(v_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: if select_titles and isinstance(titles, Movies) and len(titles) > 1:
console.print(Padding(Rule("[rule.text]Select Titles"), (1, 2))) console.print(Padding(Rule("[rule.text]Select Titles"), (1, 2)))
selection_start = time.time() selection_start = time.monotonic()
selected_idx = select_multiple( selected_idx = select_multiple(
[str(movie) for movie in titles], [str(movie) for movie in titles],
minimal_count=1, minimal_count=1,
@@ -1827,7 +1827,7 @@ class dl:
if not selected_idx: if not selected_idx:
console.print(Padding(":x: Selection Cancelled...", (0, 5, 1, 5))) console.print(Padding(":x: Selection Cancelled...", (0, 5, 1, 5)))
return self.outcome() return self.outcome()
start_time += time.time() - selection_start start_time += time.monotonic() - selection_start
keep = set(selected_idx) keep = set(selected_idx)
for i in range(len(titles) - 1, -1, -1): for i in range(len(titles) - 1, -1, -1):
@@ -1874,7 +1874,7 @@ class dl:
if current_season_header_idx != -1: if current_season_header_idx != -1:
dependencies[current_season_header_idx].append(current_ui_idx) dependencies[current_season_header_idx].append(current_ui_idx)
selection_start = time.time() selection_start = time.monotonic()
selected_ui_idx = select_multiple( selected_ui_idx = select_multiple(
selection_titles, selection_titles,
@@ -1889,7 +1889,7 @@ class dl:
console.print(Padding(":x: Selection Cancelled...", (0, 5, 1, 5))) console.print(Padding(":x: Selection Cancelled...", (0, 5, 1, 5)))
return self.outcome() return self.outcome()
selection_end = time.time() selection_end = time.monotonic()
start_time += selection_end - selection_start start_time += selection_end - selection_start
selected_idx = [] selected_idx = []
@@ -2317,7 +2317,7 @@ class dl:
disk_check = None if skip_dl or sample else DiskCheck(title.tracks, self.log.warning) 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: try:
with SyncLive(Padding(download_table, (1, 5)), console=console, refresh_per_second=20): with SyncLive(Padding(download_table, (1, 5)), console=console, refresh_per_second=20):
+15 -15
View File
@@ -703,7 +703,7 @@ def dispatch_parts(
yield {"total": total_size} yield {"total": total_size}
total_bytes = 0 total_bytes = 0
last_report = time.time() last_report = time.monotonic()
speed_window = SpeedWindow(last_report) speed_window = SpeedWindow(last_report)
completed = False completed = False
worker_error = False worker_error = False
@@ -723,7 +723,7 @@ def dispatch_parts(
total_bytes += advance total_bytes += advance
yield {"advance": advance} yield {"advance": advance}
now = time.time() now = time.monotonic()
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:
@@ -862,7 +862,7 @@ def download(
elif tmp_file.exists(): elif tmp_file.exists():
resume_offset = tmp_file.stat().st_size resume_offset = tmp_file.stat().st_size
_time = time.time _time = time.monotonic
use_raw = is_requests_session(session) use_raw = is_requests_session(session)
item_range = has_range_header(kwargs) item_range = has_range_header(kwargs)
@@ -1475,7 +1475,7 @@ def download_multiprocess(
yield dict(advance=skipped) yield dict(advance=skipped)
total_bytes = 0 total_bytes = 0
start_time = time.time() start_time = time.monotonic()
last_speed_report = start_time last_speed_report = start_time
speed_window = SpeedWindow(start_time) speed_window = SpeedWindow(start_time)
done_count = 0 done_count = 0
@@ -1535,7 +1535,7 @@ def download_multiprocess(
yield dict(advance=1) yield dict(advance=1)
yield event yield event
now = time.time() now = time.monotonic()
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:
@@ -1839,7 +1839,7 @@ def requests(
raise raise
else: else:
total_bytes = 0 total_bytes = 0
start_time = time.time() start_time = time.monotonic()
last_speed_report = start_time last_speed_report = start_time
speed_window = SpeedWindow(start_time) speed_window = SpeedWindow(start_time)
last_hedge_check = 0.0 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. # 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 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 # 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: def download_worker(index: int, url_item: dict[str, Any], hedge: bool = False) -> None:
item = dict(url_item) item = dict(url_item)
@@ -1898,7 +1898,7 @@ def requests(
# under seg_lock: the hedge scan iterates seg_start.items() on the main # under seg_lock: the hedge scan iterates seg_start.items() on the main
# thread, and a first-time key insert during that iteration raises # thread, and a first-time key insert during that iteration raises
with seg_lock: with seg_lock:
seg_start[index] = time.time() seg_start[index] = time.monotonic()
for event in download( for event in download(
session=session, session=session,
segmented=segmented_batch, segmented=segmented_batch,
@@ -1920,7 +1920,7 @@ def requests(
return return
seg_done.add(index) seg_done.add(index)
if not hedge: if not hedge:
seg_durations.append(time.time() - seg_start[index]) seg_durations.append(time.monotonic() - seg_start[index])
os.replace(target, save_path) os.replace(target, save_path)
event = dict(event, file_downloaded=save_path) event = dict(event, file_downloaded=save_path)
event_queue.put(event) event_queue.put(event)
@@ -2006,7 +2006,7 @@ def requests(
part_target.unlink(missing_ok=True) part_target.unlink(missing_ok=True)
return return
seg_done.add(index) 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) os.replace(part_target, save_path)
event_queue.put(dict(file_downloaded=save_path, written=size)) event_queue.put(dict(file_downloaded=save_path, written=size))
event_queue.put(dict(advance=1)) event_queue.put(dict(advance=1))
@@ -2061,7 +2061,7 @@ def requests(
part_target = save_path.with_name(f"{save_path.name}.tp.!dev") part_target = save_path.with_name(f"{save_path.name}.tp.!dev")
with open(part_target, "wb") as f: with open(part_target, "wb") as f:
f.truncate(size) f.truncate(size)
seg_start[index] = time.time() seg_start[index] = time.monotonic()
tail_boosted.add(index) tail_boosted.add(index)
abort = threading.Event() abort = threading.Event()
part_aborts.append(abort) part_aborts.append(abort)
@@ -2089,7 +2089,7 @@ def requests(
queue_depth = submission_window(max_workers) queue_depth = submission_window(max_workers)
if controller: if controller:
submit(controller.update(time.time(), len(remaining))) submit(controller.update(time.monotonic(), len(remaining)))
else: else:
submit(queue_depth) submit(queue_depth)
@@ -2110,7 +2110,7 @@ def requests(
if written: if written:
total_bytes += written total_bytes += written
if controller: if controller:
controller.record_bytes(written, time.time()) controller.record_bytes(written, time.monotonic())
yield event yield event
if pending_advance > 0: if pending_advance > 0:
@@ -2120,7 +2120,7 @@ def requests(
if DOWNLOAD_CANCELLED.is_set(): if DOWNLOAD_CANCELLED.is_set():
remaining.clear() remaining.clear()
now = time.time() now = time.monotonic()
target = max_workers target = max_workers
if controller: if controller:
@@ -2249,7 +2249,7 @@ def requests(
if pending_advance > 0: if pending_advance > 0:
yield dict(advance=pending_advance) yield dict(advance=pending_advance)
elapsed = time.time() - 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) download_speed = math.ceil(total_bytes / elapsed)
yield dict(downloaded=f"{filesize.decimal(download_speed)}/s") yield dict(downloaded=f"{filesize.decimal(download_speed)}/s")
+2 -2
View File
@@ -362,8 +362,8 @@ class ExpressVPN(Proxy):
) )
interval = int(data.get("interval") or 5) interval = int(data.get("interval") or 5)
deadline = time.time() + int(data.get("expires_in") or self.DEVICE_POLL_TIMEOUT) deadline = time.monotonic() + int(data.get("expires_in") or self.DEVICE_POLL_TIMEOUT)
while time.time() < deadline: while time.monotonic() < deadline:
time.sleep(interval) time.sleep(interval)
poll = self.request( poll = self.request(
"POST", "POST",
+12 -12
View File
@@ -609,7 +609,7 @@ class Gluetun(Proxy):
to Docker with --env-file, never as "-e KEY=VALUE" arguments, so the credentials stay out of 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. process listings. unshackle overwrites and deletes the file once "docker run" returns.
""" """
start_time = time.time() start_time = time.monotonic()
log_event( log_event(
"gluetun_container_create_start", "gluetun_container_create_start",
@@ -764,7 +764,7 @@ class Gluetun(Proxy):
message=f"Docker run timed out for {container_name}", message=f"Docker run timed out for {container_name}",
context={"container_name": container_name}, context={"container_name": container_name},
success=False, 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 raise RuntimeError("Docker run command timed out") from None
@@ -780,7 +780,7 @@ class Gluetun(Proxy):
"stderr": error_msg, "stderr": error_msg,
}, },
success=False, success=False,
duration_ms=(time.time() - start_time) * 1000, duration_ms=(time.monotonic() - start_time) * 1000,
) )
raise RuntimeError(f"Docker run failed: {error_msg}") 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, "container_id": result.stdout.strip()[:12] if result.stdout else None,
}, },
success=True, success=True,
duration_ms=(time.time() - start_time) * 1000, duration_ms=(time.monotonic() - start_time) * 1000,
) )
finally: finally:
if env_file_path: if env_file_path:
@@ -941,7 +941,7 @@ class Gluetun(Proxy):
Returns: Returns:
True if container is ready, False if it failed or timed out True if container is ready, False if it failed or timed out
""" """
start_time = time.time() start_time = time.monotonic()
last_error = None last_error = None
log_event( log_event(
@@ -951,7 +951,7 @@ class Gluetun(Proxy):
context={"container_name": container_name, "timeout": timeout}, context={"container_name": container_name, "timeout": timeout},
) )
while time.time() - start_time < timeout: while time.monotonic() - start_time < timeout:
try: try:
if not self.is_container_running(container_name): if not self.is_container_running(container_name):
exit_info = self.get_container_exit_info(container_name) exit_info = self.get_container_exit_info(container_name)
@@ -982,7 +982,7 @@ class Gluetun(Proxy):
if proxy_ready and vpn_ready: if proxy_ready and vpn_ready:
# Give a brief moment for the proxy to fully initialize # Give a brief moment for the proxy to fully initialize
time.sleep(1) time.sleep(1)
duration_ms = (time.time() - start_time) * 1000 duration_ms = (time.monotonic() - start_time) * 1000
log_event( log_event(
"gluetun_container_ready", "gluetun_container_ready",
level="INFO", level="INFO",
@@ -1023,7 +1023,7 @@ class Gluetun(Proxy):
if last_error: if last_error:
self._last_wait_error = last_error self._last_wait_error = last_error
duration_ms = (time.time() - start_time) * 1000 duration_ms = (time.monotonic() - start_time) * 1000
log_event( log_event(
"gluetun_container_wait_timeout", "gluetun_container_wait_timeout",
level="ERROR", level="ERROR",
@@ -1090,7 +1090,7 @@ class Gluetun(Proxy):
RuntimeError: If the IP resolves to a country other than the expected one, which aborts 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 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: if query_key not in self.active_containers:
return return
@@ -1134,7 +1134,7 @@ class Gluetun(Proxy):
expected_code = expected_code.upper() expected_code = expected_code.upper()
if actual_country != expected_code: if actual_country != expected_code:
duration_ms = (time.time() - start_time) * 1000 duration_ms = (time.monotonic() - start_time) * 1000
log_event( log_event(
"gluetun_verify_mismatch", "gluetun_verify_mismatch",
level="ERROR", 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_city"] = ip_info.get("city")
self.active_containers[query_key]["ip_org"] = ip_info.get("org") 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( log_event(
"gluetun_verify_success", "gluetun_verify_success",
level="INFO", level="INFO",
@@ -1206,7 +1206,7 @@ class Gluetun(Proxy):
except Exception: except Exception:
pass pass
duration_ms = (time.time() - start_time) * 1000 duration_ms = (time.monotonic() - start_time) * 1000
log_event( log_event(
"gluetun_verify_failed", "gluetun_verify_failed",
level="ERROR", level="ERROR",
+2 -2
View File
@@ -681,10 +681,10 @@ def get_country_code(name: str) -> str | None:
def time_elapsed_since(start: float) -> str: 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. E.g., `1h56m2s`, `15m12s`, `0m55s`, e.t.c.
""" """
elapsed = int(time.time() - start) elapsed = int(time.monotonic() - start)
minutes, seconds = divmod(elapsed, 60) minutes, seconds = divmod(elapsed, 60)
hours, minutes = divmod(minutes, 60) hours, minutes = divmod(minutes, 60)