zrpc timeout & unit tests (#573)

* zrpc timeout & unit tests
This commit is contained in:
Kevin Wan
2021-03-19 18:41:26 +08:00
committed by GitHub
parent 3c6951577d
commit 4884a7b3c6
4 changed files with 119 additions and 3 deletions

View File

@@ -2,6 +2,7 @@ package serverinterceptors
import (
"context"
"sync"
"time"
"github.com/tal-tech/go-zero/core/contextx"
@@ -11,9 +12,37 @@ import (
// UnaryTimeoutInterceptor returns a func that sets timeout to incoming unary requests.
func UnaryTimeoutInterceptor(timeout time.Duration) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler) (resp interface{}, err error) {
handler grpc.UnaryHandler) (interface{}, error) {
ctx, cancel := contextx.ShrinkDeadline(ctx, timeout)
defer cancel()
return handler(ctx, req)
var resp interface{}
var err error
var lock sync.Mutex
done := make(chan struct{})
panicChan := make(chan interface{}, 1)
go func() {
defer func() {
if p := recover(); p != nil {
panicChan <- p
}
}()
lock.Lock()
defer lock.Unlock()
resp, err = handler(ctx, req)
close(done)
}()
select {
case p := <-panicChan:
panic(p)
case <-done:
lock.Lock()
defer lock.Unlock()
return resp, err
case <-ctx.Done():
return nil, ctx.Err()
}
}
}