-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathswr.go
More file actions
106 lines (89 loc) · 1.79 KB
/
Copy pathswr.go
File metadata and controls
106 lines (89 loc) · 1.79 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
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
package swr
import (
"errors"
"sync"
"time"
)
type Fetcher[T any] func() (T, error)
type Cache[T any] struct {
fetcher Fetcher[T]
refresh time.Duration
mu sync.Mutex
value *T
err error
timestamp time.Time
fetching chan struct{}
}
func New[T any](fetcher Fetcher[T], refresh time.Duration) (*Cache[T], error) {
if fetcher == nil {
return nil, errors.New("swr cache fetcher must not be nil")
}
if refresh <= 0 {
return nil, errors.New("swr cache refresh must be greater than 0")
}
c := &Cache[T]{
refresh: refresh,
fetcher: fetcher,
}
return c, nil
}
func (c *Cache[T]) Get() (T, error) {
if c == nil {
var zero T
return zero, errors.New("swr cache is nil")
}
defer c.mu.Unlock()
c.mu.Lock()
// Subsequent fetches
if c.value != nil {
// Background refresh
if time.Since(c.timestamp) > c.refresh && c.fetching == nil {
c.fetching = make(chan struct{})
go c.backgroundFetch(c.fetching)
}
return *c.value, nil
}
// Initial fetches
if c.fetching != nil {
// Await initial fetch in another goroutine
ch := c.fetching
c.mu.Unlock()
<-ch
c.mu.Lock()
} else {
c.initialFetch()
}
if c.err != nil {
var zero T
return zero, c.err
}
return *c.value, nil
}
func (c *Cache[T]) initialFetch() {
// Start initial fetch (don't block other go routines by holding a lock)
c.fetching = make(chan struct{})
c.mu.Unlock()
v, err := c.fetcher()
c.mu.Lock()
if err == nil {
c.timestamp = time.Now()
c.value = &v
}
// Update error and close channel
c.err = err
ch := c.fetching
c.fetching = nil
close(ch)
}
func (c *Cache[T]) backgroundFetch(fetching chan struct{}) {
v, err := c.fetcher()
defer c.mu.Unlock()
c.mu.Lock()
if err == nil {
c.timestamp = time.Now()
c.value = &v
}
c.err = err
close(fetching)
c.fetching = nil
}