rdune71 commited on
Commit
1fe6f63
·
1 Parent(s): ff328ca

Add Redis connection debugging and SSL support with fallback

Browse files
Files changed (2) hide show
  1. core/memory.py +44 -15
  2. test_redis_hf.py +25 -0
core/memory.py CHANGED
@@ -1,7 +1,12 @@
1
  import json
2
  import time
 
3
  from utils.config import config
4
 
 
 
 
 
5
  # Try to import redis, but handle if not available
6
  try:
7
  import redis
@@ -14,12 +19,16 @@ def get_redis_client():
14
  """Create and return Redis client with retry logic"""
15
  if not REDIS_AVAILABLE:
16
  return None
17
-
 
 
 
18
  last_exception = None
19
 
20
  for attempt in range(config.redis_retries + 1):
21
  try:
22
  # Handle empty username/password gracefully
 
23
  redis_client = redis.Redis(
24
  host=config.redis_host,
25
  port=config.redis_port,
@@ -27,17 +36,37 @@ def get_redis_client():
27
  password=config.redis_password if config.redis_password else None,
28
  decode_responses=True,
29
  socket_connect_timeout=5,
30
- socket_timeout=5
 
 
31
  )
32
  # Test the connection
33
  redis_client.ping()
 
34
  return redis_client
35
  except Exception as e:
36
- last_exception = e
37
- if attempt < config.redis_retries:
38
- time.sleep(config.redis_retry_delay * (2 ** attempt)) # Exponential backoff
39
- continue
40
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  return None
42
 
43
  # Initialize Redis connection with better error handling
@@ -45,36 +74,36 @@ redis_client = None
45
  try:
46
  redis_client = get_redis_client()
47
  if redis_client is None and REDIS_AVAILABLE:
48
- print("Warning: Could not connect to Redis - using in-memory storage")
49
  except Exception as e:
50
- print(f"Warning: Redis initialization failed: {e}")
51
 
52
  def save_user_state(user_id: str, state: dict):
53
  """Save user state to Redis with fallback to in-memory storage"""
54
  global redis_client
55
  if not redis_client:
56
  # Fallback: use in-memory storage (will not persist across restarts)
57
- print("Redis not available, using in-memory storage for user state")
58
  return False
59
-
60
  try:
61
  redis_client.hset(f"user:{user_id}", mapping=state)
62
  return True
63
  except Exception as e:
64
- print(f"Error saving user state: {e}")
65
  return False
66
 
67
  def load_user_state(user_id: str):
68
  """Load user state from Redis with fallback"""
69
  global redis_client
70
  if not redis_client:
71
- print("Redis not available, returning empty state")
72
  return {}
73
-
74
  try:
75
  return redis_client.hgetall(f"user:{user_id}")
76
  except Exception as e:
77
- print(f"Error loading user state: {e}")
78
  return {}
79
 
80
  def check_redis_health():
 
1
  import json
2
  import time
3
+ import logging
4
  from utils.config import config
5
 
6
+ # Set up logging
7
+ logging.basicConfig(level=logging.INFO)
8
+ logger = logging.getLogger(__name__)
9
+
10
  # Try to import redis, but handle if not available
11
  try:
12
  import redis
 
19
  """Create and return Redis client with retry logic"""
20
  if not REDIS_AVAILABLE:
21
  return None
22
+
23
+ # Debug print to verify secrets are loaded
24
+ logger.info(f"[DEBUG] Redis config: {config.redis_host}:{config.redis_port} | Username: {config.redis_username or '(none)'} | Has Password: {bool(config.redis_password)}")
25
+
26
  last_exception = None
27
 
28
  for attempt in range(config.redis_retries + 1):
29
  try:
30
  # Handle empty username/password gracefully
31
+ # Try with SSL first
32
  redis_client = redis.Redis(
33
  host=config.redis_host,
34
  port=config.redis_port,
 
36
  password=config.redis_password if config.redis_password else None,
37
  decode_responses=True,
38
  socket_connect_timeout=5,
39
+ socket_timeout=5,
40
+ ssl=True, # Enable TLS
41
+ ssl_cert_reqs=None # Skip cert verification
42
  )
43
  # Test the connection
44
  redis_client.ping()
45
+ logger.info("Successfully connected to Redis with SSL")
46
  return redis_client
47
  except Exception as e:
48
+ # If SSL fails, try without SSL
49
+ try:
50
+ redis_client = redis.Redis(
51
+ host=config.redis_host,
52
+ port=config.redis_port,
53
+ username=config.redis_username if config.redis_username else None,
54
+ password=config.redis_password if config.redis_password else None,
55
+ decode_responses=True,
56
+ socket_connect_timeout=5,
57
+ socket_timeout=5
58
+ )
59
+ # Test the connection
60
+ redis_client.ping()
61
+ logger.info("Successfully connected to Redis without SSL")
62
+ return redis_client
63
+ except Exception as e2:
64
+ last_exception = e2
65
+ if attempt < config.redis_retries:
66
+ time.sleep(config.redis_retry_delay * (2 ** attempt)) # Exponential backoff
67
+ continue
68
+
69
+ logger.warning(f"Could not connect to Redis after {config.redis_retries + 1} attempts: {last_exception}")
70
  return None
71
 
72
  # Initialize Redis connection with better error handling
 
74
  try:
75
  redis_client = get_redis_client()
76
  if redis_client is None and REDIS_AVAILABLE:
77
+ logger.warning("Could not connect to Redis - using in-memory storage")
78
  except Exception as e:
79
+ logger.error(f"Redis initialization failed: {e}")
80
 
81
  def save_user_state(user_id: str, state: dict):
82
  """Save user state to Redis with fallback to in-memory storage"""
83
  global redis_client
84
  if not redis_client:
85
  # Fallback: use in-memory storage (will not persist across restarts)
86
+ logger.info("Redis not available, using in-memory storage for user state")
87
  return False
88
+
89
  try:
90
  redis_client.hset(f"user:{user_id}", mapping=state)
91
  return True
92
  except Exception as e:
93
+ logger.error(f"Error saving user state: {e}")
94
  return False
95
 
96
  def load_user_state(user_id: str):
97
  """Load user state from Redis with fallback"""
98
  global redis_client
99
  if not redis_client:
100
+ logger.info("Redis not available, returning empty state")
101
  return {}
102
+
103
  try:
104
  return redis_client.hgetall(f"user:{user_id}")
105
  except Exception as e:
106
+ logger.error(f"Error loading user state: {e}")
107
  return {}
108
 
109
  def check_redis_health():
test_redis_hf.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import redis
2
+ import os
3
+
4
+ host = os.getenv("REDIS_HOST")
5
+ port = int(os.getenv("REDIS_PORT", "6379"))
6
+ username = os.getenv("REDIS_USERNAME") or None
7
+ password = os.getenv("REDIS_PASSWORD") or None
8
+
9
+ print("Connecting to Redis...")
10
+ print(f"Host: {host}, Port: {port}, Username: {username}")
11
+
12
+ try:
13
+ r = redis.Redis(
14
+ host=host,
15
+ port=port,
16
+ username=username,
17
+ password=password,
18
+ decode_responses=True,
19
+ socket_connect_timeout=5,
20
+ socket_timeout=5
21
+ )
22
+ result = r.ping()
23
+ print("✅ Ping successful:", result)
24
+ except Exception as e:
25
+ print("❌ Redis connection failed:", e)