The Google Cloud client libraries for Swift provide
`*PollingUntilDone` methods to poll long-running operations until they complete.
You might need to change the default polling limits, the backoff intervals, or
the types of polling errors that stop the polling loop. This document shows you
how to override the default polling policies in the client libraries.

## Before you begin

This document uses the Workflows API. To enable this API, follow the
[Workflows quickstart](https://docs.cloud.google.com/workflows/docs/create-workflow-gcloud.md.txt).

For complete setup instructions for the Swift client libraries, see
[Quickstart: Get started with Swift](https://docs.cloud.google.com/swift/quickstart.md.txt).

## Long-running operations

Some Google Cloud APIs perform operations that take too long to finish
within a single request-response cycle. Instead of blocking until the work
finishes, the API starts a background task on the server. It immediately returns
an operation resource that represents the in-progress work.

To get the final result, the client must periodically poll the service for the
operation's status. When you call a `*PollingUntilDone` helper method, the
client library runs this polling loop for you:

1. The client sends the initial request to start the background task on the server.
2. While the operation is still in progress, the client waits for a delay determined by the *polling backoff policy* and requests the latest status of the operation.
3. If a status check fails---for example, due to a transient network or service error---the *polling error policy* determines whether to continue polling or stop the loop. The policy also enforces overall time or attempt limits so polling doesn't run indefinitely.
4. When the server reports that the operation has finished, the helper returns the completed resource---or throws the operation's error if the background task failed on the server.

## Default polling behavior

Each client uses the following default policies for this polling loop:

- The *polling error policy* continues polling on [AIP-194](https://google.aip.dev/194) (at google.aip.dev) transient errors, `TOO_MANY_REQUESTS` errors, and I/O errors, and stops polling after 30 minutes.
- The *polling backoff policy* uses truncated exponential backoff without jitter, starting at one second and doubling between attempts up to a maximum of five minutes.

In addition, each status request made during the polling loop is an idempotent
RPC and uses the client's [retry policy](https://docs.cloud.google.com/swift/override-retry-policy.md.txt) before
reporting an error to the polling loop.

## Override the policies for a client

The policies that you set on a client apply to every long-running operation
polled through that client. To override the default polling policies for a
client, follow these steps:

1. Add the imports required to use the client library:


   ```swift
   import Foundation
   import GoogleGax
   import GoogleCloudWorkflowsV1
   ```

   <br />

2. Write a function that receives the project ID, location, and workflow ID as
   parameters:


   ```swift
   func sample(projectId: String, location: String, workflowId: String) async throws {
   ```

   <br />

3. Initialize a client that stops polling sooner than the default. Call the
   `BasePollingErrorPolicy.unbounded()` method to keep the default definition
   of transient polling errors, and chain the `withTimeLimit(_:)` and
   `withAttemptLimit(_:)` methods to set the limits. You can use either limit
   on its own:


   ```swift
   let client = try WorkflowsClient(
     ClientOptions().with {
       $0.pollingErrorPolicy = BasePollingErrorPolicy.unbounded()
         .withTimeLimit(.seconds(5 * 60))
         .withAttemptLimit(20)
     })
   ```

   <br />

4. Initialize a client that also configures a custom backoff policy between
   polling attempts:


   ```swift
   let fasterClient = try WorkflowsClient(
     ClientOptions().with {
       $0.pollingErrorPolicy = BasePollingErrorPolicy.unbounded()
         .withTimeLimit(.seconds(5 * 60))
         .withAttemptLimit(20)
       $0.pollingBackoffPolicy = ExponentialBackoff(
         clamping: .milliseconds(500),
         maximumDelay: .seconds(10),
         scaling: 1.5
       )
     })
   try await fasterClient.deleteWorkflowPollingUntilDone(
     name: "projects/\(projectId)/locations/\(location)/workflows/\(workflowId)"
   )
   ```

   <br />

The library also provides the following polling error policies:

- `AIP194.unbounded()`: continues polling only on `UNAVAILABLE` errors. You can chain this policy with the `continueOnIO()` and `continueOnTooManyRequests()` methods.
- `AlwaysPoll.unbounded()`: continues polling on all errors.

If your app has requirements that the built-in types don't cover, you can
implement the `PollingErrorPolicy` and `PollingBackoffPolicy` protocols.

## Override the policy for a single request

Every `*PollingUntilDone` method accepts a `RequestOptions` value. The polling
policies that it sets apply to that operation only and take precedence over the
client configuration:

```swift
let options = RequestOptions().with {
  $0.pollingErrorPolicy = BasePollingErrorPolicy.unbounded().withTimeLimit(.seconds(60))
  $0.pollingBackoffPolicy = ExponentialBackoff(
    clamping: .milliseconds(250),
    maximumDelay: .seconds(5)
  )
}
try await client.deleteWorkflowPollingUntilDone(
  request: DeleteWorkflowRequest().with {
    $0.name = "projects/\(projectId)/locations/\(location)/workflows/\(workflowId)"
  },
  options: options)
```

## Complete code

The following example shows the complete code for this document:

```swift
import Foundation
import GoogleGax
import GoogleCloudWorkflowsV1

func sample(projectId: String, location: String, workflowId: String) async throws {
  let client = try WorkflowsClient(
    ClientOptions().with {
      $0.pollingErrorPolicy = BasePollingErrorPolicy.unbounded()
        .withTimeLimit(.seconds(5 * 60))
        .withAttemptLimit(20)
    })
  let fasterClient = try WorkflowsClient(
    ClientOptions().with {
      $0.pollingErrorPolicy = BasePollingErrorPolicy.unbounded()
        .withTimeLimit(.seconds(5 * 60))
        .withAttemptLimit(20)
      $0.pollingBackoffPolicy = ExponentialBackoff(
        clamping: .milliseconds(500),
        maximumDelay: .seconds(10),
        scaling: 1.5
      )
    })
  try await fasterClient.deleteWorkflowPollingUntilDone(
    name: "projects/\(projectId)/locations/\(location)/workflows/\(workflowId)"
  )
  let options = RequestOptions().with {
    $0.pollingErrorPolicy = BasePollingErrorPolicy.unbounded().withTimeLimit(.seconds(60))
    $0.pollingBackoffPolicy = ExponentialBackoff(
      clamping: .milliseconds(250),
      maximumDelay: .seconds(5)
    )
  }
  try await client.deleteWorkflowPollingUntilDone(
    request: DeleteWorkflowRequest().with {
      $0.name = "projects/\(projectId)/locations/\(location)/workflows/\(workflowId)"
    },
    options: options)
}
```

## What's next

- Learn how to [override the default endpoint](https://docs.cloud.google.com/swift/override-endpoint.md.txt).
- Learn how to [override the default authentication
  credentials](https://docs.cloud.google.com/swift/override-credentials).
- Learn how to [override the default retry
  policies](https://docs.cloud.google.com/swift/override-retry-policy).
- Learn how to [enable logging](https://docs.cloud.google.com/swift/enable-logging.md.txt) to troubleshoot requests and responses.
- Learn how to configure [package traits](https://docs.cloud.google.com/swift/package-traits.md.txt) for large client libraries.
- Browse the [Swift Cloud Client Libraries](https://docs.cloud.google.com/swift/reference.md.txt) reference documentation.