You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

55 lines
1.7 KiB

  1. // Copyright 2016 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package internal
  15. import (
  16. "context"
  17. "time"
  18. gax "github.com/googleapis/gax-go/v2"
  19. )
  20. // Retry calls the supplied function f repeatedly according to the provided
  21. // backoff parameters. It returns when one of the following occurs:
  22. // When f's first return value is true, Retry immediately returns with f's second
  23. // return value.
  24. // When the provided context is done, Retry returns with an error that
  25. // includes both ctx.Error() and the last error returned by f.
  26. func Retry(ctx context.Context, bo gax.Backoff, f func() (stop bool, err error)) error {
  27. return retry(ctx, bo, f, gax.Sleep)
  28. }
  29. func retry(ctx context.Context, bo gax.Backoff, f func() (stop bool, err error),
  30. sleep func(context.Context, time.Duration) error) error {
  31. var lastErr error
  32. for {
  33. stop, err := f()
  34. if stop {
  35. return err
  36. }
  37. // Remember the last "real" error from f.
  38. if err != nil && err != context.Canceled && err != context.DeadlineExceeded {
  39. lastErr = err
  40. }
  41. p := bo.Pause()
  42. if cerr := sleep(ctx, p); cerr != nil {
  43. if lastErr != nil {
  44. return Annotatef(lastErr, "retry failed with %v; last error", cerr)
  45. }
  46. return cerr
  47. }
  48. }
  49. }