Refactor cache L2 storage to use SQLAlchemy DB

Replaces the L2 cache layer's SQLite implementation with an async SQLAlchemy-based database model (CacheEntries). Updates cache_manager.py to use db_query and db_save for cache operations, adds semantic cache handling with ChromaDB, and introduces async cache clearing and expiration cleaning methods. Adds the CacheEntries model and integrates it into the database API.
This commit is contained in:
雅诺狐
2025-08-18 18:30:17 +08:00
parent 7856c6a8e9
commit bcbcabb0d8
3 changed files with 233 additions and 90 deletions

View File

@@ -9,6 +9,7 @@ from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import QueuePool
import os
import datetime
import time
from src.common.logger import get_logger
import threading
from contextlib import contextmanager
@@ -476,6 +477,40 @@ class AntiInjectionStats(Base):
)
class CacheEntries(Base):
"""工具缓存条目模型"""
__tablename__ = 'cache_entries'
id = Column(Integer, primary_key=True, autoincrement=True)
cache_key = Column(get_string_field(500), nullable=False, unique=True, index=True)
"""缓存键,包含工具名、参数和代码哈希"""
cache_value = Column(Text, nullable=False)
"""缓存的数据JSON格式"""
expires_at = Column(Float, nullable=False, index=True)
"""过期时间戳"""
tool_name = Column(get_string_field(100), nullable=False, index=True)
"""工具名称"""
created_at = Column(Float, nullable=False, default=lambda: time.time())
"""创建时间戳"""
last_accessed = Column(Float, nullable=False, default=lambda: time.time())
"""最后访问时间戳"""
access_count = Column(Integer, nullable=False, default=0)
"""访问次数"""
__table_args__ = (
Index('idx_cache_entries_key', 'cache_key'),
Index('idx_cache_entries_expires_at', 'expires_at'),
Index('idx_cache_entries_tool_name', 'tool_name'),
Index('idx_cache_entries_created_at', 'created_at'),
)
# 数据库引擎和会话管理
_engine = None
_SessionLocal = None