-
Notifications
You must be signed in to change notification settings - Fork 0
/
singledo.go
125 lines (105 loc) · 2.19 KB
/
singledo.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
package singledo
import (
"sync"
"time"
)
type call[M any] struct {
wg sync.WaitGroup
val M
err error
}
type Single[M any] struct {
mux sync.Mutex
last time.Time
wait time.Duration
call *call[M]
result *Result[M]
}
type Result[M any] struct {
Val M
Err error
}
func (s *Single[M]) Do(fn func() (M, error)) (v M, shared bool, err error) {
s.mux.Lock()
now := time.Now()
if now.Before(s.last.Add(s.wait)) {
s.mux.Unlock()
return s.result.Val, true, s.result.Err
}
if call := s.call; call != nil {
s.mux.Unlock()
call.wg.Wait()
return call.val, true, call.err
}
call := &call[M]{}
call.wg.Add(1)
s.call = call
s.mux.Unlock()
call.val, call.err = fn()
call.wg.Done()
s.mux.Lock()
s.call = nil
s.result = &Result[M]{Val: call.val, Err: call.err}
s.last = now
s.mux.Unlock()
return call.val, false, call.err
}
func (s *Single[M]) DoWithoutCacheOnFail(fn func() (M, error)) (v M, shared bool, err error) {
s.mux.Lock()
now := time.Now()
if now.Before(s.last.Add(s.wait)) {
s.mux.Unlock()
return s.result.Val, true, s.result.Err
}
if call := s.call; call != nil {
s.mux.Unlock()
call.wg.Wait()
return call.val, true, call.err
}
call := &call[M]{}
call.wg.Add(1)
s.call = call
s.mux.Unlock()
call.val, call.err = fn()
call.wg.Done()
if call.err != nil {
return call.val, false, call.err
}
s.mux.Lock()
s.call = nil
s.result = &Result[M]{Val: call.val, Err: call.err}
s.last = now
s.mux.Unlock()
return call.val, false, call.err
}
func (s *Single[M]) MustDoWithoutCacheOnFail(fn func() (M, error)) (v M, shared bool, err error) {
s.mux.Lock()
now := time.Now()
call := &call[M]{}
call.wg.Add(1)
s.call = call
s.mux.Unlock()
call.val, call.err = fn()
call.wg.Done()
if call.err != nil {
return call.val, false, call.err
}
s.mux.Lock()
s.call = nil
s.result = &Result[M]{Val: call.val, Err: call.err}
s.last = now
s.mux.Unlock()
return call.val, false, call.err
}
func (s *Single[M]) DoFast(fn func() (M, error)) (v M, err error) {
v, _, err = s.Do(fn)
return
}
func (s *Single[M]) Reset() {
s.mux.Lock()
s.last = time.Time{}
s.mux.Unlock()
}
func NewSingle[M any](wait time.Duration) *Single[M] {
return &Single[M]{wait: wait}
}