rdune71 commited on
Commit
b283a26
·
1 Parent(s): 34a92ea

Simplify Redis connection with exact working configuration from Redis Cloud

Browse files
Files changed (3) hide show
  1. README.md +20 -1
  2. core/redis_client.py +31 -63
  3. verify_redis.py +57 -0
README.md CHANGED
@@ -155,4 +155,23 @@ Model Not Found:
155
  Diagnostic Scripts:
156
  - Run python test_ollama_connection.py to verify Ollama connectivity.
157
  - Run python diagnose_ollama.py for detailed connection diagnostics.
158
- - Run python test_redis_connection.py to verify Redis connectivity.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
  Diagnostic Scripts:
156
  - Run python test_ollama_connection.py to verify Ollama connectivity.
157
  - Run python diagnose_ollama.py for detailed connection diagnostics.
158
+ - Run python verify_redis.py to verify Redis connectivity with exact configuration.
159
+
160
+ ## Confirmed Working Configuration
161
+
162
+ The Redis connection has been tested and confirmed working with this exact configuration:
163
+
164
+ """Basic connection example."""
165
+ import redis
166
+ r = redis.Redis(
167
+ host='redis-10296.c245.us-east-1-3.ec2.redns.redis-cloud.com',
168
+ port=10296,
169
+ decode_responses=True,
170
+ username="default",
171
+ password="p0ZiQGG9V4cS9NcNpeiBzaOz3YmtXcYW",
172
+ )
173
+ success = r.set('foo', 'bar') # True
174
+ result = r.get('foo')
175
+ print(result) # >>> bar
176
+
177
+ This exact configuration is now implemented in the application.
core/redis_client.py CHANGED
@@ -8,7 +8,7 @@ from utils.config import config
8
  logger = logging.getLogger(__name__)
9
 
10
  class RedisClient:
11
- """Enhanced Redis client with proper connection handling"""
12
  _instance = None
13
  _redis_client = None
14
 
@@ -23,94 +23,62 @@ class RedisClient:
23
  self._connect()
24
 
25
  def _connect(self):
26
- """Establish Redis connection with proper error handling for Redis Cloud"""
27
  logger.info(f"Attempting Redis connection with:")
28
  logger.info(f" Host: {config.redis_host}")
29
  logger.info(f" Port: {config.redis_port}")
30
  logger.info(f" Username: {'SET' if config.redis_username else 'NOT SET'}")
31
  logger.info(f" Password: {'SET' if config.redis_password else 'NOT SET'}")
32
- logger.info(f" SSL Disabled: {config.redis_disable_ssl}")
33
 
34
  if not config.redis_host or config.redis_host == "localhost":
35
  logger.info("Redis not configured, skipping connection")
36
  return None
37
 
38
- # Parse host and port
39
- host, port = self._parse_host_port(config.redis_host, config.redis_port)
40
-
41
- if config.redis_disable_ssl:
42
- # Non-SSL connection
43
- try:
44
- logger.info(f"Connecting to Redis at {host}:{port} without SSL")
45
- self._redis_client = redis.Redis(
46
- host=host,
47
- port=port,
48
- username=config.redis_username if config.redis_username else "default",
49
- password=config.redis_password,
50
- decode_responses=True,
51
- socket_connect_timeout=15,
52
- socket_timeout=15,
53
- health_check_interval=30,
54
- retry_on_timeout=True
55
- )
56
- self._redis_client.ping()
57
- logger.info("Successfully connected to Redis without SSL")
58
- return
59
- except Exception as e:
60
- logger.error(f"Non-SSL connection failed: {e}")
61
- self._redis_client = None
62
- return
63
-
64
- # SSL connection (default for Redis Cloud)
65
  try:
66
- logger.info(f"Connecting to Redis Cloud at {host}:{port} with SSL")
67
  self._redis_client = redis.Redis(
68
- host=host,
69
- port=port,
70
  username=config.redis_username if config.redis_username else "default",
71
  password=config.redis_password,
72
  decode_responses=True,
73
  socket_connect_timeout=15,
74
  socket_timeout=15,
75
  ssl=True,
76
- ssl_cert_reqs='required', # Proper SSL certificate validation
77
  health_check_interval=30,
78
  retry_on_timeout=True
79
  )
 
80
  self._redis_client.ping()
81
- logger.info("Successfully connected to Redis Cloud with SSL")
82
  return
 
83
  except Exception as e:
84
- logger.error(f"Redis Cloud SSL connection failed: {e}")
85
  self._redis_client = None
86
 
87
- def _parse_host_port(self, host_string: str, default_port: int) -> tuple:
88
- """Parse host and port from host string"""
89
- if not host_string:
90
- return "localhost", default_port
91
-
92
- # Remove any whitespace and control characters
93
- host_string = host_string.strip()
94
- host_string = re.sub(r'[\r\n\t\0]+', '', host_string)
95
-
96
- # Handle case where port is included in REDIS_HOST (e.g., "host:port")
97
- if ':' in host_string and not host_string.startswith('['): # Not IPv6
98
- # Check if the part after : is a valid port number
99
- parts = host_string.rsplit(':', 1)
100
- try:
101
- host = parts[0]
102
- port = int(parts[1])
103
- # Validate that this looks like a port (0-65535)
104
- if 1 <= port <= 65535:
105
- return host, port
106
- else:
107
- # Invalid port, use default
108
- return host_string, default_port
109
- except ValueError:
110
- # Port is not a valid integer, use default
111
- return host_string, default_port
112
-
113
- return host_string, default_port
114
 
