You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/zrpc/internal/serverinterceptors/timeoutinterceptor.go

49 lines
1014 B
Go

4 years ago
package serverinterceptors
import (
"context"
"sync"
4 years ago
"time"
"github.com/tal-tech/go-zero/core/contextx"
4 years ago
"google.golang.org/grpc"
)
// UnaryTimeoutInterceptor returns a func that sets timeout to incoming unary requests.
4 years ago
func UnaryTimeoutInterceptor(timeout time.Duration) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler) (interface{}, error) {
4 years ago
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()
}
4 years ago
}
}