-
Notifications
You must be signed in to change notification settings - Fork 6
/
auto_cache_entry.go
120 lines (101 loc) · 2.22 KB
/
auto_cache_entry.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
package cache
import (
"sync"
"time"
"go-cache/errors"
)
// EntryAutoCache contains data
type EntryAutoCache struct {
name string
value interface{}
updater func() (interface{}, error)
interval time.Duration
run bool
ticker *time.Ticker
mutex sync.RWMutex
signals chan struct{}
logger IAutoCacheLogger
}
// CreateEntryAutoCache returns new instance of EntryAutoCache
func CreateEntryAutoCache(updater func() (interface{}, error), interval time.Duration, name string, logger IAutoCacheLogger) *EntryAutoCache {
return &EntryAutoCache{
name: name,
run: false,
updater: updater,
interval: interval,
logger: logger,
}
}
// GetValue returns the result of processing the updater
func (entry *EntryAutoCache) GetValue() (interface{}, error) {
entry.mutex.RLock()
if !entry.run {
entry.mutex.RUnlock()
if err := entry.process(); err != nil {
return nil, err
}
entry.mutex.RLock()
}
defer entry.mutex.RUnlock()
if entry.value == nil {
return nil, errors.Errorf("Value is not set")
}
return entry.value, nil
}
// Start starts updater process in goroutine
func (entry *EntryAutoCache) Start() error {
if entry.run {
return nil
}
entry.run = true
entry.signals = make(chan struct{}, 1)
entry.ticker = time.NewTicker(entry.interval)
if err := entry.process(); err != nil {
return err
}
go func() {
defer func() {
if r := recover(); r != nil {
entry.logger.Criticalf("Panic in entry.loop(), %v", r)
}
}()
entry.loop()
}()
return nil
}
// Stop stops updater process
func (entry *EntryAutoCache) Stop() {
entry.mutex.Lock()
defer entry.mutex.Unlock()
if entry.run {
entry.run = false
entry.value = nil
entry.ticker.Stop()
entry.signals <- struct{}{}
}
}
func (entry *EntryAutoCache) process() error {
entry.mutex.RLock()
updater := entry.updater
name := entry.name
entry.mutex.RUnlock()
if value, err := updater(); err == nil {
entry.mutex.Lock()
entry.value = value
entry.mutex.Unlock()
} else {
entry.logger.Errorf("Auto cache updater \"%s\" error: %s", name, err)
return err
}
return nil
}
func (entry *EntryAutoCache) loop() {
for {
select {
case <-entry.ticker.C:
entry.process()
case <-entry.signals:
return
}
}
}