File size: 5,049 Bytes
b0666c1
 
 
 
 
4c94669
b0666c1
 
bcc2979
b0666c1
4c94669
822f946
b0666c1
 
 
 
 
822f946
b0666c1
 
c59b861
b0666c1
 
 
 
 
 
 
822f946
b0666c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c59b861
b0666c1
 
 
 
 
 
 
 
4c94669
 
b0666c1
 
 
 
 
 
 
4c94669
 
 
 
 
 
 
c59b861
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# app/db.py
import time
import logging
from typing import Optional

from pymongo import MongoClient
from pymongo.errors import ServerSelectionTimeoutError, ConfigurationError
import certifi
from qdrant_client import QdrantClient  # Add this import

from app.page_speed.config import settings

logger = logging.getLogger(__name__)
# Configure logger if root logger not configured by app
if not logging.getLogger().handlers:
    # Basic configuration for standalone testing; in real app your main config may override this.
    logging.basicConfig(level=logging.INFO)

# Tunable timeout (ms)
MONGO_SERVER_SELECTION_TIMEOUT_MS = 20000  # 20 seconds

def _create_mongo_client() -> MongoClient:
    """
    Create and return a MongoClient configured to use TLS with certifi CA bundle.
    This function intentionally passes tls=True and tlsCAFile to make TLS explicit and reliable.
    """
    uri = settings.mongo_uri
    logger.info("Creating MongoClient for URI: %s", uri)

    try:
        client = MongoClient(
            uri,
            tls=True,
            tlsCAFile=certifi.where(),
            serverSelectionTimeoutMS=MONGO_SERVER_SELECTION_TIMEOUT_MS,
        )
        logger.debug("MongoClient created with explicit TLS and certifi CA bundle.")
        return client
    except TypeError as e:
        # In case an older pymongo version doesn't accept tls* keywords (unlikely if pymongo[srv] is installed)
        logger.warning("MongoClient creation with tls arguments failed (%s). Falling back without tls args.", e)
        client = MongoClient(uri, serverSelectionTimeoutMS=MONGO_SERVER_SELECTION_TIMEOUT_MS)
        return client
    except Exception as e:
        logger.exception("Unexpected exception while creating MongoClient: %s", e)
        raise

# Instantiate client and perform startup connectivity check (ping) with retries
mongo_client: Optional[MongoClient] = None
_last_exc: Optional[Exception] = None

try:
    mongo_client = _create_mongo_client()
    # Retry ping a few times to get useful logs for TLS failures
    for attempt in range(1, 4):
        try:
            logger.info("Pinging MongoDB (attempt %d)...", attempt)
            mongo_client.admin.command("ping")
            logger.info("Successfully connected to MongoDB.")
            _last_exc = None
            break
        except ServerSelectionTimeoutError as e:
            _last_exc = e
            logger.exception("ServerSelectionTimeoutError pinging MongoDB on attempt %d: %s", attempt, e)
        except ConfigurationError as e:
            _last_exc = e
            logger.exception("ConfigurationError pinging MongoDB: %s", e)
            break
        except Exception as e:
            _last_exc = e
            logger.exception("Unexpected error pinging MongoDB on attempt %d: %s", attempt, e)
        time.sleep(1 * attempt)
except Exception as e:
    _last_exc = e
    logger.exception("MongoClient creation failed: %s", e)

if _last_exc:
    # Fail fast β€” raising here prevents the app from running in a broken state.
    # If you prefer not to raise in development, replace `raise` with `logger.error(...)` and continue.
    raise _last_exc

# Select DB and collections
mongo_db = mongo_client[settings.mongo_db]
vectorstore_meta_coll = mongo_db["vectorstore_metadata"]
chat_collection_name = settings.mongo_collection

def get_mongo_client() -> MongoClient:
    """Return the active MongoClient instance."""
    return mongo_client

def get_vectorstore_collection():
    return vectorstore_meta_coll

# ─────────────────────────────────────────────
# Qdrant Setup
# ─────────────────────────────────────────────
# If Qdrant is running locally
qdrant_client = QdrantClient(
    url=settings.qdrant_url,  # e.g. "http://localhost:6333"
    api_key=settings.qdrant_api_key or None
)

# # ____________________________________________________________
# #Local MongoDB Connection
# # ____________________________________________________________

# # db.py
# from pymongo import MongoClient
# from app.page_speed.config import settings
# from qdrant_client import QdrantClient

# # Always connect to local MongoDB
# mongo_client = MongoClient("mongodb://localhost:27017/")

# # Select the database from settings
# mongo_db = mongo_client[settings.mongo_db]

# # Collections
# vectorstore_meta_coll = mongo_db["vectorstore_metadata"]
# chat_collection_name = settings.mongo_collection

# # ─────────────────────────────────────────────
# # Qdrant Setup
# # ─────────────────────────────────────────────
# # If Qdrant is running locally
# qdrant_client = QdrantClient(
#     url=settings.qdrant_url,  # e.g. "http://localhost:6333"
#     api_key=settings.qdrant_api_key or None
# )