-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsync.go
343 lines (280 loc) · 6.45 KB
/
sync.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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
package core
import (
"context"
"runtime"
"sync"
"sync/atomic"
)
// SpinLock is a simple CompareAndSwap locking mechanism.
type SpinLock uint32
func (sl *SpinLock) ptr() *uint32 {
if sl == nil {
return nil
}
return (*uint32)(sl)
}
// TryLock attempts to acquire the lock
func (sl *SpinLock) TryLock() bool {
return atomic.CompareAndSwapUint32(sl.ptr(), 0, 1)
}
// Lock blocks until it can acquire the lock
func (sl *SpinLock) Lock() {
for !sl.TryLock() {
runtime.Gosched() // yield
}
}
// Unlock releases the lock
func (sl *SpinLock) Unlock() {
if !atomic.CompareAndSwapUint32(sl.ptr(), 1, 0) {
panic("invalid SpinLock.Unlock")
}
}
// WaitGroup is a safer way to run workers
type WaitGroup struct {
mu sync.Mutex
wg sync.WaitGroup
err atomic.Value
errCh chan error
onError func(error) error
}
func (wg *WaitGroup) init() {
wg.mu.Lock()
if wg.errCh == nil {
wg.errCh = make(chan error)
go wg.watchErrCh()
}
wg.mu.Unlock()
}
// OnError sets a helper that will be called when
// a worker returns an error or panics
func (wg *WaitGroup) OnError(fn func(error) error) {
wg.onError = fn
}
func (wg *WaitGroup) watchErrCh() {
defer close(wg.errCh)
for {
err, ok := <-wg.errCh
switch {
case !ok:
// wtf
return
case wg.onError != nil:
// process
err = wg.onError(err)
}
switch {
case err == nil:
// error dismissed
case wg.err.CompareAndSwap(nil, err):
// first, we are done.
return
}
}
}
// Go spawns a supervised goroutine
func (wg *WaitGroup) Go(fn func() error) {
wg.GoCatch(fn, nil)
}
// GoCatch spawns a supervised goroutine, and uses a given function
// to intercept the returned error
func (wg *WaitGroup) GoCatch(fn func() error, catch func(error) error) {
wg.init()
if fn != nil {
wg.wg.Add(1)
go func() {
defer wg.wg.Done()
wg.run(fn, catch)
}()
}
}
func (wg *WaitGroup) run(fn func() error, catch func(error) error) {
var c1, c2 Catcher
err := c1.Do(fn)
if err != nil && catch != nil {
err = c2.Do(func() error {
return catch(err)
})
}
if err != nil {
wg.tryReportError(err)
}
}
func (wg *WaitGroup) tryReportError(err error) {
wg.wg.Add(1)
go func() {
defer wg.wg.Done()
defer func() {
// ignore if errCh is closed
_ = recover()
}()
wg.errCh <- err
}()
}
// Wait waits until all workers have finished, and returns
// the first error
func (wg *WaitGroup) Wait() error {
wg.wg.Wait()
return wg.Err()
}
// Done returns a channel that gets closed when all workers
// have finished.
func (wg *WaitGroup) Done() <-chan struct{} {
done := make(chan struct{})
go func() {
defer close(done)
wg.wg.Wait()
}()
return done
}
// Err returns the first error
func (wg *WaitGroup) Err() error {
if err, ok := wg.err.Load().(error); ok {
return err
}
return nil
}
// ErrGroup handles a group of workers where all are canceled once one fails.
// As it's based on [WaitGroup] it also catches panics.
type ErrGroup struct {
wg WaitGroup
ctx context.Context
cancel context.CancelCauseFunc
cancelled atomic.Bool
onError func(error)
Parent context.Context
}
// SetDefaults fills gaps in the config and initializes
// the internal structure.
func (eg *ErrGroup) SetDefaults() {
if eg.Parent == nil {
eg.Parent = context.Background()
}
if eg.ctx == nil {
ctx, cancel := context.WithCancelCause(eg.Parent)
eg.ctx = ctx
eg.cancel = cancel
eg.wg.OnError(eg.wgError)
}
}
func (eg *ErrGroup) init() {
eg.wg.mu.Lock()
defer eg.wg.mu.Unlock()
if eg.ctx == nil {
// once
eg.SetDefaults()
}
}
// OnError sets a helper that will be called when
// a worker returns an error or panics
func (eg *ErrGroup) OnError(fn func(error)) {
eg.onError = fn
}
// Cancel initiates a shutdown of the group. The returned
// value indicates if it was the first time.
func (eg *ErrGroup) Cancel(cause error) bool {
eg.init()
if cause == nil {
cause = context.Canceled
}
return eg.doCancel(cause)
}
func (eg *ErrGroup) doCancel(cause error) bool {
var first bool
if eg.cancelled.CompareAndSwap(false, true) {
// cancel once
eg.cancel(cause)
first = true
}
// and notify others
if fn := eg.onError; fn != nil {
fn(cause)
}
return first
}
func (eg *ErrGroup) wgError(err error) error {
if eg.doCancel(err) {
// first
return err
}
return nil
}
// Context returns the cancellable context used with the workers
func (eg *ErrGroup) Context() context.Context {
eg.init()
return eg.ctx
}
// Cancelled returns a channel marker to know when the Group has
// been cancelled and the shutdown has been initiated.
//
// Cancelled() doesn't indicate all workers have finished, for that
// call [ErrGroup.Wait] or [ErrGroup.Done].
func (eg *ErrGroup) Cancelled() <-chan struct{} {
eg.init()
return eg.ctx.Done()
}
// Done returns a channel that gets closed when all workers
// have finished.
func (eg *ErrGroup) Done() <-chan struct{} {
eg.init()
return eg.wg.Done()
}
// IsCancelled tells the [ErrGroup] has been cancelled
func (eg *ErrGroup) IsCancelled() bool {
return eg.cancelled.Load()
}
// Wait waits until all workers in the group have finished.
func (eg *ErrGroup) Wait() error {
return eg.wg.Wait()
}
// Err returns the error that initiated the group's shutdown.
func (eg *ErrGroup) Err() error {
return eg.wg.Err()
}
// Go spawns a worker and an optional shutdown routine to be invoked
// when the [ErrGroup] is cancelled, otherwise the provided context needs
// to be monitored and shutdown called.
func (eg *ErrGroup) Go(run func(context.Context) error, shutdown func() error) {
// run with default error catcher
eg.GoCatch(run, nil)
if shutdown != nil {
// shutdown
s2 := func() error {
<-eg.ctx.Done()
return shutdown()
}
// don't intercept shutdown's return error
eg.wg.GoCatch(s2, nil)
}
}
// GoCatch runs a worker on the Group, with a custom error handler.
func (eg *ErrGroup) GoCatch(run func(context.Context) error,
catch func(context.Context, error) error) {
//
var r2 func() error
var c2 func(error) error
if run == nil {
PanicWrap(ErrInvalid, "run function not specified")
}
eg.init()
// wrap runner
r2 = func() error {
return run(eg.ctx)
}
if catch != nil {
// wrap catcher
c2 = func(err error) error {
return catch(eg.ctx, err)
}
} else {
// use default error catcher
c2 = eg.defaultErrGroupCatcher
}
// always intercepting errors
eg.wg.GoCatch(r2, c2)
}
func (eg *ErrGroup) defaultErrGroupCatcher(err error) error {
if err != nil && eg.IsCancelled() {
err = context.Canceled
}
return err
}