Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
refactor: unify simple cache
NTFSvolume583a9f6c8f91
diff --git a/cyberdrop_dl/aio.py b/cyberdrop_dl/aio.pyindex 5155ab561..f3591cfcb 100644--- a/cyberdrop_dl/aio.py+++ b/cyberdrop_dl/aio.py@@ -17,6 +17,8 @@ from weakref import WeakValueDictionaryfrom aiolimiter.leakybucket import AsyncLimiterfrom typing_extensions import Sentinel+from cyberdrop_dl.constants import MISSING+if TYPE_CHECKING:from collections.abc import (AsyncGenerator,@@ -34,9 +36,6 @@ if TYPE_CHECKING:from _typeshed import OpenBinaryMode, OpenTextMode-_MISSING = Sentinel("_MISSING")--class _AsyncChain:"""Like itertools.chain, but for async iterables"""@@ -151,16 +150,16 @@ def cached[T](fn: Callable[[], Awaitable[T]], *, ttl: float | None = None) -> Cadef _perpetual_cache[T](fn: Callable[[], Awaitable[T]]) -> Callable[[], CoroutineType[Any, Any, T]]:lock = asyncio.Lock()- cached_value: T | Sentinel = _MISSING+ cached_value: T | Sentinel = MISSING@functools.wraps(fn)async def wrapper() -> T:nonlocal cached_value- if cached_value is not _MISSING:+ if cached_value is not MISSING:return cast("T", cached_value)async with lock:- if cached_value is not _MISSING:+ if cached_value is not MISSING:return cast("T", cached_value)cached_value = await fn()@@ -219,8 +218,8 @@ class AsyncIteratorWrapper[T]: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:+ value = await asyncio.to_thread(next, self._iterator, MISSING)+ if value is MISSING:raise StopAsyncIteration from Nonereturn cast("T", value)diff --git a/cyberdrop_dl/constants.py b/cyberdrop_dl/constants.pyindex c75492768..9475c2a20 100644--- a/cyberdrop_dl/constants.py+++ b/cyberdrop_dl/constants.py@@ -6,6 +6,7 @@ from enum import Enum, StrEnum, autofrom typing import TYPE_CHECKING, finalfrom rich.text import Text+from typing_extensions import Sentinelfrom cyberdrop_dl import __version__, env@@ -17,6 +18,7 @@ LOGS_DATETIME_FORMAT = "%Y%m%d_%H%M%S"LOGS_DATE_FORMAT = "%Y_%m_%d"STARTUP_TIME_STR = datetime.datetime.now().strftime(LOGS_DATETIME_FORMAT) # noqa: DTZ005CDL_USER_AGENT = f"cyberdrop-dl/{__version__}"+MISSING = Sentinel("MISSING")MAIN_LOG_FILE: ContextVar[Path] = ContextVar("MAIN_LOG_FILE")diff --git a/cyberdrop_dl/models/__init__.py b/cyberdrop_dl/models/__init__.pyindex e144e75eb..160826782 100644--- a/cyberdrop_dl/models/__init__.py+++ b/cyberdrop_dl/models/__init__.py@@ -1,12 +1,12 @@"""Pydantic models"""-import functoolsfrom typing import Any, ClassVar, TypedDictfrom cyclopts import Parameterfrom pydantic import AnyUrl, BaseModel, Secret, SerializationInfo, TypeAdapter, model_serializer, model_validatorfrom cyberdrop_dl import env+from cyberdrop_dl.utils import fast_cacheclass DeferedModel(@@ -128,7 +128,7 @@ def merge_models[M: BaseModel](default: M, new: M) -> M:return default.model_validate(updated_dict)+@fast_cachedef type_adapter[T](cls: type[T]) -> TypeAdapter[T]:"""Get a type adapter for this class.diff --git a/cyberdrop_dl/utils/__init__.py b/cyberdrop_dl/utils/__init__.pyindex 88a292ef6..bc9632160 100644--- a/cyberdrop_dl/utils/__init__.py+++ b/cyberdrop_dl/utils/__init__.py@@ -6,15 +6,16 @@ import itertoolsimport loggingimport platformimport sys-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, cast+from cyberdrop_dl.constants import MISSINGfrom cyberdrop_dl.utils._dataclasses import DictDataclass, deserialize, filter_data # noqa: F401from cyberdrop_dl.utils._errors import error_handling_context, error_handling_wrapper # noqa: F401from cyberdrop_dl.utils._url import parse_http_url as parse_url # noqa: F401from cyberdrop_dl.utils._url import remove_trailing_slash # noqa: F401if TYPE_CHECKING:- from collections.abc import Generator, Iterable+ from collections.abc import Callable, Generator, Iterablefrom contextvars import ContextVar@@ -104,3 +105,18 @@ def unique[T](itr: Iterable[T], /) -> Generator[T]:if ele not in seen:seen.add(ele)yield ele+++def fast_cache[T, R](fn: Callable[[T], R]) -> Callable[[T], R]:+ "Like functools.cache but for single argument funciton and without all the stats logic"+ cache: dict[T, R] = {}++ def compute(obj: T) -> R:+ val = cache.get(obj, MISSING)+ if val is not MISSING:+ return cast("R", val)++ cache[obj] = val = fn(obj)+ return val++ return computediff --git a/cyberdrop_dl/utils/_dataclasses.py b/cyberdrop_dl/utils/_dataclasses.pyindex eb70cc799..2f14563b1 100644--- a/cyberdrop_dl/utils/_dataclasses.py+++ b/cyberdrop_dl/utils/_dataclasses.py@@ -3,7 +3,8 @@ from __future__ import annotationsimport dataclassesfrom typing import TYPE_CHECKING, Any, ClassVar, Protocol, Self-from typing_extensions import Sentinel+from cyberdrop_dl.constants import MISSING+from cyberdrop_dl.utils import fast_cacheif TYPE_CHECKING:from collections.abc import Mapping@@ -14,18 +15,15 @@ class _DataClass(Protocol):_FIELDS_CACHE: dict[type, tuple[str, ...]] = {}-_MISSING = Sentinel("_MISSING")+@fast_cachedef _fields(cls: type[_DataClass]) -> tuple[str, ...]:- if fields := _FIELDS_CACHE.get(cls):- return fields- fields = _FIELDS_CACHE[cls] = tuple(f.name for f in dataclasses.fields(cls) if f.init)- return fields+ return tuple(f.name for f in dataclasses.fields(cls) if f.init)def filter_data[DataClassT: _DataClass](cls: type[DataClassT], data: Mapping[str, Any], /) -> dict[str, Any]:- return {name: value for name in _fields(cls) if (value := data.get(name, _MISSING)) is not _MISSING}+ return {name: value for name in _fields(cls) if (value := data.get(name, MISSING)) is not MISSING}def deserialize[DataClassT: _DataClass](