go-zero/zrpc/internal/clientinterceptors/timeoutinterceptor.go

48 lines
1.2 KiB
Go
Raw Permalink Normal View History

2020-07-26 17:09:05 +08:00
package clientinterceptors
import (
"context"
"time"
"google.golang.org/grpc"
)
2023-10-26 08:55:26 +08:00
// TimeoutCallOption is a call option that controls timeout.
type TimeoutCallOption struct {
grpc.EmptyCallOption
timeout time.Duration
}
2021-03-01 23:52:44 +08:00
// TimeoutInterceptor is an interceptor that controls timeout.
2020-07-26 17:09:05 +08:00
func TimeoutInterceptor(timeout time.Duration) grpc.UnaryClientInterceptor {
return func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn,
2020-07-26 17:09:05 +08:00
invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
2023-10-26 08:55:26 +08:00
t := getTimeoutFromCallOptions(opts, timeout)
if t <= 0 {
2021-02-19 10:24:03 +08:00
return invoker(ctx, method, req, reply, cc, opts...)
}
ctx, cancel := context.WithTimeout(ctx, t)
2020-07-26 17:09:05 +08:00
defer cancel()
2021-07-24 22:29:02 +08:00
return invoker(ctx, method, req, reply, cc, opts...)
2020-07-26 17:09:05 +08:00
}
}
2023-10-26 08:55:26 +08:00
// WithCallTimeout returns a call option that controls method call timeout.
func WithCallTimeout(timeout time.Duration) grpc.CallOption {
return TimeoutCallOption{
timeout: timeout,
}
}
func getTimeoutFromCallOptions(opts []grpc.CallOption, defaultTimeout time.Duration) time.Duration {
for _, opt := range opts {
if o, ok := opt.(TimeoutCallOption); ok {
return o.timeout
}
}
return defaultTimeout
}