2018-10-30 14:58:48 +00:00
|
|
|
import time, typing, uuid
|
2018-09-29 11:53:39 +00:00
|
|
|
|
|
|
|
class Cache(object):
|
|
|
|
def __init__(self):
|
|
|
|
self._items = {}
|
|
|
|
self._item_to_id = {}
|
|
|
|
|
2018-10-30 14:58:48 +00:00
|
|
|
def cache(self, item: typing.Any) -> str:
|
2018-09-29 11:53:39 +00:00
|
|
|
return self._cache(item, None)
|
2018-10-30 14:58:48 +00:00
|
|
|
def temporary_cache(self, item: typing.Any, timeout: float)-> str:
|
2018-10-30 17:49:35 +00:00
|
|
|
return self._cache(item, time.monotonic()+timeout)
|
|
|
|
def _cache(self, item: typing.Any, timeout: typing.Optional[float]) -> str:
|
2018-09-29 11:53:39 +00:00
|
|
|
id = str(uuid.uuid4())
|
2018-10-30 17:49:35 +00:00
|
|
|
self._items[id] = [item, timeout]
|
2018-09-29 11:53:39 +00:00
|
|
|
self._item_to_id[item] = id
|
|
|
|
return id
|
|
|
|
|
2018-10-30 17:49:35 +00:00
|
|
|
def next_expiration(self) -> typing.Optional[float]:
|
2018-09-29 11:53:39 +00:00
|
|
|
expirations = [self._items[id][1] for id in self._items]
|
|
|
|
expirations = list(filter(None, expirations))
|
|
|
|
if not expirations:
|
|
|
|
return None
|
2019-06-22 22:30:15 +00:00
|
|
|
now = time.monotonic()
|
|
|
|
expirations = [e-now for e in expirations]
|
2018-09-29 11:53:39 +00:00
|
|
|
return max(min(expirations), 0)
|
|
|
|
|
|
|
|
def expire(self):
|
|
|
|
now = time.monotonic()
|
|
|
|
expired = []
|
|
|
|
for id in self._items:
|
|
|
|
item, expiration = self._items[id]
|
|
|
|
if expiration and expiration <= now:
|
|
|
|
expired.append(id)
|
|
|
|
for id in expired:
|
2018-09-30 17:00:23 +00:00
|
|
|
item, expiration = self._items[id]
|
2018-09-29 11:53:39 +00:00
|
|
|
del self._items[id]
|
|
|
|
del self._item_to_id[item]
|
|
|
|
|
2018-10-30 14:58:48 +00:00
|
|
|
def has_item(self, item: typing.Any) -> bool:
|
2018-09-29 11:53:39 +00:00
|
|
|
return item in self._item_to_id
|
|
|
|
|
2018-10-30 14:58:48 +00:00
|
|
|
def get(self, id: str) -> typing.Any:
|
2018-09-29 11:53:39 +00:00
|
|
|
item, expiration = self._items[id]
|
|
|
|
return item
|
|
|
|
|
2018-10-30 14:58:48 +00:00
|
|
|
def get_expiration(self, item: typing.Any) -> float:
|
2018-09-29 11:53:39 +00:00
|
|
|
id = self._item_to_id[item]
|
|
|
|
item, expiration = self._items[id]
|
|
|
|
return expiration
|
2018-10-30 14:58:48 +00:00
|
|
|
def until_expiration(self, item: typing.Any) -> float:
|
2018-09-29 11:53:39 +00:00
|
|
|
expiration = self.get_expiration(item)
|
|
|
|
return expiration-time.monotonic()
|