File size: 7,283 Bytes
5a585eb
29ca692
3d560cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a585eb
3d560cd
 
 
 
 
da81392
3d560cd
 
 
 
 
 
5a585eb
3d560cd
 
 
 
da81392
5a585eb
 
26a899a
220a9a0
 
 
 
da81392
26a899a
 
 
 
 
 
 
 
 
 
 
da81392
 
26a899a
 
 
da81392
 
26a899a
 
 
 
 
 
 
 
 
da81392
26a899a
3d560cd
da81392
26a899a
3d560cd
 
26a899a
 
 
 
 
 
 
 
 
 
220a9a0
 
26a899a
3d560cd
 
 
 
da81392
3d560cd
26a899a
3d560cd
 
 
26a899a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da81392
26a899a
 
 
 
 
 
3d560cd
 
5a585eb
3d560cd
26a899a
 
da81392
3d560cd
da81392
3d560cd
 
da81392
 
 
3d560cd
 
da81392
3d560cd
 
 
 
 
 
 
 
 
 
 
da81392
3d560cd
 
da81392
3d560cd
da81392
5a585eb
3d560cd
da81392
3d560cd
5a585eb
3d560cd
 
c58df45
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# 1. modules/database/database_init.py

import os
import logging
from azure.cosmos import CosmosClient
from pymongo import MongoClient
import certifi

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

# Variables globales para Cosmos DB SQL API
cosmos_client = None
user_database = None
user_container = None
application_requests_container = None
user_feedback_container = None
user_sessions_container = None

# Variables globales para Cosmos DB MongoDB API
mongo_client = None
mongo_db = None

###################################################################
def verify_container_partition_key(container, expected_path):
    """Verifica la configuraci贸n de partition key de un contenedor"""
    try:
        container_props = container.read()
        partition_key_paths = container_props['partitionKey']['paths']
        logger.info(f"Container: {container.id}, Partition Key Paths: {partition_key_paths}")
        return expected_path in partition_key_paths
    except Exception as e:
        logger.error(f"Error verificando partition key en {container.id}: {str(e)}")
        return False

###################################################################
def get_container(container_name):
    """Obtiene un contenedor espec铆fico"""
    logger.info(f"Solicitando contenedor: {container_name}")
    
    if not initialize_cosmos_sql_connection():
        logger.error("No se pudo inicializar la conexi贸n")
        return None
    
    # Verificar estado de los contenedores
    containers_status = {
        "users": user_container is not None,
        "users_sessions": user_sessions_container is not None,
        "application_requests": application_requests_container is not None,
        "user_feedback": user_feedback_container is not None  # A帽adido
    }
    
    logger.info(f"Estado actual de los contenedores: {containers_status}")
    
    # Mapear nombres a contenedores
    containers = {
        "users": user_container,
        "users_sessions": user_sessions_container,
        "application_requests": application_requests_container,
        "user_feedback": user_feedback_container  # A帽adido
    }
    
    container = containers.get(container_name)
    
    if container is None:
        logger.error(f"Contenedor '{container_name}' no encontrado o no inicializado")
        logger.error(f"Contenedores disponibles: {[k for k, v in containers_status.items() if v]}")
        return None
        
    logger.info(f"Contenedor '{container_name}' obtenido exitosamente")
    return container
###################################################################

def initialize_cosmos_sql_connection():
    """Inicializa la conexi贸n a Cosmos DB SQL API"""
    global cosmos_client, user_database, user_container, user_sessions_container, application_requests_container, user_feedback_container  # A帽adida aqu铆 user_feedback_container

    try:
        # Verificar conexi贸n existente
        if all([
            cosmos_client,
            user_database, 
            user_container,
            user_sessions_container,
            application_requests_container,
            user_feedback_container
        ]):
            logger.debug("Todas las conexiones ya est谩n inicializadas")
            return True

        # Obtener credenciales
        cosmos_endpoint = os.environ.get("COSMOS_ENDPOINT")
        cosmos_key = os.environ.get("COSMOS_KEY")
        
        if not cosmos_endpoint or not cosmos_key:
            raise ValueError("COSMOS_ENDPOINT y COSMOS_KEY deben estar configurados")

        # Inicializar cliente y base de datos
        cosmos_client = CosmosClient(cosmos_endpoint, cosmos_key)
        user_database = cosmos_client.get_database_client("user_database")
        
        # Inicializar contenedores
        try:
            user_container = user_database.get_container_client("users")
            logger.info("Contenedor 'users' inicializado correctamente")
        except Exception as e:
            logger.error(f"Error inicializando contenedor 'users': {str(e)}")
            user_container = None

        try:
            user_sessions_container = user_database.get_container_client("users_sessions")
            logger.info("Contenedor 'users_sessions' inicializado correctamente")
        except Exception as e:
            logger.error(f"Error inicializando contenedor 'users_sessions': {str(e)}")
            user_sessions_container = None

        try:
            application_requests_container = user_database.get_container_client("application_requests")
            logger.info("Contenedor 'application_requests' inicializado correctamente")
        except Exception as e:
            logger.error(f"Error inicializando contenedor 'application_requests': {str(e)}")
            application_requests_container = None

        try:
            user_feedback_container = user_database.get_container_client("user_feedback")
            logger.info("Contenedor 'user_feedback' inicializado correctamente")
        except Exception as e:
            logger.error(f"Error inicializando contenedor 'user_feedback': {str(e)}")
            user_feedback_container = None

        # Verificar el estado de los contenedores
        containers_status = {
            'users': user_container is not None,
            'users_sessions': user_sessions_container is not None,
            'application_requests': application_requests_container is not None,
            'user_feedback': user_feedback_container is not None
        }
        
        logger.info(f"Estado de los contenedores: {containers_status}")
        
        if all(containers_status.values()):
            logger.info("Todos los contenedores inicializados correctamente")
            return True
        else:
            logger.error("No se pudieron inicializar todos los contenedores")
            return False

    except Exception as e:
        logger.error(f"Error al conectar con Cosmos DB SQL API: {str(e)}")
        return False


###################################################################
def initialize_mongodb_connection():
    """Inicializa la conexi贸n a MongoDB"""
    global mongo_client, mongo_db
    try:
        connection_string = os.getenv("MONGODB_CONNECTION_STRING")
        if not connection_string:
            raise ValueError("MONGODB_CONNECTION_STRING debe estar configurado")

        mongo_client = MongoClient(
            connection_string,
            tls=True,
            tlsCAFile=certifi.where(),
            retryWrites=False,
            serverSelectionTimeoutMS=5000,
            connectTimeoutMS=10000,
            socketTimeoutMS=10000
        )
        
        mongo_db = mongo_client['aideatext_db']
        return True
    except Exception as e:
        logger.error(f"Error conectando a MongoDB: {str(e)}")
        return False

###################################################################
def initialize_database_connections():
    """Inicializa todas las conexiones"""
    return initialize_cosmos_sql_connection() and initialize_mongodb_connection()

###################################################################
def get_mongodb():
    """Obtiene la conexi贸n MongoDB"""
    if mongo_db is None:
        initialize_mongodb_connection()
    return mongo_db