rdune71's picture
Fix session state initialization and improve Redis error handling
3c74ffa
raw
history blame
2.28 kB
import json
import time
from utils.config import config
# Try to import redis, but handle if not available
try:
import redis
REDIS_AVAILABLE = True
except ImportError:
REDIS_AVAILABLE = False
redis = None
def get_redis_client():
"""Create and return Redis client with retry logic"""
if not REDIS_AVAILABLE:
return None
last_exception = None
for attempt in range(config.redis_retries + 1):
try:
redis_client = redis.Redis(
host=config.redis_host,
port=config.redis_port,
username=config.redis_username,
password=config.redis_password,
decode_responses=True,
socket_connect_timeout=5,
socket_timeout=5
)
# Test the connection
redis_client.ping()
return redis_client
except Exception as e:
last_exception = e
if attempt < config.redis_retries:
time.sleep(config.redis_retry_delay * (2 ** attempt)) # Exponential backoff
continue
return None
# Initialize Redis connection
redis_client = None
try:
redis_client = get_redis_client()
except Exception as e:
print(f"Warning: Could not connect to Redis: {e}")
def save_user_state(user_id: str, state: dict):
"""Save user state to Redis with retry logic"""
if not redis_client:
print("Redis not available, skipping save_user_state")
return False
try:
redis_client.hset(f"user:{user_id}", mapping=state)
return True
except Exception as e:
print(f"Error saving user state: {e}")
return False
def load_user_state(user_id: str):
"""Load user state from Redis with retry logic"""
if not redis_client:
print("Redis not available, returning empty state")
return {}
try:
return redis_client.hgetall(f"user:{user_id}")
except Exception as e:
print(f"Error loading user state: {e}")
return {}
def check_redis_health():
"""Check if Redis is healthy"""
if not redis_client:
return False
try:
redis_client.ping()
return True
except:
return False