github.com/gravitational/teleport/api@v0.0.0-20240507183017-3110591cbafc/breaker/interceptors.go (about) 1 // Copyright 2022 Gravitational, Inc 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package breaker 16 17 import ( 18 "context" 19 20 "google.golang.org/grpc" 21 ) 22 23 // UnaryClientInterceptor is a unary gRPC client interceptor that uses the provided CircuitBreaker to track errors 24 // returned from the outgoing calls. 25 func UnaryClientInterceptor(cb *CircuitBreaker) grpc.UnaryClientInterceptor { 26 return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { 27 _, err := cb.Execute(func() (interface{}, error) { 28 err := invoker(ctx, method, req, reply, cc, opts...) 29 return nil, err 30 }) 31 return err 32 } 33 } 34 35 // StreamClientInterceptor is a stream gRPC client interceptor that uses the provided CircuitBreaker to track errors 36 // returned from the outgoing calls. 37 func StreamClientInterceptor(cb *CircuitBreaker) grpc.StreamClientInterceptor { 38 return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) { 39 stream, err := cb.Execute(func() (interface{}, error) { 40 return streamer(ctx, desc, cc, method, opts...) 41 }) 42 43 if stream == nil { 44 return nil, err 45 } 46 47 if cs, ok := stream.(grpc.ClientStream); ok { 48 return cs, err 49 } 50 51 return nil, err 52 } 53 }