timeoutinterceptor.go 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. type (
  15. // ServerSpecifiedTimeoutConf defines specified timeout for gRPC method.
  16. ServerSpecifiedTimeoutConf struct {
  17. FullMethod string
  18. Timeout time.Duration
  19. }
  20. specifiedTimeoutCache map[string]time.Duration
  21. )
  22. // UnaryTimeoutInterceptor returns a func that sets timeout to incoming unary requests.
  23. func UnaryTimeoutInterceptor(timeout time.Duration, specifiedTimeouts ...ServerSpecifiedTimeoutConf) grpc.UnaryServerInterceptor {
  24. cache := cacheSpecifiedTimeout(specifiedTimeouts)
  25. return func(ctx context.Context, req any, info *grpc.UnaryServerInfo,
  26. handler grpc.UnaryHandler) (any, error) {
  27. t := getTimeoutByUnaryServerInfo(info, timeout, cache)
  28. ctx, cancel := context.WithTimeout(ctx, t)
  29. defer cancel()
  30. var resp any
  31. var err error
  32. var lock sync.Mutex
  33. done := make(chan struct{})
  34. // create channel with buffer size 1 to avoid goroutine leak
  35. panicChan := make(chan any, 1)
  36. go func() {
  37. defer func() {
  38. if p := recover(); p != nil {
  39. // attach call stack to avoid missing in different goroutine
  40. panicChan <- fmt.Sprintf("%+v\n\n%s", p, strings.TrimSpace(string(debug.Stack())))
  41. }
  42. }()
  43. lock.Lock()
  44. defer lock.Unlock()
  45. resp, err = handler(ctx, req)
  46. close(done)
  47. }()
  48. select {
  49. case p := <-panicChan:
  50. panic(p)
  51. case <-done:
  52. lock.Lock()
  53. defer lock.Unlock()
  54. return resp, err
  55. case <-ctx.Done():
  56. err := ctx.Err()
  57. if errors.Is(err, context.Canceled) {
  58. err = status.Error(codes.Canceled, err.Error())
  59. } else if errors.Is(err, context.DeadlineExceeded) {
  60. err = status.Error(codes.DeadlineExceeded, err.Error())
  61. }
  62. return nil, err
  63. }
  64. }
  65. }
  66. func cacheSpecifiedTimeout(specifiedTimeouts []ServerSpecifiedTimeoutConf) specifiedTimeoutCache {
  67. cache := make(specifiedTimeoutCache, len(specifiedTimeouts))
  68. for _, st := range specifiedTimeouts {
  69. if st.FullMethod != "" {
  70. cache[st.FullMethod] = st.Timeout
  71. }
  72. }
  73. return cache
  74. }
  75. func getTimeoutByUnaryServerInfo(info *grpc.UnaryServerInfo, defaultTimeout time.Duration, specifiedTimeout specifiedTimeoutCache) time.Duration {
  76. if ts, ok := info.Server.(TimeoutStrategy); ok {
  77. return ts.GetTimeoutByFullMethod(info.FullMethod, defaultTimeout)
  78. } else if v, ok := specifiedTimeout[info.FullMethod]; ok {
  79. return v
  80. }
  81. return defaultTimeout
  82. }
  83. type TimeoutStrategy interface {
  84. GetTimeoutByFullMethod(fullMethod string, defaultTimeout time.Duration) time.Duration
  85. }