Skip to content

[Storage] [WIP] Handwritten BlockBlobClient #2505

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 22 additions & 93 deletions sdk/storage/azure_storage_blob/src/clients/blob_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,12 @@

use crate::{
generated::clients::BlobClient as GeneratedBlobClient,
generated::models::{
BlobClientDownloadResult, BlobClientGetPropertiesResult,
BlockBlobClientCommitBlockListResult, BlockBlobClientStageBlockResult,
BlockBlobClientUploadResult,
},
generated::models::{BlobClientDownloadResult, BlobClientGetPropertiesResult},
models::{AccessTier, BlockList, BlockListType, BlockLookupList},
pipeline::StorageHeadersPolicy,
BlobClientDeleteOptions, BlobClientDownloadOptions, BlobClientGetPropertiesOptions,
BlobClientOptions, BlobClientSetMetadataOptions, BlobClientSetPropertiesOptions,
BlobClientSetTierOptions, BlockBlobClientCommitBlockListOptions,
BlockBlobClientGetBlockListOptions, BlockBlobClientStageBlockOptions,
BlockBlobClientUploadOptions,
BlobClientSetTierOptions, BlockBlobClient, BlockBlobClientOptions,
};
use azure_core::{
credentials::TokenCredential,
Expand All @@ -29,6 +23,7 @@ use std::sync::Arc;
/// A client to interact with a specific Azure storage blob, although that blob may not yet exist.
pub struct BlobClient {
endpoint: Url,
credential: Arc<dyn TokenCredential>,
client: GeneratedBlobClient,
}

Expand Down Expand Up @@ -75,10 +70,29 @@ impl BlobClient {
)?;
Ok(Self {
endpoint: endpoint.parse()?,
credential,
client,
})
}

/// Returns a new instance of BlockBlobClient.
///
/// # Arguments
///
/// * `options` - Optional configuration for the client.
pub fn get_block_blob_client(
&self,
options: Option<BlockBlobClientOptions>,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we have a precedent on whether sub-clients should inherit options, or should they be explicitly set and default otherwise.

I think for Service vs. Container vs. Blob it makes sense to not be passing the options bag, but I could see the argument since these subclients are all Blob-based -- but wanted to see if we have any precedent in other languages.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, will change this to block_blob_client as per subclient naming guidelines.

) -> Result<BlockBlobClient> {
BlockBlobClient::new(
self.endpoint().as_str(),
self.container_name().to_string(),
self.blob_name().to_string(),
self.credential.clone(),
options,
)
}

