-
Notifications
You must be signed in to change notification settings - Fork 0
/
connect.go
76 lines (56 loc) · 1.41 KB
/
connect.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package mongohelper
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"time"
)
func (l *Link) defineLink(opts *options.ClientOptions) error {
ctx, cancel := context.WithTimeout(context.Background(), l.connTimeout())
defer cancel()
c, err := mongo.Connect(ctx, opts)
if err != nil {
l.log("link.defineLink.mongo.Connect", err.Error())
return err
}
l.client = c
return nil
}
func (l *Link) ping() error {
ctx, cancel := context.WithTimeout(context.Background(), l.connTimeout())
defer cancel()
err := l.client.Ping(ctx, readpref.Primary())
if err != nil {
l.log("link.ping", err.Error())
}
return err
}
// connect tries to conect database using the given options
func (l *Link) connect() error {
opts := options.Client().ApplyURI(l.connectionString())
opts.SetConnectTimeout(l.connTimeout())
opts.SetMaxConnIdleTime(8 * time.Hour)
opts.SetSocketTimeout(l.execTimeout())
opts.SetMinPoolSize(10)
opts.SetAppName(l.appName())
// It's not possible to restore from errors in options validation
if err := l.defineLink(opts); err != nil {
return err
}
for {
err := l.ping()
if err != nil {
l.log("link.mongo.Ping", err.Error())
if l.insistOnFail() && l.canInsist() {
l.wait()
l.increment()
continue
} else {
return err
}
}
l.notifyConnection()
return nil
}
}