替换默认重试政策

适用于 Swift 的 Google Cloud 客户端库会自动重试因暂时性错误而失败的请求。某些应用需要不同的行为:它们可能需要更快地失败、尝试更长时间,或重试库认为不安全而无法重试的请求。本文档介绍了如何替换默认重试政策。

准备工作

本文档使用 Secret Manager API。如需启用此 API,请按照 Secret Manager 快速入门中的说明操作。验证您的主账号是否具有获取和列出 Secret 的权限,例如 Secret Manager Viewer Identity and Access Management (IAM) 角色 (roles/secretmanager.viewer)。

如需查看 Swift 客户端库的完整设置说明,请参阅快速入门:Swift 使用入门。

默认重试行为

每个客户端都配置了三个政策,这些政策共同控制重试:

  • 重试政策决定了是否重试错误以及何时停止重试。默认情况下,它仅针对幂等请求重试 google.aip.dev 上的 AIP-194 暂时性错误和 I/O 错误,并在 60 秒或 10 次尝试(以先到者为准)后停止。
  • 退避政策决定了两次尝试之间的等待时间。默认情况下,它使用指数退避算法,从 1 秒开始,然后翻倍,最长为 1 分钟。
  • 重试限制器可防止客户端向已发生故障的服务添加负载。默认情况下,它使用自适应调节器。

客户端仅在安全的情况下才会重试请求:要么请求在发送任何数据之前失败,要么错误是暂时性的且请求是幂等的。客户端库使用保守的幂等性启发法:只有 GET 和 PUT 请求符合条件。

替换客户端的政策

您在客户端上设置的政策适用于通过该客户端发出的每个请求。如需替换客户端的默认重试政策,请按以下步骤操作:

  1. 添加使用客户端库所需的导入:

    import Foundation
    import GoogleGax
    import GoogleCloudSecretManagerV1

  2. 编写一个接收项目 ID 作为参数的函数:

    func sample(projectId: String) async throws {

  3. 初始化一个比默认重试次数更早停止重试的客户端。使用 BaseRetryPolicy.unbounded() 保留哪些错误是暂时性错误的默认定义,并链接 withTimeLimit(_:) 和 withAttemptLimit(_:) 来设置限制。您可以单独使用其中任何一个限制:

    let client = try SecretManagerServiceClient(
      ClientOptions().with {
        $0.retryPolicy = BaseRetryPolicy.unbounded().withTimeLimit(.seconds(10)).withAttemptLimit(3)
      })

  4. 初始化一个客户端,该客户端还配置了两次尝试之间的自定义退避政策:

    let slowerClient = try SecretManagerServiceClient(
      ClientOptions().with {
        $0.retryPolicy = BaseRetryPolicy.unbounded().withTimeLimit(.seconds(10)).withAttemptLimit(3)
        $0.backoffPolicy = ExponentialBackoff(
          clamping: .milliseconds(250),
          maximumDelay: .seconds(5),
          scaling: 1.5
        )
      })

该库提供了其他重试政策:AlwaysRetry.unbounded() 会重试每个错误(仅在操作具有幂等性时才安全),而 NeverRetry 会停用重试。如果应用的需求未涵盖在内置类型中,则可以实现 RetryPolicy 协议。

针对单个请求覆盖政策

每个客户端方法都接受 RequestOptions 值。它设置的政策仅适用于该请求,并且优先于客户端配置:

let options = RequestOptions().with {
  $0.retryPolicy = NeverRetry()
}
let secret = try await client.getSecret(
  request: GetSecretRequest().with { $0.name = "projects/\(projectId)/secrets/my-secret" },
  options: options)
print("secret: \(secret)")

重试库认为不安全的请求

由于幂等性启发式方法较为保守,因此默认情况下,即使服务将某些请求记录为可安全重复,也不会重试这些请求。受 etag 保护的删除请求就是一个例子:重复该请求无法删除资源的其他版本。在 RequestOptions 上将 idempotent 设置为 true,以指示可以安全地重试请求:

let retried = RequestOptions().with {
  $0.retryPolicy = BaseRetryPolicy.unbounded().withTimeLimit(.seconds(30))
  $0.idempotent = true
}
try await slowerClient.deleteSecret(
  request: DeleteSecretRequest().with {
    $0.name = "projects/\(projectId)/secrets/my-secret"
    $0.etag = "\"an-etag-from-a-previous-read\""
  },
  options: retried)

完整代码

以下示例显示了本文档的完整代码:

import Foundation
import GoogleGax
import GoogleCloudSecretManagerV1

func sample(projectId: String) async throws {
  let client = try SecretManagerServiceClient(
    ClientOptions().with {
      $0.retryPolicy = BaseRetryPolicy.unbounded().withTimeLimit(.seconds(10)).withAttemptLimit(3)
    })
  let slowerClient = try SecretManagerServiceClient(
    ClientOptions().with {
      $0.retryPolicy = BaseRetryPolicy.unbounded().withTimeLimit(.seconds(10)).withAttemptLimit(3)
      $0.backoffPolicy = ExponentialBackoff(
        clamping: .milliseconds(250),
        maximumDelay: .seconds(5),
        scaling: 1.5
      )
    })
  let options = RequestOptions().with {
    $0.retryPolicy = NeverRetry()
  }
  let secret = try await client.getSecret(
    request: GetSecretRequest().with { $0.name = "projects/\(projectId)/secrets/my-secret" },
    options: options)
  print("secret: \(secret)")
  let retried = RequestOptions().with {
    $0.retryPolicy = BaseRetryPolicy.unbounded().withTimeLimit(.seconds(30))
    $0.idempotent = true
  }
  try await slowerClient.deleteSecret(
    request: DeleteSecretRequest().with {
      $0.name = "projects/\(projectId)/secrets/my-secret"
      $0.etag = "\"an-etag-from-a-previous-read\""
    },
    options: retried)
}

后续步骤