timeoutinterceptor.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package serverinterceptors
  2. import (
  3. "context"
  4. "fmt"
  5. "runtime/debug"
  6. "strings"
  7. "sync"
  8. "time"
  9. "google.golang.org/grpc"
  10. "google.golang.org/grpc/codes"
  11. "google.golang.org/grpc/status"
  12. )
  13. // UnaryTimeoutInterceptor returns a func that sets timeout to incoming unary requests.
  14. func UnaryTimeoutInterceptor(timeout time.Duration) grpc.UnaryServerInterceptor {
  15. return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo,
  16. handler grpc.UnaryHandler) (interface{}, error) {
  17. ctx, cancel := context.WithTimeout(ctx, timeout)
  18. defer cancel()
  19. var resp interface{}
  20. var err error
  21. var lock sync.Mutex
  22. done := make(chan struct{})
  23. // create channel with buffer size 1 to avoid goroutine leak
  24. panicChan := make(chan interface{}, 1)
  25. go func() {
  26. defer func() {
  27. if p := recover(); p != nil {
  28. // attach call stack to avoid missing in different goroutine
  29. panicChan <- fmt.Sprintf("%+v\n\n%s", p, strings.TrimSpace(string(debug.Stack())))
  30. }
  31. }()
  32. lock.Lock()
  33. defer lock.Unlock()
  34. resp, err = handler(ctx, req)
  35. close(done)
  36. }()
  37. select {
  38. case p := <-panicChan:
  39. panic(p)
  40. case <-done:
  41. lock.Lock()
  42. defer lock.Unlock()
  43. return resp, err
  44. case <-ctx.Done():
  45. err := ctx.Err()
  46. if err == context.Canceled {
  47. err = status.Error(codes.Canceled, err.Error())
  48. } else if err == context.DeadlineExceeded {
  49. err = status.Error(codes.DeadlineExceeded, err.Error())
  50. }
  51. return nil, err
  52. }
  53. }
  54. }