Spaces:
Paused
Paused
File size: 5,315 Bytes
529090e | 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 | import neo4j, { Driver, Session, SessionConfig } from 'neo4j-driver';
/**
* Neo4jService - Hybrid Cloud/Local Graph Database Connection
*
* Automatically switches between:
* - LOCAL (dev): bolt://localhost:7687 or Docker neo4j:7687
* - CLOUD (prod): neo4j+s://<id>.databases.neo4j.io (AuraDB)
*
* Features:
* - Self-healing with automatic reconnection
* - Connection pooling
* - Health checks
* - Singleton pattern
*/
export class Neo4jService {
private driver: Driver | null = null;
private isConnecting: boolean = false;
private reconnectAttempts: number = 0;
private maxReconnectAttempts: number = 10;
private reconnectDelay: number = 5000;
constructor() {
this.connect();
}
/**
* Determines connection URI based on environment
*/
private getConnectionConfig(): { uri: string; user: string; password: string } {
const isProduction = process.env.NODE_ENV === 'production';
const hasCloudUri = process.env.NEO4J_URI?.includes('neo4j.io');
// Cloud (AuraDB) - when explicitly configured or in production with cloud URI
if (hasCloudUri) {
console.log('π©οΈ Neo4j Mode: CLOUD (AuraDB)');
return {
uri: process.env.NEO4J_URI!,
user: process.env.NEO4J_USER || 'neo4j',
password: process.env.NEO4J_PASSWORD || ''
};
}
// Local Docker (default for dev)
console.log('π³ Neo4j Mode: LOCAL (Docker)');
return {
uri: process.env.NEO4J_URI || 'bolt://localhost:7687',
user: process.env.NEO4J_USER || 'neo4j',
password: process.env.NEO4J_PASSWORD || 'password'
};
}
/**
* Initializes connection with self-healing retry logic
*/
private async connect(): Promise<void> {
if (this.driver || this.isConnecting) return;
this.isConnecting = true;
const config = this.getConnectionConfig();
try {
console.log(`π Connecting to Neural Graph at ${config.uri}...`);
this.driver = neo4j.driver(
config.uri,
neo4j.auth.basic(config.user, config.password),
{
maxConnectionLifetime: 3 * 60 * 60 * 1000, // 3 hours
maxConnectionPoolSize: 50,
connectionAcquisitionTimeout: 10000, // 10 seconds
connectionTimeout: 30000, // 30 seconds
}
);
// Verify connectivity
await this.driver.verifyConnectivity();
console.log('π’ NEURAL CORTEX CONNECTED - Neo4j is Online');
this.reconnectAttempts = 0;
this.isConnecting = false;
} catch (error: any) {
console.error('π΄ Failed to connect to Neural Graph:', error.message);
this.driver = null;
this.isConnecting = false;
// Self-healing: Retry with exponential backoff
if (this.reconnectAttempts < this.maxReconnectAttempts) {
this.reconnectAttempts++;
const delay = this.reconnectDelay * Math.pow(1.5, this.reconnectAttempts - 1);
console.log(`β³ Retry attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts} in ${delay/1000}s...`);
setTimeout(() => this.connect(), delay);
} else {
console.error('π Max reconnection attempts reached. Neural Graph is OFFLINE.');
}
}
}
/**
* Get a session for graph operations
* Triggers reconnect if disconnected
*/
public getSession(config?: SessionConfig): Session {
if (!this.driver) {
this.connect();
throw new Error('Neural Graph is currently offline. Reconnection in progress...');
}
return this.driver.session(config);
}
/**
* Execute a Cypher query with automatic session management
*/
public async query<T = any>(cypher: string, params: Record<string, any> = {}): Promise<T[]> {
const session = this.getSession();
try {
const result = await session.run(cypher, params);
return result.records.map(record => record.toObject() as T);
} finally {
await session.close();
}
}
/**
* Execute a write transaction
*/
public async write<T = any>(cypher: string, params: Record<string, any> = {}): Promise<T[]> {
const session = this.getSession();
try {
const result = await session.executeWrite(tx => tx.run(cypher, params));
return result.records.map(record => record.toObject() as T);
} finally {
await session.close();
}
}
/**
* Health check for monitoring
*/
public async checkHealth(): Promise<{ status: string; mode: string; latency?: number }> {
if (!this.driver) {
return { status: 'offline', mode: 'unknown' };
}
const start = Date.now();
try {
await this.driver.verifyConnectivity();
const latency = Date.now() - start;
const mode = process.env.NEO4J_URI?.includes('neo4j.io') ? 'cloud' : 'local';
return { status: 'online', mode, latency };
} catch (e) {
return { status: 'error', mode: 'unknown' };
}
}
/**
* Graceful shutdown
*/
public async disconnect(): Promise<void> {
if (this.driver) {
await this.driver.close();
this.driver = null;
console.log('π Neural Graph connection closed.');
}
}
/**
* Check if connected
*/
public isConnected(): boolean {
return this.driver !== null;
}
}
// Singleton instance
export const neo4jService = new Neo4jService();
|