fix: cache Neo4j driver failure state to avoid 60s retry on every request
get_global_driver() now sets _driver_unavailable=True when the initial connection fails, so subsequent calls fail immediately instead of spending 60s retrying each time. Added reset_global_driver() to allow manual reconnection after Neo4j comes back up. Also fixes APP_BOLT_URL in .env: was bolt://bolt.classroomcopilot.ai (public IP, port not exposed), now bolt://192.168.0.209:7687 (LAN). Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
parent
7ca21ef538
commit
84f7fa9de1
@ -127,16 +127,39 @@ def close_driver(driver: Optional[Driver]) -> None:
|
|||||||
logger.info("Closing driver")
|
logger.info("Closing driver")
|
||||||
driver.close()
|
driver.close()
|
||||||
|
|
||||||
# Global driver instance
|
# Global driver instance — None means not yet initialised, _driver_unavailable=True means connection failed
|
||||||
_driver: Optional[Driver] = None
|
_driver: Optional[Driver] = None
|
||||||
|
_driver_unavailable: bool = False
|
||||||
|
|
||||||
def get_global_driver() -> Optional[Driver]:
|
def get_global_driver() -> Optional[Driver]:
|
||||||
"""Get or create the global Neo4j driver instance."""
|
"""Get or create the global Neo4j driver instance.
|
||||||
global _driver
|
|
||||||
|
Caches both success and failure so a broken Neo4j connection causes
|
||||||
|
a single 60-second retry at startup, then fast-fails on every
|
||||||
|
subsequent call instead of hanging for 60s each time.
|
||||||
|
"""
|
||||||
|
global _driver, _driver_unavailable
|
||||||
|
if _driver_unavailable:
|
||||||
|
return None
|
||||||
if _driver is None:
|
if _driver is None:
|
||||||
_driver = get_driver()
|
_driver = get_driver()
|
||||||
|
if _driver is None:
|
||||||
|
_driver_unavailable = True
|
||||||
|
logger.error("Neo4j driver unavailable — all subsequent Neo4j calls will fail fast until process restarts")
|
||||||
return _driver
|
return _driver
|
||||||
|
|
||||||
|
def reset_global_driver() -> None:
|
||||||
|
"""Reset the cached driver, forcing a reconnection attempt on the next call.
|
||||||
|
|
||||||
|
Call this if Neo4j becomes available after the process started.
|
||||||
|
"""
|
||||||
|
global _driver, _driver_unavailable
|
||||||
|
if _driver:
|
||||||
|
close_driver(_driver)
|
||||||
|
_driver = None
|
||||||
|
_driver_unavailable = False
|
||||||
|
logger.info("Global Neo4j driver reset — will reconnect on next request")
|
||||||
|
|
||||||
@contextmanager
|
@contextmanager
|
||||||
def get_session(database: Optional[str] = None) -> Generator[Session, None, None]:
|
def get_session(database: Optional[str] = None) -> Generator[Session, None, None]:
|
||||||
"""Get a Neo4j session using the global driver."""
|
"""Get a Neo4j session using the global driver."""
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user