[go: up one dir, main page]

Crate azure_core

Source
Expand description

§Azure Core shared client library for Rust

azure_core provides shared primitives, abstractions, and helpers for modern Rust Azure SDK client libraries. These libraries follow the Azure SDK Design Guidelines for Rust and can typically be identified by package and namespaces names starting with azure_, e.g. azure_identity.

azure_core allows client libraries to expose common functionality in a consistent fashion so that once you learn how to use these APIs in one client library, you will know how to use them in other client libraries.

Source code | Package (crates.io) | API Reference Documentation

§Getting started

Typically, you will not need to install azure_core; it will be installed for you when you install one of the client libraries using it. In case you want to install it explicitly - to implement your own client library, for example - you can find the crates.io package here.

§Key concepts

The main shared concepts of azure_core - and Azure SDK libraries using azure_core - include:

  • Configuring service clients, e.g. configuring retries, logging (ClientOptions).
  • Accessing HTTP response details (Response<T>).
  • Paging and asynchronous streams (Pager<T>).
  • Errors from service requests in a consistent fashion. (azure_core::Error).
  • Customizing requests (ClientOptions).
  • Abstractions for representing Azure SDK credentials. (TokenCredentials).

§Thread safety

We guarantee that all client instance methods are thread-safe and independent of each other (guidelines). This ensures that the recommendation of reusing client instances is always safe, even across threads.

§Additional concepts

Client options | Accessing the response | Handling Errors Results | Consuming Service Methods Returning Pager<T>

§Examples

NOTE: Samples in this file apply only to packages that follow Azure SDK Design Guidelines. Names of such packages typically start with azure_.

§Configuring service clients using ClientOptions

Azure SDK client libraries typically expose one or more service client types that are the main starting points for calling corresponding Azure services. You can easily find these client types as their names end with the word Client. For example, SecretClient can be used to call the Key Vault service and interact with secrets, and KeyClient can be used to access Key Vault service cryptographic keys.

These client types can be instantiated by calling a simple new function that takes various configuration options.These options are passed as a parameter that extends ClientOptions class exposed by azure_core. Various service specific options are usually added to its subclasses, but a set of SDK-wide options are available directly on ClientOptions.

use azure_core::ClientOptions;
use azure_identity::DefaultAzureCredential;
use azure_security_keyvault_secrets::{SecretClient, SecretClientOptions};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let credential = DefaultAzureCredential::new()?;

    let options = SecretClientOptions {
        api_version: "7.5".to_string(),
        ..Default::default()
    };

    let client = SecretClient::new(
        "https://your-key-vault-name.vault.azure.net/",
        credential.clone(),
        Some(options),
    )?;

    Ok(())
}

§Accessing HTTP response details using Response<T>

Service clients have methods that can be used to call Azure services. We refer to these client methods as service methods. Service methods return a shared azure_core type Response<T> where T is either a Model type or a ResponseBody representing a raw stream of bytes. This type provides access to both the deserialized result of the service call, and to the details of the HTTP response returned from the server.

use azure_core::Response;
use azure_identity::DefaultAzureCredential;
use azure_security_keyvault_secrets::{models::SecretBundle, SecretClient};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // create a client
    let credential = DefaultAzureCredential::new()?;
    let client = SecretClient::new(
        "https://your-key-vault-name.vault.azure.net/",
        credential.clone(),
        None,
    )?;

    // call a service method, which returns Response<T>
    let response = client.get_secret("secret-name", "", None).await?;

    // Response<T> has two main accessors:
    // 1. The `into_body()` function consumes self to deserialize into a model type
    let secret = response.into_body().await?;

    // get response again because it was moved in above statement
    let response: Response<SecretBundle> = client.get_secret("secret-name", "", None).await?;

    // 2. The deconstruct() method for accessing all the details of the HTTP response
    let (status, headers, body) = response.deconstruct();

    // for example, you can access HTTP status
    println!("Status: {}", status);

    // or the headers
    for (header_name, header_value) in headers.iter() {
        println!("{}: {}", header_name.as_str(), header_value.as_str());
    }

    Ok(())
}

§Handling errors results

When a service call fails, the returned Result will contain an Error. The Error type provides a status property with an HTTP status code and an error_code property with a service-specific error code.

use azure_core::{error::{ErrorKind, HttpError}, Response, StatusCode};
use azure_identity::DefaultAzureCredential;
use azure_security_keyvault_secrets::SecretClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // create a client
    let credential = DefaultAzureCredential::new()?;
    let client = SecretClient::new(
        "https://your-key-vault-name.vault.azure.net/",
        credential.clone(),
        None,
    )?;

    match client.get_secret("secret-name", "", None).await {
        Ok(secret) => println!("Secret: {:?}", secret.into_body().await?.value),
        Err(e) => match e.kind() {
            ErrorKind::HttpResponse { status, error_code, .. } if *status == StatusCode::NotFound => {
                // handle not found error
                if let Some(code) = error_code {
                    println!("ErrorCode: {}", code);
                } else {
                    println!("Secret not found, but no error code provided.");
                }
            },
            _ => println!("An error occurred: {e:?}"),
        },
    }

    Ok(())
}

