forked from CodeGraphContext/CodeGraphContext
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
248 lines (217 loc) · 10 KB
/
Copy pathdatabase.py
File metadata and controls
248 lines (217 loc) · 10 KB
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# src/codegraphcontext/core/database.py
"""
This module provides a thread-safe singleton manager for the Neo4j database connection.
"""
import os
import re
import threading
from typing import Optional, Tuple
from neo4j import GraphDatabase, Driver
from codegraphcontext.utils.debug_log import debug_log, info_logger, error_logger, warning_logger
class DatabaseManager:
"""
Manages the Neo4j database driver as a singleton to ensure only one
connection pool is created and shared across the application.
This pattern is crucial for performance and resource management in a
multi-threaded or asynchronous application.
"""
_instance = None
_driver: Optional[Driver] = None
_lock = threading.Lock() # Lock to ensure thread-safe initialization.
def __new__(cls):
"""Standard singleton pattern implementation."""
if cls._instance is None:
with cls._lock:
# Double-check locking to prevent race conditions.
if cls._instance is None:
cls._instance = super(DatabaseManager, cls).__new__(cls)
return cls._instance
def __init__(self):
"""
Initializes the manager by reading credentials from environment variables.
The `_initialized` flag prevents re-initialization on subsequent calls.
"""
if hasattr(self, '_initialized'):
return
self.neo4j_uri = os.getenv('NEO4J_URI')
self.neo4j_username = os.getenv('NEO4J_USERNAME', 'neo4j')
self.neo4j_password = os.getenv('NEO4J_PASSWORD')
self._initialized = True
def get_driver(self) -> Driver:
"""
Gets the Neo4j driver instance, creating it if it doesn't exist.
This method is thread-safe.
Raises:
ValueError: If Neo4j credentials are not set in environment variables.
Returns:
The active Neo4j Driver instance.
"""
if self._driver is None:
with self._lock:
if self._driver is None:
# Ensure all necessary credentials are provided.
if not all([self.neo4j_uri, self.neo4j_username, self.neo4j_password]):
raise ValueError(
"Neo4j credentials must be set via environment variables:\n"
"- NEO4J_URI\n"
"- NEO4J_USERNAME\n"
"- NEO4J_PASSWORD"
)
#validating the config before creating the driver/attempting connection
is_valid, validation_error = self.validate_config(
self.neo4j_uri,
self.neo4j_username,
self.neo4j_password
)
if not is_valid:
error_logger(f"Configuration validation failed: {validation_error}")
raise ValueError(validation_error)
info_logger(f"Creating Neo4j driver connection to {self.neo4j_uri}")
self._driver = GraphDatabase.driver(
self.neo4j_uri,
auth=(self.neo4j_username, self.neo4j_password)
)
# Test the connection immediately to fail fast if credentials are wrong.
try:
with self._driver.session() as session:
session.run("RETURN 1").consume()
info_logger("Neo4j connection established successfully")
except Exception as e:
# Use detailed error messages from test_connection
_, detailed_error = self.test_connection(
self.neo4j_uri,
self.neo4j_username,
self.neo4j_password
)
error_logger(f"Failed to connect to Neo4j: {e}")
if self._driver:
self._driver.close()
self._driver = None
raise
return self._driver
def close_driver(self):
"""Closes the Neo4j driver connection if it exists."""
if self._driver is not None:
with self._lock:
if self._driver is not None:
info_logger("Closing Neo4j driver")
self._driver.close()
self._driver = None
def is_connected(self) -> bool:
"""Checks if the database connection is currently active."""
if self._driver is None:
return False
try:
with self._driver.session() as session:
session.run("RETURN 1").consume()
return True
except Exception:
return False
def get_backend_type(self) -> str:
"""Returns the database backend type."""
return 'neo4j'
@staticmethod
def validate_config(uri: str, username: str, password: str) -> Tuple[bool, Optional[str]]:
"""
Validates Neo4j configuration parameters.
Returns:
Tuple[bool, Optional[str]]: (is_valid, error_message)
"""
# Validate URI format
# Modified regex to make port optional "(:\\d+)?"
uri_pattern = r'^(neo4j|neo4j\+s|neo4j\+ssc|bolt|bolt\+s|bolt\+ssc)://[^:]+(:\d+)?$'
if not re.match(uri_pattern, uri):
return False, (
"Invalid Neo4j URI format.\n"
"Expected format: neo4j://host:port or bolt://host:port\n"
"Example: neo4j://localhost:7687\n"
"Common mistake: Missing 'neo4j://' or 'bolt://' prefix"
)
# Validate username
if not username or len(username.strip()) == 0:
return False, (
"Username cannot be empty.\n"
"Default Neo4j username is 'neo4j'"
)
# Validate password
if not password or len(password.strip()) == 0:
return False, (
"Password cannot be empty.\n"
"Tip: If you just set up Neo4j, use the password you configured during setup"
)
return True, None
@staticmethod
def test_connection(uri: str, username: str, password: str) -> Tuple[bool, Optional[str]]:
"""
Tests the Neo4j database connection.
Returns:
Tuple[bool, Optional[str]]: (is_connected, error_message)
"""
try:
from neo4j import GraphDatabase
import socket
# First, test if the host is reachable
try:
# Extract host and port from URI
host_port = uri.split('://')[1]
if ':' in host_port:
host = host_port.split(':')[0]
port = int(host_port.split(':')[1])
else:
host = host_port
port = 7687 # Default Neo4j port
# Test socket connection
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5)
result = sock.connect_ex((host, port))
sock.close()
if result != 0:
return False, (
f"Cannot reach Neo4j server at {host}:{port}\n"
"Troubleshooting:\n"
" • Is Neo4j running? Check with: docker ps (for Docker)\n"
" • Is the port correct? Default is 7687\n"
" • Is there a firewall blocking the connection?\n"
f" • Try: docker compose up -d (if using Docker)"
)
except Exception as e:
return False, f"Error parsing URI or checking connectivity: {str(e)}"
# Now test Neo4j authentication
driver = GraphDatabase.driver(uri, auth=(username, password))
with driver.session() as session:
result = session.run("RETURN 'Connection successful' as status")
result.single()
driver.close()
return True, None
except Exception as e:
error_msg = str(e).lower()
# Provide specific error messages for common issues
if "authentication" in error_msg or "unauthorized" in error_msg:
return False, (
"Authentication failed - Invalid username or password\n"
"Troubleshooting:\n"
" • Default username is 'neo4j'\n"
" • Did you change the password during initial setup?\n"
" • If you forgot the password, you may need to reset Neo4j:\n"
" - Stop: docker compose down\n"
" - Remove data: docker volume rm <volume_name>\n"
" - Restart: docker compose up -d"
)
elif "serviceunAvailable" in error_msg or "failed to establish connection" in error_msg:
return False, (
"Neo4j service is not available\n"
"Troubleshooting:\n"
" • Is Neo4j running? Check: docker ps\n"
" • Start Neo4j: docker compose up -d\n"
" • Check logs: docker compose logs neo4j\n"
" • Wait 30-60 seconds after starting for Neo4j to initialize"
)
elif "unable to retrieve routing information" in error_msg:
return False, (
"Cannot connect to Neo4j routing\n"
"Troubleshooting:\n"
" • Try using 'bolt://' instead of 'neo4j://' in the URI\n"
" • Example: bolt://localhost:7687"
)
else:
return False, f"Connection failed: {str(e)}"