Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
refactor: add custom Pool class
NTFSvolumeb6a9556e7090
diff --git a/cyberdrop_dl/crawlers/fileditch.py b/cyberdrop_dl/crawlers/fileditch.pyindex 2b69b77ec..6f3bdf7e9 100644--- a/cyberdrop_dl/crawlers/fileditch.py+++ b/cyberdrop_dl/crawlers/fileditch.py@@ -1,5 +1,6 @@from __future__ import annotations+import asyncioimport dataclassesimport hashlibimport json@@ -69,7 +70,7 @@ class FileditchCrawler(Crawler):try:async with self._startup_lock:self.log.warning("Solving proof of work challenge for %s\n%s", url, dict(pow))- solution = await multi_process.async_race(_pow_worker, pow.pow_challenge, pow.pow_diff)+ solution = await asyncio.to_thread(multi_process.race, _pow_worker, pow.pow_challenge, pow.pow_diff)except TimeoutError:msg = f"Unable to solve challenge {pow.pow_challenge} after {multi_process.TIMEOUT.get()} seconds"diff --git a/cyberdrop_dl/ddos_guard.py b/cyberdrop_dl/ddos_guard.pyindex a19fbe8be..92a1c55f4 100644--- a/cyberdrop_dl/ddos_guard.py+++ b/cyberdrop_dl/ddos_guard.py@@ -180,19 +180,18 @@ class Anubis(DDosGuard):@classmethodasync def solve(cls, challenge: _AnubisChallenge) -> _AnubisSolution:- return await asyncio.to_thread(cls._solve, challenge)+ return await asyncio.to_thread(_solve_anubis_challenge, challenge)- @classmethod- def _solve(cls, challenge: _AnubisChallenge, *, timeout: float = 30.0) -> _AnubisSolution:- try:- with multi_process.ctx(timeout=timeout):- result = multi_process.race(_anubis_worker, challenge.data, challenge.difficulty)- except TimeoutError:- msg = f"Unable to solve Anubis challenge after {timeout:0.2f} seconds: {challenge}"- raise DDOSGuardError(msg) from None- nonce, checksum = result.value- return _AnubisSolution(challenge.id, nonce, checksum, challenge.difficulty, result.elapsed)+def _solve_anubis_challenge(challenge: _AnubisChallenge) -> _AnubisSolution:+ try:+ result = multi_process.race(_anubis_worker, challenge.data, challenge.difficulty)+ except TimeoutError:+ msg = f"Unable to solve Anubis challenge after {multi_process.TIMEOUT.get():0.2f} seconds: {challenge}"+ raise DDOSGuardError(msg) from None++ nonce, checksum = result.value+ return _AnubisSolution(challenge.id, nonce, checksum, challenge.difficulty, result.elapsed)@dataclasses.dataclass(slots=True, frozen=True)@@ -221,11 +220,11 @@ class _AnubisSolution:)-def _anubis_worker(start: int, step: int, challenge: str, difficulty: int) -> tuple[int, str] | None:- nonce = start+def _anubis_worker(worker_idx: int, max_workers: int, challenge: str, difficulty: int) -> tuple[int, str]:+ nonce = worker_idxtarget = "0" * difficultywhile True:checksum = hashlib.sha256(f"{challenge}{nonce}".encode()).hexdigest()if checksum.startswith(target):return nonce, checksum- nonce += step+ nonce += max_workersdiff --git a/cyberdrop_dl/multi_process.py b/cyberdrop_dl/multi_process.pyindex 7fe184251..534d98c3e 100644--- a/cyberdrop_dl/multi_process.py+++ b/cyberdrop_dl/multi_process.py@@ -1,28 +1,47 @@from __future__ import annotations+import concurrent.futuresimport contextlibimport dataclasses+import multiprocessing as mpimport osimport sys+import timefrom contextvars import ContextVarfrom typing import TYPE_CHECKING, Concatenate-from cyberdrop_dl import aiofrom cyberdrop_dl.constants import MISSINGfrom cyberdrop_dl.utils import enter_contextif TYPE_CHECKING:- from collections.abc import Callable, Generator+ from collections.abc import Callable, Generator, IterableTIMEOUT: ContextVar[float | None] = ContextVar("TIMEOUT", default=30.0)MAX_WORKERS: ContextVar[int | None] = ContextVar("MAX_WORKERS", default=None)+class PoolExecutor(concurrent.futures.ProcessPoolExecutor):+ @property+ def workers(self) -> int:+ return len(self._processes)++ @property+ def max_workers(self) -> int:+ return self._max_workers # pyright: ignore[reportAttributeAccessIssue]++ def __init__(self) -> None:+ cpu_limit = max(cpu_count() // 2, 1)+ max_workers = MAX_WORKERS.get()+ super().__init__(+ max_workers=cpu_limit if not max_workers else min(max_workers, cpu_limit),+ mp_context=mp.get_context("spawn"),+ )++@dataclasses.dataclass(slots=True)class RaceResult[T]:value: Telapsed: float- workers: int@contextlib.contextmanager@@ -38,36 +57,45 @@ def ctx(yield-def race[**P, R](- worker: Callable[Concatenate[int, int, P], R | None], *args: P.args, **kwargs: P.kwargs-) -> RaceResult[R]:- """Execute a worker function across multiple processes in a race condition, returning the first non-None result.+def inject_timeout[**P, T, R](+ func: Callable[Concatenate[Iterable[concurrent.futures.Future[T]], float | None, P], R],+) -> Callable[Concatenate[Iterable[concurrent.futures.Future[T]], P], R]:- All other processes are cancelled on exit.- """- import multiprocessing as mp- import time- from concurrent.futures import ProcessPoolExecutor, as_completed+ def wrapper(futures: Iterable[concurrent.futures.Future[T]], *args: P.args, **kwargs: P.kwargs) -> R:+ return func(futures, TIMEOUT.get(), *args, **kwargs)++ return wrapper- cpu_limit = max(cpu_count() // 2, 1)- max_workers = MAX_WORKERS.get()- max_workers = cpu_limit if not max_workers else min(max_workers, cpu_limit)- start_time = time.monotonic()- with ProcessPoolExecutor(max_workers=max_workers, mp_context=mp.get_context("spawn")) as executor:- futures = [executor.submit(worker, idx, max_workers, *args, **kwargs) for idx in range(max_workers)]+as_completed = inject_timeout(concurrent.futures.as_completed)+wait = inject_timeout(concurrent.futures.wait)- for future in as_completed(futures, timeout=TIMEOUT.get()):- result = future.result()- if result is not None:- elapsed = time.monotonic() - start_time- executor.shutdown(wait=False, cancel_futures=True)- return RaceResult(result, elapsed, max_workers)- raise RuntimeError("None of the workers found a solution")+def wait_for_one[T](futures: Iterable[concurrent.futures.Future[T]], /) -> concurrent.futures.Future[T]:+ new_futs = wait(futures, return_when=concurrent.futures.FIRST_COMPLETED)+ return next(iter(new_futs.done))-async_race = aio.to_thread(race)+def race[**P, R](worker: Callable[Concatenate[int, int, P], R], *args: P.args, **kwargs: P.kwargs) -> RaceResult[R]:+ """Execute a worker function across multiple processes, returning the first one to complete.++ Worker id and max workers are injected as the first arguments to the worker. They should be useded as seeds.++ All processes are cancelled on exit.+ """++ start_time = time.monotonic()+ executor = PoolExecutor()+ try:+ futures = (+ executor.submit(worker, idx, executor.max_workers, *args, **kwargs) for idx in range(executor.max_workers)+ )+ result = wait_for_one(futures).result()+ elapsed = time.monotonic() - start_time+ return RaceResult(result, elapsed)+ finally:+ executor.shutdown(wait=False, cancel_futures=True)+if sys.platform not in {"win32", "darwin"} and hasattr(os, "sched_getaffinity"):