azure_storage_blob 0.10.0

Microsoft Azure Blob Storage client library for Rust
Documentation
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
// Code generated by Microsoft (R) Rust Code Generator. DO NOT EDIT.

use crate::generated::models::{
    BlobServiceClientFindBlobsByTagsOptions, BlobServiceClientGetAccountInfoOptions,
    BlobServiceClientGetAccountInfoResult, BlobServiceClientGetPropertiesOptions,
    BlobServiceClientGetStatisticsOptions, BlobServiceClientListContainersOptions,
    BlobServiceClientSetPropertiesOptions, BlobServiceProperties, FilterBlobSegment,
    ListContainersSegmentResponse, StorageServiceStats,
};
use azure_core::{
    error::CheckSuccessOptions,
    fmt::SafeDebug,
    http::{
        pager::{PagerContinuation, PagerResult, PagerState},
        ClientOptions, Method, NoFormat, Pager, Pipeline, PipelineSendOptions, RawResponse,
        Request, RequestContent, Response, Url, UrlExt, XmlFormat,
    },
    tracing, xml, Result,
};

#[tracing::client]
pub struct BlobServiceClient {
    pub(crate) endpoint: Url,
    pub(crate) pipeline: Pipeline,
    pub(crate) version: String,
}

/// Options used when creating a `BlobServiceClient`
#[derive(Clone, SafeDebug)]
pub struct BlobServiceClientOptions {
    /// Allows customization of the client.
    pub client_options: ClientOptions,
    /// Specifies the version of the operation to use for this request.
    pub version: String,
}

impl BlobServiceClient {
    /// Returns the Url associated with this client.
    pub fn endpoint(&self) -> &Url {
        &self.endpoint
    }

    /// The Filter Blobs operation enables callers to list blobs across all containers whose tags match a given search expression.
    ///
    /// # Arguments
    ///
    /// * `filter_expression` - Filters the results to return only to return only blobs whose tags match the specified expression.
    /// * `options` - Optional parameters for the request.
    #[tracing::function("Storage.Blob.BlobServiceClient.findBlobsByTags")]
    pub async fn find_blobs_by_tags(
        &self,
        filter_expression: &str,
        options: Option<BlobServiceClientFindBlobsByTagsOptions<'_>>,
    ) -> Result<Response<FilterBlobSegment, XmlFormat>> {
        let options = options.unwrap_or_default();
        let ctx = options.method_options.context.to_borrowed();
        let mut url = self.endpoint.clone();
        let mut query_builder = url.query_builder();
        query_builder.append_pair("comp", "blobs");
        if let Some(include) = options.include.as_ref() {
            query_builder.set_pair(
                "include",
                include
                    .iter()
                    .map(|i| i.to_string())
                    .collect::<Vec<String>>()
                    .join(","),
            );
        }
        if let Some(marker) = options.marker.as_ref() {
            query_builder.set_pair("marker", marker);
        }
        if let Some(maxresults) = options.maxresults {
            query_builder.set_pair("maxresults", maxresults.to_string());
        }
        if let Some(timeout) = options.timeout {
            query_builder.set_pair("timeout", timeout.to_string());
        }
        query_builder.set_pair("where", filter_expression);
        query_builder.build();
        let mut request = Request::new(url, Method::Get);
        request.insert_header("accept", "application/xml");
        request.insert_header("x-ms-version", &self.version);
        let rsp = self
            .pipeline
            .send(
                &ctx,
                &mut request,
                Some(PipelineSendOptions {
                    check_success: CheckSuccessOptions {
                        success_codes: &[200],
                    },
                    ..Default::default()
                }),
            )
            .await?;
        Ok(rsp.into())
    }

