42 lines
1.1 KiB
Python
42 lines
1.1 KiB
Python
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import time
|
||
|
|
from collections import OrderedDict
|
||
|
|
|
||
|
|
|
||
|
|
class SynologyChatDedupe:
|
||
|
|
def __init__(self, ttl_seconds: int = 300, max_entries: int = 10000):
|
||
|
|
self._ttl_seconds = ttl_seconds
|
||
|
|
self._max_entries = max_entries
|
||
|
|
self._store: OrderedDict[str, float] = OrderedDict()
|
||
|
|
|
||
|
|
def is_duplicate(self, key: str) -> bool:
|
||
|
|
now = time.monotonic()
|
||
|
|
if key in self._store:
|
||
|
|
ts = self._store[key]
|
||
|
|
if now - ts < self._ttl_seconds:
|
||
|
|
return True
|
||
|
|
del self._store[key]
|
||
|
|
return False
|
||
|
|
|
||
|
|
def mark_seen(self, key: str) -> None:
|
||
|
|
now = time.monotonic()
|
||
|
|
if key in self._store:
|
||
|
|
self._store.move_to_end(key)
|
||
|
|
self._store[key] = now
|
||
|
|
self._evict()
|
||
|
|
|
||
|
|
def _evict(self) -> None:
|
||
|
|
while len(self._store) > self._max_entries:
|
||
|
|
self._store.popitem(last=False)
|
||
|
|
|
||
|
|
def reset(self) -> None:
|
||
|
|
self._store.clear()
|
||
|
|
|
||
|
|
@property
|
||
|
|
def ttl_seconds(self) -> int:
|
||
|
|
return self._ttl_seconds
|
||
|
|
|
||
|
|
@property
|
||
|
|
def max_entries(self) -> int:
|
||
|
|
return self._max_entries
|