ForcePilot/backend/package/yuxi/channel/routing/cache.py
Kris bab30f2715
Some checks failed
Deploy VitePress site to Pages / build (push) Has been cancelled
Ruff Format Check / Ruff Format & Lint (push) Has been cancelled
Deploy VitePress site to Pages / Deploy (push) Has been cancelled
feat:0715
2026-07-15 12:30:58 +08:00

83 lines
2.8 KiB
Python

"""路由缓存"""
import asyncio
import time
from collections import OrderedDict
from dataclasses import dataclass
from typing import Any
@dataclass
class _CacheEntry:
value: Any
timestamp: float
class RouteCache:
"""基于 OrderedDict 的进程内 LRU 缓存,上限 4000 条,默认 TTL 60 秒。
使用 asyncio.Lock 保护并发访问;批量失效时收集待删除 key 后统一移除。
"""
def __init__(self, maxsize: int = 4000, ttl_seconds: float = 60) -> None:
self.maxsize = max(maxsize, 1)
self.ttl = ttl_seconds
self._data: OrderedDict[str, _CacheEntry] = OrderedDict()
self._lock = asyncio.Lock()
def _is_expired(self, entry: _CacheEntry) -> bool:
return time.time() - entry.timestamp > self.ttl
async def get(self, key: str) -> Any | None:
async with self._lock:
entry = self._data.get(key)
if entry is None:
return None
if self._is_expired(entry):
self._data.pop(key, None)
return None
self._data.move_to_end(key)
return entry.value
async def set(self, key: str, value: Any) -> None:
async with self._lock:
if key in self._data:
self._data.move_to_end(key)
else:
while len(self._data) >= self.maxsize:
self._data.popitem(last=False)
self._data[key] = _CacheEntry(value=value, timestamp=time.time())
async def clear(self) -> None:
async with self._lock:
self._data.clear()
async def invalidate_by_channel(self, channel_type: str) -> int:
"""移除所有以 `channel_type:` 开头的缓存条目,返回移除数量。"""
prefix = f"{channel_type}:"
async with self._lock:
keys_to_remove = [k for k in self._data if k.startswith(prefix)]
for k in keys_to_remove:
self._data.pop(k, None)
return len(keys_to_remove)
async def invalidate_by_account(self, channel_type: str, account_id: str) -> int:
"""移除所有以 `channel_type:account_id:` 开头的缓存条目,返回移除数量。"""
prefix = f"{channel_type}:{account_id}:"
async with self._lock:
keys_to_remove = [k for k in self._data if k.startswith(prefix)]
for k in keys_to_remove:
self._data.pop(k, None)
return len(keys_to_remove)
_default_route_cache: RouteCache | None = None
def get_default_route_cache() -> RouteCache:
"""返回全局共享的默认路由缓存实例。"""
global _default_route_cache
if _default_route_cache is None:
_default_route_cache = RouteCache(maxsize=4000, ttl_seconds=60)
return _default_route_cache