-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathgowrapper.go
71 lines (65 loc) · 1.67 KB
/
gowrapper.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
package circuit
import (
"context"
"github.com/cep21/circuit/v4/faststats"
)
// goroutineWrapper contains logic to wrap normal run methods inside a goroutine so they can end early
// if the goroutine continues to run
type goroutineWrapper struct {
skipCatchPanics faststats.AtomicBoolean
lostErrors func(err error, panics interface{})
}
func (g *goroutineWrapper) run(runFunc func(context.Context) error) func(context.Context) error {
if runFunc == nil {
return nil
}
return func(ctx context.Context) error {
var panicResult chan interface{}
if !g.skipCatchPanics.Get() {
panicResult = make(chan interface{}, 1)
}
runFuncErr := make(chan error, 1)
go func() {
if panicResult != nil {
defer func() {
if r := recover(); r != nil {
panicResult <- r
}
}()
}
runFuncErr <- runFunc(ctx)
}()
select {
case <-ctx.Done():
// runFuncErr is a lost error.
if g.lostErrors != nil {
go g.waitForErrors(runFuncErr, panicResult)
}
return ctx.Err()
case err := <-runFuncErr:
return err
case panicVal := <-panicResult:
panic(panicVal)
}
}
}
func (g *goroutineWrapper) fallback(runFunc func(context.Context, error) error) func(context.Context, error) error {
if runFunc == nil {
return nil
}
return func(ctx context.Context, err error) error {
return g.run(func(funcCtx context.Context) error {
return runFunc(funcCtx, err)
})(ctx)
}
}
func (g *goroutineWrapper) waitForErrors(runFuncErr chan error, panicResults chan interface{}) {
select {
case err := <-runFuncErr:
g.lostErrors(err, nil)
case panicResult := <-panicResults:
g.lostErrors(nil, panicResult)
}
close(runFuncErr)
close(panicResults)
}