§Consuming service methods returning Pager<T>

If a service call returns multiple values in pages, it would return Result<Pager<T>> as a result. You can iterator over each page’s vector of results.

use azure_identity::DefaultAzureCredential;
use azure_security_keyvault_secrets::{ResourceExt, SecretClient};
use futures::TryStreamExt;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // create a client
    let credential = DefaultAzureCredential::new()?;
    let client = SecretClient::new(
        "https://your-key-vault-name.vault.azure.net/",
        credential.clone(),
        None,
    )?;

    // get a stream
    let mut pager = client.get_secrets(None)?.into_stream();

    // poll the pager until there are no more SecretListResults
    while let Some(secrets) = pager.try_next().await? {
        let Some(secrets) = secrets.into_body().await?.value else {
            continue;
        };

        // loop through secrets in SecretsListResults
        for secret in secrets {
            // get the secret name from the ID
            let name = secret.resource_id()?.name;
            println!("Found secret with name: {}", name);
        }
    }

    Ok(())
}

§Contributing

See the CONTRIBUTING.md for details on building, testing, and contributing to these libraries.

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://opensource.microsoft.com/cla/.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the [Microsoft Open Source Code of Conduct]. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

Modules§

authority_hosts
A list of known Azure authority hosts
base64
Base64 encoding and decoding functions.
builders
Client options and client method options builders.
content_type
Constants related to the Content-Type header
credentials
Azure authentication and authorization.
date
Date and time parsing and formatting functions.
error
headers
hmac
json
JSON serialization functions.
lro
parsing
Parser helper utilities.
query_param
Constants related to query parameters
request_options
resource_manager_endpoint
Endpoints for Azure Resource Manager in different Azure clouds
sleep
Sleep functions.
test
Shared utilities for testing client libraries built on azure_core.
tokio
xml
XML serialization functions.

Macros§

future
Declare a Future with the given name
static_url

Structs§

BearerTokenCredentialPolicy
Bytes
A cheaply cloneable and sliceable chunk of contiguous memory.
BytesStream
Convenience struct that maps a bytes::Bytes buffer into a stream.
ClientMethodOptions
Method options allow customization of client method calls.
ClientOptions
Client options allow customization of general client policies, retry options, and more.
Context
Pipeline execution context.
CustomHeaders
Custom headers to add to a request.
CustomHeadersPolicy
Policy to add CustomHeaders to a request.
Error
An error encountered when communicating with the service.
Etag
ExponentialRetryOptions
Options for how an exponential retry strategy should behave.
ExponentialRetryPolicy
Retry policy with exponential back-off.
FixedRetryOptions
Options for how a fixed retry strategy should behave.
FixedRetryPolicy
Retry policy with a fixed back-off.
NoRetryPolicy
Retry policy that does not retry.
Pager
Represents a paginated result across multiple requests.
Pipeline
Execution pipeline.
Request
A pipeline request.
RequestContent
The body content of a service client request. This allows callers to pass a model to serialize or raw content to client methods.
Response
An HTTP response.
ResponseBody
A response body stream.
RetryOptions
Specify how retries should behave.
TelemetryOptions
Telemetry options.
TelemetryPolicy
TransportOptions
Transport options.
TransportPolicy
Url
A parsed URL record.
Uuid
A Universally Unique Identifier (UUID).

Enums§

Body
An HTTP Body.
LeaseAction
The lease action to perform on an Azure resource.
LeaseDuration
Lease duration of an Azure resource.
LeaseState
State of a lease of an Azure resource.
LeaseStatus
Lease status of an Azure resource.
Method
HTTP request methods.
StatusCode
HTTP response status codes.

Constants§

EMPTY_BODY
An empty HTTP body.

Traits§

AppendToUrlQuery
Add a new query pair into the target Url’s query string.
Header
View a type as an HTTP header.
HttpClient
An HTTP client which can send requests.
Model
Trait that represents types that can be deserialized from an HTTP response body.
Policy
A pipeline policy.
RetryPolicy
A retry policy.
SeekableStream
Enable a type implementing AsyncRead to be consumed as if it were a Stream of Bytes.

Functions§

get_retry_after
Get the duration to delay between retry attempts, provided by the headers from the response.
new_http_client
Create a new HttpClient.
sleep
Waits until duration has elapsed.

Type Aliases§

PinnedStream
PolicyResult
A specialized Result type for policies.
RequestId
A unique identifier for a request.
Result
A convenience alias for Result where the error type is hard coded to Error.
SessionToken
A unique session token.