retry.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2016 Google Inc. All Rights Reserved.
  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. "fmt"
  17. "time"
  18. gax "github.com/googleapis/gax-go"
  19. "golang.org/x/net/context"
  20. )
  21. // Retry calls the supplied function f repeatedly according to the provided
  22. // backoff parameters. It returns when one of the following occurs:
  23. // When f's first return value is true, Retry immediately returns with f's second
  24. // return value.
  25. // When the provided context is done, Retry returns with an error that
  26. // includes both ctx.Error() and the last error returned by f.
  27. func Retry(ctx context.Context, bo gax.Backoff, f func() (stop bool, err error)) error {
  28. return retry(ctx, bo, f, gax.Sleep)
  29. }
  30. func retry(ctx context.Context, bo gax.Backoff, f func() (stop bool, err error),
  31. sleep func(context.Context, time.Duration) error) error {
  32. var lastErr error
  33. for {
  34. stop, err := f()
  35. if stop {
  36. return err
  37. }
  38. // Remember the last "real" error from f.
  39. if err != nil && err != context.Canceled && err != context.DeadlineExceeded {
  40. lastErr = err
  41. }
  42. p := bo.Pause()
  43. if cerr := sleep(ctx, p); cerr != nil {
  44. if lastErr != nil {
  45. return fmt.Errorf("%v; last function err: %v", cerr, lastErr)
  46. }
  47. return cerr
  48. }
  49. }
  50. }