mongodbConnectionManager.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. import { Meteor } from 'meteor/meteor';
  2. import { mongodbDriverManager } from './mongodbDriverManager';
  3. /**
  4. * MongoDB Connection Manager
  5. *
  6. * This module handles MongoDB connections with automatic driver selection
  7. * based on detected MongoDB server version and wire protocol compatibility.
  8. *
  9. * Features:
  10. * - Automatic driver selection based on MongoDB version
  11. * - Connection retry with different drivers on wire protocol errors
  12. * - Fallback mechanism for unsupported versions
  13. * - Connection pooling and management
  14. */
  15. class MongoDBConnectionManager {
  16. constructor() {
  17. this.connections = new Map();
  18. this.connectionConfigs = new Map();
  19. this.retryAttempts = 3;
  20. this.retryDelay = 1000; // 1 second
  21. }
  22. /**
  23. * Create a MongoDB connection with automatic driver selection
  24. * @param {string} connectionString - MongoDB connection string
  25. * @param {Object} options - Connection options
  26. * @returns {Promise<Object>} - MongoDB connection object
  27. */
  28. async createConnection(connectionString, options = {}) {
  29. const connectionId = this.generateConnectionId(connectionString);
  30. // Check if we already have a working connection
  31. if (this.connections.has(connectionId)) {
  32. const existingConnection = this.connections.get(connectionId);
  33. if (existingConnection.status === 'connected') {
  34. return existingConnection;
  35. }
  36. }
  37. // Try to connect with automatic driver selection
  38. return await this.connectWithDriverSelection(connectionString, options, connectionId);
  39. }
  40. /**
  41. * Connect with automatic driver selection and retry logic
  42. * @param {string} connectionString - MongoDB connection string
  43. * @param {Object} options - Connection options
  44. * @param {string} connectionId - Connection identifier
  45. * @returns {Promise<Object>} - MongoDB connection object
  46. */
  47. async connectWithDriverSelection(connectionString, options, connectionId) {
  48. let lastError = null;
  49. let currentDriver = null;
  50. // First, try with the default driver (if we have a detected version)
  51. if (mongodbDriverManager.detectedVersion) {
  52. currentDriver = mongodbDriverManager.getDriverForVersion(mongodbDriverManager.detectedVersion);
  53. } else {
  54. // Start with the most recent driver
  55. currentDriver = 'mongodb8legacy';
  56. }
  57. // Try connection with different drivers
  58. for (let attempt = 0; attempt < this.retryAttempts; attempt++) {
  59. try {
  60. console.log(`Attempting MongoDB connection with driver: ${currentDriver} (attempt ${attempt + 1})`);
  61. const connection = await this.connectWithDriver(currentDriver, connectionString, options);
  62. // Record successful connection
  63. mongodbDriverManager.recordConnectionAttempt(
  64. currentDriver,
  65. mongodbDriverManager.detectedVersion || 'unknown',
  66. true
  67. );
  68. // Store connection
  69. this.connections.set(connectionId, {
  70. connection,
  71. driver: currentDriver,
  72. version: mongodbDriverManager.detectedVersion || 'unknown',
  73. status: 'connected',
  74. connectionString,
  75. options,
  76. createdAt: new Date()
  77. });
  78. return connection;
  79. } catch (error) {
  80. lastError = error;
  81. console.error(`Connection attempt ${attempt + 1} failed with driver ${currentDriver}:`, error.message);
  82. // Try to detect MongoDB version from error
  83. const detectedVersion = mongodbDriverManager.detectVersionFromError(error);
  84. if (detectedVersion && detectedVersion !== 'unknown') {
  85. mongodbDriverManager.detectedVersion = detectedVersion;
  86. currentDriver = mongodbDriverManager.getDriverForVersion(detectedVersion);
  87. console.log(`Detected MongoDB version ${detectedVersion}, switching to driver ${currentDriver}`);
  88. } else {
  89. // Try next fallback driver
  90. const nextDriver = mongodbDriverManager.getNextFallbackDriver();
  91. if (nextDriver) {
  92. currentDriver = nextDriver;
  93. console.log(`Trying fallback driver: ${currentDriver}`);
  94. } else {
  95. console.error('No more fallback drivers available');
  96. break;
  97. }
  98. }
  99. // Record failed attempt
  100. mongodbDriverManager.recordConnectionAttempt(
  101. currentDriver,
  102. detectedVersion || 'unknown',
  103. false,
  104. error
  105. );
  106. // Wait before retry
  107. if (attempt < this.retryAttempts - 1) {
  108. await this.delay(this.retryDelay * (attempt + 1));
  109. }
  110. }
  111. }
  112. // All attempts failed
  113. throw new Error(`Failed to connect to MongoDB after ${this.retryAttempts} attempts. Last error: ${lastError?.message}`);
  114. }
  115. /**
  116. * Connect using a specific driver
  117. * @param {string} driverName - Driver package name
  118. * @param {string} connectionString - MongoDB connection string
  119. * @param {Object} options - Connection options
  120. * @returns {Promise<Object>} - MongoDB connection object
  121. */
  122. async connectWithDriver(driverName, connectionString, options) {
  123. try {
  124. // Dynamically import the driver
  125. const driver = await import(driverName);
  126. const MongoClient = driver.MongoClient;
  127. // Set default options
  128. const defaultOptions = {
  129. useNewUrlParser: true,
  130. useUnifiedTopology: true,
  131. maxPoolSize: 10,
  132. serverSelectionTimeoutMS: 5000,
  133. socketTimeoutMS: 45000,
  134. ...options
  135. };
  136. // Create connection
  137. const client = new MongoClient(connectionString, defaultOptions);
  138. await client.connect();
  139. // Test the connection
  140. await client.db('admin').admin().ping();
  141. return client;
  142. } catch (error) {
  143. throw new Error(`Failed to connect with driver ${driverName}: ${error.message}`);
  144. }
  145. }
  146. /**
  147. * Get connection by ID
  148. * @param {string} connectionId - Connection identifier
  149. * @returns {Object|null} - Connection object or null
  150. */
  151. getConnection(connectionId) {
  152. return this.connections.get(connectionId) || null;
  153. }
  154. /**
  155. * Close a connection
  156. * @param {string} connectionId - Connection identifier
  157. * @returns {Promise<boolean>} - Whether connection was closed successfully
  158. */
  159. async closeConnection(connectionId) {
  160. const connection = this.connections.get(connectionId);
  161. if (connection && connection.connection) {
  162. try {
  163. await connection.connection.close();
  164. this.connections.delete(connectionId);
  165. console.log(`Closed MongoDB connection: ${connectionId}`);
  166. return true;
  167. } catch (error) {
  168. console.error(`Error closing MongoDB connection ${connectionId}:`, error.message);
  169. return false;
  170. }
  171. }
  172. return false;
  173. }
  174. /**
  175. * Close all connections
  176. * @returns {Promise<number>} - Number of connections closed
  177. */
  178. async closeAllConnections() {
  179. let closedCount = 0;
  180. const connectionIds = Array.from(this.connections.keys());
  181. for (const connectionId of connectionIds) {
  182. if (await this.closeConnection(connectionId)) {
  183. closedCount++;
  184. }
  185. }
  186. console.log(`Closed ${closedCount} MongoDB connections`);
  187. return closedCount;
  188. }
  189. /**
  190. * Get connection statistics
  191. * @returns {Object} - Connection statistics
  192. */
  193. getConnectionStats() {
  194. const connections = Array.from(this.connections.values());
  195. const connected = connections.filter(conn => conn.status === 'connected').length;
  196. const disconnected = connections.length - connected;
  197. return {
  198. total: connections.length,
  199. connected,
  200. disconnected,
  201. connections: connections.map(conn => ({
  202. id: this.getConnectionIdFromConnection(conn),
  203. driver: conn.driver,
  204. version: conn.version,
  205. status: conn.status,
  206. createdAt: conn.createdAt
  207. }))
  208. };
  209. }
  210. /**
  211. * Generate a unique connection ID
  212. * @param {string} connectionString - MongoDB connection string
  213. * @returns {string} - Unique connection ID
  214. */
  215. generateConnectionId(connectionString) {
  216. // Create a hash of the connection string for unique ID
  217. let hash = 0;
  218. for (let i = 0; i < connectionString.length; i++) {
  219. const char = connectionString.charCodeAt(i);
  220. hash = ((hash << 5) - hash) + char;
  221. hash = hash & hash; // Convert to 32-bit integer
  222. }
  223. return `mongodb_${Math.abs(hash)}`;
  224. }
  225. /**
  226. * Get connection ID from connection object
  227. * @param {Object} connection - Connection object
  228. * @returns {string} - Connection ID
  229. */
  230. getConnectionIdFromConnection(connection) {
  231. return this.generateConnectionId(connection.connectionString);
  232. }
  233. /**
  234. * Utility function to delay execution
  235. * @param {number} ms - Milliseconds to delay
  236. * @returns {Promise} - Promise that resolves after delay
  237. */
  238. delay(ms) {
  239. return new Promise(resolve => setTimeout(resolve, ms));
  240. }
  241. /**
  242. * Reset all connections and driver manager state
  243. */
  244. reset() {
  245. this.connections.clear();
  246. this.connectionConfigs.clear();
  247. mongodbDriverManager.reset();
  248. }
  249. }
  250. // Create singleton instance
  251. const mongodbConnectionManager = new MongoDBConnectionManager();
  252. // Export for use in other modules
  253. export { mongodbConnectionManager, MongoDBConnectionManager };
  254. // MongoDB Connection Manager initialized (status available in Admin Panel)