115
  def get_client(self) -> Optional[redis.Redis]:
116
  """Get Redis client instance"""
 
8
  logger = logging.getLogger(__name__)
9
 
10
  class RedisClient:
11
+ """Simplified Redis client with proven working configuration"""
12
  _instance = None
13
  _redis_client = None
14
 
 
23
  self._connect()
24
 
25
  def _connect(self):
26
+ """Establish Redis connection with simplified configuration"""
27
  logger.info(f"Attempting Redis connection with:")
28
  logger.info(f" Host: {config.redis_host}")
29
  logger.info(f" Port: {config.redis_port}")
30
  logger.info(f" Username: {'SET' if config.redis_username else 'NOT SET'}")
31
  logger.info(f" Password: {'SET' if config.redis_password else 'NOT SET'}")
 
32
 
33
  if not config.redis_host or config.redis_host == "localhost":
34
  logger.info("Redis not configured, skipping connection")
35
  return None
36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  try:
38
+ logger.info(f"Connecting to Redis Cloud at {config.redis_host}:{config.redis_port}")
39
  self._redis_client = redis.Redis(
40
+ host=config.redis_host,
41
+ port=config.redis_port,
42
  username=config.redis_username if config.redis_username else "default",
43
  password=config.redis_password,
44
  decode_responses=True,
45
  socket_connect_timeout=15,
46
  socket_timeout=15,
47
  ssl=True,
 
48
  health_check_interval=30,
49
  retry_on_timeout=True
50
  )
51
+
52
  self._redis_client.ping()
53
+ logger.info("Successfully connected to Redis Cloud")
54
  return
55
+
56
  except Exception as e:
57
+ logger.error(f"Redis connection failed: {e}")
58
  self._redis_client = None
59
 
60
+ def test_basic_connection(self):
61
+ """Test basic Redis connection with known working config"""
62
+ try:
63
+ test_client = redis.Redis(
64
+ host='redis-10296.c245.us-east-1-3.ec2.redns.redis-cloud.com',
65
+ port=10296,
66
+ username="default",
67
+ password="p0ZiQGG9V4cS9NcNpeiBzaOz3YmtXcYW",
68
+ decode_responses=True,
69
+ socket_connect_timeout=10,
70
+ socket_timeout=10,
71
+ ssl=True
72
+ )
73
+
74
+ test_client.ping()
75
+ test_client.set('test_key', 'test_value')
76
+ result = test_client.get('test_key')
77
+ logger.info(f"Basic connection test successful: {result}")
78
+ return True
79
+ except Exception as e:
80
+ logger.error(f"Basic connection test failed: {e}")
81
+ return False
 
 
 
 
 
82
 
83
  def get_client(self) -> Optional[redis.Redis]:
84
  """Get Redis client instance"""
verify_redis.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import os
3
+ from pathlib import Path
4
+
5
+ # Add project root to path
6
+ project_root = Path(__file__).parent
7
+ sys.path.append(str(project_root))
8
+
9
+ from core.redis_client import redis_client
10
+
11
+ def main():
12
+ """Verify Redis connection with exact configuration"""
13
+ print("Verifying Redis connection with exact configuration...")
14
+
15
+ # Test the basic connection method
16
+ success = redis_client.test_basic_connection()
17
+
18
+ if success:
19
+ print("\n✅ Redis connection verified successfully!")
20
+ print("The exact configuration from Redis Cloud works correctly.")
21
+ else:
22
+ print("\n❌ Redis connection verification failed!")
23
+ print("Please check your configuration and network connectivity.")
24
+ return 1
25
+
26
+ # Also test the actual client being used
27
+ print("\nTesting application Redis client...")
28
+ client = redis_client.get_client()
29
+
30
+ if client is None:
31
+ print("❌ Application Redis client is None")
32
+ return 1
33
+
34
+ try:
35
+ client.ping()
36
+ print("✅ Application Redis client ping successful")
37
+
38
+ # Test set/get operations
39
+ client.set('app_test_key', 'app_test_value')
40
+ value = client.get('app_test_key')
41
+ client.delete('app_test_key') # Cleanup
42
+
43
+ if value == 'app_test_value':
44
+ print("✅ Set/Get operations work correctly")
45
+ print("\n🎉 All Redis connection tests passed!")
46
+ return 0
47
+ else:
48
+ print("❌ Set/Get operations failed")
49
+ return 1
50
+
51
+ except Exception as e:
52
+ print(f"❌ Application Redis client test failed: {e}")
53
+ return 1
54
+
55
+ if __name__ == "__main__":
56
+ exit_code = main()
57
+ sys.exit(exit_code)