azure_storage_blob 0.8.0

Microsoft Azure Blob Storage client library for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) Rust Code Generator. DO NOT EDIT.

use crate::generated::models::{
    BlobServiceClientFindBlobsByTagsOptions, BlobServiceClientGetAccountInfoOptions,
    BlobServiceClientGetAccountInfoResult, BlobServiceClientGetPropertiesOptions,
    BlobServiceClientGetStatisticsOptions, BlobServiceClientGetUserDelegationKeyOptions,
    BlobServiceClientListContainersSegmentOptions, BlobServiceClientSetPropertiesOptions,
    BlobServiceProperties, FilterBlobSegment, KeyInfo, ListContainersSegmentResponse,
    StorageServiceStats, UserDelegationKey,
};
use azure_core::{
    credentials::TokenCredential,
    error::CheckSuccessOptions,
    fmt::SafeDebug,
    http::{
        pager::{PagerResult, PagerState},
        policies::{auth::BearerTokenAuthorizationPolicy, Policy},
        ClientOptions, Method, NoFormat, Pager, Pipeline, PipelineSendOptions, RawResponse,
        Request, RequestContent, Response, Url, UrlExt, XmlFormat,
    },
    tracing, xml, Result,
};
use std::sync::Arc;

#[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 {
    /// Creates a new BlobServiceClient, using Entra ID authentication.
    ///
    /// # Arguments
    ///
    /// * `endpoint` - Service host
    /// * `credential` - An implementation of [`TokenCredential`](azure_core::credentials::TokenCredential) that can provide an
    ///   Entra ID token to use when authenticating.
    /// * `options` - Optional configuration for the client.
    #[tracing::new("Storage.Blob.Service")]
    pub fn new(
        endpoint: &str,
        credential: Arc<dyn TokenCredential>,
        options: Option<BlobServiceClientOptions>,
    ) -> Result<Self> {
        let options = options.unwrap_or_default();
        let endpoint = Url::parse(endpoint)?;
        if !endpoint.scheme().starts_with("http") {
            return Err(azure_core::Error::with_message(
                azure_core::error::ErrorKind::Other,
                format!("{endpoint} must use http(s)"),
            ));
        }
        let auth_policy: Arc<dyn Policy> = Arc::new(BearerTokenAuthorizationPolicy::new(
            credential,
            vec!["https://storage.azure.com/.default"],
        ));
        Ok(Self {
            endpoint,
            version: options.version,
            pipeline: Pipeline::new(
                option_env!("CARGO_PKG_NAME"),
                option_env!("CARGO_PKG_VERSION"),
                options.client_options,
                Vec::default(),
                vec![auth_policy],
                None,
            ),
        })
    }

    /// 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.Service.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("content-type", "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.Service.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("content-type", "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 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.Service.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("content-type", "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.Service.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("content-type", "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 a user delegation key for the Blob service. This is only a valid operation when using bearer token authentication.
    ///
    /// # Arguments
    ///
    /// * `key_info` - Key information provided in the request
    /// * `options` - Optional parameters for the request.
    #[tracing::function("Storage.Blob.Service.getUserDelegationKey")]
    pub async fn get_user_delegation_key(
        &self,
        key_info: RequestContent<KeyInfo, XmlFormat>,
        options: Option<BlobServiceClientGetUserDelegationKeyOptions<'_>>,
    ) -> Result<Response<UserDelegationKey, 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", "userdelegationkey")
            .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::Post);
        request.insert_header("accept", "application/xml");
        request.insert_header("content-type", "application/xml");
        request.insert_header("x-ms-version", &self.version);
        request.set_body(key_info);
        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.Service.listContainersSegment")]
    pub fn list_containers_segment(
        &self,
        options: Option<BlobServiceClientListContainersSegmentOptions<'_>>,
    ) -> Result<Pager<ListContainersSegmentResponse, XmlFormat, String>> {
        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<String>, 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);
                    query_builder.build();
                }
                let mut request = Request::new(url, Method::Get);
                request.insert_header("accept", "application/xml");
                request.insert_header("content-type", "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: 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.Service.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("2025-11-05"),
        }
    }
}