-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflight.go
More file actions
143 lines (101 loc) · 1.8 KB
/
flight.go
File metadata and controls
143 lines (101 loc) · 1.8 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
package singleflight
import (
"sync"
"nikand.dev/go/batch"
)
type (
Group[Res any] struct {
mu sync.Mutex
flight[Res]
}
KeyedGroups[Key comparable, Res any] struct {
mu sync.Mutex
active map[Key]*flight[Res]
pool map[*flight[Res]]struct{}
}
flight[Res any] struct {
cond sync.Cond
res Res
err error
cnt int
}
Func[Res any] = func() (Res, error)
PanicError = batch.PanicError
)
func (g *Group[Res]) Do(f Func[Res]) (res Res, err error) {
defer g.mu.Unlock()
g.mu.Lock()
return g.do(f, &g.mu)
}
func (g *flight[Res]) do(f func() (Res, error), mu *sync.Mutex) (res Res, err error) {
if g.cond.L == nil {
g.cond.L = mu
}
for g.cnt < 0 {
g.cond.Wait()
}
defer func() {
g.cond.Broadcast()
g.cnt++
if g.cnt != 0 {
return
}
var zero Res
g.res = zero
g.err = nil
}()
g.cnt++
if g.cnt != 1 {
g.cond.Wait()
return g.res, g.err
}
func() {
defer func() {
p := recover()
if p == nil {
return
}
g.err = PanicError{Panic: p}
panic(p)
}()
defer mu.Lock()
mu.Unlock()
g.res, g.err = f()
}()
if g.cnt < 0 {
panic("singleflight: inconsistent state")
}
g.cnt = -g.cnt
return g.res, g.err
}
func (g *KeyedGroups[Key, Res]) Do(key Key, f Func[Res]) (res Res, err error) {
defer g.mu.Unlock()
g.mu.Lock()
if g.active == nil {
g.active = map[Key]*flight[Res]{}
g.pool = map[*flight[Res]]struct{}{}
}
s, ok := g.active[key]
if !ok {
s = g.get()
g.active[key] = s
}
defer func() {
if s.cnt != 0 {
return
}
delete(g.active, key)
g.pool[s] = struct{}{}
}()
return s.do(f, &g.mu)
}
func (g *KeyedGroups[Key, Res]) get() *flight[Res] {
for s := range g.pool {
delete(g.pool, s)
return s
}
return &flight[Res]{}
}
func AsPanicError(err error) (PanicError, bool) {
return batch.AsPanicError(err)
}