    /// Returns the sku name and account kind.
    ///
    /// # Arguments
    ///
    /// * `options` - Optional parameters for the request.
    ///
    /// ## Response Headers
    ///
    /// The returned [`Response`](azure_core::http::Response) implements the [`BlobServiceClientGetAccountInfoResultHeaders`] trait, which provides
    /// access to response headers. For example:
    ///
    /// ```no_run
    /// use azure_core::{Result, http::{Response, NoFormat}};
    /// use azure_storage_blob::models::{BlobServiceClientGetAccountInfoResult, BlobServiceClientGetAccountInfoResultHeaders};
    /// async fn example() -> Result<()> {
    ///     let response: Response<BlobServiceClientGetAccountInfoResult, NoFormat> = unimplemented!();
    ///     // Access response headers
    ///     if let Some(account_kind) = response.account_kind()? {
    ///         println!("x-ms-account-kind: {:?}", account_kind);
    ///     }
    ///     if let Some(is_hierarchical_namespace_enabled) = response.is_hierarchical_namespace_enabled()? {
    ///         println!("x-ms-is-hns-enabled: {:?}", is_hierarchical_namespace_enabled);
    ///     }
    ///     if let Some(sku_name) = response.sku_name()? {
    ///         println!("x-ms-sku-name: {:?}", sku_name);
    ///     }
    ///     Ok(())
    /// }
    /// ```
    ///
    /// ### Available headers
    /// * [`account_kind`()](crate::generated::models::BlobServiceClientGetAccountInfoResultHeaders::account_kind) - x-ms-account-kind
    /// * [`is_hierarchical_namespace_enabled`()](crate::generated::models::BlobServiceClientGetAccountInfoResultHeaders::is_hierarchical_namespace_enabled) - x-ms-is-hns-enabled
    /// * [`sku_name`()](crate::generated::models::BlobServiceClientGetAccountInfoResultHeaders::sku_name) - x-ms-sku-name
    ///
    /// [`BlobServiceClientGetAccountInfoResultHeaders`]: crate::generated::models::BlobServiceClientGetAccountInfoResultHeaders
    #[tracing::function("Storage.Blob.BlobServiceClient.getAccountInfo")]
    pub async fn get_account_info(
        &self,
        options: Option<BlobServiceClientGetAccountInfoOptions<'_>>,
    ) -> Result<Response<BlobServiceClientGetAccountInfoResult, NoFormat>> {
        let options = options.unwrap_or_default();
        let ctx = options.method_options.context.to_borrowed();
        let mut url = self.endpoint.clone();
        let mut query_builder = url.query_builder();
        query_builder
            .append_pair("comp", "properties")
            .append_pair("restype", "account");
        if let Some(timeout) = options.timeout {
            query_builder.set_pair("timeout", timeout.to_string());
        }
        query_builder.build();
        let mut request = Request::new(url, Method::Get);
        request.insert_header("x-ms-version", &self.version);
        let rsp = self
            .pipeline
            .send(
                &ctx,
                &mut request,
                Some(PipelineSendOptions {
                    check_success: CheckSuccessOptions {
                        success_codes: &[200],
                    },
                    ..Default::default()
                }),
            )
            .await?;
        Ok(rsp.into())
    }

    /// Retrieves properties of a storage account's Blob service, including properties for Storage Analytics and CORS (Cross-Origin
    /// Resource Sharing) rules.
    ///
    /// # Arguments
    ///
    /// * `options` - Optional parameters for the request.
    #[tracing::function("Storage.Blob.BlobServiceClient.getProperties")]
    pub async fn get_properties(
        &self,
        options: Option<BlobServiceClientGetPropertiesOptions<'_>>,
    ) -> Result<Response<BlobServiceProperties, XmlFormat>> {
        let options = options.unwrap_or_default();
        let ctx = options.method_options.context.to_borrowed();
        let mut url = self.endpoint.clone();
        let mut query_builder = url.query_builder();
        query_builder
            .append_pair("comp", "properties")
            .append_pair("restype", "service");
        if let Some(timeout) = options.timeout {
            query_builder.set_pair("timeout", timeout.to_string());
        }
        query_builder.build();
        let mut request = Request::new(url, Method::Get);
        request.insert_header("accept", "application/xml");
        request.insert_header("x-ms-version", &self.version);
        let rsp = self
            .pipeline
            .send(
                &ctx,
                &mut request,
                Some(PipelineSendOptions {
                    check_success: CheckSuccessOptions {
                        success_codes: &[200],
                    },
                    ..Default::default()
                }),
            )
            .await?;
        Ok(rsp.into())
    }

    /// Retrieves statistics related to replication for the Blob service. It is only available on the secondary location endpoint
    /// when read-access geo-redundant replication is enabled for the storage account.
    ///
    /// # Arguments
    ///
    /// * `options` - Optional parameters for the request.
    #[tracing::function("Storage.Blob.BlobServiceClient.getStatistics")]
    pub async fn get_statistics(
        &self,
        options: Option<BlobServiceClientGetStatisticsOptions<'_>>,
    ) -> Result<Response<StorageServiceStats, XmlFormat>> {
        let options = options.unwrap_or_default();
        let ctx = options.method_options.context.to_borrowed();
        let mut url = self.endpoint.clone();
        let mut query_builder = url.query_builder();
        query_builder
            .append_pair("comp", "stats")
            .append_pair("restype", "service");
        if let Some(timeout) = options.timeout {
            query_builder.set_pair("timeout", timeout.to_string());
        }
        query_builder.build();
        let mut request = Request::new(url, Method::Get);
        request.insert_header("accept", "application/xml");
        request.insert_header("x-ms-version", &self.version);
        let rsp = self
            .pipeline
            .send(
                &ctx,
                &mut request,
                Some(PipelineSendOptions {
                    check_success: CheckSuccessOptions {
                        success_codes: &[200],
                    },
                    ..Default::default()
                }),
            )
            .await?;
        Ok(rsp.into())
    }

