-
Notifications
You must be signed in to change notification settings - Fork 7
/
breaker.go
53 lines (50 loc) · 1.41 KB
/
breaker.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
package tsf
import (
"context"
"github.com/go-kratos/kratos/v2/errors"
"github.com/go-kratos/kratos/v2/middleware"
"github.com/go-kratos/kratos/v2/transport"
"github.com/tencentyun/tsf-go/breaker"
)
func BreakerMiddleware(opts ...ClientOption) middleware.Middleware {
var o clientOpionts
for _, opt := range opts {
opt(&o)
}
if o.breakerCfg != nil && o.breakerCfg.SwitchOff {
return func(handler middleware.Handler) middleware.Handler {
return func(ctx context.Context, req interface{}) (interface{}, error) {
return handler(ctx, req)
}
}
}
group := breaker.NewGroup(o.breakerCfg)
return func(handler middleware.Handler) middleware.Handler {
return func(ctx context.Context, req interface{}) (reply interface{}, err error) {
if tr, ok := transport.FromClientContext(ctx); ok {
if tr.Operation() != "" {
breaker := group.Get(tr.Operation())
if err = breaker.Allow(); err != nil {
return
}
defer func() {
if err != nil {
if o.breakerErrorHook != nil {
if !o.breakerErrorHook(ctx, tr.Operation(), err) {
breaker.MarkFailed()
return
}
} else if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) || errors.FromError(err).GetCode() >= 500 {
breaker.MarkFailed()
return
}
}
breaker.MarkSuccess()
}()
}
}
reply, err = handler(ctx, req)
return
}
}
}