summaryrefslogtreecommitdiff
path: root/vendor/github.com/sjtug/cerberus/core/pool.go
blob: 5d6268a0a70e5cec7da24fb2392a72c6b9a18345 (plain)
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
package core

import (
	"sync"

	"go.uber.org/zap"
)

var (
	lock     sync.RWMutex
	instance *Instance
)

// GetInstance returns an instance of given config.
// If there already exists an instance (during server reload), it will be updated with the new config.
// Otherwise, a new instance will be created.
// User can pass in an optional logger to log basic metrics about the initialized state.
func GetInstance(config Config, logger *zap.Logger) (*Instance, error) {
	lock.Lock()
	defer lock.Unlock()

	if instance == nil {
		// Initialize a new instance.
		state, pendingElems, blocklistElems, approvalElems, err := NewInstanceState(config)
		if err != nil {
			return nil, err
		}

		logger.Info("cerberus state initialized",
			zap.Int64("pending_elems", pendingElems),
			zap.Int64("blocklist_elems", blocklistElems),
			zap.Int64("approval_elems", approvalElems),
		)
		instance = &Instance{
			Config:        config,
			InstanceState: state,
		}
		return instance, nil
	}

	// Update the existing instance with the new config.
	err := instance.UpdateWithConfig(config, logger)
	if err != nil {
		return nil, err
	}

	return instance, nil
}