forked from latolukasz/beeorm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
registry.go
369 lines (337 loc) · 10.4 KB
/
registry.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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
package beeorm
import (
"database/sql"
"fmt"
"log"
"math"
"os"
"reflect"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
"github.com/go-redis/redis/v9"
_ "github.com/go-sql-driver/mysql" // force this mysql driver
)
type Registry struct {
mysqlPools map[string]MySQLPoolConfig
localCachePools map[string]LocalCachePoolConfig
redisPools map[string]RedisPoolConfig
entities map[string]reflect.Type
enums map[string]Enum
defaultEncoding string
defaultCollate string
redisStreamGroups map[string]map[string]map[string]bool
redisStreamPools map[string]string
}
func NewRegistry() *Registry {
return &Registry{}
}
func (r *Registry) Validate() (validated ValidatedRegistry, err error) {
if r.defaultEncoding == "" {
r.defaultEncoding = "utf8mb4"
}
if r.defaultCollate == "" {
r.defaultCollate = "0900_ai_ci"
}
maxPoolLen := 0
registry := &validatedRegistry{}
registry.registry = r
_, offset := time.Now().Zone()
registry.timeOffset = int64(offset)
l := len(r.entities)
registry.tableSchemas = make(map[reflect.Type]*tableSchema, l)
registry.entities = make(map[string]reflect.Type)
if registry.mySQLServers == nil {
registry.mySQLServers = make(map[string]MySQLPoolConfig)
}
for k, v := range r.mysqlPools {
if len(k) > maxPoolLen {
maxPoolLen = len(k)
}
db, err := sql.Open("mysql", v.GetDataSourceURI())
checkError(err)
var version string
err = db.QueryRow("SELECT VERSION()").Scan(&version)
checkError(err)
v.(*mySQLPoolConfig).version, _ = strconv.Atoi(strings.Split(version, ".")[0])
var autoincrement uint64
var maxConnections int
var skip string
err = db.QueryRow("SHOW VARIABLES LIKE 'auto_increment_increment'").Scan(&skip, &autoincrement)
checkError(err)
v.(*mySQLPoolConfig).autoincrement = autoincrement
err = db.QueryRow("SHOW VARIABLES LIKE 'max_connections'").Scan(&skip, &maxConnections)
checkError(err)
var waitTimeout int
err = db.QueryRow("SHOW VARIABLES LIKE 'wait_timeout'").Scan(&skip, &waitTimeout)
checkError(err)
maxConnections = int(math.Max(math.Floor(float64(maxConnections)*0.5), 1))
maxLimit := v.getMaxConnections()
if maxLimit == 0 {
maxLimit = maxConnections
}
maxLimit = int(math.Min(float64(maxConnections), float64(maxLimit)))
waitTimeout = int(math.Max(float64(waitTimeout), 180))
waitTimeout = int(math.Min(float64(waitTimeout), 180))
db.SetMaxOpenConns(maxLimit)
db.SetMaxIdleConns(int(float64(maxLimit) * 0.33))
db.SetConnMaxLifetime(time.Duration(waitTimeout) * time.Second)
v.(*mySQLPoolConfig).client = db
registry.mySQLServers[k] = v
}
if registry.localCacheServers == nil {
registry.localCacheServers = make(map[string]LocalCachePoolConfig)
}
for k, v := range r.localCachePools {
registry.localCacheServers[k] = v
if len(k) > maxPoolLen {
maxPoolLen = len(k)
}
}
if registry.redisServers == nil {
registry.redisServers = make(map[string]RedisPoolConfig)
}
for k, v := range r.redisPools {
registry.redisServers[k] = v
if len(k) > maxPoolLen {
maxPoolLen = len(k)
}
}
if registry.enums == nil {
registry.enums = make(map[string]Enum)
}
for k, v := range r.enums {
registry.enums[k] = v
}
hasLog := false
for name, entityType := range r.entities {
tableSchema := &tableSchema{}
err := tableSchema.init(r, entityType)
if err != nil {
return nil, err
}
registry.tableSchemas[entityType] = tableSchema
registry.entities[name] = entityType
if tableSchema.hasLog {
hasLog = true
}
}
_, has := r.redisStreamPools[LazyChannelName]
if !has {
r.RegisterRedisStream(LazyChannelName, "default", []string{BackgroundConsumerGroupName})
}
if hasLog {
_, has = r.redisStreamPools[LogChannelName]
if !has {
r.RegisterRedisStream(LogChannelName, "default", []string{BackgroundConsumerGroupName})
}
}
if len(r.redisStreamGroups) > 0 {
_, has = r.redisStreamPools[RedisStreamGarbageCollectorChannelName]
if !has {
r.RegisterRedisStream(RedisStreamGarbageCollectorChannelName, "default", []string{BackgroundConsumerGroupName})
}
}
registry.redisStreamGroups = r.redisStreamGroups
registry.redisStreamPools = r.redisStreamPools
registry.defaultQueryLogger = &defaultLogLogger{maxPoolLen: maxPoolLen, logger: log.New(os.Stderr, "", 0)}
engine := registry.CreateEngine()
for _, schema := range registry.tableSchemas {
_, err := checkStruct(schema, engine.(*engineImplementation), schema.t, make(map[string]*index), make(map[string]*foreignIndex), nil, "")
if err != nil {
return nil, errors.Wrapf(err, "invalid entity struct '%s'", schema.t.String())
}
schema.registry = registry
}
return registry, nil
}
func (r *Registry) SetDefaultEncoding(encoding string) {
r.defaultEncoding = encoding
}
func (r *Registry) SetDefaultCollate(collate string) {
r.defaultCollate = collate
}
func (r *Registry) RegisterEntity(entity ...Entity) {
if r.entities == nil {
r.entities = make(map[string]reflect.Type)
}
for _, e := range entity {
t := reflect.TypeOf(e)
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
r.entities[t.String()] = t
}
}
func (r *Registry) RegisterEnumStruct(code string, val interface{}, defaultValue ...string) {
enum := initEnum(val, defaultValue...)
if r.enums == nil {
r.enums = make(map[string]Enum)
}
r.enums[code] = enum
}
func (r *Registry) RegisterEnum(code string, values []string, defaultValue ...string) {
e := enum{}
e.fields = values
e.defaultValue = values[0]
if len(defaultValue) > 0 {
e.defaultValue = defaultValue[0]
}
e.mapping = make(map[string]int)
for i, name := range values {
e.mapping[name] = i + 1
}
if r.enums == nil {
r.enums = make(map[string]Enum)
}
r.enums[code] = &e
}
func (r *Registry) RegisterMySQLPool(dataSourceName string, code ...string) {
r.registerSQLPool(dataSourceName, code...)
}
func (r *Registry) RegisterLocalCache(size int, code ...string) {
dbCode := "default"
if len(code) > 0 {
dbCode = code[0]
}
if r.localCachePools == nil {
r.localCachePools = make(map[string]LocalCachePoolConfig)
}
r.localCachePools[dbCode] = newLocalCacheConfig(dbCode, size)
}
func (r *Registry) RegisterRedis(address, namespace string, db int, code ...string) {
r.RegisterRedisWithCredentials(address, namespace, "", "", db, code...)
}
func (r *Registry) RegisterRedisWithCredentials(address, namespace, user, password string, db int, code ...string) {
options := &redis.Options{
Addr: address,
DB: db,
ConnMaxIdleTime: time.Minute * 2,
Username: user,
Password: password,
}
if strings.HasSuffix(address, ".sock") {
options.Network = "unix"
}
client := redis.NewClient(options)
r.registerRedis(client, code, address, namespace, db)
}
func (r *Registry) RegisterRedisSentinel(masterName, namespace string, db int, sentinels []string, code ...string) {
r.RegisterRedisSentinelWithCredentials(masterName, namespace, "", "", db, sentinels, code...)
}
func (r *Registry) RegisterRedisSentinelWithCredentials(masterName, namespace, user, password string, db int, sentinels []string, code ...string) {
options := &redis.FailoverOptions{
MasterName: masterName,
SentinelAddrs: sentinels,
DB: db,
ConnMaxIdleTime: time.Minute * 2,
Username: user,
Password: password,
}
client := redis.NewFailoverClient(options)
r.registerRedis(client, code, fmt.Sprintf("%v", sentinels), namespace, db)
}
func (r *Registry) RegisterRedisSentinelWithOptions(namespace string, opts redis.FailoverOptions, db int, sentinels []string, code ...string) {
opts.DB = db
opts.SentinelAddrs = sentinels
if opts.ConnMaxIdleTime == 0 {
opts.ConnMaxIdleTime = time.Minute * 2
}
client := redis.NewFailoverClient(&opts)
r.registerRedis(client, code, fmt.Sprintf("%v", sentinels), namespace, db)
}
func (r *Registry) RegisterRedisStream(name string, redisPool string, groups []string) {
if r.redisStreamGroups == nil {
r.redisStreamGroups = make(map[string]map[string]map[string]bool)
r.redisStreamPools = make(map[string]string)
}
_, has := r.redisStreamPools[name]
if has {
panic(fmt.Errorf("stream with name %s already exists", name))
}
r.redisStreamPools[name] = redisPool
if r.redisStreamGroups[redisPool] == nil {
r.redisStreamGroups[redisPool] = make(map[string]map[string]bool)
}
groupsMap := make(map[string]bool, len(groups))
for _, group := range groups {
groupsMap[group] = true
}
r.redisStreamGroups[redisPool][name] = groupsMap
}
func (r *Registry) registerSQLPool(dataSourceName string, code ...string) {
dbCode := "default"
if len(code) > 0 {
dbCode = code[0]
}
and := "?"
if strings.Index(dataSourceName, "?") > 0 {
and = "&"
}
dataSourceName += and + "multiStatements=true"
db := &mySQLPoolConfig{code: dbCode, dataSourceName: dataSourceName}
if r.mysqlPools == nil {
r.mysqlPools = make(map[string]MySQLPoolConfig)
}
parts := strings.Split(dataSourceName, "/")
dbName := strings.Split(parts[len(parts)-1], "?")[0]
pos := strings.Index(dataSourceName, "limit_connections=")
if pos > 0 {
val := dataSourceName[pos+18:]
val = strings.Split(val, "&")[0]
db.maxConnections, _ = strconv.Atoi(val)
dataSourceName = strings.Replace(dataSourceName, "limit_connections="+val, "", -1)
dataSourceName = strings.Trim(dataSourceName, "?&")
dataSourceName = strings.Replace(dataSourceName, "?&", "?", -1)
db.dataSourceName = dataSourceName
}
db.databaseName = dbName
r.mysqlPools[dbCode] = db
}
func (r *Registry) registerRedis(client *redis.Client, code []string, address, namespace string, db int) {
dbCode := "default"
if len(code) > 0 {
dbCode = code[0]
}
redisCache := &redisCacheConfig{code: dbCode, client: client, address: address, namespace: namespace,
hasNamespace: namespace != "", db: db}
if r.redisPools == nil {
r.redisPools = make(map[string]RedisPoolConfig)
}
r.redisPools[dbCode] = redisCache
}
type RedisPoolConfig interface {
GetCode() string
GetDatabase() int
GetAddress() string
GetNamespace() string
HasNamespace() bool
getClient() *redis.Client
}
type redisCacheConfig struct {
code string
client *redis.Client
db int
address string
namespace string
hasNamespace bool
}
func (p *redisCacheConfig) GetCode() string {
return p.code
}
func (p *redisCacheConfig) GetDatabase() int {
return p.db
}
func (p *redisCacheConfig) GetAddress() string {
return p.address
}
func (p *redisCacheConfig) GetNamespace() string {
return p.namespace
}
func (p *redisCacheConfig) HasNamespace() bool {
return p.hasNamespace
}
func (p *redisCacheConfig) getClient() *redis.Client {
return p.client
}