Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix : Incorrect MongoDB Connection Logs #1355

Merged
merged 20 commits into from
Jan 8, 2025
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 24 additions & 4 deletions pkg/gofr/datasource/mongo/mongo.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"net/url"
"time"

"go.opentelemetry.io/otel/attribute"
Expand Down Expand Up @@ -83,13 +84,23 @@ func (c *Client) UseTracer(tracer any) {

// Connect establishes a connection to MongoDB and registers metrics using the provided configuration when the client was Created.
func (c *Client) Connect() {
c.logger.Debugf("connecting to MongoDB at %v to database %v", c.config.URI, c.config.Database)
var host string

c.logger.Debugf("connecting to MongoDB at %v to database %v", c.config.Host, c.config.Database)
coolwednesday marked this conversation as resolved.
Show resolved Hide resolved

uri := c.config.URI

if uri == "" {
uri = fmt.Sprintf("mongodb://%s:%s@%s:%d/%s?authSource=admin",
c.config.User, c.config.Password, c.config.Host, c.config.Port, c.config.Database)

host = c.config.Host
} else {
host = getDBHost(uri)

if host == "" {
c.logger.Debug("failed to parse URI: incorrect format provided")
}
}

timeout := c.config.ConnectionTimeout
Expand All @@ -108,18 +119,27 @@ func (c *Client) Connect() {
}

if err = m.Ping(ctx, nil); err != nil {
c.logger.Errorf("could not connect to mongoDB at %v due to err: %v", c.config.URI, err)
c.logger.Errorf("could not connect to mongoDB at %v due to err: %v", host, err)
coolwednesday marked this conversation as resolved.
Show resolved Hide resolved
return
}

c.logger.Logf("connected to mongoDB successfully at %v to database %v", c.config.URI, c.config.Database)
c.logger.Logf("connected to mongoDB successfully at %v to database %v", host, c.config.Database)
coolwednesday marked this conversation as resolved.
Show resolved Hide resolved

mongoBuckets := []float64{.05, .075, .1, .125, .15, .2, .3, .5, .75, 1, 2, 3, 4, 5, 7.5, 10}
c.metrics.NewHistogram("app_mongo_stats", "Response time of MONGO queries in milliseconds.", mongoBuckets...)
coolwednesday marked this conversation as resolved.
Show resolved Hide resolved

c.Database = m.Database(c.config.Database)

c.logger.Logf("connected to MongoDB at %v to database %v", uri, c.Database)
c.logger.Logf("connected to MongoDB at %v to database %v", host, c.Database)
}

func getDBHost(uri string) (host string) {
parsedURL, err := url.Parse(uri)
coolwednesday marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return ""
}

return parsedURL.Hostname()
}

// InsertOne inserts a single document into the specified collection.
Expand Down
43 changes: 42 additions & 1 deletion pkg/gofr/datasource/mongo/mongo_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,47 @@ func Test_NewMongoClient(t *testing.T) {
assert.NotNil(t, client)
}

func TestGetDBHost(t *testing.T) {
tests := []struct {
name string
uri string
expected string
}{
{
name: "Valid URI with host and port",
uri: "mongodb://username:password@hostname:27017/database?authSource=admin",
expected: "hostname",
},
{
name: "Valid URI with IP address as host",
uri: "mongodb://username:[email protected]:27017/database?authSource=admin",
expected: "192.168.1.1",
},
{
name: "Invalid URI with no host",
uri: "mongodb://username:password@:27017/database?authSource=admin",
expected: "",
},
{
name: "Empty URI",
uri: "",
expected: "",
},
{
name: "Malformed URI",
uri: "mongodb:/username:password@hostname:27017/database?authSource=admin",
expected: "",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := getDBHost(tt.uri)
assert.Equal(t, tt.expected, result, "Test case: %s", tt.name)
})
}
}

func Test_NewMongoClientError(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
Expand All @@ -46,7 +87,7 @@ func Test_NewMongoClientError(t *testing.T) {
logger.EXPECT().Debugf("connecting to MongoDB at %v to database %v", "mongo", "test")
logger.EXPECT().Errorf("error while connecting to MongoDB, err:%v", gomock.Any())

client := New(Config{URI: "mongo", Database: "test"})
client := New(Config{Host: "mongo", Database: "test"})
client.UseLogger(logger)
client.UseMetrics(metrics)
client.Connect()
Expand Down
Loading