Call long-running operations

Some Google Cloud APIs perform operations that take longer to complete than the duration of a typical HTTP request-response cycle. These operations are known as long-running operations (LROs). Instead of blocking until the work finishes, these API methods return an operation resource, and the client polls the service periodically until the operation completes.

The Google Cloud client libraries for Swift provide helper methods that handle polling and exponential backoff automatically. This document shows you how to use these polling helper methods.

Before you begin

This document uses the Workflows API. To enable this API, follow the Workflows quickstart. Verify that your principal has the Workflows Admin Identity and Access Management (IAM) role (roles/workflows.admin), and add swift-google-cloud-workflows-v1 to your Package.swift dependencies.

For complete setup instructions for the Swift client libraries, see Quickstart: Get started with Swift.

Make an API request with a long-running operation

In this example, you use a WorkflowsClient instance to create a workflow. The createWorkflowPollingUntilDone method starts the operation and automatically polls until the operation completes, returning the created Workflow resource. To make an API request with a long-running operation, follow these steps:

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

    import Foundation
    import GoogleGax
    import GoogleCloudWorkflowsV1

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

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

  3. Initialize the client with the default options:

    let client = try WorkflowsClient()

  4. Create the workflow and poll the operation until it completes:

    let workflow = Workflow().with {
      $0.description = "A sample workflow"
      $0.sourceCode = .sourceContents(
        """
        main:
          steps:
            - returnStep:
                return "Hello World!"
        """
      )
    }
    let response = try await client.createWorkflowPollingUntilDone(
      parent: "projects/\(projectId)/locations/\(location)",
      workflow: workflow,
      workflowId: workflowId
    )
    print("Workflow created: \(response.name)")

When the operation finishes, createWorkflowPollingUntilDone returns the created Workflow resource. You can confirm that the workflow exists in your project by running gcloud workflows describe:

gcloud workflows describe WORKFLOW_ID \
    --location=LOCATION

Replace WORKFLOW_ID and LOCATION with your workflow ID and location.

Operation return types

Depending on the underlying API design, the return type of a *PollingUntilDone helper method varies:

  • gRPC and AIP-151 APIs: for APIs that follow the AIP-151 specification on google.aip.dev, such as Workflows and Cloud Run, the operation service metadata includes the response type of the target resource. In these libraries, polling helpers unwrap the operation and return the target resource directly, such as a Workflow or Service resource.
  • Discovery-based APIs: for APIs such as Compute Engine, the Discovery document schema defines operation methods as returning a service Operation status resource, such as GoogleCloudComputeV1.Operation. When the task finishes, the polling helper returns this completed Operation resource rather than fetching the created or modified resource.

To retrieve the created or modified resource after a Discovery-based operation completes, await the polling helper method. Then call the corresponding get method for the target resource using the identifiers from the request or properties on the returned Operation resource, such as operation.targetLink. If the operation fails, the polling helper throws an error.

Clean up

To avoid incurring charges on your Google Cloud account for the resources used in this document, see Workflows pricing and delete the workflow you created:

gcloud workflows delete WORKFLOW_ID \
    --location=LOCATION

Complete code

The following example shows the complete code for this document:

import Foundation
import GoogleGax
import GoogleCloudWorkflowsV1

func sample(projectId: String, location: String, workflowId: String) async throws {
  let client = try WorkflowsClient()
  let workflow = Workflow().with {
    $0.description = "A sample workflow"
    $0.sourceCode = .sourceContents(
      """
      main:
        steps:
          - returnStep:
              return "Hello World!"
      """
    )
  }
  let response = try await client.createWorkflowPollingUntilDone(
    parent: "projects/\(projectId)/locations/\(location)",
    workflow: workflow,
    workflowId: workflowId
  )
  print("Workflow created: \(response.name)")
}

What's next