-
Notifications
You must be signed in to change notification settings - Fork 3
/
breaker.go
33 lines (26 loc) · 829 Bytes
/
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
package breaker
import (
"context"
"errors"
breaker "github.com/sony/gobreaker"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// UnaryClientInterceptor for breaker.
func UnaryClientInterceptor() grpc.UnaryClientInterceptor {
cb := breaker.NewCircuitBreaker(breaker.Settings{})
return func(ctx context.Context, fullMethod string, req, resp any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
operation := func() (any, error) {
return nil, invoker(ctx, fullMethod, req, resp, cc, opts...)
}
_, err := cb.Execute(operation)
if err != nil {
if errors.Is(err, breaker.ErrOpenState) || errors.Is(err, breaker.ErrTooManyRequests) {
return status.Error(codes.Unavailable, err.Error())
}
return err
}
return nil
}
}