timetable-mgr/dbAccess/client.go

80 lines
2.1 KiB
Go
Raw Normal View History

2023-07-17 12:48:36 +01:00
package dbAccess
2023-07-15 22:32:46 +01:00
import (
"git.fjla.uk/owlboard/timetable-mgr/helpers"
"git.fjla.uk/owlboard/timetable-mgr/log"
"go.uber.org/zap"
2023-07-15 23:00:48 +01:00
2023-07-15 22:32:46 +01:00
"context"
2023-07-18 00:25:13 +01:00
"time"
2023-07-15 22:32:46 +01:00
2023-07-18 00:25:13 +01:00
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
2023-07-15 22:32:46 +01:00
)
// Provide the DB Connection to other functions
var MongoClient (*mongo.Client)
2023-07-18 00:25:13 +01:00
// Builds the DB URI based on the loaded configuration parameters
func getDbUri(cfg *helpers.Configuration) string {
var uri = "mongodb://" + cfg.DbUser + ":" + cfg.DbPass + "@" + cfg.DbHost + ":" + cfg.DbPort
2023-07-18 00:25:13 +01:00
return uri
}
2023-07-27 21:11:08 +01:00
// Configure bsonOpts
var bsonOpts = &options.BSONOptions{
UseJSONStructTags: true,
}
func InitDataAccess(cfg *helpers.Configuration) {
log.Debug("Starting database connection")
url := getDbUri(cfg)
const maxRetries = 8
for attempt := 1; attempt <= maxRetries; attempt++ {
log.Info("Attempting to connect to database", zap.Int("attempt", attempt), zap.Int("max-tries", maxRetries))
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI(url).SetBSONOptions(bsonOpts))
if err != nil {
log.Warn("Error connecting to database", zap.Int("attempt", attempt), zap.Int("max-tries", maxRetries))
cancel()
if attempt != maxRetries {
helpers.BackoffDelay(attempt)
}
continue
}
err = client.Ping(ctx, nil)
if err != nil {
log.Warn("Error pinging database", zap.Int("attempt", attempt), zap.Int("max-tries", maxRetries))
cancel()
if attempt != maxRetries {
helpers.BackoffDelay(attempt)
}
continue
}
MongoClient = client
log.Info("Database connection successful")
return
2023-07-18 00:25:13 +01:00
}
log.Fatal("Failed to connect to database on multiple attempts", zap.Int("attempts", maxRetries))
2023-07-18 00:25:13 +01:00
}
2023-07-21 10:02:55 +01:00
// Closes the connection to the database - used for cleanup functions
2023-07-21 10:02:55 +01:00
func CloseMongoClient() {
if MongoClient != nil {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := MongoClient.Disconnect(ctx); err != nil {
2024-04-14 19:03:13 +01:00
log.Warn("Error disconnecting MongoDB client: " + err.Error())
2023-07-21 10:02:55 +01:00
} else {
2024-04-14 19:03:13 +01:00
log.Info("MongoDB client disconnected.")
2023-07-21 10:02:55 +01:00
}
}
}