.
This commit is contained in:
@@ -1,11 +1,3 @@
|
||||
"""
|
||||
Copyright 2025 Google. This software is provided as-is, without warranty or
|
||||
representation for any use or purpose. Your use of it is subject to your
|
||||
agreement with Google.
|
||||
|
||||
Redis service for caching conversation sessions.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime
|
||||
@@ -13,7 +5,7 @@ from redis.asyncio import Redis
|
||||
|
||||
from ..config import Settings
|
||||
from ..models import ConversationSessionDTO
|
||||
from ..models.notification import NotificationSessionDTO, NotificationDTO
|
||||
from ..models.notification import NotificationSession, Notification
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -28,14 +20,14 @@ class RedisService:
|
||||
self.redis: Redis | None = None
|
||||
self.session_ttl = 2592000 # 30 days in seconds
|
||||
self.notification_ttl = 2592000 # 30 days in seconds
|
||||
self.qr_session_ttl = 86400 # 24 hours in seconds
|
||||
|
||||
async def connect(self):
|
||||
"""Connect to Redis."""
|
||||
self.redis = Redis(
|
||||
host=self.settings.redis_host,
|
||||
port=self.settings.redis_port,
|
||||
password=self.settings.redis_password,
|
||||
ssl=self.settings.redis_ssl,
|
||||
password=self.settings.redis_pwd,
|
||||
decode_responses=True,
|
||||
)
|
||||
logger.info(
|
||||
@@ -188,7 +180,9 @@ class RedisService:
|
||||
logger.debug(f"Saved message to Redis: {session_id}")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Error saving message to Redis for session {session_id}: {str(e)}")
|
||||
logger.error(
|
||||
f"Error saving message to Redis for session {session_id}: {str(e)}"
|
||||
)
|
||||
return False
|
||||
|
||||
async def get_messages(self, session_id: str) -> list:
|
||||
@@ -225,10 +219,14 @@ class RedisService:
|
||||
logger.error(f"Error parsing message JSON: {str(e)}")
|
||||
continue
|
||||
|
||||
logger.debug(f"Retrieved {len(messages)} messages from Redis for session: {session_id}")
|
||||
logger.debug(
|
||||
f"Retrieved {len(messages)} messages from Redis for session: {session_id}"
|
||||
)
|
||||
return messages
|
||||
except Exception as e:
|
||||
logger.error(f"Error retrieving messages from Redis for session {session_id}: {str(e)}")
|
||||
logger.error(
|
||||
f"Error retrieving messages from Redis for session {session_id}: {str(e)}"
|
||||
)
|
||||
return []
|
||||
|
||||
# ====== Notification Methods ======
|
||||
@@ -241,7 +239,7 @@ class RedisService:
|
||||
"""Generate Redis key for phone-to-notification mapping."""
|
||||
return f"notification:phone_to_notification:{phone}"
|
||||
|
||||
async def save_or_append_notification(self, new_entry: NotificationDTO) -> None:
|
||||
async def save_or_append_notification(self, new_entry: Notification) -> None:
|
||||
"""
|
||||
Save or append notification entry to session.
|
||||
|
||||
@@ -267,20 +265,20 @@ class RedisService:
|
||||
if existing_session:
|
||||
# Append to existing session
|
||||
updated_notifications = existing_session.notificaciones + [new_entry]
|
||||
updated_session = NotificationSessionDTO(
|
||||
session_id=notification_session_id,
|
||||
updated_session = NotificationSession(
|
||||
sessionId=notification_session_id,
|
||||
telefono=phone_number,
|
||||
fecha_creacion=existing_session.fecha_creacion,
|
||||
ultima_actualizacion=datetime.now(),
|
||||
fechaCreacion=existing_session.fechaCreacion,
|
||||
ultimaActualizacion=datetime.now(),
|
||||
notificaciones=updated_notifications,
|
||||
)
|
||||
else:
|
||||
# Create new session
|
||||
updated_session = NotificationSessionDTO(
|
||||
session_id=notification_session_id,
|
||||
updated_session = NotificationSession(
|
||||
sessionId=notification_session_id,
|
||||
telefono=phone_number,
|
||||
fecha_creacion=datetime.now(),
|
||||
ultima_actualizacion=datetime.now(),
|
||||
fechaCreacion=datetime.now(),
|
||||
ultimaActualizacion=datetime.now(),
|
||||
notificaciones=[new_entry],
|
||||
)
|
||||
|
||||
@@ -288,7 +286,7 @@ class RedisService:
|
||||
await self._cache_notification_session(updated_session)
|
||||
|
||||
async def _cache_notification_session(
|
||||
self, session: NotificationSessionDTO
|
||||
self, session: NotificationSession
|
||||
) -> bool:
|
||||
"""Cache notification session in Redis."""
|
||||
if not self.redis:
|
||||
@@ -315,7 +313,7 @@ class RedisService:
|
||||
|
||||
async def get_notification_session(
|
||||
self, session_id: str
|
||||
) -> NotificationSessionDTO | None:
|
||||
) -> NotificationSession | None:
|
||||
"""Retrieve notification session from Redis."""
|
||||
if not self.redis:
|
||||
raise RuntimeError("Redis client not connected")
|
||||
@@ -329,7 +327,7 @@ class RedisService:
|
||||
|
||||
try:
|
||||
session_dict = json.loads(data)
|
||||
session = NotificationSessionDTO.model_validate(session_dict)
|
||||
session = NotificationSession.model_validate(session_dict)
|
||||
logger.info(f"Notification session {session_id} retrieved from Redis")
|
||||
return session
|
||||
except Exception as e:
|
||||
|
||||
Reference in New Issue
Block a user