[GODRIVER-980] Add mongo.Client.ConnectAndPing and mongo.ConnectAndPing Created: 18/Apr/19  Updated: 07/Aug/20  Resolved: 07/Aug/20

Status: Closed
Project: Go Driver
Component/s: CRUD
Affects Version/s: None
Fix Version/s: None

Type: New Feature Priority: Major - P3
Reporter: Kristofer Brandow (Inactive) Assignee: Unassigned
Resolution: Won't Fix Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Currently mongo.Client.Connect and mongo.Connect start up background goroutines and don't wait for the deployment to actually be discovered. Users should use the mongo.Client.Ping method to ensure the deployment is actually discovered and available. To allow users to do this with a single method or function, add the mongo.Client.ConnectAndPing method and mongo.ConnectAndPing function.



 Comments   
Comment by David Bayo Alcaide [ 03/Sep/19 ]

But Connect method has wrong behaviour because is not returning an error if mongod service is down.

Here I have my method for connecting to MongoDB and err is always nil, in spite of mongod process is down

var once sync.Once
var client *mongo.Client
 
func Get(dbName string) *mongo.Database {
	ctx, cancel := context.WithTimeout(context.TODO(), CONNECT_TIMEOUT)
	defer cancel()
 
	once.Do(func() {
		var err error
 
		clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
		clientOptions.SetHeartbeatInterval(time.Second * 5)
		clientOptions.SetMaxPoolSize(20)
		clientOptions.SetMinPoolSize(2)
		clientOptions.SetRetryWrites(true)
		clientOptions.SetServerSelectionTimeout(time.Second * 3)
		clientOptions.SetConnectTimeout(CONNECT_TIMEOUT)
 
		c, err := mongo.NewClient(clientOptions)
 
		if err != nil {
			panic(err)
		}
 
		err = c.Connect(ctx)
 
		if err != nil {
			panic(err)
		}
 
		client = c
	})
 
	db := client.Database(dbName)
 
	return db
}

Panic never called and It should be do it

Comment by David Golden [ 18/Apr/19 ]

Ping is just one way to do that, so maybe the name should be general to the task, not the specific mechanism, such as ConnectVerify or ConnectBlocking. The underlying behavior only needs to select a primary (assuming you don't take a read preference argument); there's no need to actually run the ping command for discovery.

Generated at Thu Feb 08 08:35:23 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.