Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: allow caching to inner TTL entries

NTFSvolumecb72761d79e4
diff --git a/cyberdrop_dl/cache.py b/cyberdrop_dl/cache.py
index 2d5764c4d..7a10e13bd 100644
--- a/cyberdrop_dl/cache.py
+++ b/cyberdrop_dl/cache.py
@@ -74,6 +74,11 @@ class TTLCacheAdapter[T]:
_keys: tuple[str, ...] = ()
__root: dict[str, _CachedValue[Any]] = dataclasses.field(init=False, repr=False)
+ def create_child(self, *keys: str) -> Self:
+ if not keys:
+ return self
+ return type(self)(self._root, keys)
+
def _lookup_path(self, *keys: str) -> str:
return ".".join([*self._keys, *keys])
@@ -166,11 +171,11 @@ type _SupportsDiskCacheCallable[T] = Callable[[_HasTTLCache[Any]], Awaitable[T]]
class _CachedMethod[T, R]:
"""Use as a class method decorator."""
- def __init__(self, fn: Callable[[Any], Awaitable[R]], key: str | None, ttl: float | None) -> None:
+ def __init__(self, fn: Callable[[Any], Awaitable[R]], key: tuple[str, ...] | str | None, ttl: float | None) -> None:
self.wrapped: Callable[[Any], Awaitable[R]] = fn
self.__doc__ = fn.__doc__
self.name: str = fn.__name__
- self.key: str = key or fn.__name__
+ self.key: tuple[str, ...] | str = key or fn.__name__
self.ttl: float | None = ttl
self._cached_fn: CachedAsyncFunc[R] | None = None
@@ -206,16 +211,26 @@ class _DiskCachedMethod[R](_CachedMethod[_HasTTLCache[Any], R]):
return inst.cache
+def _normalize_key(key: tuple[str, ...] | str) -> tuple[list[str], str]:
+ keys = key
+ if isinstance(keys, str):
+ keys = keys.split(".")
+
+ *parent_keys, key = keys
+ return parent_keys, key
+
+
def cached_fn[T](
fn: Callable[[], Awaitable[T]],
cache: TTLCacheAdapter[T] | None = None,
*,
- key: str | None = None,
+ key: tuple[str, ...] | str | None = None,
ttl: float | None = None,
) -> CachedAsyncFunc[T]:
- key = key or fn.__name__
+ parent_keys, key = _normalize_key(key or fn.__name__)
cache = cache or _ttl_from_callable(fn)
+ cache = cache.create_child(*parent_keys)
lock = asyncio.Lock()
@functools.wraps(fn)
@@ -236,7 +251,7 @@ def cached_fn[T](
def cached_method[T](
- key: str | None = None, *, ttl: float | None = None
+ key: tuple[str, ...] | str | None = None, *, ttl: float | None = None
) -> Callable[[Callable[[Any], Coroutine[Any, Any, T]]], _InMemoryCachedMethod[T]]:
"""Keep the last result of this method in memory until TTL expires
@@ -249,7 +264,7 @@ def cached_method[T](
def disk_cached_method[T](
- key: str | None = None, *, ttl: float | None = None
+ key: tuple[str, ...] | str | None = None, *, ttl: float | None = None
) -> Callable[[Callable[[Any], Coroutine[Any, Any, T]]], _DiskCachedMethod[T]]:
"""Keep the last result of this method in memory until TTL expires
diff --git a/tests/test_cache.py b/tests/test_cache.py
index d78da3b01..c619cec94 100644
--- a/tests/test_cache.py
+++ b/tests/test_cache.py
@@ -11,6 +11,7 @@ from cyberdrop_dl.cache import (
_IN_MEMORY_CACHE,
TTLCacheAdapter,
_DiskCachedMethod,
+ _normalize_key,
cache_context,
cached_fn,
disk_cached_method,
@@ -214,3 +215,56 @@ async def test_ttl_cache_method() -> None:
assert await inst.compute() == 2
await asyncio.sleep(0.2 + 0.1)
assert await inst.compute() == 3
+
+
+ ("key", "expected_parent_keys", "expected_key"),
+ [
+ ("key", [], "key"),
+ ("parent.inner", ["parent"], "inner"),
+ ("a.b.c", ["a", "b"], "c"),
+ ],
+)
+def test_normalize_key(key: tuple[str, ...], expected_parent_keys: list[str,], expected_key: str) -> None:
+ parents, real_key = _normalize_key(key)
+ assert parents == expected_parent_keys
+ assert real_key == expected_key
+
+
+def test_ttl_child() -> None:
+ cache = {}
+ ttl_cache = TTLCacheAdapter(cache, ("a", "b"))
+ ttl_cache["c"] = 1
+
+ assert cache == {
+ "a": {
+ "b": {
+ "c": {
+ "value": 1,
+ "ttl": None,
+ "created_at": mock.ANY,
+ }
+ }
+ }
+ }
+ assert ttl_cache.create_child() is ttl_cache
+ inner = ttl_cache.create_child("d")
+ inner["f"] = 2
+ assert cache == {
+ "a": {
+ "b": {
+ "c": {
+ "value": 1,
+ "ttl": None,
+ "created_at": mock.ANY,
+ },
+ "d": {
+ "f": {
+ "value": 2,
+ "ttl": None,
+ "created_at": mock.ANY,
+ }
+ },
+ }
+ }
+ }