    /// The List Containers Segment operation returns a list of the containers under the specified account
    ///
    /// # Arguments
    ///
    /// * `options` - Optional parameters for the request.
    #[tracing::function("Storage.Blob.BlobServiceClient.listContainers")]
    pub fn list_containers(
        &self,
        options: Option<BlobServiceClientListContainersOptions<'_>>,
    ) -> Result<Pager<ListContainersSegmentResponse, XmlFormat>> {
        let options = options.unwrap_or_default().into_owned();
        let pipeline = self.pipeline.clone();
        let mut first_url = self.endpoint.clone();
        let mut query_builder = first_url.query_builder();
        query_builder.append_pair("comp", "list");
        if let Some(include) = options.include.as_ref() {
            query_builder.set_pair(
                "include",
                include
                    .iter()
                    .map(|i| i.to_string())
                    .collect::<Vec<String>>()
                    .join(","),
            );
        }
        if let Some(marker) = options.marker.as_ref() {
            query_builder.set_pair("marker", marker);
        }
        if let Some(maxresults) = options.maxresults {
            query_builder.set_pair("maxresults", maxresults.to_string());
        }
        if let Some(prefix) = options.prefix.as_ref() {
            query_builder.set_pair("prefix", prefix);
        }
        if let Some(timeout) = options.timeout {
            query_builder.set_pair("timeout", timeout.to_string());
        }
        query_builder.build();
        let version = self.version.clone();
        Ok(Pager::new(
            move |marker: PagerState, pager_options| {
                let mut url = first_url.clone();
                if let PagerState::More(marker) = marker {
                    let mut query_builder = url.query_builder();
                    query_builder.set_pair("marker", marker.as_ref());
                    query_builder.build();
                }
                let mut request = Request::new(url, Method::Get);
                request.insert_header("accept", "application/xml");
                request.insert_header("x-ms-version", &version);
                let pipeline = pipeline.clone();
                Box::pin(async move {
                    let rsp = pipeline
                        .send(
                            &pager_options.context,
                            &mut request,
                            Some(PipelineSendOptions {
                                check_success: CheckSuccessOptions {
                                    success_codes: &[200],
                                },
                                ..Default::default()
                            }),
                        )
                        .await?;
                    let (status, headers, body) = rsp.deconstruct();
                    let res: ListContainersSegmentResponse = xml::from_xml(&body)?;
                    let rsp = RawResponse::from_bytes(status, headers, body).into();
                    Ok(match res.next_marker {
                        Some(next_marker) if !next_marker.is_empty() => PagerResult::More {
                            response: rsp,
                            continuation: PagerContinuation::Token(next_marker),
                        },
                        _ => PagerResult::Done { response: rsp },
                    })
                })
            },
            Some(options.method_options),
        ))
    }

    /// Sets properties for a storage account's Blob service endpoint, including properties for Storage Analytics and CORS (Cross-Origin
    /// Resource Sharing) rules
    ///
    /// # Arguments
    ///
    /// * `storage_service_properties` - The storage service properties to set.
    /// * `options` - Optional parameters for the request.
    #[tracing::function("Storage.Blob.BlobServiceClient.setProperties")]
    pub async fn set_properties(
        &self,
        storage_service_properties: RequestContent<BlobServiceProperties, XmlFormat>,
        options: Option<BlobServiceClientSetPropertiesOptions<'_>>,
    ) -> Result<Response<(), NoFormat>> {
        let options = options.unwrap_or_default();
        let ctx = options.method_options.context.to_borrowed();
        let mut url = self.endpoint.clone();
        let mut query_builder = url.query_builder();
        query_builder
            .append_pair("comp", "properties")
            .append_pair("restype", "service");
        if let Some(timeout) = options.timeout {
            query_builder.set_pair("timeout", timeout.to_string());
        }
        query_builder.build();
        let mut request = Request::new(url, Method::Put);
        request.insert_header("content-type", "application/xml");
        request.insert_header("x-ms-version", &self.version);
        request.set_body(storage_service_properties);
        let rsp = self
            .pipeline
            .send(
                &ctx,
                &mut request,
                Some(PipelineSendOptions {
                    check_success: CheckSuccessOptions {
                        success_codes: &[202],
                    },
                    ..Default::default()
                }),
            )
            .await?;
        Ok(rsp.into())
    }
}

impl Default for BlobServiceClientOptions {
    fn default() -> Self {
        Self {
            client_options: ClientOptions::default(),
            version: String::from("2026-04-06"),
        }
    }
}