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

49 lines
1014 B
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package serverinterceptors
import (
"context"
"sync"
2020-07-26 17:09:05 +08:00
"time"
2020-08-08 16:40:10 +08:00
"github.com/tal-tech/go-zero/core/contextx"
2020-07-26 17:09:05 +08:00
"google.golang.org/grpc"
)
2021-03-01 23:52:44 +08:00
// UnaryTimeoutInterceptor returns a func that sets timeout to incoming unary requests.
2020-07-26 17:09:05 +08:00
func UnaryTimeoutInterceptor(timeout time.Duration) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler) (interface{}, error) {
2020-07-26 17:09:05 +08:00
ctx, cancel := contextx.ShrinkDeadline(ctx, timeout)
defer cancel()
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()
}
2020-07-26 17:09:05 +08:00
}
}