github.com/msales/pkg/v3@v3.24.0/grpcx/middleware/breaker.go (about) 1 package middleware 2 3 import ( 4 "context" 5 "errors" 6 7 "github.com/msales/pkg/v3/breaker" 8 "github.com/msales/pkg/v3/stats" 9 "google.golang.org/grpc" 10 ) 11 12 const ( 13 breakerErrorKey = "breaker.error" 14 stateTag = "state" 15 nameTag = "name" 16 ) 17 18 // WithClientBreaker adds breaker to client request. 19 func WithClientBreaker(br *breaker.Breaker, name string) grpc.UnaryClientInterceptor { 20 return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { 21 err := br.Run(func() error { 22 return invoker(ctx, method, req, reply, cc, opts...) 23 }) 24 25 if errors.Is(err, breaker.ErrOpenState) { 26 _ = stats.Inc(ctx, breakerErrorKey, 1, 1.0, stateTag, "open", nameTag, name) 27 } 28 29 if errors.Is(err, breaker.ErrTooManyRequests) { 30 _ = stats.Inc(ctx, breakerErrorKey, 1, 1.0, stateTag, "too_many_requests", nameTag, name) 31 } 32 33 return err 34 } 35 }