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

53 lines
1.2 KiB
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package serverinterceptors
import (
"context"
2021-08-15 15:33:45 +08:00
"fmt"
"runtime/debug"
"strings"
"sync"
2020-07-26 17:09:05 +08:00
"time"
"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) {
ctx, cancel := context.WithTimeout(ctx, timeout)
2020-07-26 17:09:05 +08:00
defer cancel()
var resp interface{}
var err error
var lock sync.Mutex
done := make(chan struct{})
// create channel with buffer size 1 to avoid goroutine leak
panicChan := make(chan interface{}, 1)
go func() {
defer func() {
if p := recover(); p != nil {
2021-08-15 15:33:45 +08:00
// attach call stack to avoid missing in different goroutine
panicChan <- fmt.Sprintf("%+v\n\n%s", p, strings.TrimSpace(string(debug.Stack())))
}
}()
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
}
}