-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminerva.go
81 lines (68 loc) · 1.79 KB
/
minerva.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
package minerva
import (
"context"
"fmt"
"github.com/pkg/errors"
)
// Options hold various configuration for minerva
type Options struct {
PrefixKey string
}
var defaultOptions = Options{
PrefixKey: "config",
}
// Minerva is the main struct that glue all components for creating remote config
type Minerva struct {
remoteClient RemoteClient
remoteConfig map[string]string
cancelFunc context.CancelFunc
context context.Context
options Options
}
// New create Minerva with default Options
func New(remoteClient RemoteClient) *Minerva {
return &Minerva{
remoteClient: remoteClient,
remoteConfig: map[string]string{},
options: defaultOptions,
}
}
// NewWithOptions create Minerva with custom options
func NewWithOptions(remoteClient RemoteClient, options Options) *Minerva {
return &Minerva{
remoteClient: remoteClient,
remoteConfig: map[string]string{},
options: options,
}
}
// Get a key value in remote config
func (m *Minerva) Get(key string) string {
_, isKeyPresent := m.remoteConfig[key]
remoteConfigKey := fmt.Sprintf("%s:%s", m.options.PrefixKey, key)
if !isKeyPresent {
m.remoteConfig[key] = m.remoteClient.Get(remoteConfigKey)
}
return m.remoteConfig[key]
}
// Watch all changes happening on remote config and apply it on local config
func (m *Minerva) Watch() error {
ctx, cancel := context.WithCancel(context.Background())
m.context = ctx
m.cancelFunc = cancel
keyEventChannel, err := m.remoteClient.Watch(ctx, m.options.PrefixKey)
go func(ctx context.Context) {
for {
select {
case keyEvent := <-keyEventChannel:
m.remoteConfig[keyEvent.AffectedKey] = keyEvent.Value
case <-ctx.Done():
return
}
}
}(ctx)
return errors.Wrap(err, "Error in watching key event")
}
// Close watcher
func (m *Minerva) Close() {
m.cancelFunc()
}