Contents

googleapis/swift-google-gax

Core runtime, transport, and resilience infrastructure for Google Cloud client

Overview

GAX (Google API Extensions) provides the runtime protocols, networking abstractions, and resilience utilities that power Google Cloud client libraries for Swift.

A default-initialized client is expected to work in most environments. However, specific deployments may need to tweak retry policies, backoff intervals, authentication credentials, target endpoints, request throttling, structured error handling, or long-running operations.

Client Configuration

The primary type to configure clients is ClientOptions. Use this type to override default endpoints (e.g. for VPC Service Controls, regional endpoints, or emulators), credentials, logging (via Apple's swift-log), and default retry or polling policies.

Request Options

When individual requests require distinct handling (such as longer deadlines or suppressed retries), pass a RequestOptions instance to configure that specific call.

Structured Error Handling

Client libraries throw RequestError when an operation fails. RequestError distinguishes between service errors (ServiceError) with status details, HTTP transport errors (HTTPDetails), I/O failures, and exhausted retries.

Retry Loop Control

Retry loops are governed by three orthogonal controls:

  • RetryPolicy: Controls which errors are retryable (BaseRetryPolicy.defaultPolicy,

BaseRetryPolicy.unbounded(), decorated with .withAttemptLimit(:) and/or .withTimeLimit(:)).

  • BackoffPolicy: Determines how long the client waits before retrying (ExponentialBackoff).
  • RetryThrottler: Suppresses retries to prevent retry storms (AdaptiveThrottler, CircuitBreaker).

Polling Loop Control

Polling loops for long-running operations (LRO) provide two orthogonal controls:

  • PollingErrorPolicy: Controls which polling errors are retryable (BasePollingErrorPolicy).
  • PollingBackoffPolicy: Determines the interval between polling attempts (ExponentialBackoff).

Libraries & Products

This package provides the GoogleGax library: core HTTP transport (using AsyncHTTPClient and SwiftNIO), client and request configuration options (ClientOptions, RequestOptions), retry and backoff loops, circuit breakers, adaptive throttlers, LRO polling policies, and error models.

For gRPC transport support, see the separate swift-google-gax-grpc (GoogleGaxGRPC) package.

Features

  • Client Configuration (ClientOptions): Override default endpoints (e.g.

for VPC Service Controls, regional/locational endpoints, or local emulators), authentication credentials, structured logging (via Apple's swift-log), and default retry/polling policies.

  • Per-Request Overrides (RequestOptions): Fine-tune retry behavior,

timeouts, or custom headers on individual API calls.

  • Resilience & Retry Policies:

- RetryPolicy protocol with standard implementations including BaseRetryPolicy (handles transient I/O and idempotent errors per AIP-194), AlwaysRetry, and NeverRetry. - Decorators to cap retry attempts (.withAttemptLimit(:)) and total elapsed time (.withTimeLimit(:)). - Exponential backoff with randomized jitter (ExponentialBackoff). - Overload protection via AdaptiveThrottler (stochastic retry suppression based on success/failure ratio) and CircuitBreaker.

  • Long-Running Operations (LRO): Polling error policies

(BasePollingErrorPolicy) and backoff policies for tracking asynchronous, long-running operations until completion (AIP-151).

  • Strongly Typed Error Handling: Comprehensive error model via

RequestError, including service errors (ServiceError) with Google RPC status codes and status details (StatusDetail), HTTP transport errors (HTTPDetails), I/O errors, and exhausted retry deadlines.

  • Pagination: Asynchronous sequences and helpers for paginated APIs.

Requirements

For the minimum supported Swift version and platform requirements, see the Requirements section in the google-cloud-swift repository.

Installation

Add swift-google-gax as a package dependency:

swift package add-dependency https://github.com/googleapis/swift-google-gax.git --from 0.1.0

Then add GoogleGax to your target's dependencies:

swift package add-target-dependency GoogleGax <target-name> --package swift-google-gax

Usage

Configuring ClientOptions

You can configure client-level options such as endpoints, credentials, retry policies, and backoff parameters:

import Foundation
import GoogleAuth
import GoogleGax

let options = try ClientOptions().with {
    // Custom endpoint (e.g. for VPC-SC, private access, or emulators)
    $0.endpoint = "https://private.googleapis.com"

    // Override credentials
    $0.credentials = try Credentials()

    // Configure retry policy (max 5 attempts and max 60 seconds)
    $0.retryPolicy = BaseRetryPolicy.unbounded()
        .withAttemptLimit(5)
        .withTimeLimit(.seconds(60))

    // Configure exponential backoff
    $0.backoffPolicy = try ExponentialBackoff(
        initialDelay: .milliseconds(200),
        maximumDelay: .seconds(15),
        scaling: 1.5
    )
}

Per-Request Overrides (RequestOptions)

When a specific request needs distinct handling, pass a RequestOptions instance:

import GoogleGax

// Disable retries for a specific call
let requestOptions = RequestOptions().with {
    $0.retryPolicy = NeverRetry()
}

Error Handling

When an operation fails, the client libraries throw a RequestError:

import GoogleGax

do {
    // Perform API call using a client
} catch let error as RequestError {
    switch error {
    case .service(let serviceError):
        print("Service error: \(serviceError.code) - \(serviceError.message)")
        for detail in serviceError.details {
            print("Status detail: \(detail)")
        }
    case .http(let httpDetails):
        print("HTTP error with status code: \(httpDetails.statusCode)")
    case .io(let ioError):
        print("Transport I/O error: \(ioError)")
    case .exhausted(let exhausted):
        print("Retries exhausted after \(exhausted.maximumDuration): \(exhausted.source)")
    @unknown default:
        print("Request failed: \(error)")
    }
}

See Also

Contributing

Contributions to this library are always welcome and highly encouraged.

All development, issues, and pull requests are managed in the google-cloud-swift monorepo. See CONTRIBUTING.md for details on getting started.

License

Apache 2.0 - See LICENSE for more information.

Package Metadata

Repository: googleapis/swift-google-gax

Default branch: main

README: README.md