Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: add async cache utils (#1886)

NTFSvolume9928aa3f6e36
diff --git a/cyberdrop_dl/aio.py b/cyberdrop_dl/aio.py
index d6a2f2834..d14c94f8c 100644
--- a/cyberdrop_dl/aio.py
+++ b/cyberdrop_dl/aio.py
@@ -6,9 +6,11 @@ from __future__ import annotations
import asyncio
import contextlib
import dataclasses
+import functools
import shutil
import sys
import tempfile
+import time
from pathlib import Path
from stat import S_ISREG
from typing import IO, TYPE_CHECKING, Any, AnyStr, Generic, ParamSpec, Self, TypeVar, TypeVarTuple, cast, overload
@@ -19,6 +21,7 @@ from typing_extensions import Sentinel
if TYPE_CHECKING:
from collections.abc import AsyncGenerator, AsyncIterator, Awaitable, Callable, Coroutine, Iterable, Iterator
+ from types import CoroutineType
from _typeshed import OpenBinaryMode, OpenTextMode
@@ -71,6 +74,66 @@ class RateLimiter(AsyncLimiter):
return cls(max_rate=0, time_period=1)
[email protected](slots=True, frozen=True)
+class _CachedValue(Generic[_T]):
+ value: _T
+ ttl: float | None
+ created_at: float = dataclasses.field(init=False, default_factory=time.monotonic)
+
+ @property
+ def is_expired(self) -> bool:
+ if self.ttl is None:
+ return False
+ return time.monotonic() - self.created_at >= self.ttl
+
+
+def cached(
+ *, ttl: float | None = None
+) -> Callable[[Callable[[], Awaitable[_T]]], Callable[[], CoroutineType[Any, Any, _T]]]:
+ if ttl is None:
+ return _perpertual_cache
+
+ def make_decorator(fn: Callable[[], Awaitable[_T]]) -> Callable[[], CoroutineType[Any, Any, _T]]:
+ lock = asyncio.Lock()
+ cached_value: _CachedValue[_T] | None = None
+
+ @functools.wraps(fn)
+ async def call() -> _T:
+ nonlocal cached_value
+ async with lock:
+ if cached_value is not None and not cached_value.is_expired:
+ return cached_value.value
+
+ cached_value = _CachedValue(await fn(), ttl=ttl)
+
+ return cached_value.value
+
+ return call
+
+ return make_decorator
+
+
+def _perpertual_cache(fn: Callable[[], Awaitable[_T]]) -> Callable[[], CoroutineType[Any, Any, _T]]:
+ lock = asyncio.Lock()
+ cached_value: _T | Sentinel = _MISSING
+
+ @functools.wraps(fn)
+ async def call() -> _T:
+ nonlocal cached_value
+ if cached_value is not _MISSING:
+ return cast("_T", cached_value)
+
+ async with lock:
+ if cached_value is not _MISSING:
+ return cast("_T", cached_value)
+
+ cached_value = await fn()
+
+ return cached_value
+
+ return call
+
+
@dataclasses.dataclass(slots=True, eq=False)
class AsyncIOWrapper(Generic[AnyStr]):
"""An asynchronous context manager wrapper for a file object."""
diff --git a/tests/test_aio.py b/tests/test_aio.py
new file mode 100644
index 000000000..e69cf91fe
--- /dev/null
+++ b/tests/test_aio.py
@@ -0,0 +1,42 @@
+from __future__ import annotations
+
+import asyncio
+
+from cyberdrop_dl import aio
+
+
+class Spy:
+ def __init__(self, value: object) -> None:
+ self.value: object = value
+ self.calls: int = 0
+
+ async def __call__(self) -> object:
+ self.calls += 1
+ return self.value
+
+
+async def test_cache_returns_same_value_while_not_expired() -> None:
+ ttl = 2.0
+ spy = Spy("test 1")
+ factory = aio.cached(ttl=ttl)(spy)
+ first = await factory()
+ second = await factory()
+
+ assert first == second
+ assert spy.calls == 1
+ await asyncio.sleep(ttl + 0.1)
+ _ = await factory()
+ assert spy.calls == 2
+
+
+async def test_concurrent_calls_execute_only_once() -> None:
+ spy = Spy("test 2")
+
+ @aio.cached(ttl=60)
+ async def factory() -> object:
+ await asyncio.sleep(0.02)
+ return await spy()
+
+ results = await asyncio.gather(*(factory() for _ in range(10)))
+ assert len(set(results)) == 1
+ assert spy.calls == 1