user_profile.py 2.09 KB
import sys
from pathlib import Path
import time

# Add the project root to Python path
current_dir = Path(__file__).parent
project_root = current_dir.parent.parent
sys.path.append(str(project_root))
sys.path.append(str(project_root / 'snapshot_pb/generated'))

from typing import Optional
import redis
from config.app_config import REDIS_CONFIG
from config.logging_config import get_app_logger
from user_profile_pb2 import UserProfile

logger = get_app_logger(__name__)

class UserProfileManager:
    def __init__(self):
        self.redis_client = redis.Redis(
            host=REDIS_CONFIG['host'],
            port=REDIS_CONFIG['port'],
            db=REDIS_CONFIG['snapshot_db'],
            password=REDIS_CONFIG['password'],
            decode_responses=False
        )

    def get_user_profile(self, uid: str) -> Optional[UserProfile]:
        """Get user profile from Redis"""
        logger.debug(f"Fetching user profile for uid: {uid}")
        
        profile_key = f"user_profile:{uid}"
        if not self.redis_client.exists(profile_key):
            logger.debug(f"No profile data found for uid: {uid}")
            return None
            
        # Measure Redis fetch time
        fetch_start = time.time()
        profile_data = self.redis_client.get(profile_key)
        fetch_time = time.time() - fetch_start
        
        if not profile_data:
            logger.debug(f"No profile data found for uid: {uid}")
            return None

        try:
            # Measure deserialization time
            deserialize_start = time.time()
            profile = UserProfile()
            profile.ParseFromString(profile_data)
            deserialize_time = time.time() - deserialize_start
            logger.info(f"REDIS_COST_TIME: key: {profile_key}, Response size: {len(profile_data)//1024}KB, Redis fetch: {fetch_time*1000:.2f}ms, Deserialization: {deserialize_time*1000:.2f}ms for uid: {uid}")
            return profile

        except Exception as e:
            logger.error(f"Error deserializing profile data for uid {uid}: {str(e)}")
            return None