invoke.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. // Copyright 2014 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 storage
  15. import (
  16. "context"
  17. "errors"
  18. "fmt"
  19. "io"
  20. "net"
  21. "net/url"
  22. "strings"
  23. "cloud.google.com/go/internal"
  24. "cloud.google.com/go/internal/version"
  25. sinternal "cloud.google.com/go/storage/internal"
  26. "github.com/google/uuid"
  27. gax "github.com/googleapis/gax-go/v2"
  28. "github.com/googleapis/gax-go/v2/callctx"
  29. "google.golang.org/api/googleapi"
  30. "google.golang.org/grpc/codes"
  31. "google.golang.org/grpc/status"
  32. )
  33. var defaultRetry *retryConfig = &retryConfig{}
  34. var xGoogDefaultHeader = fmt.Sprintf("gl-go/%s gccl/%s", version.Go(), sinternal.Version)
  35. const (
  36. xGoogHeaderKey = "x-goog-api-client"
  37. idempotencyHeaderKey = "x-goog-gcs-idempotency-token"
  38. )
  39. // run determines whether a retry is necessary based on the config and
  40. // idempotency information. It then calls the function with or without retries
  41. // as appropriate, using the configured settings.
  42. func run(ctx context.Context, call func(ctx context.Context) error, retry *retryConfig, isIdempotent bool) error {
  43. attempts := 1
  44. invocationID := uuid.New().String()
  45. if retry == nil {
  46. retry = defaultRetry
  47. }
  48. if (retry.policy == RetryIdempotent && !isIdempotent) || retry.policy == RetryNever {
  49. ctxWithHeaders := setInvocationHeaders(ctx, invocationID, attempts)
  50. return call(ctxWithHeaders)
  51. }
  52. bo := gax.Backoff{}
  53. if retry.backoff != nil {
  54. bo.Multiplier = retry.backoff.Multiplier
  55. bo.Initial = retry.backoff.Initial
  56. bo.Max = retry.backoff.Max
  57. }
  58. var errorFunc func(err error) bool = ShouldRetry
  59. if retry.shouldRetry != nil {
  60. errorFunc = retry.shouldRetry
  61. }
  62. return internal.Retry(ctx, bo, func() (stop bool, err error) {
  63. ctxWithHeaders := setInvocationHeaders(ctx, invocationID, attempts)
  64. err = call(ctxWithHeaders)
  65. if retry.maxAttempts != nil && attempts >= *retry.maxAttempts {
  66. return true, err
  67. }
  68. attempts++
  69. return !errorFunc(err), err
  70. })
  71. }
  72. // Sets invocation ID headers on the context which will be propagated as
  73. // headers in the call to the service (for both gRPC and HTTP).
  74. func setInvocationHeaders(ctx context.Context, invocationID string, attempts int) context.Context {
  75. invocationHeader := fmt.Sprintf("gccl-invocation-id/%v gccl-attempt-count/%v", invocationID, attempts)
  76. xGoogHeader := strings.Join([]string{invocationHeader, xGoogDefaultHeader}, " ")
  77. ctx = callctx.SetHeaders(ctx, xGoogHeaderKey, xGoogHeader)
  78. ctx = callctx.SetHeaders(ctx, idempotencyHeaderKey, invocationID)
  79. return ctx
  80. }
  81. // ShouldRetry returns true if an error is retryable, based on best practice
  82. // guidance from GCS. See
  83. // https://cloud.google.com/storage/docs/retry-strategy#go for more information
  84. // on what errors are considered retryable.
  85. //
  86. // If you would like to customize retryable errors, use the WithErrorFunc to
  87. // supply a RetryOption to your library calls. For example, to retry additional
  88. // errors, you can write a custom func that wraps ShouldRetry and also specifies
  89. // additional errors that should return true.
  90. func ShouldRetry(err error) bool {
  91. if err == nil {
  92. return false
  93. }
  94. if errors.Is(err, io.ErrUnexpectedEOF) {
  95. return true
  96. }
  97. switch e := err.(type) {
  98. case *net.OpError:
  99. if strings.Contains(e.Error(), "use of closed network connection") {
  100. // TODO: check against net.ErrClosed (go 1.16+) instead of string
  101. return true
  102. }
  103. case *googleapi.Error:
  104. // Retry on 408, 429, and 5xx, according to
  105. // https://cloud.google.com/storage/docs/exponential-backoff.
  106. return e.Code == 408 || e.Code == 429 || (e.Code >= 500 && e.Code < 600)
  107. case *url.Error:
  108. // Retry socket-level errors ECONNREFUSED and ECONNRESET (from syscall).
  109. // Unfortunately the error type is unexported, so we resort to string
  110. // matching.
  111. retriable := []string{"connection refused", "connection reset"}
  112. for _, s := range retriable {
  113. if strings.Contains(e.Error(), s) {
  114. return true
  115. }
  116. }
  117. case interface{ Temporary() bool }:
  118. if e.Temporary() {
  119. return true
  120. }
  121. }
  122. // UNAVAILABLE, RESOURCE_EXHAUSTED, and INTERNAL codes are all retryable for gRPC.
  123. if st, ok := status.FromError(err); ok {
  124. if code := st.Code(); code == codes.Unavailable || code == codes.ResourceExhausted || code == codes.Internal {
  125. return true
  126. }
  127. }
  128. // Unwrap is only supported in go1.13.x+
  129. if e, ok := err.(interface{ Unwrap() error }); ok {
  130. return ShouldRetry(e.Unwrap())
  131. }
  132. return false
  133. }