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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
pub use crate::generated::clients::{BlobClient, BlobClientOptions};
use crate::{
logging::apply_storage_logging_defaults,
models::{
method_options::BlobClientManagedDownloadOptions, BlobClientDownloadOptions,
BlobClientDownloadResult, BlobClientUploadOptions, BlobClientUploadResult,
StorageErrorCode,
},
pipeline::StorageHeadersPolicy,
AppendBlobClient, BlockBlobClient, PageBlobClient,
};
use azure_core::{
credentials::TokenCredential,
error::ErrorKind,
http::{
policies::{auth::BearerTokenAuthorizationPolicy, Policy},
response::{AsyncResponse, PinnedStream},
NoFormat, Pipeline, RequestContent, StatusCode, Url, UrlExt,
},
tracing, Bytes, Result,
};
use std::sync::Arc;
impl BlobClient {
/// Creates a new BlobClient, using Entra ID authentication.
///
/// # Arguments
///
/// * `endpoint` - The full URL of the Azure storage account, for example `https://myaccount.blob.core.windows.net/`
/// * `container_name` - The name of the container containing this blob.
/// * `blob_name` - The name of the blob to interact with.
/// * `credential` - An optional implementation of [`TokenCredential`] that can provide an Entra ID token to use when authenticating.
/// * `options` - Optional configuration for the client.
pub fn new(
endpoint: &str,
container_name: &str,
blob_name: &str,
credential: Option<Arc<dyn TokenCredential>>,
options: Option<BlobClientOptions>,
) -> Result<Self> {
let mut url = Url::parse(endpoint)?;
{
let mut path_segments = url.path_segments_mut().map_err(|_| {
azure_core::Error::with_message(
azure_core::error::ErrorKind::Other,
"Invalid endpoint URL: Failed to parse out path segments from provided endpoint URL.",
)
})?;
path_segments.extend([container_name, blob_name]);
}
Self::from_url(url, credential, options)
}
/// Creates a new BlobClient from a blob URL.
///
/// # Arguments
///
/// * `blob_url` - The full URL of the blob, for example `https://myaccount.blob.core.windows.net/mycontainer/myblob`.
/// * `credential` - An optional implementation of [`TokenCredential`] that can provide an Entra ID token to use when authenticating.
/// * `options` - Optional configuration for the client.
#[tracing::new("Storage.Blob.Blob")]
pub fn from_url(
blob_url: Url,
credential: Option<Arc<dyn TokenCredential>>,
options: Option<BlobClientOptions>,
) -> Result<Self> {
let mut options = options.unwrap_or_default();
apply_storage_logging_defaults(&mut options.client_options);
let storage_headers_policy = Arc::new(StorageHeadersPolicy);
options
.client_options
.per_call_policies
.push(storage_headers_policy);
if let Some(token_credential) = credential {
if !blob_url.scheme().starts_with("https") {
return Err(azure_core::Error::with_message(
azure_core::error::ErrorKind::Other,
format!("{blob_url} must use https"),
));
}
let auth_policy: Arc<dyn Policy> = Arc::new(BearerTokenAuthorizationPolicy::new(
token_credential,
vec!["https://storage.azure.com/.default"],
));
options.client_options.per_try_policies.push(auth_policy);
}
let pipeline = Pipeline::new(
option_env!("CARGO_PKG_NAME"),
option_env!("CARGO_PKG_VERSION"),
options.client_options.clone(),
Vec::default(),
Vec::default(),
None,
);
Ok(Self {
endpoint: blob_url,
version: options.version,
pipeline,
})
}
/// The managed download operation retrieves the content of an existing blob.
///
/// # Arguments
///
/// * `options` - Optional parameters for the request.
pub async fn managed_download(
&self,
_options: Option<BlobClientManagedDownloadOptions<'_>>,
) -> Result<PinnedStream> {
unimplemented!("BlobClient::managed_download() was unintentionally exported in 0.10.0 and will be removed in a future release.")
}
/// Returns a new instance of AppendBlobClient.
pub fn append_blob_client(&self) -> AppendBlobClient {
AppendBlobClient {
endpoint: self.endpoint.clone(),
pipeline: self.pipeline.clone(),
version: self.version.clone(),
tracer: self.tracer.clone(),
}
}
/// Returns a new instance of BlockBlobClient.
pub fn block_blob_client(&self) -> BlockBlobClient {
BlockBlobClient {
endpoint: self.endpoint.clone(),
pipeline: self.pipeline.clone(),
version: self.version.clone(),
tracer: self.tracer.clone(),
}
}
/// Returns a new instance of PageBlobClient.
pub fn page_blob_client(&self) -> PageBlobClient {
PageBlobClient {
endpoint: self.endpoint.clone(),
pipeline: self.pipeline.clone(),
version: self.version.clone(),
tracer: self.tracer.clone(),
}
}
/// Gets the URL of the resource this client is configured for.
pub fn url(&self) -> &Url {
&self.endpoint
}
/// Creates a new BlobClient targeting a specific blob version.
///
/// # Arguments
///
/// * `version_id` - The version ID of the blob to target.
pub fn with_version(&self, version_id: &str) -> Result<Self> {
let mut versioned_endpoint = self.endpoint.clone();
{
let mut query_builder = versioned_endpoint.query_builder();
query_builder.set_pair("versionid", version_id);
query_builder.build();
}
Ok(Self {
endpoint: versioned_endpoint,
pipeline: self.pipeline.clone(),
version: self.version.clone(),
tracer: self.tracer.clone(),
})
}
/// Creates a new BlobClient targeting a specific blob snapshot.
///
/// # Arguments
///
/// * `snapshot` - The snapshot ID of the blob to target.
pub fn with_snapshot(&self, snapshot: &str) -> Result<Self> {
let mut snapshot_endpoint = self.endpoint.clone();
{
let mut query_builder = snapshot_endpoint.query_builder();
query_builder.set_pair("snapshot", snapshot);
query_builder.build();
}
Ok(Self {
endpoint: snapshot_endpoint,
pipeline: self.pipeline.clone(),
version: self.version.clone(),
tracer: self.tracer.clone(),
})
}
/// Downloads a blob from the service, including its metadata and properties.
///
/// * `options` - Optional configuration for the request.
pub async fn download(
&self,
options: Option<BlobClientDownloadOptions<'_>>,
) -> Result<AsyncResponse<BlobClientDownloadResult>> {
self.download_internal(options).await
}
/// Uploads content to a block blob, overwriting any existing blob by default.
///
/// Updating an existing block blob overwrites any existing metadata on the blob. Use [`BlobClientUploadOptions::with_if_not_exists()`] to fail instead of overwriting.
/// To perform a partial update of the content of a block blob, use [`BlockBlobClient::stage_block()`] and [`BlockBlobClient::commit_block_list()`] directly.
///
/// # Arguments
///
/// * `content` - The content to upload.
/// * `options` - Optional parameters for the request.
pub async fn upload(
&self,
content: RequestContent<Bytes, NoFormat>,
options: Option<BlobClientUploadOptions<'_>>,
) -> Result<BlobClientUploadResult> {
self.block_blob_client().upload(content, options).await
}
/// Checks if the blob exists.
///
/// Returns `true` if the blob exists, `false` if the blob does not exist, and propagates all other errors.
pub async fn exists(&self) -> Result<bool> {
match self.get_properties(None).await {
Ok(_) => Ok(true),
Err(e) if e.http_status() == Some(StatusCode::NotFound) => match e.kind() {
ErrorKind::HttpResponse {
error_code: Some(error_code),
..
} if error_code == StorageErrorCode::BlobNotFound.as_ref()
|| error_code == StorageErrorCode::ContainerNotFound.as_ref() =>
{
Ok(false)
}
// Propagate all other error types.
_ => Err(e),
},
Err(e) => Err(e),
}
}
}