File size: 1,743 Bytes
41aafc4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Redis connection and cache instance.
Provides Redis client for OTP storage and rate limiting.
"""
import redis.asyncio as redis
# from insightfy_utils.logging import get_logger  # TODO: Uncomment when package is available
import logging
from app.core.config import settings

# logger = get_logger(__name__)  # TODO: Uncomment when insightfy_utils is available
logger = logging.getLogger(__name__)

# Redis client instance
redis_client: redis.Redis = None


async def connect_to_redis():
    """
    Establish connection to Redis.
    Called during application startup.
    """
    global redis_client
    try:
        logger.info("Connecting to Redis", extra={
            "host": settings.REDIS_HOST,
            "port": settings.REDIS_PORT,
            "db": settings.REDIS_DB
        })
        
        redis_client = redis.Redis(
            host=settings.REDIS_HOST,
            port=settings.REDIS_PORT,
            password=settings.REDIS_PASSWORD,
            db=settings.REDIS_DB,
            decode_responses=True
        )
        
        # Test the connection
        await redis_client.ping()
        
        logger.info("Successfully connected to Redis")
    except Exception as e:
        logger.error("Failed to connect to Redis", exc_info=e)
        raise


async def close_redis_connection():
    """
    Close Redis connection.
    Called during application shutdown.
    """
    global redis_client
    if redis_client:
        logger.info("Closing Redis connection")
        await redis_client.close()
        logger.info("Redis connection closed")


def get_redis() -> redis.Redis:
    """
    Get Redis client instance.
    
    Returns:
        redis.Redis: Redis client instance
    """
    return redis_client