diff --git a/src/Project/mongodb.go b/src/Project/mongodb.go new file mode 100644 index 0000000000000000000000000000000000000000..33bd24ab8b3b06df8fd9788b87f9cfa8e3af69e3 --- /dev/null +++ b/src/Project/mongodb.go @@ -0,0 +1,97 @@ +package project + +import ( + "context" + "fmt" + "log" + "time" + + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" +) + +// MongoManager handles MongoDB connection management and database operations +// This struct encapsulates the MongoDB client and database references +// It provides a centralized way to manage database connections throughout the application +type MongoManager struct { + client *mongo.Client // The MongoDB client for connection management + db *mongo.Database // The specific database instance for this application +} + +// NewMongoManager creates and initializes a new MongoDB connection manager +// This function establishes a connection to MongoDB with optimized settings +// and returns a manager instance that can be used throughout the application +func NewMongoManager(uri, dbName string) (*MongoManager, error) { + log.Printf("INFO: Connecting to MongoDB at %s, database: %s", uri, dbName) + + // Configure MongoDB client options for optimal performance + clientOptions := options.Client().ApplyURI(uri) + + // Set connection pool parameters for handling concurrent requests efficiently + // MaxPoolSize: Maximum number of connections in the pool (100 connections) + // This allows the application to handle many concurrent database operations + clientOptions.SetMaxPoolSize(100) + + // MinPoolSize: Minimum number of connections to maintain (10 connections) + // This ensures quick response times by keeping connections ready + clientOptions.SetMinPoolSize(10) + + // MaxConnIdleTime: How long idle connections stay open (30 seconds) + // This balances resource usage with connection availability + clientOptions.SetMaxConnIdleTime(30 * time.Second) + + log.Printf("DEBUG: MongoDB connection pool configured - max: 100, min: 10, idle timeout: 30s") + + // Attempt to create a connection to MongoDB using the configured options + client, err := mongo.Connect(context.TODO(), clientOptions) + if err != nil { + log.Printf("ERROR: Failed to connect to MongoDB: %v", err) + return nil, fmt.Errorf("failed to connect to MongoDB: %w", err) + } + + log.Println("DEBUG: MongoDB client created, testing connection...") + + // Test the connection by pinging the MongoDB server + // This ensures that the connection is actually working before proceeding + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() // Ensure the context is cleaned up after the ping + + if err := client.Ping(ctx, nil); err != nil { + log.Printf("ERROR: MongoDB ping failed: %v", err) + return nil, fmt.Errorf("failed to ping MongoDB: %w", err) + } + + log.Printf("INFO: Successfully connected to MongoDB database '%s'", dbName) + + // Return a configured MongoManager instance + return &MongoManager{ + client: client, // Store the client for connection management + db: client.Database(dbName), // Store the database reference for operations + }, nil +} + +// GetDatabase returns the MongoDB database instance for performing operations +// This method provides access to the database for repositories and other components +// that need to interact with MongoDB collections +func (m *MongoManager) GetDatabase() *mongo.Database { + log.Printf("DEBUG: Returning database instance: %s", m.db.Name()) + return m.db +} + +// Close gracefully shuts down the MongoDB connection +// This method should be called when the application is shutting down +// to ensure all connections are properly closed and resources are released +func (m *MongoManager) Close() error { + log.Println("INFO: Closing MongoDB connection...") + + // Disconnect the MongoDB client using a background context + // This ensures that ongoing operations can complete before disconnection + err := m.client.Disconnect(context.Background()) + if err != nil { + log.Printf("ERROR: Failed to close MongoDB connection: %v", err) + return err + } + + log.Println("INFO: MongoDB connection closed successfully") + return nil +}