mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-26 19:05:13 +00:00
style: turn on ruff UP and B rules and fix every finding
This commit is contained in:
+18
-18
@@ -40,7 +40,7 @@ import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from shutil import rmtree
|
||||
from typing import Any, Optional
|
||||
from typing import Any
|
||||
|
||||
import click
|
||||
import fault_server # local sibling (scripts/): fault-injection server + payload verifier
|
||||
@@ -105,7 +105,7 @@ class SegmentHandler(http.server.BaseHTTPRequestHandler):
|
||||
server.connections += 1
|
||||
self.slow_conn = server.connections <= server.faults["slow_conn"]
|
||||
|
||||
def _parse_range(self, total: int) -> Optional[tuple[int, int]]:
|
||||
def _parse_range(self, total: int) -> tuple[int, int] | None:
|
||||
header = self.headers.get("Range")
|
||||
if not header or not header.startswith("bytes="):
|
||||
return None
|
||||
@@ -214,8 +214,8 @@ class SegmentHandler(http.server.BaseHTTPRequestHandler):
|
||||
|
||||
|
||||
def run_batch(
|
||||
urls: list[str], out_dir: Path, workers: int, session: Optional[Any], adaptive: bool = False, procs: int = 1
|
||||
) -> tuple[float, list[float], Optional[BaseException]]:
|
||||
urls: list[str], out_dir: Path, workers: int, session: Any | None, adaptive: bool = False, procs: int = 1
|
||||
) -> tuple[float, list[float], BaseException | None]:
|
||||
"""Download one batch through the real code path.
|
||||
|
||||
Returns (wall seconds, completion timestamps relative to start, error-or-None).
|
||||
@@ -223,7 +223,7 @@ def run_batch(
|
||||
"""
|
||||
DOWNLOAD_CANCELLED.clear()
|
||||
completions: list[float] = []
|
||||
err: Optional[BaseException] = None
|
||||
err: BaseException | None = None
|
||||
start = time.perf_counter()
|
||||
try:
|
||||
for event in download_batch(
|
||||
@@ -258,7 +258,7 @@ def run_batch(
|
||||
return wall, completions, err, strays, locked, pool_threads
|
||||
|
||||
|
||||
def incomplete_segments(out_dir: Path, expected: int, expected_bytes: Optional[bytes]) -> list[int]:
|
||||
def incomplete_segments(out_dir: Path, expected: int, expected_bytes: bytes | None) -> list[int]:
|
||||
"""Segment indexes that are missing, empty, or (synthetic mode) not byte-identical.
|
||||
|
||||
Content compare (not just size) is required: on a mid-body interruption the downloader
|
||||
@@ -331,9 +331,9 @@ def sweep(
|
||||
urls: list[str],
|
||||
workers: list[int],
|
||||
runs: int,
|
||||
session: Optional[Any],
|
||||
server: Optional[SegmentServer],
|
||||
expected_bytes: Optional[bytes],
|
||||
session: Any | None,
|
||||
server: SegmentServer | None,
|
||||
expected_bytes: bytes | None,
|
||||
adaptive: bool = False,
|
||||
procs: int = 1,
|
||||
) -> list[Row]:
|
||||
@@ -468,7 +468,7 @@ def print_fault_report(rows: list[FaultRow], runs: int, segments: int, profile:
|
||||
)
|
||||
|
||||
|
||||
def _procs_notice(procs: int, n_urls: int, session: Optional[Any]) -> None:
|
||||
def _procs_notice(procs: int, n_urls: int, session: Any | None) -> None:
|
||||
"""Warn loudly when --procs cannot engage, so a run is never mistaken for a multiprocess test."""
|
||||
if procs <= 1:
|
||||
return
|
||||
@@ -490,7 +490,7 @@ def run_fault_mode(
|
||||
seg_size: int,
|
||||
worker_counts: list[int],
|
||||
runs: int,
|
||||
session: Optional[Any],
|
||||
session: Any | None,
|
||||
adaptive: bool,
|
||||
procs: int,
|
||||
seed: int,
|
||||
@@ -650,12 +650,12 @@ def main(
|
||||
fault_slow_conn: int,
|
||||
part_size_mib: int,
|
||||
fast_timeouts: bool,
|
||||
urls_file: Optional[str],
|
||||
impersonate: Optional[str],
|
||||
urls_file: str | None,
|
||||
impersonate: str | None,
|
||||
adaptive: bool,
|
||||
procs: int,
|
||||
no_read1: bool,
|
||||
fault_profile: Optional[str],
|
||||
fault_profile: str | None,
|
||||
seed: int,
|
||||
) -> None:
|
||||
"""Benchmark downloader throughput vs worker count, with optional fault injection."""
|
||||
@@ -668,12 +668,12 @@ def main(
|
||||
"tail_slow_once": fault_tail_slow_once,
|
||||
"slow_conn": fault_slow_conn,
|
||||
}
|
||||
server: Optional[SegmentServer] = None
|
||||
session: Optional[Any] = None
|
||||
server: SegmentServer | None = None
|
||||
session: Any | None = None
|
||||
saved: dict[str, Any] = {}
|
||||
saved_network: Optional[dict] = None
|
||||
saved_network: dict | None = None
|
||||
total = segments
|
||||
expected_bytes: Optional[bytes] = None # synthetic reference buffer; None in real-URL mode
|
||||
expected_bytes: bytes | None = None # synthetic reference buffer; None in real-URL mode
|
||||
|
||||
if fast_timeouts: # bench-only: patched globals are read at call time inside download()
|
||||
fast = {"READ_TIMEOUT": 2, "RETRY_WAIT": 1, "HEDGE_MIN_WAIT": 1.0}
|
||||
|
||||
@@ -45,7 +45,7 @@ import threading
|
||||
import time
|
||||
from dataclasses import asdict, dataclass
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from typing import Any, Optional
|
||||
from typing import Any
|
||||
|
||||
MIB = 1024 * 1024
|
||||
DEFAULT_SEED = 1729
|
||||
@@ -186,7 +186,7 @@ class FaultServer(ThreadingHTTPServer):
|
||||
"""Deterministic per-(path, attempt) fault gate: fires for ``pct`` percent of them."""
|
||||
if pct <= 0:
|
||||
return False
|
||||
digest = hashlib.sha256(f"{self.seed}:{kind}:{path}:{attempt}".encode("utf-8")).digest()
|
||||
digest = hashlib.sha256(f"{self.seed}:{kind}:{path}:{attempt}".encode()).digest()
|
||||
return (int.from_bytes(digest[:4], "big") / 0xFFFFFFFF) * 100.0 < pct
|
||||
|
||||
def reset_counters(self) -> None:
|
||||
@@ -212,7 +212,7 @@ class FaultHandler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *_: Any) -> None: # silence per-request logging
|
||||
pass
|
||||
|
||||
def _parse_range(self, total: int) -> Optional[tuple[int, int]]:
|
||||
def _parse_range(self, total: int) -> tuple[int, int] | None:
|
||||
header = self.headers.get("Range")
|
||||
if not header or not header.startswith("bytes="):
|
||||
return None
|
||||
@@ -372,7 +372,7 @@ class FaultHandler(BaseHTTPRequestHandler):
|
||||
time.sleep(per_chunk)
|
||||
|
||||
|
||||
def resolve_profile(name: str, overrides: Optional[dict[str, Any]] = None) -> FaultProfile:
|
||||
def resolve_profile(name: str, overrides: dict[str, Any] | None = None) -> FaultProfile:
|
||||
"""Return a copy of the named preset with any non-None ``overrides`` applied."""
|
||||
if name not in PROFILES:
|
||||
raise KeyError(f"unknown profile {name!r}; choices: {', '.join(sorted(PROFILES))}")
|
||||
|
||||
@@ -18,7 +18,7 @@ import re
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
from typing import Any
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import requests
|
||||
@@ -56,7 +56,7 @@ EXCLUDED: dict[str, str] = {
|
||||
"https://storage.googleapis.com/shaka-demo-assets/heliocentrism-xlink/heliocentrism.mpd": "xlink:href remote Periods are not resolved",
|
||||
}
|
||||
|
||||
Stream = tuple[str, str, str, Optional[dict[str, Any]]]
|
||||
Stream = tuple[str, str, str, dict[str, Any] | None]
|
||||
|
||||
|
||||
def dashif_streams() -> list[Stream]:
|
||||
@@ -128,7 +128,7 @@ def shaka_packager_streams() -> list[Stream]:
|
||||
]
|
||||
|
||||
|
||||
def kind_of(head: bytes) -> Optional[str]:
|
||||
def kind_of(head: bytes) -> str | None:
|
||||
"""Tell the manifest type from the first bytes, since many manifest URLs have no telling extension."""
|
||||
text = head.lstrip(b"\xef\xbb\xbf").lstrip()
|
||||
if text.startswith(b"#EXTM3U"):
|
||||
@@ -145,7 +145,7 @@ def file_name(source: str, name: str, url: str, kind: str) -> str:
|
||||
return f"{kind}/{source}-{slug}-{hashlib.sha1(url.encode()).hexdigest()[:8]}.{EXTENSIONS[kind]}"
|
||||
|
||||
|
||||
def fetch(stream: Stream) -> Optional[dict[str, Any]]:
|
||||
def fetch(stream: Stream) -> dict[str, Any] | None:
|
||||
"""Download one manifest into OUT and return its index entry, or None when it is not a manifest."""
|
||||
source, name, url, expect = stream
|
||||
try:
|
||||
|
||||
@@ -22,7 +22,7 @@ import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from tempfile import mkdtemp
|
||||
from typing import Any, Optional
|
||||
from typing import Any
|
||||
|
||||
import click
|
||||
from requests import Session
|
||||
@@ -94,7 +94,7 @@ class Counter:
|
||||
self.files += 1
|
||||
|
||||
|
||||
def pick_track(tracks: object, which: str) -> Optional[Any]:
|
||||
def pick_track(tracks: object, which: str) -> Any | None:
|
||||
vids = list(getattr(tracks, "videos", []))
|
||||
if not vids:
|
||||
auds = list(getattr(tracks, "audio", []))
|
||||
|
||||
@@ -19,7 +19,7 @@ import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
from tempfile import mkdtemp
|
||||
from typing import Any, Optional
|
||||
from typing import Any
|
||||
|
||||
import click
|
||||
from requests import Session
|
||||
@@ -34,7 +34,7 @@ STREAMS: list[tuple[str, str]] = [
|
||||
("sony-1a", "https://dash.akamaized.net/dash264/TestCases/1a/sony/SNE_DASH_SD_CASE1A_REVISED.mpd"),
|
||||
]
|
||||
|
||||
guard_results: list[Optional[tuple[int, int]]] = []
|
||||
guard_results: list[tuple[int, int] | None] = []
|
||||
|
||||
|
||||
def install_guard_spy() -> bool:
|
||||
@@ -43,7 +43,7 @@ def install_guard_spy() -> bool:
|
||||
if orig is None:
|
||||
return False
|
||||
|
||||
def spy(is_subtitle: bool, segments: Any, init_len: int) -> Optional[tuple[int, int]]:
|
||||
def spy(is_subtitle: bool, segments: Any, init_len: int) -> tuple[int, int] | None:
|
||||
result = orig(is_subtitle, segments, init_len)
|
||||
guard_results.append(result)
|
||||
return result
|
||||
|
||||
Reference in New Issue
Block a user