2020-07-26 17:09:05 +08:00
|
|
|
package clientinterceptors
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"google.golang.org/grpc"
|
|
|
|
)
|
|
|
|
|
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 interface{}, cc *grpc.ClientConn,
|
|
|
|
invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
|
2021-02-19 10:44:39 +08:00
|
|
|
if timeout <= 0 {
|
2021-02-19 10:24:03 +08:00
|
|
|
return invoker(ctx, method, req, reply, cc, opts...)
|
|
|
|
}
|
2021-02-19 10:44:39 +08:00
|
|
|
|
2021-04-05 21:20:35 +08:00
|
|
|
ctx, cancel := context.WithTimeout(ctx, timeout)
|
2020-07-26 17:09:05 +08:00
|
|
|
defer cancel()
|
2021-03-19 18:41:26 +08:00
|
|
|
|
2021-03-21 16:54:34 +08:00
|
|
|
// create channel with buffer size 1 to avoid goroutine leak
|
|
|
|
done := make(chan error, 1)
|
2021-03-19 18:41:26 +08:00
|
|
|
panicChan := make(chan interface{}, 1)
|
|
|
|
go func() {
|
|
|
|
defer func() {
|
|
|
|
if p := recover(); p != nil {
|
|
|
|
panicChan <- p
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
done <- invoker(ctx, method, req, reply, cc, opts...)
|
|
|
|
}()
|
|
|
|
|
|
|
|
select {
|
|
|
|
case p := <-panicChan:
|
|
|
|
panic(p)
|
|
|
|
case err := <-done:
|
|
|
|
return err
|
|
|
|
case <-ctx.Done():
|
|
|
|
return ctx.Err()
|
|
|
|
}
|
2020-07-26 17:09:05 +08:00
|
|
|
}
|
|
|
|
}
|