Spaces:
Sleeping

File size: 3,667 Bytes
0b355ec
 
 
78a6fc9
 
0b355ec
 
7851df6
 
 
 
 
 
 
 
 
 
 
 
 
0b355ec
7851df6
 
 
 
 
 
78a6fc9
0b355ec
 
 
 
 
 
 
 
78a6fc9
0b355ec
 
 
 
78a6fc9
0b355ec
 
7851df6
 
 
 
 
 
 
 
0b355ec
 
7851df6
 
 
 
 
0b355ec
 
78a6fc9
 
 
 
 
 
0b355ec
 
 
7851df6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78a6fc9
 
 
7851df6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const mongoose = require('mongoose');
const logger = require('./logger');

let isConnected = false;

const connectDB = async () => {
  try {
    // Enhanced MongoDB connection options for production stability
    const mongoOptions = {
      maxPoolSize: 10,
      serverSelectionTimeoutMS: 5000,
      socketTimeoutMS: 45000,
      bufferMaxEntries: 0,
      bufferCommands: false,
      autoIndex: process.env.NODE_ENV !== 'production',
      maxIdleTimeMS: 30000,
      minPoolSize: 2,
      retryWrites: true,
      retryReads: true
    };

    const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/uga-chatbot';

    logger.info('Attempting to connect to MongoDB...');
    const conn = await mongoose.connect(mongoUri, mongoOptions);

    logger.info(`MongoDB Connected Successfully: ${conn.connection.host}`);
    isConnected = true;

    // Connection event listeners
    mongoose.connection.on('error', (err) => {
      logger.error('MongoDB connection error:', err);
    });

    mongoose.connection.on('disconnected', () => {
      logger.warn('MongoDB disconnected');
      isConnected = false;
    });

    mongoose.connection.on('reconnected', () => {
      logger.info('MongoDB reconnected');
      isConnected = true;
    });

    // Enhanced connection event listeners
    mongoose.connection.on('connecting', () => {
      logger.info('MongoDB attempting to reconnect...');
    });

    mongoose.connection.on('connected', () => {
      logger.info('MongoDB connected');
      isConnected = true;
    });

    // Create indexes if needed
    if (process.env.NODE_ENV !== 'production') {
      await ensureIndexes();
    }

  } catch (error) {
    logger.error('Error connecting to MongoDB:', error.message);
    logger.warn('MongoDB unavailable - running without persistent storage');
    // Don't exit process for MongoDB connection failure in production
    // This allows the app to run with local AI only
    if (process.env.NODE_ENV !== 'production') {
      process.exit(1);
    }
  }
};

// Ensure database indexes are created
const ensureIndexes = async () => {
  try {
    // Import models to ensure indexes are created
    require('../models/User');
    require('../models/UGAEvent');

    // Check if ChatHistory model exists
    const fs = require('fs');
    const path = require('path');
    const chatHistoryPath = path.join(__dirname, '../models/ChatHistory.js');

    if (fs.existsSync(chatHistoryPath)) {
      require('../models/ChatHistory');
    } else {
      // Import from root models directory
      const rootChatHistoryPath = path.join(__dirname, '../../../models/ChatHistory.js');
      if (fs.existsSync(rootChatHistoryPath)) {
        require('../../../models/ChatHistory');
      }
    }

    logger.info('Database indexes ensured');
  } catch (error) {
    logger.warn('Could not ensure indexes:', error.message);
  }
};

// Helper function to check if database is available
const isDatabaseConnected = () => isConnected && mongoose.connection.readyState === 1;

// Graceful shutdown handler
const gracefulShutdown = async () => {
  if (mongoose.connection.readyState !== 0) {
    try {
      await mongoose.connection.close();
      logger.info('MongoDB connection closed through app termination');
    } catch (error) {
      logger.error('Error closing MongoDB connection:', error.message);
    }
  }
  isConnected = false;
};

// Setup graceful shutdown handlers
process.on('SIGINT', gracefulShutdown);
process.on('SIGTERM', gracefulShutdown);
process.on('SIGUSR2', gracefulShutdown); // Nodemon restart

module.exports = {
  connectDB,
  isDatabaseConnected,
  gracefulShutdown,
  ensureIndexes
};