forked from Oskang09/goloquent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
replica.go
203 lines (166 loc) · 4.03 KB
/
replica.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
package goloquent
import (
"context"
"fmt"
"strings"
"sync/atomic"
"time"
)
type replica struct {
secondary map[string]*DB
readonly map[string]*DB
roundRobin int64
}
type replicaResolver int
const (
DefaultReplicaResolver replicaResolver = iota
ReplicaResolvePrimaryOnly
ReplicaResolveSecondaryOnly
ReplicaResolveReadOnly
)
var (
writeNext uint32
readNext uint32
)
func transformList(listDB map[string]*DB) []*DB {
outDB := make([]*DB, 0)
for _, db := range listDB {
outDB = append(outDB, db)
}
return outDB
}
func (r *replica) resolveDatabase(resolver replicaResolver, op dbOperation) *DB {
resolverList := make([]*DB, 0)
switch resolver {
case ReplicaResolvePrimaryOnly:
return nil
case ReplicaResolveSecondaryOnly:
if len(r.secondary) == 0 {
return nil
}
if len(r.secondary) == 1 {
return transformList(r.secondary)[0]
}
resolverList = append(resolverList, transformList(r.secondary)...)
case ReplicaResolveReadOnly:
if len(r.readonly) == 0 {
return nil
}
if len(r.readonly) == 1 {
return transformList(r.readonly)[0]
}
resolverList = append(resolverList, transformList(r.readonly)...)
case DefaultReplicaResolver:
if op == operationRead {
resolverList = append(resolverList, nil)
resolverList = append(resolverList, transformList(r.secondary)...)
resolverList = append(resolverList, transformList(r.readonly)...)
}
if op == operationWrite {
resolverList = append(resolverList, nil)
resolverList = append(resolverList, transformList(r.secondary)...)
}
}
if len(resolverList) == 1 {
return resolverList[0]
}
next := uint32(0)
if op == operationRead {
next = atomic.AddUint32(&readNext, 1)
} else {
next = atomic.AddUint32(&writeNext, 1)
}
return resolverList[int(next)%len(resolverList)]
}
type ReplicaConfig struct {
Username string
Password string
Host string
Port string
Database string
UnixSocket string
TLSConfig string
ReadOnly bool
CharSet *CharSet
Logger LogHandler
Native NativeHandler
}
func (db *DB) ReplicaPingInterval(seconds int64) error {
// only allow add replicas on primary connection
if db.replica == nil {
return fmt.Errorf("goloquent: unsupported replica action on non-primary db")
}
db.replicaPingInterval = seconds
return nil
}
func (db *DB) Replica(ctx context.Context, driver string, conf ReplicaConfig) error {
// only allow add replicas on primary connection
if db.replica == nil {
return fmt.Errorf("goloquent: unsupported replica action on non-primary db")
}
driver = strings.TrimSpace(strings.ToLower(driver))
dialect, ok := GetDialect(driver)
if !ok {
panic(fmt.Errorf("goloquent: unsupported database driver %q", driver))
}
config := Config{
Username: conf.Username,
Password: conf.Password,
Host: conf.Host,
Port: conf.Port,
TLSConfig: conf.TLSConfig,
Database: conf.Database,
UnixSocket: conf.UnixSocket,
CharSet: conf.CharSet,
Logger: conf.Logger,
}
config.Normalize()
conn, err := dialect.Open(config)
if err != nil {
return err
}
if conf.Native != nil {
conf.Native(conn)
}
client := Client{
driver: driver,
sqlCommon: conn,
dialect: dialect,
CharSet: *config.CharSet,
logger: config.Logger,
}
dialect.SetDB(client)
replicaDB := &DB{
id: fmt.Sprintf("%s:%d", driver, time.Now().UnixNano()),
driver: driver,
name: dialect.CurrentDB(ctx),
client: client,
dialect: dialect,
}
go func() {
for {
pingContext, cancel := context.WithTimeout(context.TODO(), time.Second*time.Duration(db.replicaPingInterval))
defer cancel()
select {
case <-pingContext.Done():
err := conn.PingContext(ctx)
if conf.ReadOnly {
if err != nil {
delete(db.replica.readonly, replicaDB.id)
} else {
db.replica.readonly[replicaDB.id] = replicaDB
}
} else {
if err != nil {
delete(db.replica.secondary, replicaDB.id)
} else {
db.replica.secondary[replicaDB.id] = replicaDB
}
}
case <-ctx.Done():
break
}
}
}()
return nil
}