github.heygears.com/openimsdk/tools@v0.0.49/db/mongoutil/common.go (about) 1 // Copyright © 2024 OpenIM open source community. 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 "fmt" 20 "go.mongodb.org/mongo-driver/mongo" 21 "strings" 22 ) 23 24 const ( 25 defaultMaxPoolSize = 100 26 defaultMaxRetry = 3 27 ) 28 29 // buildMongoURI constructs the MongoDB URI from the provided configuration. 30 func buildMongoURI(config *Config) string { 31 credentials := "" 32 if config.Username != "" && config.Password != "" { 33 credentials = fmt.Sprintf("%s:%s@", config.Username, config.Password) 34 } 35 return fmt.Sprintf("mongodb://%s%s/%s?maxPoolSize=%d", credentials, strings.Join(config.Address, ","), config.Database, config.MaxPoolSize) 36 } 37 38 // shouldRetry determines whether an error should trigger a retry. 39 func shouldRetry(ctx context.Context, err error) bool { 40 select { 41 case <-ctx.Done(): 42 return false 43 default: 44 if cmdErr, ok := err.(mongo.CommandError); ok { 45 return cmdErr.Code != 13 && cmdErr.Code != 18 46 } 47 return true 48 } 49 }