diff --git a/api/ovdashboard_api/__init__.py b/api/ovdashboard_api/__init__.py index 4fa6c6e..2baa131 100644 --- a/api/ovdashboard_api/__init__.py +++ b/api/ovdashboard_api/__init__.py @@ -1,8 +1,10 @@ import asyncio import functools +import time from typing import Any import caldav +from async_lru import alru_cache from webdav3 import client as WebDAVclient from .config import SETTINGS @@ -31,6 +33,28 @@ def run_in_executor(f): return inner +def get_ttl_hash(seconds: int = 20) -> int: + """ + Return the same value within `seconds` time period + https://stackoverflow.com/a/55900800 + """ + return round(time.time() / seconds) + + +def timed_alru_cache(**decorator_kwargs): + def decorate(f): + @alru_cache(**decorator_kwargs) + @functools.wraps(f) + async def wrapper(ttl_hash: int, *args, **kwargs): + del ttl_hash + + return await f(*args, **kwargs) + + return wrapper + + return decorate + + @functools.lru_cache def webdav_resource(remote_path: Any) -> WebDAVclient.Resource: return _WEBDAV_CLIENT.resource(remote_path) diff --git a/api/ovdashboard_api/dav_file.py b/api/ovdashboard_api/dav_file.py index c774a15..c6f9902 100644 --- a/api/ovdashboard_api/dav_file.py +++ b/api/ovdashboard_api/dav_file.py @@ -1,32 +1,19 @@ import logging -import time from dataclasses import dataclass from io import BytesIO -from typing import Any, Optional +from typing import Any -from async_lru import alru_cache from webdav3.client import Resource -from . import run_in_executor, webdav_resource +from . import get_ttl_hash, run_in_executor, timed_alru_cache, webdav_resource _logger = logging.getLogger(__name__) -def _get_ttl_hash(seconds: int = 20) -> int: - """ - Return the same value within `seconds` time period - https://stackoverflow.com/a/55900800 - """ - return round(time.time() / seconds) - - -@alru_cache(maxsize=20) +@timed_alru_cache(maxsize=20) async def _get_buffer( remote_path: Any, - ttl_hash: Optional[int] = None, ) -> BytesIO: - del ttl_hash - @run_in_executor def buffer_inner(resource: Resource) -> BytesIO: _logger.info(f"updating {resource}") @@ -46,8 +33,8 @@ class DavFile: @property async def __buffer(self) -> BytesIO: return await _get_buffer( + ttl_hash=get_ttl_hash(), remote_path=self.remote_path, - ttl_hash=_get_ttl_hash(20), ) @property