sheddinginterceptor.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package serverinterceptors
  2. import (
  3. "context"
  4. "sync"
  5. "git.i2edu.net/i2/go-zero/core/load"
  6. "git.i2edu.net/i2/go-zero/core/stat"
  7. "google.golang.org/grpc"
  8. )
  9. const serviceType = "rpc"
  10. var (
  11. sheddingStat *load.SheddingStat
  12. lock sync.Mutex
  13. )
  14. // UnarySheddingInterceptor returns a func that does load shedding on processing unary requests.
  15. func UnarySheddingInterceptor(shedder load.Shedder, metrics *stat.Metrics) grpc.UnaryServerInterceptor {
  16. ensureSheddingStat()
  17. return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo,
  18. handler grpc.UnaryHandler) (val interface{}, err error) {
  19. sheddingStat.IncrementTotal()
  20. var promise load.Promise
  21. promise, err = shedder.Allow()
  22. if err != nil {
  23. metrics.AddDrop()
  24. sheddingStat.IncrementDrop()
  25. return
  26. }
  27. defer func() {
  28. if err == context.DeadlineExceeded {
  29. promise.Fail()
  30. } else {
  31. sheddingStat.IncrementPass()
  32. promise.Pass()
  33. }
  34. }()
  35. return handler(ctx, req)
  36. }
  37. }
  38. func ensureSheddingStat() {
  39. lock.Lock()
  40. if sheddingStat == nil {
  41. sheddingStat = load.NewSheddingStat(serviceType)
  42. }
  43. lock.Unlock()
  44. }