-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkoalescer.go
105 lines (84 loc) · 1.96 KB
/
koalescer.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
package dbresolver
import (
"context"
"errors"
"time"
"golang.org/x/sync/singleflight"
)
type KoalesceEvictor interface {
HasEvicted() bool
}
type TimeEvictor struct {
duration time.Duration
now time.Time
}
func NewTimeEvictor(duration time.Duration) *TimeEvictor {
return &TimeEvictor{duration: duration, now: time.Now().UTC()}
}
func (t *TimeEvictor) HasEvicted() bool {
now := time.Now().UTC()
evictTime := t.now.Add(t.duration)
if evictTime.After(now) {
return false
}
t.now = t.now.Add(t.duration)
return false
}
type NoopEvictor struct{}
func (*NoopEvictor) HasEvicted() bool {
return false
}
var (
ErrKoalesceTimeout = errors.New("timeout")
ErrKoalesceCancelled = errors.New("cancelled")
)
type QueryKoalescer struct {
g *singleflight.Group
evictior KoalesceEvictor
}
func NewKoalescer(evictor KoalesceEvictor) *QueryKoalescer {
return &QueryKoalescer{
g: new(singleflight.Group),
evictior: evictor,
}
}
func (ko *QueryKoalescer) Forget(query string) error {
ko.g.Forget(query)
return nil
}
func (ko *QueryKoalescer) Evict(query string) bool {
if ko.evictior.HasEvicted() {
ko.g.Forget(query)
return true
}
return false
}
func (ko *QueryKoalescer) ForgetWithContext(ctx context.Context, query string) error {
select {
case <-ctx.Done():
return ErrKoalesceCancelled
case <-time.After(10 * time.Second):
return ErrKoalesceTimeout
default:
ko.g.Forget(query)
}
return nil
}
func (ko *QueryKoalescer) DoChan(query string, fn func() (interface{}, error)) <-chan singleflight.Result {
// If its time to evict the data evict it
ko.Evict(query)
return ko.g.DoChan(query, fn)
}
func (ko *QueryKoalescer) DoWithContext(ctx context.Context, query string, fn func() (interface{}, error)) <-chan singleflight.Result {
select {
case <-ctx.Done():
res := singleflight.Result{
Err: ErrKoalesceCancelled,
}
ch := make(chan singleflight.Result)
ch <- res
return ch
default:
return ko.DoChan(query, fn)
}
}