Spaces:
Build error
Build error
File size: 17,302 Bytes
0ca462b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 | """
Intent Engine - Search Session Manager
Redis-backed session storage for search pagination with support for:
- Distributed session storage across multiple workers/containers
- Configurable TTL with automatic expiration
- On-demand result fetching from backends
- Cursor-based and offset-based pagination
- Session metadata tracking
Usage:
from app.config.search_session_manager import get_session_manager
manager = get_session_manager()
session_id = await manager.create_session(...)
session = await manager.get_session(session_id)
"""
import json
import logging
import uuid
from datetime import UTC, datetime
from app.config.settings import get_settings
logger = logging.getLogger(__name__)
class SearchSessionData:
"""Data class for search session information"""
def __init__(
self,
session_id: str,
query: str,
total_results: int,
intent: dict | None = None,
page_size: int = 20,
max_results: int = 100,
ttl_minutes: int = 10,
cache_results: bool = True,
):
self.session_id = session_id
self.query = query
self.total_results = total_results
self.intent = intent
self.page_size = page_size
self.max_results = max_results
self.ttl_minutes = ttl_minutes
self.cache_results = cache_results
self.created_at = datetime.now(UTC)
self.accessed_at = datetime.now(UTC)
self.all_results: list[dict] = [] # Cached results
self.backend_fetched_pages: list[int] = [] # Track fetched pages
self.result_count: int = 0 # Total results cached
def to_dict(self) -> dict:
"""Serialize session data to dictionary"""
return {
"session_id": self.session_id,
"query": self.query,
"total_results": self.total_results,
"intent": self.intent,
"page_size": self.page_size,
"max_results": self.max_results,
"ttl_minutes": self.ttl_minutes,
"cache_results": self.cache_results,
"created_at": self.created_at.isoformat(),
"accessed_at": self.accessed_at.isoformat(),
"all_results": self.all_results,
"backend_fetched_pages": self.backend_fetched_pages,
"result_count": self.result_count,
}
@classmethod
def from_dict(cls, data: dict) -> "SearchSessionData":
"""Deserialize session data from dictionary"""
session = cls(
session_id=data["session_id"],
query=data["query"],
total_results=data["total_results"],
intent=data.get("intent"),
page_size=data.get("page_size", 20),
max_results=data.get("max_results", 100),
ttl_minutes=data.get("ttl_minutes", 10),
cache_results=data.get("cache_results", True),
)
session.created_at = datetime.fromisoformat(data["created_at"])
session.accessed_at = datetime.fromisoformat(data["accessed_at"])
session.all_results = data.get("all_results", [])
session.backend_fetched_pages = data.get("backend_fetched_pages", [])
session.result_count = data.get("result_count", len(session.all_results))
return session
class SearchSessionManager:
"""
Manages search sessions with Redis-backed storage.
Features:
- Create, read, update, delete search sessions
- Automatic TTL management
- Result caching and on-demand fetching
- Pagination support (offset and cursor-based)
"""
def __init__(self):
self._redis = None
self._enabled = False
self._key_prefix = "search:session"
self._settings = get_settings()
# In-memory fallback (development only)
self._memory_store: dict[str, SearchSessionData] = {}
async def initialize(self):
"""Initialize Redis connection"""
if self._redis is not None:
return
try:
from app.config.redis_cache import cache as redis_cache
if redis_cache and redis_cache._client:
self._redis = redis_cache._client
self._enabled = True
logger.info("Search Session Manager using Redis storage")
else:
logger.warning("Redis not available, using in-memory storage (development mode)")
self._enabled = False
except Exception as e:
logger.warning(f"Failed to initialize Redis for sessions: {e}. Using in-memory storage.")
self._enabled = False
async def close(self):
"""Cleanup resources"""
# Redis connection is managed by redis_cache module
self._memory_store.clear()
def _generate_key(self, session_id: str) -> str:
"""Generate Redis key for session"""
return f"{self._key_prefix}:{session_id}"
async def create_session(
self,
query: str,
results: list[dict],
total_results: int,
intent: dict | None = None,
page_size: int = 20,
max_results: int = 100,
ttl_minutes: int = 10,
cache_results: bool = True,
) -> str:
"""
Create a new search session with initial results.
Args:
query: Search query string
results: Initial list of results (first page)
total_results: Total number of results available
intent: Extracted intent data
page_size: Number of results per page
max_results: Maximum results to cache
ttl_minutes: Session TTL in minutes
cache_results: Whether to cache results in Redis
Returns:
Session ID
"""
session_id = str(uuid.uuid4())
session_data = SearchSessionData(
session_id=session_id,
query=query,
total_results=total_results,
intent=intent,
page_size=page_size,
max_results=max_results,
ttl_minutes=ttl_minutes,
cache_results=cache_results,
)
# Store initial results
session_data.all_results = results[:max_results]
session_data.result_count = len(results)
# Store in Redis or memory
if self._enabled and self._redis:
key = self._generate_key(session_id)
ttl_seconds = ttl_minutes * 60
await self._redis.setex(
key,
ttl_seconds,
json.dumps(session_data.to_dict(), default=str),
)
logger.debug(f"Created session {session_id} in Redis (TTL: {ttl_seconds}s)")
else:
self._memory_store[session_id] = session_data
logger.debug(f"Created session {session_id} in memory")
return session_id
async def get_session(self, session_id: str) -> SearchSessionData | None:
"""
Retrieve session by ID.
Args:
session_id: Session identifier
Returns:
SearchSessionData or None if not found/expired
"""
if self._enabled and self._redis:
key = self._generate_key(session_id)
data = await self._redis.get(key)
if data:
# Update accessed_at timestamp
session_data = SearchSessionData.from_dict(json.loads(data))
session_data.accessed_at = datetime.now(UTC)
# Refresh TTL on access
ttl_seconds = session_data.ttl_minutes * 60
await self._redis.setex(
key,
ttl_seconds,
json.dumps(session_data.to_dict(), default=str),
)
return session_data
return None
session_data = self._memory_store.get(session_id)
if session_data:
session_data.accessed_at = datetime.now(UTC)
return session_data
async def update_session(self, session_data: SearchSessionData) -> bool:
"""
Update session data.
Args:
session_data: Updated session data
Returns:
True if successful, False if session not found
"""
session_data.accessed_at = datetime.now(UTC)
if self._enabled and self._redis:
key = self._generate_key(session_data.session_id)
exists = await self._redis.exists(key)
if not exists:
return False
ttl_seconds = session_data.ttl_minutes * 60
await self._redis.setex(
key,
ttl_seconds,
json.dumps(session_data.to_dict(), default=str),
)
return True
if session_data.session_id not in self._memory_store:
return False
self._memory_store[session_data.session_id] = session_data
return True
async def append_results(
self,
session_id: str,
results: list[dict],
start_index: int,
page_number: int | None = None,
) -> bool:
"""
Append new results to session cache.
Args:
session_id: Session identifier
results: New results to append
start_index: Index where results should start
page_number: Optional page number to track
Returns:
True if successful
"""
session_data = await self.get_session(session_id)
if not session_data:
return False
# Extend all_results list if needed
current_len = len(session_data.all_results)
if start_index >= current_len:
# Pad with None if there's a gap
session_data.all_results.extend([None] * (start_index - current_len))
session_data.all_results.extend(results)
else:
# Insert at specific positions
for i, result in enumerate(results):
idx = start_index + i
if idx < len(session_data.all_results):
session_data.all_results[idx] = result
else:
session_data.all_results.append(result)
session_data.result_count = len([r for r in session_data.all_results if r is not None])
if page_number is not None and page_number not in session_data.backend_fetched_pages:
session_data.backend_fetched_pages.append(page_number)
return await self.update_session(session_data)
async def extend_ttl(self, session_id: str, additional_minutes: int) -> bool:
"""
Extend session TTL.
Args:
session_id: Session identifier
additional_minutes: Minutes to add to TTL
Returns:
True if successful
"""
session_data = await self.get_session(session_id)
if not session_data:
return False
session_data.ttl_minutes += additional_minutes
return await self.update_session(session_data)
async def delete_session(self, session_id: str) -> bool:
"""
Delete a session.
Args:
session_id: Session identifier
Returns:
True if deleted, False if not found
"""
if self._enabled and self._redis:
key = self._generate_key(session_id)
deleted = await self._redis.delete(key)
return deleted > 0
if session_id in self._memory_store:
del self._memory_store[session_id]
return True
return False
async def get_cached_results(
self,
session_id: str,
start_index: int,
page_size: int,
) -> tuple[list[dict], bool]:
"""
Get cached results for a specific range.
Args:
session_id: Session identifier
start_index: Starting index
page_size: Number of results to return
Returns:
Tuple of (results, has_more_in_cache)
"""
session_data = await self.get_session(session_id)
if not session_data:
return [], False
end_index = start_index + page_size
cached_results = session_data.all_results[start_index:end_index]
# Filter out None values (from padding)
valid_results = [r for r in cached_results if r is not None]
has_more = end_index < len(session_data.all_results)
return valid_results, has_more
def calculate_pagination(
self,
page: int,
page_size: int,
total_cached: int,
total_available: int,
) -> dict:
"""
Calculate pagination metadata.
Args:
page: Current page number (1-indexed)
page_size: Results per page
total_cached: Total results in cache
total_available: Total results available from backend
Returns:
Pagination metadata
"""
start_index = (page - 1) * page_size
end_index = start_index + page_size
return {
"page": page,
"page_size": page_size,
"start_index": start_index,
"end_index": min(end_index, total_available),
"has_more": end_index < total_available,
"total_cached": total_cached,
"total_available": total_available,
"cache_coverage": min(100, (total_cached / max(1, total_available)) * 100),
}
async def get_session_stats(self) -> dict:
"""
Get session manager statistics.
Returns:
Statistics dictionary
"""
stats = {
"storage_type": "redis" if self._enabled else "memory",
"enabled": self._enabled,
"active_sessions": 0,
}
if self._enabled and self._redis:
try:
keys = await self._redis.keys(f"{self._key_prefix}:*")
stats["active_sessions"] = len(keys)
except Exception as e:
logger.error(f"Error getting session stats: {e}")
else:
stats["active_sessions"] = len(self._memory_store)
return stats
async def cleanup_expired(self, grace_period_seconds: int = 60) -> int:
"""
Clean up expired sessions (for manual cleanup).
Args:
grace_period_seconds: Extra time to wait after TTL expires
Returns:
Number of sessions deleted
"""
import json
from datetime import UTC, datetime
deleted_count = 0
now = datetime.now(UTC)
if self._enabled and self._redis:
keys = await self._redis.keys(f"{self._key_prefix}:*")
for key in keys:
try:
session_data = await self._redis.get(key)
if not session_data:
continue
session = json.loads(session_data)
ttl_minutes = session.get("ttl_minutes", 10)
created_at_str = session.get("created_at")
if not created_at_str:
await self._redis.delete(key)
deleted_count += 1
continue
created_at = datetime.fromisoformat(created_at_str.replace("Z", "+00:00"))
age_seconds = (now - created_at).total_seconds()
ttl_seconds = (ttl_minutes * 60) + grace_period_seconds
if age_seconds > ttl_seconds:
await self._redis.delete(key)
deleted_count += 1
logger.debug(f"Deleted expired session: {key}")
except Exception as e:
logger.warning(f"Error cleaning up session {key}: {e}")
# Delete corrupted sessions
await self._redis.delete(key)
deleted_count += 1
else:
# Memory mode cleanup
expired = [
sid
for sid, session in self._memory_store.items()
if (now - session.created_at).total_seconds() > (session.ttl_minutes * 60) + grace_period_seconds
]
for sid in expired:
del self._memory_store[sid]
deleted_count = len(expired)
if deleted_count > 0:
logger.info(f"Cleaned up {deleted_count} expired sessions")
return deleted_count
# Singleton instance
_session_manager: SearchSessionData | None = None
def get_session_manager() -> SearchSessionManager:
"""Get or create session manager singleton"""
global _session_manager
if _session_manager is None:
_session_manager = SearchSessionManager()
return _session_manager
async def initialize_session_manager():
"""Initialize session manager on application startup"""
manager = get_session_manager()
await manager.initialize()
logger.info("Search Session Manager initialized")
async def close_session_manager():
"""Cleanup session manager on application shutdown"""
manager = get_session_manager()
await manager.close()
logger.info("Search Session Manager closed")
|