-
Notifications
You must be signed in to change notification settings - Fork 31
/
store.go
65 lines (54 loc) · 1.4 KB
/
store.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
// Copyright 2019-2020 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
package config
import (
"context"
"fmt"
"log"
"sync/atomic"
"time"
"github.com/grab/async"
)
// store stores the config and reloads it after 5 seconds
type store struct {
config atomic.Value
configurers []Configurer
loadInterval time.Duration // the repeat interval in seconds to load the config
}
func newStore(li time.Duration, co []Configurer) *store {
s := &store{
loadInterval: li,
configurers: co,
}
c, err := s.value()
if err != nil {
panic(fmt.Sprintf("unable to load config, err is %v", err))
}
s.config.Store(c)
return s
}
// sets a watch to reload the config after every loadInterval seconds
func (cs *store) watch(ctx context.Context) {
async.Repeat(ctx, cs.loadInterval, cs.reload)
}
// reloads the config
func (cs *store) reload(ctx context.Context) (interface{}, error) {
newConfig, err := cs.value()
if err != nil {
return nil, err
}
cs.config.Store(newConfig)
return nil, nil
}
// value ...
func (cs *store) value() (*Config, error) {
c := new(Config)
// Iterate through all the loaders to fill this config object
for _, p := range cs.configurers {
if err := p.Configure(c); err != nil {
log.Printf("%+v : error in loadig config %s", p, err)
return nil, err
}
}
return c, nil
}