Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions cachify/features/never_die.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,18 @@ def revive(self):


def _run_sync_function_and_cache(entry: NeverDieCacheEntry):
"""Run a function and cache its result"""
try:
cached = entry.config.storage.get(entry.cache_key, False)
if cached and cached.is_fresh(entry.ttl):
entry.reset()
return

with entry.config.sync_lock(entry.cache_key):
cached = entry.config.storage.get(entry.cache_key, False)
if cached and cached.is_fresh(entry.ttl):
entry.reset()
return

result = entry.function(*entry.args, **entry.kwargs)
entry.config.storage.set(entry.cache_key, result, None)
entry.reset()
Expand All @@ -86,9 +95,18 @@ def _run_sync_function_and_cache(entry: NeverDieCacheEntry):


async def _run_async_function_and_cache(entry: NeverDieCacheEntry):
"""Run a function and cache its result"""
try:
cached = await entry.config.storage.aget(entry.cache_key, False)
if cached and cached.is_fresh(entry.ttl):
entry.reset()
return

async with entry.config.async_lock(entry.cache_key):
cached = await entry.config.storage.aget(entry.cache_key, False)
if cached and cached.is_fresh(entry.ttl):
entry.reset()
return

result = await entry.function(*entry.args, **entry.kwargs)
await entry.config.storage.aset(entry.cache_key, result, None)
entry.reset()
Expand Down
5 changes: 5 additions & 0 deletions cachify/types/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ def is_expired(self) -> bool:

return self.time() > self.expires_at

def is_fresh(self, ttl: float) -> bool:
return self.time() - self.cached_at < ttl


@dataclass(frozen=True, slots=True)
class CacheConfig:
Expand All @@ -49,6 +52,8 @@ class CacheEntryProtocol(Protocol):

def is_expired(self) -> bool: ...

def is_fresh(self, ttl: float) -> bool: ...


class CacheStorage(Protocol):
"""Protocol defining the interface for cache storage."""
Expand Down