interceptors_test.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Licensed to the LF AI & Data foundation under one
  2. // or more contributor license agreements. See the NOTICE file
  3. // distributed with this work for additional information
  4. // regarding copyright ownership. The ASF licenses this file
  5. // to you under the Apache License, Version 2.0 (the
  6. // "License"); you may not use this file except in compliance
  7. // with the License. You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. package client
  17. import (
  18. "context"
  19. "math"
  20. "testing"
  21. "time"
  22. "github.com/stretchr/testify/assert"
  23. "google.golang.org/grpc"
  24. "github.com/milvus-io/milvus-proto/go-api/v2/commonpb"
  25. )
  26. var (
  27. mockInvokerError error
  28. mockInvokerReply interface{}
  29. mockInvokeTimes = 0
  30. )
  31. var mockInvoker grpc.UnaryInvoker = func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, opts ...grpc.CallOption) error {
  32. mockInvokeTimes++
  33. return mockInvokerError
  34. }
  35. func resetMockInvokeTimes() {
  36. mockInvokeTimes = 0
  37. }
  38. func TestRateLimitInterceptor(t *testing.T) {
  39. maxRetry := uint(3)
  40. maxBackoff := 3 * time.Second
  41. inter := RetryOnRateLimitInterceptor(maxRetry, maxBackoff, func(ctx context.Context, attempt uint) time.Duration {
  42. return 60 * time.Millisecond * time.Duration(math.Pow(2, float64(attempt)))
  43. })
  44. ctx := context.Background()
  45. // with retry
  46. mockInvokerReply = &commonpb.Status{ErrorCode: commonpb.ErrorCode_RateLimit}
  47. resetMockInvokeTimes()
  48. err := inter(ctx, "", nil, mockInvokerReply, nil, mockInvoker)
  49. assert.NoError(t, err)
  50. assert.Equal(t, maxRetry, uint(mockInvokeTimes))
  51. // without retry
  52. ctx1 := context.WithValue(ctx, RetryOnRateLimit, false)
  53. resetMockInvokeTimes()
  54. err = inter(ctx1, "", nil, mockInvokerReply, nil, mockInvoker)
  55. assert.NoError(t, err)
  56. assert.Equal(t, uint(1), uint(mockInvokeTimes))
  57. }