timeoutinterceptor.go 1.4 KB

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