github.heygears.com/openimsdk/tools@v0.0.49/db/mongoutil/verify.go (about)

     1  // Copyright © 2023 OpenIM. All rights reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package mongoutil
    16  
    17  import (
    18  	"context"
    19  
    20  	"github.com/openimsdk/tools/errs"
    21  	"go.mongodb.org/mongo-driver/mongo"
    22  	"go.mongodb.org/mongo-driver/mongo/options"
    23  )
    24  
    25  // CheckMongo tests the MongoDB connection without retries.
    26  func Check(ctx context.Context, config *Config) error {
    27  	if err := config.ValidateAndSetDefaults(); err != nil {
    28  		return err
    29  	}
    30  
    31  	clientOpts := options.Client().ApplyURI(config.Uri)
    32  	mongoClient, err := mongo.Connect(ctx, clientOpts)
    33  	if err != nil {
    34  		return errs.WrapMsg(err, "MongoDB connect failed", "URI", config.Uri, "Database", config.Database, "MaxPoolSize", config.MaxPoolSize)
    35  	}
    36  
    37  	defer func() {
    38  		if err := mongoClient.Disconnect(ctx); err != nil {
    39  			_ = mongoClient.Disconnect(ctx)
    40  		}
    41  	}()
    42  
    43  	if err = mongoClient.Ping(ctx, nil); err != nil {
    44  		return errs.WrapMsg(err, "MongoDB ping failed", "URI", config.Uri, "Database", config.Database, "MaxPoolSize", config.MaxPoolSize)
    45  	}
    46  
    47  	return nil
    48  }
    49  
    50  // ValidateAndSetDefaults validates the configuration and sets default values.
    51  func (c *Config) ValidateAndSetDefaults() error {
    52  	if c.Uri == "" && len(c.Address) == 0 {
    53  		return errs.New("either Uri or Address must be provided")
    54  	}
    55  	if c.Database == "" {
    56  		return errs.New("database is required")
    57  	}
    58  	if c.MaxPoolSize <= 0 {
    59  		c.MaxPoolSize = defaultMaxPoolSize
    60  	}
    61  	if c.MaxRetry <= 0 {
    62  		c.MaxRetry = defaultMaxRetry
    63  	}
    64  	if c.Uri == "" {
    65  		c.Uri = buildMongoURI(c)
    66  	}
    67  	return nil
    68  }