Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: rework aio module (#32)

NTFSvolume057781f84512
diff --git a/cyberdrop_dl/aio.py b/cyberdrop_dl/aio.py
new file mode 100644
index 000000000..43a07a6a1
--- /dev/null
+++ b/cyberdrop_dl/aio.py
@@ -0,0 +1,318 @@
+"""Async versions of builtins and some path operations"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import dataclasses
+import shutil
+import sys
+import tempfile
+from abc import ABC, abstractmethod
+from pathlib import Path
+from stat import S_ISREG
+from typing import (
+ IO,
+ TYPE_CHECKING,
+ Any,
+ AnyStr,
+ Generic,
+ ParamSpec,
+ Self,
+ TypeVar,
+ TypeVarTuple,
+ cast,
+ final,
+ overload,
+)
+from weakref import WeakValueDictionary
+
+from typing_extensions import Sentinel
+
+if TYPE_CHECKING:
+ from collections.abc import AsyncGenerator, AsyncIterator, Awaitable, Callable, Coroutine, Iterable, Iterator
+ from types import TracebackType
+
+ from _typeshed import OpenBinaryMode, OpenTextMode
+
+
+_T = TypeVar("_T")
+_Ts = TypeVarTuple("_Ts")
+_R = TypeVar("_R")
+_P = ParamSpec("_P")
+_MISSING = Sentinel("_MISSING")
+
+
[email protected](slots=True, eq=False)
+class WeakAsyncLocks(Generic[_T]):
+ """A WeakValueDictionary wrapper for asyncio.Locks.
+
+ Unused locks are automatically garbage collected. When trying to retrieve a
+ lock that does not exists, a new lock will be created.
+ """
+
+ _locks: WeakValueDictionary[_T, asyncio.Lock] = dataclasses.field(init=False, default_factory=WeakValueDictionary)
+
+ def __getitem__(self, key: _T, /) -> asyncio.Lock:
+ lock = self._locks.get(key)
+ if lock is None:
+ self._locks[key] = lock = asyncio.Lock()
+ return lock
+
+
[email protected](slots=True, eq=False)
+class AsyncIOWrapper(Generic[AnyStr]):
+ """An asynchronous context manager wrapper for a file object."""
+
+ _coro: Awaitable[IO[AnyStr]]
+ _io: IO[AnyStr] = dataclasses.field(init=False)
+
+ async def __aenter__(self) -> Self:
+ self._io = await self._coro
+ return self
+
+ async def __aexit__(self, *_) -> None:
+ return await asyncio.to_thread(self._io.close)
+
+ async def __aiter__(self) -> AsyncIterator[AnyStr]:
+ while True:
+ line = await self.readline()
+ if line:
+ yield line
+ else:
+ break
+
+ async def read(self, size: int = -1) -> AnyStr:
+ return await asyncio.to_thread(self._io.read, size)
+
+ async def readline(self) -> AnyStr:
+ return await asyncio.to_thread(self._io.readline)
+
+ async def readlines(self) -> list[AnyStr]:
+ return await asyncio.to_thread(self._io.readlines)
+
+ async def write(self, b: AnyStr, /) -> int:
+ return await asyncio.to_thread(self._io.write, b)
+
+ async def writelines(self, lines: Iterable[AnyStr], /) -> None:
+ return await asyncio.to_thread(self._io.writelines, lines)
+
+
[email protected](slots=True, eq=False)
+class AsyncIteratorWrapper(Generic[_T]):
+ _coro: Awaitable[Iterable[_T]]
+ _iterator: Iterator[_T] | None = dataclasses.field(default=None, init=False)
+
+ def __aiter__(self) -> Self:
+ return self
+
+ async def __anext__(self) -> _T:
+ if self._iterator is None:
+ self._iterator = iter(await self._coro)
+ value = await asyncio.to_thread(next, self._iterator, _MISSING)
+ if value is _MISSING:
+ raise StopAsyncIteration from None
+
+ return cast("_T", value)
+
+
+class AsyncContextManagerMixin(ABC):
+ __stack: contextlib.AsyncExitStack | None = None
+
+ @final
+ @property
+ def _stack(self) -> contextlib.AsyncExitStack[bool | None]:
+ if self.__stack is None:
+ raise RuntimeError(f"{type(self).__name__} can only be used as a context manager")
+ return self.__stack
+
+ @final
+ async def __aenter__(self) -> Self:
+ if self.__stack is not None:
+ raise RuntimeError(f"{type(self).__name__} does not allow reentrance")
+ self.__stack = contextlib.AsyncExitStack()
+ _ = await self.__stack.__aenter__()
+ await self._async_ctx_()
+ return self
+
+ @final
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_val: BaseException | None,
+ exc_tb: TracebackType | None,
+ ) -> bool | None:
+ return await self._stack.__aexit__(exc_type, exc_val, exc_tb)
+
+ @abstractmethod
+ async def _async_ctx_(self) -> None: ...
+
+
+async def gather(*coros: Awaitable[_T]) -> list[_T]:
+ """Like asyncio.gather but an exception on any coro cancels all pending coros
+
+ AKA: all or nothing"""
+
+ async def run(coro: Awaitable[_R]) -> _R:
+ return await coro
+
+ async with asyncio.TaskGroup() as tg:
+ tasks = [tg.create_task(run(coro)) for coro in coros]
+
+ return [t.result() for t in tasks]
+
+
+async def map(
+ coro_factory: Callable[[_T], Awaitable[_R]],
+ params: Iterable[_T],
+ /,
+ *,
+ task_limit: int | None = None,
+) -> list[_R]:
+ """Map an async factory over a sequence of arguments with optional concurrency cap.
+
+ If `task_limit` is given, no more than that many coroutines will be “in flight” at the same time,
+ limiting memory pressure and event loop overhead"""
+ return await map_tuples(coro_factory, ((param,) for param in params), task_limit=task_limit)
+
+
+async def map_tuples(
+ coro_factory: Callable[[*_Ts], Awaitable[_R]],
+ params_batched: Iterable[tuple[*_Ts]],
+ /,
+ *,
+ task_limit: int | None = None,
+) -> list[_R]:
+ """Map an async factory over a sequence of arguments with optional concurrency cap.
+
+ If `task_limit` is given, no more than that many coroutines will be “in flight” at the same time,
+ limiting memory pressure and event loop overhead"""
+ if not task_limit:
+ return await gather(*(coro_factory(*params) for params in params_batched))
+
+ semaphore = asyncio.BoundedSemaphore(task_limit)
+ tasks: list[asyncio.Task[_R]] = []
+
+ async def run(coro: Awaitable[_R]) -> _R:
+ try:
+ return await coro
+ finally:
+ semaphore.release()
+
+ async with asyncio.TaskGroup() as tg:
+ for params in params_batched:
+ _ = await semaphore.acquire()
+ coro = coro_factory(*params)
+ tasks.append(tg.create_task(run(coro)))
+
+ return [t.result() for t in tasks]
+
+
+def run(coro: Coroutine[Any, Any, _T]) -> _T:
+ def _loop_factory() -> asyncio.AbstractEventLoop:
+ loop = asyncio.new_event_loop()
+ if sys.version_info > (3, 12):
+ loop.set_task_factory(asyncio.eager_task_factory)
+ return loop
+
+ with asyncio.Runner(loop_factory=_loop_factory) as runner:
+ return runner.run(coro)
+
+
+def to_thread(fn: Callable[_P, _R]) -> Callable[_P, Coroutine[None, None, _R]]:
+ """Convert a blocking callable into an async callable that runs in another thread"""
+
+ async def async_run(*args: _P.args, **kwargs: _P.kwargs) -> _R:
+ return await asyncio.to_thread(fn, *args, **kwargs)
+
+ return async_run
+
+
+chmod = to_thread(Path.chmod)
+copy = to_thread(shutil.copy)
+exists = to_thread(Path.exists)
+is_dir = to_thread(Path.is_dir)
+is_file = to_thread(Path.is_file)
+mkdir = to_thread(Path.mkdir)
+move = to_thread(shutil.move)
+read_bytes = to_thread(Path.read_bytes)
+read_text = to_thread(Path.read_text)
+resolve = to_thread(Path.resolve)
+stat = to_thread(Path.stat)
+touch = to_thread(Path.touch)
+unlink = remove = to_thread(Path.unlink)
+write_bytes = to_thread(Path.write_bytes)
+write_text = to_thread(Path.write_text)
+
+
+def glob(path: Path, pattern: str) -> AsyncIterator[Path]:
+ coro = asyncio.to_thread(path.glob, pattern)
+ return AsyncIteratorWrapper(coro)
+
+
+def rglob(path: Path, pattern: str) -> AsyncIterator[Path]:
+ coro = asyncio.to_thread(path.rglob, pattern)
+ return AsyncIteratorWrapper(coro)
+
+
+def iterdir(path: Path) -> AsyncIterator[Path]:
+ coro = asyncio.to_thread(path.iterdir)
+ return AsyncIteratorWrapper(coro)
+
+
+@overload
+def open(
+ path: Path,
+ mode: OpenBinaryMode,
+ buffering: int = ...,
+ encoding: str | None = ...,
+ errors: str | None = ...,
+ newline: str | None = ...,
+) -> AsyncIOWrapper[bytes]: ...
+
+
+@overload
+def open(
+ path: Path,
+ mode: OpenTextMode = ...,
+ buffering: int = ...,
+ encoding: str | None = ...,
+ errors: str | None = ...,
+ newline: str | None = ...,
+) -> AsyncIOWrapper[str]: ...
+
+
+def open(
+ path: Path,
+ mode: str = "r",
+ buffering: int = -1,
+ encoding: str | None = None,
+ errors: str | None = None,
+ newline: str | None = None,
+) -> AsyncIOWrapper[Any]:
+ coro = asyncio.to_thread(path.open, mode, buffering, encoding, errors, newline)
+ return AsyncIOWrapper(coro)
+
+
+async def get_size(path: Path) -> int | None:
+ """If path exists and is a file, returns its size. Returns `None` otherwise"""
+
+ # Manually parse stat result to make sure we only use 1 fs call
+
+ try:
+ stat_result = await stat(path)
+ except (OSError, ValueError):
+ return
+ else:
+ if not S_ISREG(stat_result.st_mode):
+ raise IsADirectoryError(path)
+ return stat_result.st_size
+
+
+async def temp_dir() -> AsyncGenerator[Path]:
+ temp_dir = await asyncio.to_thread(tempfile.TemporaryDirectory, prefix="cdl_", ignore_cleanup_errors=True)
+ try:
+ yield Path(temp_dir.name)
+ finally:
+ await asyncio.to_thread(temp_dir.cleanup)
diff --git a/cyberdrop_dl/clients/download_client.py b/cyberdrop_dl/clients/download_client.py
index 738cea3ec..a96a15f0d 100644
--- a/cyberdrop_dl/clients/download_client.py
+++ b/cyberdrop_dl/clients/download_client.py
@@ -10,13 +10,12 @@ from typing import TYPE_CHECKING, Any
import aiofiles
-from cyberdrop_dl import constants
+from cyberdrop_dl import aio, constants
from cyberdrop_dl.clients.response import AbstractResponse
from cyberdrop_dl.constants import FILE_FORMATS
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL
from cyberdrop_dl.exceptions import DDOSGuardError, DownloadError, InvalidContentTypeError, SlowDownloadError
-from cyberdrop_dl.utils import aio, dates
-from cyberdrop_dl.utils.aio import WeakAsyncLocks
+from cyberdrop_dl.utils import dates
from cyberdrop_dl.utils.logger import log, log_debug
from cyberdrop_dl.utils.utilities import get_size_or_none
@@ -49,7 +48,7 @@ class DownloadClient:
self.manager = manager
self.client_manager = client_manager
self.download_speed_threshold = self.manager.config_manager.settings_data.runtime_options.slow_download_speed
- self._server_locks = WeakAsyncLocks[str]()
+ self._server_locks = aio.WeakAsyncLocks[str]()
self.server_locked_domains: set[str] = set()
self._supports_ranges: bool = True
diff --git a/cyberdrop_dl/crawlers/bunkrr.py b/cyberdrop_dl/crawlers/bunkrr.py
index 603199ba0..c9a910a01 100644
--- a/cyberdrop_dl/crawlers/bunkrr.py
+++ b/cyberdrop_dl/crawlers/bunkrr.py
@@ -10,11 +10,12 @@ from typing import TYPE_CHECKING, Any, ClassVar
from aiohttp import ClientConnectorError
+from cyberdrop_dl import aio
from cyberdrop_dl.constants import FILE_FORMATS
from cyberdrop_dl.crawlers.crawler import Crawler, RateLimit, SupportedPaths, auto_task_id
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL
from cyberdrop_dl.exceptions import DDOSGuardError
-from cyberdrop_dl.utils import aio, css, open_graph
+from cyberdrop_dl.utils import css, open_graph
from cyberdrop_dl.utils.utilities import error_handling_wrapper, parse_url, xor_decrypt
if TYPE_CHECKING:
diff --git a/cyberdrop_dl/crawlers/hianime.py b/cyberdrop_dl/crawlers/hianime.py
index 43969c3c0..06c9e1f8a 100644
--- a/cyberdrop_dl/crawlers/hianime.py
+++ b/cyberdrop_dl/crawlers/hianime.py
@@ -6,12 +6,12 @@ from typing import TYPE_CHECKING, Any, ClassVar
import bs4
+from cyberdrop_dl.aio import WeakAsyncLocks
from cyberdrop_dl.crawlers.crawler import Crawler, SupportedPaths, auto_task_id
from cyberdrop_dl.crawlers.megacloud import MegaCloudCrawler
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL
from cyberdrop_dl.exceptions import ScrapeError
from cyberdrop_dl.utils import css
-from cyberdrop_dl.utils.aio import WeakAsyncLocks
from cyberdrop_dl.utils.utilities import error_handling_wrapper
if TYPE_CHECKING:
diff --git a/cyberdrop_dl/crawlers/rumble.py b/cyberdrop_dl/crawlers/rumble.py
index 4e22b72c9..878581bb7 100644
--- a/cyberdrop_dl/crawlers/rumble.py
+++ b/cyberdrop_dl/crawlers/rumble.py
@@ -4,12 +4,13 @@ import dataclasses
import itertools
from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple
+from cyberdrop_dl import aio
from cyberdrop_dl.compat import IntEnum
from cyberdrop_dl.crawlers.crawler import Crawler, SupportedPaths
from cyberdrop_dl.data_structures.mediaprops import Resolution, Subtitle
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL
from cyberdrop_dl.exceptions import DownloadError, ScrapeError
-from cyberdrop_dl.utils import aio, css, m3u8
+from cyberdrop_dl.utils import css, m3u8
from cyberdrop_dl.utils.utilities import error_handling_wrapper, parse_url
if TYPE_CHECKING:
@@ -206,6 +207,6 @@ class RumbleCrawler(Crawler):
)
if hls_formats:
- hls_formats = await aio.gather([resolve_m3u8(f) for f in hls_formats])
+ hls_formats = await aio.map(resolve_m3u8, hls_formats)
return max((*hls_formats, *other_formats))
diff --git a/cyberdrop_dl/downloader/downloader.py b/cyberdrop_dl/downloader/downloader.py
index 501619041..75620b80c 100644
--- a/cyberdrop_dl/downloader/downloader.py
+++ b/cyberdrop_dl/downloader/downloader.py
@@ -14,7 +14,7 @@ from typing import TYPE_CHECKING, NamedTuple, ParamSpec, TypeVar
from aiohttp import ClientConnectorError, ClientError, ClientResponseError
-from cyberdrop_dl import constants, ffmpeg
+from cyberdrop_dl import aio, constants, ffmpeg
from cyberdrop_dl.data_structures.url_objects import HlsSegment, MediaItem
from cyberdrop_dl.exceptions import (
DownloadError,
@@ -26,15 +26,12 @@ from cyberdrop_dl.exceptions import (
SkipDownloadError,
TooManyCrawlerErrors,
)
-from cyberdrop_dl.utils import aio
from cyberdrop_dl.utils.logger import log, log_debug
from cyberdrop_dl.utils.utilities import error_handling_wrapper, parse_url
# Windows epoch is January 1, 1601. Unix epoch is January 1, 1970
WIN_EPOCH_OFFSET = 116444736e9
MAC_OS_SET_FILE = None
-_VIDEO_HLS_BATCH_SIZE = 10
-_AUDIO_HLS_BATCH_SIZE = 50
# Try to import win32con for Windows constants, fallback to hardcoded values if unavailable
@@ -249,11 +246,8 @@ class Downloader:
if await asyncio.to_thread(output.is_file):
return output
- batch_size = _VIDEO_HLS_BATCH_SIZE if m3u8.media_type == "video" else _AUDIO_HLS_BATCH_SIZE
+ tasks_results = await self._download_segments(media_item, m3u8, download_folder)
- tasks_results = await aio.gather(
- self._prepare_hls_downloads(media_item, m3u8, download_folder), batch_size=batch_size
- )
n_successful = sum(1 for result in tasks_results if result.downloaded)
if n_successful != n_segmets:
@@ -291,9 +285,7 @@ class Downloader:
pass
return video, audio, subtitles
- def _prepare_hls_downloads(
- self, media_item: MediaItem, m3u8: M3U8, download_folder: Path
- ) -> list[Coroutine[None, None, SegmentDownloadResult]]:
+ def _download_segments(self, media_item: MediaItem, m3u8: M3U8, download_folder: Path):
padding = max(5, len(str(len(m3u8.segments))))
def create_segments() -> Generator[HlsSegment]:
@@ -320,7 +312,11 @@ class Downloader:
await self.start_download(seg_media_item),
)
- return [download_segment(segment) for segment in create_segments()]
+ return aio.map(
+ download_segment,
+ create_segments(),
+ task_limit=10 if m3u8.media_type == "video" else 50,
+ )
async def finalize_download(self, media_item: MediaItem, downloaded: bool) -> None:
if downloaded:
diff --git a/cyberdrop_dl/managers/client_manager.py b/cyberdrop_dl/managers/client_manager.py
index 912dc08c4..e425ce9bd 100644
--- a/cyberdrop_dl/managers/client_manager.py
+++ b/cyberdrop_dl/managers/client_manager.py
@@ -15,6 +15,7 @@ from aiohttp import ClientResponse, ClientSession
from aiolimiter import AsyncLimiter
from cyberdrop_dl import constants, ddos_guard, env
+from cyberdrop_dl.aio import WeakAsyncLocks
from cyberdrop_dl.clients.download_client import DownloadClient
from cyberdrop_dl.clients.flaresolverr import FlareSolverr
from cyberdrop_dl.clients.response import AbstractResponse
@@ -23,7 +24,6 @@ from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL, MediaItem
from cyberdrop_dl.exceptions import DDOSGuardError, DownloadError, ScrapeError, TooManyCrawlerErrors
from cyberdrop_dl.ffmpeg import probe
from cyberdrop_dl.ui.prompts.user_prompts import get_cookies_from_browsers
-from cyberdrop_dl.utils.aio import WeakAsyncLocks
from cyberdrop_dl.utils.cookie_management import read_netscape_files
from cyberdrop_dl.utils.logger import log, log_debug, log_spacer
diff --git a/cyberdrop_dl/utils/aio.py b/cyberdrop_dl/utils/aio.py
deleted file mode 100644
index 222c5dc88..000000000
--- a/cyberdrop_dl/utils/aio.py
+++ /dev/null
@@ -1,98 +0,0 @@
-"""Async versions of builtins and some path operations"""
-
-from __future__ import annotations
-
-import asyncio
-import weakref
-from stat import S_ISREG
-from typing import TYPE_CHECKING, Final, Generic, TypeVar, cast
-
-if TYPE_CHECKING:
- import pathlib
- from collections.abc import Awaitable, Sequence
-
-_T = TypeVar("_T")
-
-
-if TYPE_CHECKING:
- from collections.abc import Awaitable, Sequence
-
-
-async def gather(coros: Sequence[Awaitable[_T]], batch_size: int = 10) -> list[_T]:
- """Like `asyncio.gather`, but creates tasks lazily to minimize event loop overhead.
-
- This function ensures there are never more than `batch_size` tasks created at any given time.
-
- If any exception is raised within a task, all currently running tasks
- are cancelled and any renaming task in the queue will be ignored.
- """
-
- semaphore = asyncio.BoundedSemaphore(batch_size)
- results: list[_T] = cast("list[_T]", [None] * len(coros))
-
- async def worker(index: int, coro: Awaitable[_T]):
- try:
- result = await coro
- results[index] = result
- finally:
- semaphore.release()
-
- async with asyncio.TaskGroup() as tg:
- for index, coro in enumerate(coros):
- await semaphore.acquire()
- tg.create_task(worker(index, coro))
-
- return results
-
-
-async def stat(path: pathlib.Path):
- return await asyncio.to_thread(path.stat)
-
-
-async def is_dir(path: pathlib.Path) -> bool:
- return await asyncio.to_thread(path.is_dir)
-
-
-async def is_file(path: pathlib.Path) -> bool:
- return await asyncio.to_thread(path.is_file)
-
-
-async def exists(path: pathlib.Path) -> bool:
- return await asyncio.to_thread(path.exists)
-
-
-async def unlink(path: pathlib.Path, missing_ok: bool = False) -> None:
- return await asyncio.to_thread(path.unlink, missing_ok)
-
-
-async def get_size(path: pathlib.Path) -> int | None:
- """If path exists and is a file, returns its size. Returns `None` otherwise"""
-
- # Manually parse stat result to make sure we only use 1 fs call
-
- try:
- stat_result = await stat(path)
- except (OSError, ValueError):
- return
- else:
- if S_ISREG(stat_result.st_mode):
- return stat_result.st_size
-
-
-class WeakAsyncLocks(Generic[_T]):
- """A WeakValueDictionary wrapper for asyncio.Locks.
-
- Unused locks are automatically garbage collected. When trying to retrieve a
- lock that does not exists, a new lock will be created.
- """
-
- __slots__ = ("__locks",)
-
- def __init__(self) -> None:
- self.__locks: Final = weakref.WeakValueDictionary[_T, asyncio.Lock]()
-
- def __getitem__(self, key: _T, /) -> asyncio.Lock:
- lock = self.__locks.get(key)
- if lock is None:
- self.__locks[key] = lock = asyncio.Lock()
- return lock
diff --git a/cyberdrop_dl/utils/webhook.py b/cyberdrop_dl/utils/webhook.py
index a80197348..ed3b001a7 100644
--- a/cyberdrop_dl/utils/webhook.py
+++ b/cyberdrop_dl/utils/webhook.py
@@ -7,8 +7,7 @@ import aiofiles
import rich
from aiohttp import FormData
-from cyberdrop_dl import constants
-from cyberdrop_dl.utils import aio
+from cyberdrop_dl import aio, constants
from cyberdrop_dl.utils.logger import log, log_debug, log_spacer
if TYPE_CHECKING: