覆寫預設重試政策

Swift 的 Google Cloud 用戶端程式庫會自動重試因暫時性錯誤而失敗的要求。有些應用程式需要不同的行為:可能需要更快失敗、持續嘗試更長時間,或重試程式庫認為不安全的重試要求。本文說明如何覆寫預設重試政策。

事前準備

本文件使用 Secret Manager API。如要啟用這個 API,請按照 Secret Manager 快速入門導覽課程操作。確認主體具備取得及列出 Secret 的權限,例如 Secret Manager 檢視者 Identity and Access Management (IAM) 角色 (roles/secretmanager.viewer)。

如需 Swift 用戶端程式庫的完整設定操作說明,請參閱「快速入門導覽課程:開始使用 Swift」。

預設重試行為

每個用戶端都設定了三項政策,共同控制重試作業:

  • 重試政策會決定是否要重試錯誤,以及何時停止重試。根據預設,系統只會針對 google.aip.dev 暫時性錯誤和冪等要求的 I/O 錯誤重試 AIP-194,並在 60 秒或 10 次嘗試後停止,以先發生者為準。
  • 輪詢政策會決定每次嘗試之間的等待時間。根據預設,系統會使用指數輪詢,從一秒開始,並加倍至最多一分鐘。
  • 重試節流器可防止用戶端對已故障的服務增加負載。預設會使用自動調整節流器。

用戶端只會在安全的情況下重試要求:在傳送任何資料前要求失敗,或錯誤是暫時性的,且要求具有冪等性。用戶端程式庫會使用保守的冪等性啟發式方法:只有 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)
}

後續步驟