/// Gets the endpoint of the Storage account this client is connected to.
pub fn endpoint(&self) -> &Url {
&self.endpoint
Expand Down Expand Up @@ -132,36 +146,6 @@ impl BlobClient {
Ok(response)
}

/// Creates a new blob from a data source.
///
/// # Arguments
///
/// * `data` - The blob data to upload.
/// * `overwrite` - Whether the blob to be uploaded should overwrite the current data. If True, `upload_blob` will overwrite the existing data.
/// If False, the operation will fail with ResourceExistsError.
/// * `content_length` - Total length of the blob data to be uploaded.
/// * `options` - Optional configuration for the request.
pub async fn upload(
&self,
data: RequestContent<Bytes>,
overwrite: bool,
content_length: u64,
options: Option<BlockBlobClientUploadOptions<'_>>,
) -> Result<Response<BlockBlobClientUploadResult>> {
let mut options = options.unwrap_or_default();

if !overwrite {
options.if_none_match = Some(String::from("*"));
}

let block_blob_client = self.client.get_block_blob_client();

let response = block_blob_client
.upload(data, content_length, Some(options))
.await?;
Ok(response)
}

/// Sets user-defined metadata for the specified blob as one or more name-value pairs. Each call to this operation
/// replaces all existing metadata attached to the blob. To remove all metadata from the blob, call this operation with
/// no metadata headers.
Expand Down Expand Up @@ -190,61 +174,6 @@ impl BlobClient {
Ok(response)
}

/// Writes to a blob based on blocks specified by the list of IDs and content that make up the blob.
///
/// # Arguments
///
/// * `blocks` - The list of Blob blocks to commit.
/// * `options` - Optional configuration for the request.
pub async fn commit_block_list(
&self,
blocks: RequestContent<BlockLookupList>,
options: Option<BlockBlobClientCommitBlockListOptions<'_>>,
) -> Result<Response<BlockBlobClientCommitBlockListResult>> {
let block_blob_client = self.client.get_block_blob_client();
let response = block_blob_client.commit_block_list(blocks, options).await?;
Ok(response)
}

/// Creates a new block to be later committed as part of a blob.
///
/// # Arguments
///
/// * `block_id` - The unique identifier for the block. The identifier should be less than or equal to 64 bytes in size.
/// For a given blob, the `block_id` must be the same size for each block.
/// * `content_length` - Total length of the blob data to be staged.
/// * `data` - The content of the block.
/// * `options` - Optional configuration for the request.
pub async fn stage_block(
&self,
block_id: Vec<u8>,
content_length: u64,
body: RequestContent<Bytes>,
options: Option<BlockBlobClientStageBlockOptions<'_>>,
) -> Result<Response<BlockBlobClientStageBlockResult>> {
let block_blob_client = self.client.get_block_blob_client();
let response = block_blob_client
.stage_block(block_id, content_length, body, options)
.await?;
Ok(response)
}

/// Retrieves the list of blocks that have been uploaded as part of a block blob.
///
/// # Arguments
///
/// * `list_type` - Specifies whether to return the list of committed blocks, uncommitted blocks, or both lists together.
/// * `options` - Optional configuration for the request.
pub async fn get_block_list(
&self,
list_type: BlockListType,
options: Option<BlockBlobClientGetBlockListOptions<'_>>,
) -> Result<Response<BlockList>> {
let block_blob_client = self.client.get_block_blob_client();
let response = block_blob_client.get_block_list(list_type, options).await?;
Ok(response)
}

/// Sets the tier on a blob. Standard tiers are only applicable for Block blobs, while Premium tiers are only applicable
/// for Page blobs.
///
Expand Down
178 changes: 178 additions & 0 deletions sdk/storage/azure_storage_blob/src/clients/block_blob_client.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

use crate::{
generated::clients::BlockBlobClient as GeneratedBlockBlobClient,
generated::models::{
BlobClientDownloadResult, BlobClientGetPropertiesResult,
BlockBlobClientCommitBlockListResult, BlockBlobClientStageBlockResult,
BlockBlobClientUploadResult,
},
models::{BlockList, BlockListType, BlockLookupList, StorageServiceProperties},
pipeline::StorageHeadersPolicy,
BlobClientDeleteOptions, BlobClientDownloadOptions, BlobClientGetPropertiesOptions,
BlobClientOptions, BlobClientSetMetadataOptions, BlobClientSetPropertiesOptions,
BlobClientSetTierOptions, BlockBlobClientCommitBlockListOptions,
BlockBlobClientGetBlockListOptions, BlockBlobClientOptions, BlockBlobClientStageBlockOptions,
BlockBlobClientUploadOptions,
};
use azure_core::{
credentials::TokenCredential,
http::{
policies::{BearerTokenCredentialPolicy, Policy},
RequestContent, Response, Url,
},
Bytes, Result,
};
use std::sync::Arc;

/// A client to interact with a specific Azure storage Block blob, although that blob may not yet exist.
pub struct BlockBlobClient {
endpoint: Url,
client: GeneratedBlockBlobClient,
}

impl BlockBlobClient {
/// Creates a new BlockBlobClient, 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 Block blob.
/// * `blob_name` - The name of the Block blob to interact with.
/// * `credential` - An 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: String,
blob_name: String,
credential: Arc<dyn TokenCredential>,
options: Option<BlockBlobClientOptions>,
) -> Result<Self> {
let mut options = options.unwrap_or_default();

let storage_headers_policy = Arc::new(StorageHeadersPolicy);
options
.client_options
.per_call_policies
.push(storage_headers_policy);

let oauth_token_policy = BearerTokenCredentialPolicy::new(
credential.clone(),
["https://storage.azure.com/.default"],
);
options
.client_options
.per_try_policies
.push(Arc::new(oauth_token_policy) as Arc<dyn Policy>);

let client = GeneratedBlockBlobClient::new(
endpoint,
credential.clone(),
container_name.clone(),
blob_name.clone(),
Some(options),
)?;
Ok(Self {
endpoint: endpoint.parse()?,
client,
})
}

/// Gets the endpoint of the Storage account this client is connected to.
pub fn endpoint(&self) -> &Url {
&self.endpoint
}

/// Gets the container name of the Storage account this client is connected to.
pub fn container_name(&self) -> &str {
&self.client.container_name
}

/// Gets the blob name of the Storage account this client is connected to.
pub fn blob_name(&self) -> &str {
&self.client.blob_name
}

/// Creates a new Block blob from a data source.
///
/// # Arguments
///
/// * `data` - The blob data to upload.
/// * `overwrite` - Whether the blob to be uploaded should overwrite the current data. If True, `upload_blob` will overwrite the existing data.
/// If False, the operation will fail with ResourceExistsError.
/// * `content_length` - Total length of the blob data to be uploaded.
/// * `options` - Optional configuration for the request.
pub async fn upload(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leave this in base blob client.

&self,
data: RequestContent<Bytes>,
overwrite: bool,
content_length: u64,
options: Option<BlockBlobClientUploadOptions<'_>>,
) -> Result<Response<BlockBlobClientUploadResult>> {
let mut options: BlockBlobClientUploadOptions<'_> = options.unwrap_or_default();

if !overwrite {
options.if_none_match = Some(String::from("*"));
}

let response = self
.client
.upload(data, content_length, Some(options))
.await?;
Ok(response)
}

/// Writes to a Block blob based on blocks specified by the list of IDs and content that make up the blob.
///
/// # Arguments
///
/// * `blocks` - The list of Blob blocks to commit.
/// * `options` - Optional configuration for the request.
pub async fn commit_block_list(
&self,
blocks: RequestContent<BlockLookupList>,
options: Option<BlockBlobClientCommitBlockListOptions<'_>>,
) -> Result<Response<BlockBlobClientCommitBlockListResult>> {
let response = self.client.commit_block_list(blocks, options).await?;
Ok(response)
}

/// Creates a new block to be later committed as part of a blob.
///
/// # Arguments
///
/// * `block_id` - The unique identifier for the block. The identifier should be less than or equal to 64 bytes in size.
/// For a given blob, the `block_id` must be the same size for each block.
/// * `content_length` - Total length of the blob data to be staged.
/// * `data` - The content of the block.
/// * `options` - Optional configuration for the request.
pub async fn stage_block(
&self,
block_id: Vec<u8>,
content_length: u64,
body: RequestContent<Bytes>,
options: Option<BlockBlobClientStageBlockOptions<'_>>,
) -> Result<Response<BlockBlobClientStageBlockResult>> {
let response = self
.client
.stage_block(block_id, content_length, body, options)
.await?;
Ok(response)
}

/// Retrieves the list of blocks that have been uploaded as part of a block blob.
///
/// # Arguments
///
/// * `list_type` - Specifies whether to return the list of committed blocks, uncommitted blocks, or both lists together.
/// * `options` - Optional configuration for the request.
pub async fn get_block_list(
&self,
list_type: BlockListType,
options: Option<BlockBlobClientGetBlockListOptions<'_>>,
) -> Result<Response<BlockList>> {
let response = self.client.get_block_list(list_type, options).await?;
Ok(response)
}
}
2 changes: 2 additions & 0 deletions sdk/storage/azure_storage_blob/src/clients/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
mod blob_client;
mod blob_container_client;
mod blob_service_client;
mod block_blob_client;

pub use blob_client::BlobClient;
pub use blob_container_client::BlobContainerClient;
pub use blob_service_client::BlobServiceClient;
pub use block_blob_client::BlockBlobClient;
4 changes: 2 additions & 2 deletions sdk/storage/azure_storage_blob/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ pub mod clients;
mod generated;
mod pipeline;

pub use crate::clients::{BlobClient, BlobContainerClient, BlobServiceClient};
pub use crate::clients::{BlobClient, BlobContainerClient, BlobServiceClient, BlockBlobClient};
pub use crate::generated::clients::{
BlobClientOptions, BlobContainerClientOptions, BlobServiceClientOptions,
BlobClientOptions, BlobContainerClientOptions, BlobServiceClientOptions, BlockBlobClientOptions,
};
pub use crate::generated::models::{
BlobClientDeleteOptions, BlobClientDownloadOptions, BlobClientGetPropertiesOptions,
Expand Down
Loading
Loading