-
Notifications
You must be signed in to change notification settings - Fork 41
/
store.go
93 lines (83 loc) · 1.59 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
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
package stencil
import (
"io"
"sync"
"time"
)
type loaderFunc func(string) (*Resolver, error)
type timer struct {
ticker *time.Ticker
done chan bool
}
func (t *timer) Close() error {
t.ticker.Stop()
t.done <- true
return nil
}
func setInterval(d time.Duration, f func(), waitForReader <-chan bool) io.Closer {
ticker := time.NewTicker(d)
done := make(chan bool)
go (func() {
for {
select {
case <-done:
return
case <-ticker.C:
// wait for access
refresh := <-waitForReader
if refresh {
f()
}
}
}
})()
return &timer{ticker: ticker, done: done}
}
type store struct {
autoRefresh bool
timer io.Closer
access chan bool
loader loaderFunc
url string
data *Resolver
lock sync.RWMutex
}
func (s *store) refresh() {
val, err := s.loader(s.url)
if err == nil {
s.lock.Lock()
defer s.lock.Unlock()
s.data = val
}
}
func (s *store) notify() {
select {
case s.access <- true:
default:
}
}
func (s *store) getResolver() (*Resolver, bool) {
s.notify()
s.lock.RLock()
defer s.lock.RUnlock()
return s.data, s.data != nil
}
func (s *store) Close() {
close(s.access)
if s.timer != nil {
s.timer.Close()
}
}
func newStore(url string, options Options) (*store, error) {
loader := options.RefreshStrategy.getLoader(options)
s := &store{loader: loader, access: make(chan bool), url: url, autoRefresh: options.AutoRefresh}
val, err := loader(url)
if err != nil {
return s, err
}
s.data = val
if options.AutoRefresh {
s.timer = setInterval(options.RefreshInterval, s.refresh, s.access)
}
return s, nil
}