/
lazy_connect.go
126 lines (111 loc) · 2.55 KB
/
lazy_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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package dbconnector
import (
"context"
"crypto/tls"
"sync"
"github.com/rs/zerolog/log"
r "gopkg.in/rethinkdb/rethinkdb-go.v6"
)
// ConnectRethinkDB establishes lazy rethinkdb connection
// It will make attempt to connect with first call and reconnect after every error
func ConnectRethinkDB(
addresses []string,
username, password string,
tlsConfig *tls.Config,
poolSize int,
) *LazyRethinkSession {
const systemDatabase = "rethinkdb"
return &LazyRethinkSession{
opts: r.ConnectOpts{
Addresses: addresses,
Database: systemDatabase,
Username: username,
Password: password,
TLSConfig: tlsConfig,
MaxOpen: poolSize,
},
}
}
// LazyRethinkSession is a connection to the rethinkdb.
// It implements r.QueryExecutor interface.
// It will make attempt to connect with first call and reconnect after every error.
type LazyRethinkSession struct {
*r.Session
opts r.ConnectOpts
m sync.Mutex
}
// Close closes connections
func (l *LazyRethinkSession) Close() error {
if l.Session != nil {
return l.Session.Close()
}
return nil
}
// IsConnected returns true if session has a valid connection.
func (l *LazyRethinkSession) IsConnected() bool {
if l.Session == nil {
err := l.connect()
if err != nil {
log.Warn().Err(err).Msg("failed to connect to rethinkdb")
return false
}
}
is := l.Session.IsConnected()
if !is {
err := l.Session.Reconnect()
if err != nil {
return false
}
is = l.Session.IsConnected()
}
return is
}
// Query executes a ReQL query using the session to connect to the database
func (l *LazyRethinkSession) Query(ctx context.Context, q r.Query) (*r.Cursor, error) {
if l.Session == nil {
err := l.connect()
if err != nil {
return nil, err
}
}
cur, err := l.Session.Query(ctx, q)
if err == r.ErrConnectionClosed {
err = l.Session.Reconnect()
if err != nil {
return nil, err
}
cur, err = l.Session.Query(ctx, q)
}
return cur, err
}
// Exec executes a ReQL query using the session to connect to the database
func (l *LazyRethinkSession) Exec(ctx context.Context, q r.Query) error {
if l.Session == nil {
err := l.connect()
if err != nil {
return err
}
}
err := l.Session.Exec(ctx, q)
if err == r.ErrConnectionClosed {
err = l.Session.Reconnect()
if err != nil {
return err
}
err = l.Session.Exec(ctx, q)
}
return err
}
func (l *LazyRethinkSession) connect() error {
l.m.Lock()
defer l.m.Unlock()
var err error
if l.Session == nil {
l.Session, err = r.Connect(l.opts)
if err != nil {
// to connect at next attempt
l.Session = nil
}
}
return err
}