|
| 1 | +import asyncio |
| 2 | +import threading |
| 3 | +from abc import ABC, abstractmethod |
| 4 | +from typing import Any, Union, Hashable, Dict, Optional |
| 5 | + |
| 6 | +from llist import dllist, dllistnode |
| 7 | + |
| 8 | + |
| 9 | +class CacheBase(ABC): |
| 10 | + def __init__(self, max_size: int = 0): |
| 11 | + self._max_size: int = max_size |
| 12 | + self._loop: Optional[asyncio.AbstractEventLoop] = None |
| 13 | + self.usages: dllist = dllist() |
| 14 | + self.cache: Dict[Hashable, Any] = dict() |
| 15 | + self.lock = threading.RLock() |
| 16 | + |
| 17 | + @property |
| 18 | + def is_overflow(self) -> bool: |
| 19 | + if self._max_size == 0: |
| 20 | + return False |
| 21 | + |
| 22 | + if self._max_size < len(self.usages): |
| 23 | + return True |
| 24 | + |
| 25 | + return False |
| 26 | + |
| 27 | + @property |
| 28 | + def loop(self) -> asyncio.AbstractEventLoop: |
| 29 | + if self._loop is None: |
| 30 | + self._loop = asyncio.get_event_loop() |
| 31 | + return self._loop |
| 32 | + |
| 33 | + @abstractmethod |
| 34 | + def _on_set(self, node: dllistnode) -> None: |
| 35 | + pass |
| 36 | + |
| 37 | + def _on_expires(self, node: dllistnode) -> None: |
| 38 | + pass |
| 39 | + |
| 40 | + @abstractmethod |
| 41 | + def _on_get(self, node: dllistnode) -> Any: |
| 42 | + pass |
| 43 | + |
| 44 | + def __contains__(self, item: Hashable) -> bool: |
| 45 | + return item in self.cache |
| 46 | + |
| 47 | + def get(self, item: Hashable) -> Any: |
| 48 | + with self.lock: |
| 49 | + node: dllistnode = self.cache[item] |
| 50 | + self.loop.call_soon(self._on_get, node) |
| 51 | + return node.value[1] |
| 52 | + |
| 53 | + def expire(self, node: dllistnode): |
| 54 | + with self.lock: |
| 55 | + item, value = node.value |
| 56 | + node: Optional[dllistnode] = self.cache.pop(item, None) |
| 57 | + |
| 58 | + if node is None: |
| 59 | + return |
| 60 | + |
| 61 | + self.loop.call_soon(self._on_expires, node) |
| 62 | + self.usages.remove(node) |
| 63 | + |
| 64 | + def set(self, item: Hashable, value: Any, |
| 65 | + expiration: Union[int, float] = None) -> None: |
| 66 | + with self.lock: |
| 67 | + node: dllistnode = self.usages.append((item, value)) |
| 68 | + self.cache[item] = node |
| 69 | + |
| 70 | + self.loop.call_soon(self._on_set, node) |
| 71 | + |
| 72 | + if expiration is not None: |
| 73 | + self.loop.call_later(expiration, self.expire, node) |
0 commit comments