// backend/db/mongoose.js // Connects the backend to MongoDB. // The backend is READ-ONLY — all writes are done by the proxy server. // MongoDB URI is provided via MONGODB_URI environment variable. const mongoose = require('mongoose'); const path = require('path'); const envFile = process.env.NODE_ENV === 'production' ? '.env.production' : '.env.local'; require('dotenv').config({ path: path.join(__dirname, '../../', envFile) }); const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/backone_dpi'; async function connectDB() { if (mongoose.connection.readyState >= 1) return; // already connected const MAX_RETRIES = 5; const RETRY_DELAY = 5000; for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) { try { console.log(`[MongoDB] Connecting... (attempt ${attempt}/${MAX_RETRIES})`); await mongoose.connect(MONGODB_URI, { serverSelectionTimeoutMS: 10000, connectTimeoutMS: 10000, }); console.log('[MongoDB] ✓ Connected successfully to', MONGODB_URI); const { logCapacityStats } = require('./capacityTracker'); logCapacityStats('[MongoDB]').catch(err => console.warn('[MongoDB] Capacity log failed:', err.message)); const { pruneOutOfSubnetData } = require('../utils/subnetFilter'); pruneOutOfSubnetData().catch(() => {}); setInterval(() => pruneOutOfSubnetData().catch(() => {}), 2 * 60 * 1000).unref?.(); return; } catch (error) { console.error(`[MongoDB] ✗ Attempt ${attempt} failed: ${error.message}`); if (attempt < MAX_RETRIES) { console.log(`[MongoDB] Retrying in ${RETRY_DELAY / 1000}s...`); await new Promise(resolve => setTimeout(resolve, RETRY_DELAY)); } } } console.error('[MongoDB] Initial connection attempts failed. Scheduling background reconnect every 10s...'); // Keep retrying in the background so Docker Swarm container restarts never leave backend permanently disconnected const timer = setInterval(async () => { if (mongoose.connection.readyState >= 1) { clearInterval(timer); return; } try { console.log('[MongoDB] Background reconnect attempt...'); await mongoose.connect(MONGODB_URI, { serverSelectionTimeoutMS: 10000, connectTimeoutMS: 10000, }); console.log('[MongoDB] ✓ Background reconnect succeeded to', MONGODB_URI); clearInterval(timer); const { logCapacityStats } = require('./capacityTracker'); logCapacityStats('[MongoDB]').catch(err => console.warn('[MongoDB] Capacity log failed:', err.message)); } catch (err) { console.error(`[MongoDB] ✗ Background reconnect failed: ${err.message}`); } }, 10000); } module.exports = connectDB;