You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/zrpc/internal/serverinterceptors/breakerinterceptor.go

38 lines
1.1 KiB
Go

3 years ago
package serverinterceptors
import (
"context"
"errors"
3 years ago
"github.com/zeromicro/go-zero/core/breaker"
"github.com/zeromicro/go-zero/zrpc/internal/codes"
3 years ago
"google.golang.org/grpc"
gcodes "google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
3 years ago
)
// StreamBreakerInterceptor is an interceptor that acts as a circuit breaker.
func StreamBreakerInterceptor(svr any, stream grpc.ServerStream, info *grpc.StreamServerInfo,
3 years ago
handler grpc.StreamHandler) (err error) {
breakerName := info.FullMethod
return breaker.DoWithAcceptable(breakerName, func() error {
return handler(svr, stream)
3 years ago
}, codes.Acceptable)
}
// UnaryBreakerInterceptor is an interceptor that acts as a circuit breaker.
func UnaryBreakerInterceptor(ctx context.Context, req any, info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler) (resp any, err error) {
breakerName := info.FullMethod
err = breaker.DoWithAcceptable(breakerName, func() error {
var err error
resp, err = handler(ctx, req)
return err
}, codes.Acceptable)
if errors.Is(err, breaker.ErrServiceUnavailable) {
err = status.Error(gcodes.Unavailable, err.Error())
}
3 years ago
return resp, err
3 years ago
}