-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.go
More file actions
79 lines (69 loc) · 1.6 KB
/
cache.go
File metadata and controls
79 lines (69 loc) · 1.6 KB
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
package props
import (
"context"
"fmt"
"log"
"time"
"github.com/magiconair/properties"
)
type Poller interface {
Poll(context.Context) (*properties.Properties, error)
}
type Cache struct {
Store *Properties
Source Poller
RefreshInterval time.Duration
ExpireAfter time.Duration
}
func (c *Cache) Poll(ctx context.Context) (*properties.Properties, error) {
return c.Store.Properties(), nil
}
func (c *Cache) Start(stopCh <-chan struct{}) error {
if _, err := c.sync(context.TODO()); err != nil {
return fmt.Errorf("unable to poll: %w", err)
}
go c.syncLoop(stopCh)
return nil
}
func (c *Cache) sync(ctx context.Context) (*properties.Properties, error) {
p, err := c.Source.Poll(ctx)
if err != nil {
return p, fmt.Errorf("unable to poll: %w", err)
}
c.Store.Replace(p)
return p, nil
}
func (c *Cache) syncLoop(stopCh <-chan struct{}) {
t := time.NewTicker(c.RefreshInterval)
expire := time.AfterFunc(c.ExpireAfter, func() {
log.Printf("clearing cache due to expiry (last successful sync more than %v ago)\n", c.ExpireAfter)
c.clear()
})
defer func() {
t.Stop()
expire.Stop()
}()
for {
select {
case <-t.C:
if _, err := c.sync(context.TODO()); err != nil {
log.Println("unable to sync cache:", err)
} else {
expire.Reset(c.ExpireAfter)
}
case <-stopCh:
log.Println("stopping")
return
}
}
}
func (c *Cache) clear() {
c.Store.Replace(properties.NewProperties())
}
func NewAsyncPollerSource(p *Properties, src Poller, period time.Duration) *Cache {
return &Cache{
Store: p,
Source: src,
RefreshInterval: period,
}
}