forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.go
130 lines (108 loc) Β· 2.39 KB
/
cache.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
121
122
123
124
125
126
127
128
129
130
package provider
import (
"time"
"github.com/andig/evcc/util"
"github.com/benbjohnson/clock"
)
// Cached wraps a getter with a cache
type Cached struct {
log *util.Logger
clock clock.Clock
updated time.Time
cache time.Duration
getter interface{}
val interface{}
}
// NewCached wraps a getter with a cache
func NewCached(log *util.Logger, getter interface{}, cache time.Duration) *Cached {
return &Cached{
log: log,
clock: clock.New(),
getter: getter,
cache: cache,
}
}
// FloatGetter gets float value
func (c *Cached) FloatGetter() FloatGetter {
g, ok := c.getter.(FloatGetter)
if !ok {
if g, ok = c.getter.(func() (float64, error)); !ok {
c.log.FATAL.Fatalf("invalid type: %T", c.getter)
}
g = FloatGetter(g)
}
return FloatGetter(func() (float64, error) {
if c.clock.Since(c.updated) > c.cache {
val, err := g()
if err != nil {
return val, err
}
c.updated = c.clock.Now()
c.val = val
}
return c.val.(float64), nil
})
}
// IntGetter gets int value
func (c *Cached) IntGetter() IntGetter {
g, ok := c.getter.(IntGetter)
if !ok {
if g, ok = c.getter.(func() (int64, error)); !ok {
c.log.FATAL.Fatalf("invalid type: %T", c.getter)
}
g = IntGetter(g)
}
return IntGetter(func() (int64, error) {
if c.clock.Since(c.updated) > c.cache {
val, err := g()
if err != nil {
return val, err
}
c.updated = c.clock.Now()
c.val = val
}
return c.val.(int64), nil
})
}
// StringGetter gets string value
func (c *Cached) StringGetter() StringGetter {
g, ok := c.getter.(StringGetter)
if !ok {
if g, ok = c.getter.(func() (string, error)); !ok {
c.log.FATAL.Fatalf("invalid type: %T", c.getter)
}
g = StringGetter(g)
}
return StringGetter(func() (string, error) {
if c.clock.Since(c.updated) > c.cache {
val, err := g()
if err != nil {
return val, err
}
c.updated = c.clock.Now()
c.val = val
}
return c.val.(string), nil
})
}
// BoolGetter gets bool value
func (c *Cached) BoolGetter() BoolGetter {
g, ok := c.getter.(BoolGetter)
if !ok {
if g, ok = c.getter.(func() (bool, error)); !ok {
c.log.FATAL.Fatalf("invalid type: %T", g)
}
g = BoolGetter(g)
}
return BoolGetter(func() (bool, error) {
if c.clock.Since(c.updated) > c.cache {
val, err := g()
if err != nil {
return val, err
}
c.updated = c.clock.Now()
c.val = val
}
return c.val.(bool), nil
})
}