This is an automated email from the ASF dual-hosted git repository.
Xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/opendal.git
The following commit(s) were added to refs/heads/main by this push:
new 174eb9ee8f fix(services/azblob): fix append conditions, batch delete
correlation, copy SSE, lister, and reader metadata (#8969)
174eb9ee8f is described below
commit 174eb9ee8ffc4f08838c17b54cf9904f294e6828
Author: Xuanwo <[email protected]>
AuthorDate: Tue Nov 24 10:23:56 2026 +0800
fix(services/azblob): fix append conditions, batch delete correlation, copy
SSE, lister, and reader metadata (#8969)
---
core/Cargo.lock | 1 +
core/core/src/raw/http_util/multipart.rs | 7 +-
core/services/azblob/Cargo.toml | 1 +
core/services/azblob/src/backend.rs | 20 +-
core/services/azblob/src/core.rs | 285 +++++++++++++++--
core/services/azblob/src/deleter.rs | 506 +++++++++++++++++++++++++++++--
core/services/azblob/src/lister.rs | 140 ++++++++-
core/services/azblob/src/reader.rs | 60 +++-
core/services/azblob/src/writer.rs | 343 ++++++++++++++++++++-
9 files changed, 1273 insertions(+), 90 deletions(-)
diff --git a/core/Cargo.lock b/core/Cargo.lock
index f8c54b9fd6..cc33c4c395 100644
--- a/core/Cargo.lock
+++ b/core/Cargo.lock
@@ -8059,6 +8059,7 @@ version = "0.59.5"
dependencies = [
"base64 0.23.1",
"bytes",
+ "futures",
"http 1.5.0",
"log",
"opendal-core",
diff --git a/core/core/src/raw/http_util/multipart.rs
b/core/core/src/raw/http_util/multipart.rs
index a03d0397b1..401078b82e 100644
--- a/core/core/src/raw/http_util/multipart.rs
+++ b/core/core/src/raw/http_util/multipart.rs
@@ -397,6 +397,11 @@ impl MixedPart {
self
}
+ /// Return the multipart part headers for this mixed part.
+ pub fn part_headers(&self) -> &HeaderMap {
+ &self.part_headers
+ }
+
/// Set the method for request in this part.
pub fn method(mut self, method: Method) -> Self {
self.method = Some(method);
@@ -1116,7 +1121,7 @@ Content-Length: 846
assert_eq!(multipart.parts.len(), 3);
- assert_eq!(multipart.parts[0].part_headers, {
+ assert_eq!(multipart.parts[0].part_headers(), &{
let mut h = HeaderMap::new();
h.insert("Content-Type", "application/http".parse().unwrap());
h.insert(
diff --git a/core/services/azblob/Cargo.toml b/core/services/azblob/Cargo.toml
index afbe0fcf8b..3b6e0836b4 100644
--- a/core/services/azblob/Cargo.toml
+++ b/core/services/azblob/Cargo.toml
@@ -52,6 +52,7 @@ uuid = { workspace = true, features = ["v4", "serde"] }
reqsign-command-execute-tokio = { version = "3.0.9", default-features = false }
[dev-dependencies]
+futures = { workspace = true }
pretty_assertions = "1"
serde_json = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
diff --git a/core/services/azblob/src/backend.rs
b/core/services/azblob/src/backend.rs
index 5ac7844a1f..e7e3390cf1 100644
--- a/core/services/azblob/src/backend.rs
+++ b/core/services/azblob/src/backend.rs
@@ -44,8 +44,7 @@ use super::core::AzblobCore;
use super::core::ErrorContext;
use super::core::constants::AZBLOB_COPY_MAX_BLOCK_SIZE;
use super::core::constants::AZBLOB_COPY_MIN_BLOCK_SIZE;
-use super::core::constants::X_MS_META_PREFIX;
-use super::core::constants::X_MS_VERSION_ID;
+use super::core::parse_blob_metadata;
use super::core::parse_error;
use super::deleter::AzblobDeleter;
use super::lister::AzblobLister;
@@ -373,7 +372,7 @@ impl Builder for AzblobBuilder {
}
impl AzblobBuilder {
- fn build_backend(self) -> Result<AzblobBackend> {
+ pub(crate) fn build_backend(self) -> Result<AzblobBackend> {
debug!("backend build started: {:?}", self);
let root = normalize_root(&self.config.root.unwrap_or_default());
@@ -672,20 +671,7 @@ impl Service for AzblobBackend {
let status = resp.status();
match status {
- StatusCode::OK => {
- let headers = resp.headers();
- let mut meta = parse_into_metadata(path,
headers)?.into_builder();
- if let Some(version_id) = parse_header_to_str(headers,
X_MS_VERSION_ID)? {
- meta.version(version_id);
- }
-
- let user_meta = parse_prefixed_headers(headers,
X_MS_META_PREFIX);
- if !user_meta.is_empty() {
- meta.user_metadata(user_meta);
- }
-
- Ok(RpStat::new(meta.build()))
- }
+ StatusCode::OK => Ok(RpStat::new(parse_blob_metadata(path,
resp.headers())?)),
_ => Err(parse_error(error_ctx, resp)),
}
}
diff --git a/core/services/azblob/src/core.rs b/core/services/azblob/src/core.rs
index 8e271b75d8..c409774451 100644
--- a/core/services/azblob/src/core.rs
+++ b/core/services/azblob/src/core.rs
@@ -320,8 +320,7 @@ impl AzblobCore {
// the resource does not exist, and fail the operation if it does
exist.
if args.if_not_exists() {
req = req.header(IF_NONE_MATCH, "*");
- }
- if let Some(v) = args.if_none_match() {
+ } else if let Some(v) = args.if_none_match() {
req = req.header(IF_NONE_MATCH, v);
}
@@ -377,6 +376,7 @@ impl AzblobCore {
/// The following custom header could be set:
/// - `content-type`
/// - `x-ms-blob-cache-control`
+ /// - `x-ms-meta-*`
///
/// # Reference
///
@@ -401,6 +401,8 @@ impl AzblobCore {
if args.if_not_exists() {
req = req.header(IF_NONE_MATCH, "*");
+ } else if let Some(v) = args.if_none_match() {
+ req = req.header(IF_NONE_MATCH, v);
}
if let Some(ty) = args.content_type() {
@@ -411,6 +413,12 @@ impl AzblobCore {
req = req.header(constants::X_MS_BLOB_CACHE_CONTROL,
cache_control);
}
+ if let Some(user_metadata) = args.user_metadata() {
+ for (key, value) in user_metadata {
+ req = req.header(format!("{X_MS_META_PREFIX}{key}"), value);
+ }
+ }
+
let req = req
.extension(Operation::Write)
.extension(ServiceOperation("PutBlob"))
@@ -447,6 +455,8 @@ impl AzblobCore {
path: &str,
position: u64,
size: u64,
+ args: &OpWrite,
+ include_conditions: bool,
body: Buffer,
) -> Result<Request<Buffer>> {
let url = format!("{}?comp=appendblock", self.build_path_url(path));
@@ -458,6 +468,15 @@ impl AzblobCore {
// Set SSE headers.
req = self.insert_sse_headers(req);
+ if include_conditions {
+ if let Some(v) = args.if_match() {
+ req = req.header(IF_MATCH, v);
+ }
+ if let Some(v) = args.if_none_match() {
+ req = req.header(IF_NONE_MATCH, v);
+ }
+ }
+
let req = req
.extension(Operation::Write)
.extension(ServiceOperation("AppendBlock"))
@@ -467,15 +486,19 @@ impl AzblobCore {
Ok(req)
}
+ #[allow(clippy::too_many_arguments)]
pub async fn azblob_append_blob(
&self,
ctx: &OperationContext,
path: &str,
position: u64,
size: u64,
+ args: &OpWrite,
+ include_conditions: bool,
body: Buffer,
) -> Result<Response<Buffer>> {
- let req = self.azblob_append_blob_request(path, position, size, body)?;
+ let req =
+ self.azblob_append_blob_request(path, position, size, args,
include_conditions, body)?;
let req = self.sign(ctx, req).await?;
self.send(ctx, req).await
}
@@ -630,9 +653,7 @@ impl AzblobCore {
// write's preconditions have to be evaluated here rather than on Put
Block.
if args.if_not_exists() {
req = req.header(IF_NONE_MATCH, "*");
- }
-
- if let Some(v) = args.if_none_match() {
+ } else if let Some(v) = args.if_none_match() {
req = req.header(IF_NONE_MATCH, v);
}
@@ -686,13 +707,12 @@ impl AzblobCore {
if args.if_not_exists() {
req = req.header(IF_NONE_MATCH, "*");
+ } else if let Some(if_none_match) = args.if_none_match() {
+ req = req.header(IF_NONE_MATCH, if_none_match);
}
if let Some(if_match) = args.if_match() {
req = req.header(IF_MATCH, if_match);
}
- if let Some(if_none_match) = args.if_none_match() {
- req = req.header(IF_NONE_MATCH, if_none_match);
- }
let content = quick_xml::se::to_string(&PutBlockListRequest {
latest: block_ids
@@ -831,16 +851,18 @@ impl AzblobCore {
.header(constants::X_MS_COPY_SOURCE, source_header)
.header(CONTENT_LENGTH, 0);
+ // Set SSE headers.
+ req = self.insert_sse_headers(req);
+
// Add if_not_exists condition using If-None-Match header
if args.if_not_exists() {
req = req.header(IF_NONE_MATCH, "*");
+ } else if let Some(if_none_match) = args.if_none_match() {
+ req = req.header(IF_NONE_MATCH, if_none_match);
}
if let Some(if_match) = args.if_match() {
req = req.header(IF_MATCH, if_match);
}
- if let Some(if_none_match) = args.if_none_match() {
- req = req.header(IF_NONE_MATCH, if_none_match);
- }
req.extension(Operation::Copy)
.extension(ServiceOperation("CopyBlob"))
@@ -1294,6 +1316,174 @@ mod tests {
);
}
+ #[test]
+ fn init_appendable_blob_carries_user_metadata_and_if_none_match() {
+ let core = test_core();
+ let mut meta = HashMap::new();
+ meta.insert("author".to_string(), "alice".to_string());
+ let (args, _) = OpWrite::from_options(
+ &Capability {
+ write_with_if_none_match: true,
+ write_with_user_metadata: true,
+ ..Default::default()
+ },
+ options::WriteOptions {
+ if_none_match: Some("\"etag-1\"".to_owned()),
+ user_metadata: Some(meta),
+ ..Default::default()
+ },
+ )
+ .expect("options must lower");
+
+ let req = core
+ .azblob_init_appendable_blob_request("a.txt", &args)
+ .expect("request must build");
+
+ assert_eq!(
+ req.headers().get(IF_NONE_MATCH),
+ Some(&HeaderValue::from_static("\"etag-1\""))
+ );
+ assert_eq!(
+ req.headers().get("x-ms-meta-author"),
+ Some(&HeaderValue::from_static("alice"))
+ );
+ }
+
+ #[test]
+ fn append_blob_request_attaches_conditions_only_when_requested() {
+ let core = test_core();
+ let (args, _) = OpWrite::from_options(
+ &Capability {
+ write_with_if_match: true,
+ write_with_if_none_match: true,
+ ..Default::default()
+ },
+ options::WriteOptions {
+ if_match: Some("\"etag-1\"".to_owned()),
+ if_none_match: Some("\"etag-2\"".to_owned()),
+ ..Default::default()
+ },
+ )
+ .expect("options must lower");
+
+ let first = core
+ .azblob_append_blob_request("a.txt", 0, 5, &args, true,
Buffer::from("hello"))
+ .expect("first append request must build");
+ assert_eq!(
+ first.headers().get(IF_MATCH),
+ Some(&HeaderValue::from_static("\"etag-1\""))
+ );
+ assert_eq!(
+ first.headers().get(IF_NONE_MATCH),
+ Some(&HeaderValue::from_static("\"etag-2\""))
+ );
+
+ let second = core
+ .azblob_append_blob_request("a.txt", 5, 5, &args, false,
Buffer::from("world"))
+ .expect("second append request must build");
+ assert!(second.headers().get(IF_MATCH).is_none());
+ assert!(second.headers().get(IF_NONE_MATCH).is_none());
+ }
+
+ #[tokio::test]
+ async fn copy_blob_request_includes_sse_headers() {
+ let mut core = test_core();
+ core.encryption_key = Some(HeaderValue::from_static("dGVzdGtleQ=="));
+ core.encryption_key_sha256 =
Some(HeaderValue::from_static("c2hhMjU2"));
+ core.encryption_algorithm = Some(HeaderValue::from_static("AES256"));
+
+ let req = core
+ .azblob_copy_blob_request(
+ &OperationContext::default(),
+ "src.txt",
+ "dst.txt",
+ &OpCopy::default(),
+ )
+ .await
+ .expect("copy request must build");
+
+ let key = req
+ .headers()
+ .get(constants::X_MS_ENCRYPTION_KEY)
+ .expect("encryption key header must be set");
+ assert_eq!(key, "dGVzdGtleQ==");
+ assert!(key.is_sensitive());
+
+ let sha = req
+ .headers()
+ .get(constants::X_MS_ENCRYPTION_KEY_SHA256)
+ .expect("encryption key sha256 header must be set");
+ assert_eq!(sha, "c2hhMjU2");
+ assert!(sha.is_sensitive());
+
+ let alg = req
+ .headers()
+ .get(constants::X_MS_ENCRYPTION_ALGORITHM)
+ .expect("encryption algorithm header must be set");
+ assert_eq!(alg, "AES256");
+ assert!(alg.is_sensitive());
+ }
+
+ #[tokio::test]
+ async fn if_not_exists_and_if_none_match_do_not_emit_duplicate_header() {
+ let core = test_core();
+ let (write_args, _) = OpWrite::from_options(
+ &Capability {
+ write_with_if_not_exists: true,
+ write_with_if_none_match: true,
+ ..Default::default()
+ },
+ options::WriteOptions {
+ if_not_exists: true,
+ if_none_match: Some("\"etag-1\"".to_owned()),
+ ..Default::default()
+ },
+ )
+ .expect("write options must lower");
+
+ for req in [
+ core.azblob_put_blob_request("a.txt", Some(0), &write_args,
Buffer::new())
+ .expect("put blob request must build"),
+ core.azblob_init_appendable_blob_request("a.txt", &write_args)
+ .expect("init append request must build"),
+ core.azblob_complete_put_block_list_request("a.txt",
vec![Uuid::nil()], &write_args)
+ .expect("put block list request must build"),
+ ] {
+ let values: Vec<_> =
req.headers().get_all(IF_NONE_MATCH).iter().collect();
+ assert_eq!(values, vec![&HeaderValue::from_static("*")]);
+ }
+
+ let copy_args = OpCopy::from_options(
+ &Capability {
+ copy_with_if_not_exists: true,
+ copy_with_if_none_match: true,
+ ..Default::default()
+ },
+ options::CopyOptions {
+ if_not_exists: true,
+ if_none_match: Some("\"etag-1\"".to_owned()),
+ ..Default::default()
+ },
+ )
+ .expect("copy options must lower");
+
+ for req in [
+ core.azblob_copy_blob_request(
+ &OperationContext::default(),
+ "a.txt",
+ "b.txt",
+ ©_args,
+ )
+ .await
+ .expect("copy blob request must build"),
+ core.azblob_complete_copy_block_list_request("b.txt",
vec![Uuid::nil()], ©_args)
+ .expect("copy block list request must build"),
+ ] {
+ let values: Vec<_> =
req.headers().get_all(IF_NONE_MATCH).iter().collect();
+ assert_eq!(values, vec![&HeaderValue::from_static("*")]);
+ }
+ }
+
#[test]
fn test_serialize_put_block_list_request() {
let req = PutBlockListRequest {
@@ -1402,8 +1592,30 @@ impl ErrorContext {
}
}
+pub(crate) fn parse_blob_metadata(path: &str, headers: &http::HeaderMap) ->
Result<Metadata> {
+ let mut meta = parse_into_metadata(path, headers)?.into_builder();
+ if let Some(version_id) = parse_header_to_str(headers,
constants::X_MS_VERSION_ID)? {
+ meta.version(version_id);
+ }
+
+ let user_meta = parse_prefixed_headers(headers, X_MS_META_PREFIX);
+ if !user_meta.is_empty() {
+ meta.user_metadata(user_meta);
+ }
+
+ Ok(meta.build())
+}
+
/// Parse error response into Error.
pub fn parse_error(ctx: ErrorContext, resp: Response<Buffer>) -> Error {
+ parse_error_with_code(ctx, resp).0
+}
+
+/// Parse error response into Error together with its Azure error code if
present.
+pub(crate) fn parse_error_with_code(
+ ctx: ErrorContext,
+ resp: Response<Buffer>,
+) -> (Error, Option<String>) {
let (parts, body) = resp.into_parts();
let bs = body.to_bytes();
@@ -1436,11 +1648,14 @@ pub fn parse_error(ctx: ErrorContext, resp:
Response<Buffer>) -> Error {
_ => (ErrorKind::Unexpected, false),
};
- if let Some(azblob_error) = &azblob_error
- && !azblob_error.code.is_empty()
- {
- if let Some(classification) = parse_azblob_error_code(ctx,
&azblob_error.code, parts.status)
- {
+ let error_code = azblob_error
+ .as_ref()
+ .map(|err| err.code.as_str())
+ .filter(|code| !code.is_empty())
+ .map(str::to_owned);
+
+ if let Some(code) = error_code.as_deref() {
+ if let Some(classification) = parse_azblob_error_code(ctx, code,
parts.status) {
(kind, retryable) = classification;
} else if matches!(
parts.status,
@@ -1463,7 +1678,7 @@ pub fn parse_error(ctx: ErrorContext, resp:
Response<Buffer>) -> Error {
err = err.set_temporary();
}
- err
+ (err, error_code)
}
/// Classify documented Blob Storage state errors by native code and status.
@@ -1475,6 +1690,9 @@ fn parse_azblob_error_code(
status: StatusCode,
) -> Option<(ErrorKind, bool)> {
match code {
+ // Although the status code is 404, ContainerNotFound indicates a
missing
+ // or misconfigured container rather than a missing blob.
+ "ContainerNotFound" => Some((ErrorKind::ConfigInvalid, false)),
"ConditionNotMet" | "SourceConditionNotMet" | "TargetConditionNotMet"
if ctx.caller_condition
&& matches!(
@@ -1608,4 +1826,35 @@ mod error_tests {
assert!(!err.is_temporary(), "status {status}");
}
}
+
+ #[test]
+ fn container_not_found_is_config_invalid() {
+ let xml = r#"<?xml version="1.0" encoding="utf-8"?>
+<Error>
+ <Code>ContainerNotFound</Code>
+ <Message>The specified container does not exist.</Message>
+</Error>"#;
+ let resp = Response::builder()
+ .status(StatusCode::NOT_FOUND)
+ .header("x-ms-error-code", "ContainerNotFound")
+ .body(Buffer::from(xml))
+ .unwrap();
+ let (err, code) =
+
parse_error_with_code(ErrorContext::new(ServiceOperation("DeleteBlob")), resp);
+ assert_eq!(code.as_deref(), Some("ContainerNotFound"));
+ assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
+ assert!(!err.is_temporary());
+
+ let header_only_resp = Response::builder()
+ .status(StatusCode::NOT_FOUND)
+ .header("x-ms-error-code", "ContainerNotFound")
+ .body(Buffer::new())
+ .unwrap();
+ let err = parse_error(
+ ErrorContext::new(ServiceOperation("GetBlobProperties")),
+ header_only_resp,
+ );
+ assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
+ assert!(!err.is_temporary());
+ }
}
diff --git a/core/services/azblob/src/deleter.rs
b/core/services/azblob/src/deleter.rs
index 43f6a98cc0..ace3ffb6de 100644
--- a/core/services/azblob/src/deleter.rs
+++ b/core/services/azblob/src/deleter.rs
@@ -20,11 +20,54 @@ use std::sync::Arc;
use http::StatusCode;
use super::core::parse_error;
+use super::core::parse_error_with_code;
use super::core::*;
use opendal_core::raw::oio::BatchDeleteResult;
use opendal_core::raw::*;
use opendal_core::*;
+fn is_missing_blob_code(code: Option<&str>) -> bool {
+ matches!(code, Some("BlobNotFound" | "ParentNotFound"))
+}
+
+fn parse_batch_content_id(part: &MixedPart, batch_len: usize) -> Result<usize>
{
+ let mut values = part.part_headers().get_all("content-id").iter();
+ let Some(value) = values.next() else {
+ return Err(Error::new(
+ ErrorKind::Unexpected,
+ "invalid batch response: part is missing Content-ID header",
+ ));
+ };
+ if values.next().is_some() {
+ return Err(Error::new(
+ ErrorKind::Unexpected,
+ "invalid batch response: part contains duplicate Content-ID
header",
+ ));
+ }
+
+ let raw = value.to_str().map_err(|err| {
+ Error::new(
+ ErrorKind::Unexpected,
+ "invalid batch response: Content-ID header is not valid UTF-8",
+ )
+ .set_source(err)
+ })?;
+ let idx = raw.trim().parse::<usize>().map_err(|err| {
+ Error::new(
+ ErrorKind::Unexpected,
+ "invalid batch response: Content-ID header is not a valid index",
+ )
+ .set_source(err)
+ })?;
+ if idx >= batch_len {
+ return Err(Error::new(
+ ErrorKind::Unexpected,
+ "invalid batch response: Content-ID index out of bounds",
+ ));
+ }
+ Ok(idx)
+}
+
pub struct AzblobDeleter {
core: Arc<AzblobCore>,
ctx: OperationContext,
@@ -38,6 +81,8 @@ impl AzblobDeleter {
impl oio::BatchDelete for AzblobDeleter {
async fn delete_once(&self, path: String, args: OpDelete) -> Result<()> {
+ let error_ctx = ErrorContext::new(ServiceOperation("DeleteBlob"))
+ .with_caller_condition(args.is_conditional());
let resp = self
.core
.azblob_delete_blob(&self.ctx, &path, &args)
@@ -47,16 +92,23 @@ impl oio::BatchDelete for AzblobDeleter {
match status {
StatusCode::ACCEPTED => Ok(()),
- StatusCode::NOT_FOUND if args.if_match().is_some() =>
Err(Error::new(
- ErrorKind::ConditionNotMatch,
- "delete precondition requires a live target",
- )),
- StatusCode::NOT_FOUND => Ok(()),
- _ => Err(parse_error(
- ErrorContext::new(ServiceOperation("DeleteBlob"))
- .with_caller_condition(args.is_conditional()),
- resp,
- )),
+ // Parse 404 responses before treating them as idempotent success
so
+ // container-level errors such as ContainerNotFound still surface.
+ StatusCode::NOT_FOUND => {
+ let (err, code) = parse_error_with_code(error_ctx, resp);
+ if !is_missing_blob_code(code.as_deref()) {
+ Err(err)
+ } else if args.if_match().is_some() {
+ Err(Error::new(
+ ErrorKind::ConditionNotMatch,
+ "delete precondition requires a live target",
+ )
+ .set_source(err))
+ } else {
+ Ok(())
+ }
+ }
+ _ => Err(parse_error(error_ctx, resp)),
}
}
@@ -95,34 +147,61 @@ impl oio::BatchDelete for AzblobDeleter {
));
}
+ let has_content_id = parts
+ .iter()
+ .any(|part| part.part_headers().contains_key("content-id"));
+ let batch_len = batch.len();
+ let mut pending: Vec<Option<(String, OpDelete)>> =
batch.into_iter().map(Some).collect();
+
let mut batched_result = BatchDeleteResult::default();
- for (part, (path, args)) in parts.into_iter().zip(batch) {
+ for (pos, part) in parts.into_iter().enumerate() {
+ let idx = if has_content_id {
+ parse_batch_content_id(&part, batch_len)?
+ } else {
+ pos
+ };
+ let Some((path, args)) = pending[idx].take() else {
+ return Err(Error::new(
+ ErrorKind::Unexpected,
+ "invalid batch response: duplicate Content-ID",
+ ));
+ };
let resp = part.into_response();
+ let error_ctx =
ErrorContext::new(ServiceOperation("BatchDeleteBlobs"))
+ .with_caller_condition(args.is_conditional());
- if resp.status() == StatusCode::NOT_FOUND &&
args.if_match().is_some() {
- batched_result.failed.push((
- path,
- args,
- Error::new(
- ErrorKind::ConditionNotMatch,
- "delete precondition requires a live target",
- ),
- ));
- } else if resp.status() == StatusCode::ACCEPTED
- || resp.status() == StatusCode::NOT_FOUND
- {
- batched_result.succeeded.push((path, args));
- } else {
- let error_ctx =
ErrorContext::new(ServiceOperation("BatchDeleteBlobs"))
- .with_caller_condition(args.is_conditional());
- let err = parse_error(error_ctx, resp);
- batched_result.failed.push((path, args, err));
+ match resp.status() {
+ StatusCode::ACCEPTED => {
+ batched_result.succeeded.push((path, args));
+ }
+ StatusCode::NOT_FOUND => {
+ let (err, code) = parse_error_with_code(error_ctx, resp);
+ if !is_missing_blob_code(code.as_deref()) {
+ batched_result.failed.push((path, args, err));
+ } else if args.if_match().is_some() {
+ batched_result.failed.push((
+ path,
+ args,
+ Error::new(
+ ErrorKind::ConditionNotMatch,
+ "delete precondition requires a live target",
+ )
+ .set_source(err),
+ ));
+ } else {
+ batched_result.succeeded.push((path, args));
+ }
+ }
+ _ => {
+ let err = parse_error(error_ctx, resp);
+ batched_result.failed.push((path, args, err));
+ }
}
}
// If no object is deleted, return directly.
- if batched_result.succeeded.is_empty() {
+ if batched_result.succeeded.is_empty() &&
!batched_result.failed.is_empty() {
let err = batched_result.failed.remove(0).2;
return Err(err);
}
@@ -130,3 +209,370 @@ impl oio::BatchDelete for AzblobDeleter {
Ok(batched_result)
}
}
+
+#[cfg(test)]
+mod tests {
+ use std::error::Error as StdError;
+ use std::sync::atomic::AtomicUsize;
+ use std::sync::atomic::Ordering;
+
+ use bytes::Bytes;
+ use http::Request;
+ use http::Response;
+ use http::StatusCode;
+ use http::header::CONTENT_TYPE;
+ use opendal_core::raw::oio::BatchDelete;
+
+ use super::*;
+ use crate::backend::AzblobBuilder;
+
+ const CONTAINER_NOT_FOUND_XML: &str = r#"<?xml version="1.0"
encoding="utf-8"?>
+<Error>
+ <Code>ContainerNotFound</Code>
+ <Message>The specified container does not exist.</Message>
+</Error>"#;
+
+ const BLOB_NOT_FOUND_XML: &str = r#"<?xml version="1.0" encoding="utf-8"?>
+<Error>
+ <Code>BlobNotFound</Code>
+ <Message>The specified blob does not exist.</Message>
+</Error>"#;
+
+ const PARENT_NOT_FOUND_XML: &str = r#"<?xml version="1.0"
encoding="utf-8"?>
+<Error>
+ <Code>ParentNotFound</Code>
+ <Message>The specified parent path does not exist.</Message>
+</Error>"#;
+
+ const RESOURCE_NOT_FOUND_XML: &str = r#"<?xml version="1.0"
encoding="utf-8"?>
+<Error>
+ <Code>ResourceNotFound</Code>
+ <Message>The specified resource does not exist.</Message>
+</Error>"#;
+
+ #[derive(Clone)]
+ struct StaticTransport {
+ status: StatusCode,
+ headers: Vec<(&'static str, &'static str)>,
+ body: String,
+ requests: Arc<AtomicUsize>,
+ }
+
+ impl StaticTransport {
+ fn new(
+ status: StatusCode,
+ headers: Vec<(&'static str, &'static str)>,
+ body: impl Into<String>,
+ ) -> Self {
+ Self {
+ status,
+ headers,
+ body: body.into(),
+ requests: Arc::new(AtomicUsize::new(0)),
+ }
+ }
+ }
+
+ impl HttpTransport for StaticTransport {
+ async fn fetch(&self, _req: Request<Buffer>) ->
Result<Response<HttpBody>> {
+ self.requests.fetch_add(1, Ordering::Relaxed);
+ let mut builder = Response::builder().status(self.status);
+ for (k, v) in &self.headers {
+ builder = builder.header(*k, *v);
+ }
+ let bytes = Bytes::from(self.body.clone());
+ let size = bytes.len() as u64;
+ let body = if bytes.is_empty() {
+ HttpBody::new(futures::stream::iter(std::iter::empty()),
Some(0))
+ } else {
+ HttpBody::new(
+ futures::stream::iter(vec![Ok(Buffer::from(bytes))]),
+ Some(size),
+ )
+ };
+ Ok(builder.body(body).expect("mock response must build"))
+ }
+ }
+
+ fn deleter_with_transport(transport: StaticTransport) -> AzblobDeleter {
+ let backend = AzblobBuilder::default()
+ .container("test")
+ .endpoint("https://myaccount.blob.core.windows.net")
+ .skip_signature()
+ .build_backend()
+ .expect("azblob backend must build");
+ let ctx =
OperationContext::new().with_http_transport(HttpTransporter::new(transport));
+ AzblobDeleter::new(backend.core, ctx)
+ }
+
+ fn op_delete_if_match(etag: &str) -> OpDelete {
+ OpDelete::from_options(
+ &Capability {
+ delete_with_if_match: true,
+ ..Default::default()
+ },
+ options::DeleteOptions {
+ if_match: Some(etag.to_string()),
+ ..Default::default()
+ },
+ )
+ .expect("delete options must lower")
+ }
+
+ #[tokio::test]
+ async fn delete_once_surfaces_container_not_found_and_non_blob_404() {
+ let deleter = deleter_with_transport(StaticTransport::new(
+ StatusCode::NOT_FOUND,
+ vec![("x-ms-error-code", "ContainerNotFound")],
+ CONTAINER_NOT_FOUND_XML,
+ ));
+
+ let err = deleter
+ .delete_once("a".to_string(), OpDelete::default())
+ .await
+ .expect_err("ContainerNotFound must not be masked as Ok");
+ assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
+ assert!(!err.is_temporary());
+
+ let err = deleter
+ .delete_once("a".to_string(), op_delete_if_match("\"etag\""))
+ .await
+ .expect_err("ContainerNotFound must not be masked as
ConditionNotMatch");
+ assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
+
+ let resource_not_found_deleter =
deleter_with_transport(StaticTransport::new(
+ StatusCode::NOT_FOUND,
+ vec![("x-ms-error-code", "ResourceNotFound")],
+ RESOURCE_NOT_FOUND_XML,
+ ));
+ let err = resource_not_found_deleter
+ .delete_once("a".to_string(), OpDelete::default())
+ .await
+ .expect_err("ResourceNotFound must not be treated as missing
blob");
+ assert_eq!(err.kind(), ErrorKind::NotFound);
+ }
+
+ #[tokio::test]
+ async fn delete_once_accepts_blob_not_found_and_parent_not_found() {
+ for (code, body) in [
+ ("BlobNotFound", BLOB_NOT_FOUND_XML),
+ ("ParentNotFound", PARENT_NOT_FOUND_XML),
+ ] {
+ let deleter = deleter_with_transport(StaticTransport::new(
+ StatusCode::NOT_FOUND,
+ vec![("x-ms-error-code", code)],
+ body,
+ ));
+
+ deleter
+ .delete_once("missing".to_string(), OpDelete::default())
+ .await
+ .expect("unconditional missing blob delete should succeed");
+
+ let err = deleter
+ .delete_once("missing".to_string(),
op_delete_if_match("\"etag\""))
+ .await
+ .expect_err("conditional missing blob delete must fail");
+ assert_eq!(err.kind(), ErrorKind::ConditionNotMatch);
+ assert!(StdError::source(&err).is_some());
+ }
+ }
+
+ #[tokio::test]
+ async fn delete_batch_correlates_out_of_order_content_id_responses() {
+ let boundary = "batchresponse_test";
+ let body = format!(
+ "--{boundary}\r\n\
+Content-Type: application/http\r\n\
+Content-ID: 1\r\n\
+\r\n\
+HTTP/1.1 412 The condition specified using HTTP conditional header(s) is not
met.\r\n\
+x-ms-error-code: ConditionNotMet\r\n\
+content-type: application/xml\r\n\
+\r\n\
+<Error><Code>ConditionNotMet</Code><Message>Precondition
failed</Message></Error>\r\n\
+--{boundary}\r\n\
+Content-Type: application/http\r\n\
+Content-ID: 0\r\n\
+\r\n\
+HTTP/1.1 202 Accepted\r\n\
+x-ms-request-id: req-0\r\n\
+\r\n\
+--{boundary}--\r\n"
+ );
+ let deleter = deleter_with_transport(StaticTransport::new(
+ StatusCode::ACCEPTED,
+ vec![(
+ CONTENT_TYPE.as_str(),
+ "multipart/mixed; boundary=batchresponse_test",
+ )],
+ body,
+ ));
+
+ let result = deleter
+ .delete_batch(vec![
+ ("first".to_string(), OpDelete::default()),
+ ("second".to_string(), op_delete_if_match("\"stale\"")),
+ ])
+ .await
+ .expect("batch with partial success should return
BatchDeleteResult");
+
+ assert_eq!(result.succeeded.len(), 1);
+ assert_eq!(result.succeeded[0].0, "first");
+ assert_eq!(result.failed.len(), 1);
+ assert_eq!(result.failed[0].0, "second");
+ assert_eq!(result.failed[0].2.kind(), ErrorKind::ConditionNotMatch);
+ }
+
+ #[tokio::test]
+ async fn
delete_batch_rejects_duplicate_missing_or_out_of_bounds_content_id() {
+ let boundary = "batchresponse_invalid";
+ let cases = [
+ // Duplicate Content-ID: 0
+ format!(
+ "--{boundary}\r\nContent-Type: application/http\r\nContent-ID:
0\r\n\r\nHTTP/1.1 202 Accepted\r\n\r\n\
+--{boundary}\r\nContent-Type: application/http\r\nContent-ID:
0\r\n\r\nHTTP/1.1 202 Accepted\r\n\r\n--{boundary}--\r\n"
+ ),
+ // Out of bounds Content-ID: 2
+ format!(
+ "--{boundary}\r\nContent-Type: application/http\r\nContent-ID:
0\r\n\r\nHTTP/1.1 202 Accepted\r\n\r\n\
+--{boundary}\r\nContent-Type: application/http\r\nContent-ID:
2\r\n\r\nHTTP/1.1 202 Accepted\r\n\r\n--{boundary}--\r\n"
+ ),
+ // Missing Content-ID on second part while first has it
+ format!(
+ "--{boundary}\r\nContent-Type: application/http\r\nContent-ID:
0\r\n\r\nHTTP/1.1 202 Accepted\r\n\r\n\
+--{boundary}\r\nContent-Type: application/http\r\n\r\nHTTP/1.1 202
Accepted\r\n\r\n--{boundary}--\r\n"
+ ),
+ ];
+
+ for body in cases {
+ let deleter = deleter_with_transport(StaticTransport::new(
+ StatusCode::ACCEPTED,
+ vec![(
+ CONTENT_TYPE.as_str(),
+ "multipart/mixed; boundary=batchresponse_invalid",
+ )],
+ body,
+ ));
+
+ let err = deleter
+ .delete_batch(vec![
+ ("a".to_string(), OpDelete::default()),
+ ("b".to_string(), OpDelete::default()),
+ ])
+ .await
+ .err()
+ .expect("malformed Content-ID batch must fail");
+ assert_eq!(err.kind(), ErrorKind::Unexpected);
+ }
+ }
+
+ #[tokio::test]
+ async fn
delete_batch_surfaces_container_not_found_and_handles_missing_blobs() {
+ let boundary = "batchresponse_404";
+ let all_missing_container = format!(
+ "--{boundary}\r\n\
+Content-Type: application/http\r\n\
+Content-ID: 0\r\n\
+\r\n\
+HTTP/1.1 404 Not Found\r\n\
+x-ms-error-code: ContainerNotFound\r\n\
+content-type: application/xml\r\n\
+\r\n\
+{CONTAINER_NOT_FOUND_XML}\r\n\
+--{boundary}--\r\n"
+ );
+ let deleter = deleter_with_transport(StaticTransport::new(
+ StatusCode::ACCEPTED,
+ vec![(
+ CONTENT_TYPE.as_str(),
+ "multipart/mixed; boundary=batchresponse_404",
+ )],
+ all_missing_container,
+ ));
+
+ let err = deleter
+ .delete_batch(vec![("a".to_string(), OpDelete::default())])
+ .await
+ .err()
+ .expect("ContainerNotFound in batch delete must not succeed");
+ assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
+
+ let mixed = format!(
+ "--{boundary}\r\n\
+Content-Type: application/http\r\n\
+Content-ID: 0\r\n\
+\r\n\
+HTTP/1.1 404 Not Found\r\n\
+x-ms-error-code: BlobNotFound\r\n\
+content-type: application/xml\r\n\
+\r\n\
+{BLOB_NOT_FOUND_XML}\r\n\
+--{boundary}\r\n\
+Content-Type: application/http\r\n\
+Content-ID: 1\r\n\
+\r\n\
+HTTP/1.1 404 Not Found\r\n\
+x-ms-error-code: ContainerNotFound\r\n\
+content-type: application/xml\r\n\
+\r\n\
+{CONTAINER_NOT_FOUND_XML}\r\n\
+--{boundary}--\r\n"
+ );
+ let deleter = deleter_with_transport(StaticTransport::new(
+ StatusCode::ACCEPTED,
+ vec![(
+ CONTENT_TYPE.as_str(),
+ "multipart/mixed; boundary=batchresponse_404",
+ )],
+ mixed,
+ ));
+
+ let result = deleter
+ .delete_batch(vec![
+ ("missing-blob".to_string(), OpDelete::default()),
+ ("missing-container".to_string(), OpDelete::default()),
+ ])
+ .await
+ .expect("mixed batch should report partial result");
+ assert_eq!(result.succeeded.len(), 1);
+ assert_eq!(result.succeeded[0].0, "missing-blob");
+ assert_eq!(result.failed.len(), 1);
+ assert_eq!(result.failed[0].0, "missing-container");
+ assert_eq!(result.failed[0].2.kind(), ErrorKind::ConfigInvalid);
+
+ // Positional fallback when all parts omit Content-ID.
+ let no_content_id = format!(
+ "--{boundary}\r\n\
+Content-Type: application/http\r\n\
+\r\n\
+HTTP/1.1 202 Accepted\r\n\
+\r\n\
+--{boundary}\r\n\
+Content-Type: application/http\r\n\
+\r\n\
+HTTP/1.1 404 Not Found\r\n\
+x-ms-error-code: ParentNotFound\r\n\
+\r\n\
+{PARENT_NOT_FOUND_XML}\r\n\
+--{boundary}--\r\n"
+ );
+ let deleter = deleter_with_transport(StaticTransport::new(
+ StatusCode::ACCEPTED,
+ vec![(
+ CONTENT_TYPE.as_str(),
+ "multipart/mixed; boundary=batchresponse_404",
+ )],
+ no_content_id,
+ ));
+ let result = deleter
+ .delete_batch(vec![
+ ("a".to_string(), OpDelete::default()),
+ ("b".to_string(), OpDelete::default()),
+ ])
+ .await
+ .expect("positional fallback without Content-ID should succeed");
+ assert_eq!(result.succeeded.len(), 2);
+ assert!(result.failed.is_empty());
+ }
+}
diff --git a/core/services/azblob/src/lister.rs
b/core/services/azblob/src/lister.rs
index 83b11b3688..11161a093c 100644
--- a/core/services/azblob/src/lister.rs
+++ b/core/services/azblob/src/lister.rs
@@ -84,10 +84,8 @@ impl oio::PageList for AzblobLister {
// Try our best to check whether this list is done.
//
// - Check `next_marker`
- if let Some(next_marker) = output.next_marker.as_ref() {
- ctx.done = next_marker.is_empty();
- };
- ctx.token = output.next_marker.clone().unwrap_or_default();
+ ctx.done = output.next_marker.as_deref().is_none_or(str::is_empty);
+ ctx.token = output.next_marker.unwrap_or_default();
let prefixes = output.blobs.blob_prefix;
@@ -111,12 +109,25 @@ impl oio::PageList for AzblobLister {
} else {
MetadataBuilder::file(object.properties.content_length)
};
- meta.etag(format!("\"{}\"", object.properties.etag.as_str()))
- .content_md5(object.properties.content_md5)
- .content_type(object.properties.content_type)
- .last_modified(Timestamp::parse_rfc2822(
+ if !object.properties.etag.is_empty() {
+ let etag = object.properties.etag.as_str();
+ if etag.starts_with('"') && etag.ends_with('"') && etag.len()
>= 2 {
+ meta.etag(etag);
+ } else {
+ meta.etag(format!("\"{etag}\""));
+ }
+ }
+ if !object.properties.content_md5.is_empty() {
+ meta.content_md5(object.properties.content_md5);
+ }
+ if !object.properties.content_type.is_empty() {
+ meta.content_type(object.properties.content_type);
+ }
+ if !object.properties.last_modified.is_empty() {
+ meta.last_modified(Timestamp::parse_rfc2822(
object.properties.last_modified.as_str(),
)?);
+ }
let de = oio::Entry::with(path, meta.build());
ctx.entries.push_back(de);
@@ -125,3 +136,116 @@ impl oio::PageList for AzblobLister {
Ok(())
}
}
+
+#[cfg(test)]
+mod tests {
+ use std::sync::Arc;
+ use std::sync::atomic::AtomicUsize;
+ use std::sync::atomic::Ordering;
+
+ use bytes::Bytes;
+ use http::Request;
+ use http::Response;
+ use http::StatusCode;
+ use opendal_core::*;
+
+ use crate::backend::AzblobBuilder;
+
+ #[derive(Clone)]
+ struct SinglePageListTransport {
+ body: &'static str,
+ requests: Arc<AtomicUsize>,
+ }
+
+ impl HttpTransport for SinglePageListTransport {
+ async fn fetch(&self, _req: Request<Buffer>) ->
Result<Response<HttpBody>> {
+ let n = self.requests.fetch_add(1, Ordering::Relaxed) + 1;
+ assert!(
+ n <= 2,
+ "list must not loop infinitely when NextMarker is absent"
+ );
+ let bytes = Bytes::from_static(self.body.as_bytes());
+ let size = bytes.len() as u64;
+ Ok(Response::builder()
+ .status(StatusCode::OK)
+ .body(HttpBody::new(
+ futures::stream::iter(vec![Ok(Buffer::from(bytes))]),
+ Some(size),
+ ))
+ .expect("mock response must build"))
+ }
+ }
+
+ #[tokio::test]
+ async fn list_stops_when_next_marker_missing_and_skips_empty_properties() {
+ let xml = r#"<?xml version="1.0" encoding="utf-8"?>
+<EnumerationResults ServiceEndpoint="https://myaccount.blob.core.windows.net/"
ContainerName="test">
+ <Blobs>
+ <Blob>
+ <Name>append.log</Name>
+ <Properties>
+ <Last-Modified>Tue, 24 Nov 2026 01:24:30 GMT</Last-Modified>
+ <Etag>0x8D123</Etag>
+ <Content-Length>12</Content-Length>
+ <Content-Type />
+ <Content-MD5 />
+ </Properties>
+ </Blob>
+ <Blob>
+ <Name>quoted.bin</Name>
+ <Properties>
+ <Last-Modified>Tue, 24 Nov 2026 01:24:30 GMT</Last-Modified>
+ <Etag>"0x8D456"</Etag>
+ <Content-Length>34</Content-Length>
+ <Content-Type>application/octet-stream</Content-Type>
+ <Content-MD5>llJ/+jOlx5GdA1sL7SdKuw==</Content-MD5>
+ </Properties>
+ </Blob>
+ <Blob>
+ <Name>no-etag.bin</Name>
+ <Properties>
+ <Last-Modified>Tue, 24 Nov 2026 01:24:30 GMT</Last-Modified>
+ <Etag />
+ <Content-Length>0</Content-Length>
+ </Properties>
+ </Blob>
+ </Blobs>
+</EnumerationResults>"#;
+
+ let requests = Arc::new(AtomicUsize::new(0));
+ let transport = SinglePageListTransport {
+ body: xml,
+ requests: requests.clone(),
+ };
+ let op = Operator::new(
+ AzblobBuilder::default()
+ .container("test")
+ .endpoint("https://myaccount.blob.core.windows.net")
+ .skip_signature(),
+ )
+ .expect("azblob operator must build")
+
.with_context(OperationContext::new().with_http_transport(HttpTransporter::new(transport)));
+
+ let entries = op.list("").await.expect("list must terminate cleanly");
+ assert_eq!(requests.load(Ordering::Relaxed), 1);
+
+ let by_path: std::collections::HashMap<_, _> = entries
+ .into_iter()
+ .map(|e| (e.path().to_string(), e.metadata().clone()))
+ .collect();
+
+ let append_meta = &by_path["append.log"];
+ assert_eq!(append_meta.etag(), Some("\"0x8D123\""));
+ assert_eq!(append_meta.content_md5(), None);
+ assert_eq!(append_meta.content_type(), None);
+
+ let quoted_meta = &by_path["quoted.bin"];
+ assert_eq!(quoted_meta.etag(), Some("\"0x8D456\""));
+ assert_eq!(quoted_meta.content_md5(),
Some("llJ/+jOlx5GdA1sL7SdKuw=="));
+ assert_eq!(quoted_meta.content_type(),
Some("application/octet-stream"));
+
+ let no_etag_meta = &by_path["no-etag.bin"];
+ assert_eq!(no_etag_meta.etag(), None);
+ assert_eq!(no_etag_meta.content_md5(), None);
+ }
+}
diff --git a/core/services/azblob/src/reader.rs
b/core/services/azblob/src/reader.rs
index 537405cc5d..c74163de18 100644
--- a/core/services/azblob/src/reader.rs
+++ b/core/services/azblob/src/reader.rs
@@ -17,6 +17,7 @@
use super::backend::*;
use super::core::ErrorContext;
+use super::core::parse_blob_metadata;
use super::core::parse_error;
use http::Response;
use http::StatusCode;
@@ -62,7 +63,7 @@ impl oio::StreamRead for AzblobReader {
let status = resp.status();
let (rp, stream) = match status {
StatusCode::OK | StatusCode::PARTIAL_CONTENT => (
- RpRead::new(parse_into_metadata(path, resp.headers())?),
+ RpRead::new(parse_blob_metadata(path, resp.headers())?),
resp.into_body(),
),
_ => {
@@ -75,3 +76,60 @@ impl oio::StreamRead for AzblobReader {
Ok((rp, Box::new(stream) as Box<dyn oio::ReadStreamDyn>))
}
}
+
+#[cfg(test)]
+mod tests {
+ use bytes::Bytes;
+ use http::Request;
+ use http::Response;
+ use http::StatusCode;
+ use opendal_core::raw::oio::StreamRead;
+
+ use super::*;
+
+ #[derive(Clone)]
+ struct StaticGetTransport;
+
+ impl HttpTransport for StaticGetTransport {
+ async fn fetch(&self, _req: Request<Buffer>) ->
Result<Response<HttpBody>> {
+ let body = Bytes::from_static(b"hello");
+ Ok(Response::builder()
+ .status(StatusCode::OK)
+ .header("content-length", "5")
+ .header("etag", "\"0x8D123\"")
+ .header("x-ms-version-id", "2024-01-01T00:00:00.0000000Z")
+ .header("x-ms-meta-author", "alice")
+ .header("x-ms-meta-env", "prod")
+ .body(HttpBody::new(
+ futures::stream::iter(vec![Ok(Buffer::from(body))]),
+ Some(5),
+ ))
+ .expect("mock response must build"))
+ }
+ }
+
+ #[tokio::test]
+ async fn reader_open_extracts_version_id_and_user_metadata() {
+ let backend = AzblobBuilder::default()
+ .container("test")
+ .endpoint("https://myaccount.blob.core.windows.net")
+ .skip_signature()
+ .build_backend()
+ .expect("azblob backend must build");
+ let ctx =
+
OperationContext::new().with_http_transport(HttpTransporter::new(StaticGetTransport));
+ let reader = AzblobReader::new(backend, ctx, "a.txt",
OpRead::default());
+
+ let (rp, _stream) = reader
+ .open(BytesRange::from(..))
+ .await
+ .expect("reader open must succeed");
+ let meta = rp.metadata().expect("metadata must be present");
+
+ assert_eq!(meta.version(), Some("2024-01-01T00:00:00.0000000Z"));
+ assert_eq!(meta.etag(), Some("\"0x8D123\""));
+ let user_meta = meta.user_metadata().expect("user metadata must be
parsed");
+ assert_eq!(user_meta.get("author"), Some("alice"));
+ assert_eq!(user_meta.get("env"), Some("prod"));
+ }
+}
diff --git a/core/services/azblob/src/writer.rs
b/core/services/azblob/src/writer.rs
index 0e0ae2a151..029d969b36 100644
--- a/core/services/azblob/src/writer.rs
+++ b/core/services/azblob/src/writer.rs
@@ -16,6 +16,8 @@
// under the License.
use std::sync::Arc;
+use std::sync::atomic::AtomicBool;
+use std::sync::atomic::Ordering;
use http::StatusCode;
use uuid::Uuid;
@@ -37,6 +39,7 @@ pub struct AzblobWriter {
op: OpWrite,
path: String,
+ conditions_checked: AtomicBool,
}
impl AzblobWriter {
@@ -46,6 +49,7 @@ impl AzblobWriter {
ctx,
op,
path,
+ conditions_checked: AtomicBool::new(false),
}
}
@@ -105,6 +109,21 @@ impl oio::AppendWrite for AzblobWriter {
Ok(parse_content_length(headers)?.unwrap_or_default())
}
StatusCode::NOT_FOUND => {
+ let err = parse_error(
+ ErrorContext::new(ServiceOperation("GetBlobProperties")),
+ resp,
+ );
+ if err.kind() != ErrorKind::NotFound {
+ return Err(err);
+ }
+ if self.op.if_match().is_some() {
+ return Err(Error::new(
+ ErrorKind::ConditionNotMatch,
+ "write precondition requires a live target",
+ )
+ .set_source(err));
+ }
+
let resp = self
.core
.azblob_init_appendable_blob(&self.ctx, &self.path,
&self.op)
@@ -113,12 +132,11 @@ impl oio::AppendWrite for AzblobWriter {
let status = resp.status();
match status {
StatusCode::CREATED => {
- // do nothing
+ self.conditions_checked.store(true, Ordering::Relaxed);
}
_ => {
return Err(parse_error(
- ErrorContext::new(ServiceOperation("PutBlob"))
- .with_if_not_exists(self.op.if_not_exists())
+ self.error_context(ServiceOperation("PutBlob"))
.with_append_blob_initialization(true),
resp,
));
@@ -134,38 +152,96 @@ impl oio::AppendWrite for AzblobWriter {
}
async fn append(&self, offset: u64, size: u64, body: Buffer) ->
Result<Metadata> {
+ let include_conditions =
!self.conditions_checked.load(Ordering::Relaxed);
+
// Azure rejects `Append Block` with an empty body, and an empty append
// changes nothing, so read the blob properties instead of appending.
if size == 0 {
+ let stat_args = if include_conditions {
+ OpStat::from(options::StatOptions {
+ if_match: self.op.if_match().map(str::to_owned),
+ if_none_match: self.op.if_none_match().map(str::to_owned),
+ ..Default::default()
+ })
+ } else {
+ OpStat::default()
+ };
+ let error_ctx = if include_conditions {
+ self.error_context(ServiceOperation("GetBlobProperties"))
+ } else {
+ ErrorContext::new(ServiceOperation("GetBlobProperties"))
+ };
+
let resp = self
.core
- .azblob_get_blob_properties(&self.ctx, &self.path,
&OpStat::default())
+ .azblob_get_blob_properties(&self.ctx, &self.path, &stat_args)
.await?;
let meta = AzblobWriter::parse_metadata(resp.headers())?;
let status = resp.status();
return match status {
- StatusCode::OK => Ok(meta),
- _ => Err(parse_error(
- ErrorContext::new(ServiceOperation("GetBlobProperties")),
- resp,
- )),
+ StatusCode::OK => {
+ self.conditions_checked.store(true, Ordering::Relaxed);
+ Ok(meta)
+ }
+ _ => {
+ let err = parse_error(error_ctx, resp);
+ if include_conditions
+ && self.op.if_match().is_some()
+ && err.kind() == ErrorKind::NotFound
+ {
+ Err(Error::new(
+ ErrorKind::ConditionNotMatch,
+ "write precondition requires a live target",
+ )
+ .set_source(err))
+ } else {
+ Err(err)
+ }
+ }
};
}
let resp = self
.core
- .azblob_append_blob(&self.ctx, &self.path, offset, size, body)
+ .azblob_append_blob(
+ &self.ctx,
+ &self.path,
+ offset,
+ size,
+ &self.op,
+ include_conditions,
+ body,
+ )
.await?;
let meta = AzblobWriter::parse_metadata(resp.headers())?;
let status = resp.status();
match status {
- StatusCode::CREATED => Ok(meta),
- _ => Err(parse_error(
- ErrorContext::new(ServiceOperation("AppendBlock")),
- resp,
- )),
+ StatusCode::CREATED => {
+ self.conditions_checked.store(true, Ordering::Relaxed);
+ Ok(meta)
+ }
+ _ => {
+ let error_ctx = if include_conditions {
+ self.error_context(ServiceOperation("AppendBlock"))
+ } else {
+ ErrorContext::new(ServiceOperation("AppendBlock"))
+ };
+ let err = parse_error(error_ctx, resp);
+ if include_conditions
+ && self.op.if_match().is_some()
+ && err.kind() == ErrorKind::NotFound
+ {
+ Err(Error::new(
+ ErrorKind::ConditionNotMatch,
+ "write precondition requires a live target",
+ )
+ .set_source(err))
+ } else {
+ Err(err)
+ }
+ }
}
}
}
@@ -233,3 +309,240 @@ impl oio::BlockWrite for AzblobWriter {
Ok(())
}
}
+
+#[cfg(test)]
+mod tests {
+ use std::collections::VecDeque;
+ use std::sync::Arc;
+ use std::sync::Mutex;
+
+ use bytes::Bytes;
+ use http::HeaderMap;
+ use http::Method;
+ use http::Request;
+ use http::Response;
+ use http::StatusCode;
+ use http::header::IF_MATCH;
+ use http::header::IF_NONE_MATCH;
+ use opendal_core::*;
+
+ use crate::backend::AzblobBuilder;
+
+ #[derive(Clone)]
+ struct RecordedRequest {
+ method: Method,
+ uri: String,
+ headers: HeaderMap,
+ }
+
+ #[derive(Clone)]
+ struct ScriptedTransport {
+ responses: Arc<Mutex<VecDeque<Response<Bytes>>>>,
+ requests: Arc<Mutex<Vec<RecordedRequest>>>,
+ }
+
+ impl ScriptedTransport {
+ fn new(responses: Vec<Response<Bytes>>) -> Self {
+ Self {
+ responses: Arc::new(Mutex::new(VecDeque::from(responses))),
+ requests: Arc::new(Mutex::new(Vec::new())),
+ }
+ }
+ }
+
+ impl HttpTransport for ScriptedTransport {
+ async fn fetch(&self, req: Request<Buffer>) ->
Result<Response<HttpBody>> {
+ self.requests.lock().unwrap().push(RecordedRequest {
+ method: req.method().clone(),
+ uri: req.uri().to_string(),
+ headers: req.headers().clone(),
+ });
+
+ let resp = self
+ .responses
+ .lock()
+ .unwrap()
+ .pop_front()
+ .expect("unexpected HTTP request");
+ let (parts, body) = resp.into_parts();
+ let size = body.len() as u64;
+ let stream_body = if body.is_empty() {
+ HttpBody::new(futures::stream::iter(std::iter::empty()),
Some(0))
+ } else {
+ HttpBody::new(
+ futures::stream::iter(vec![Ok(Buffer::from(body))]),
+ Some(size),
+ )
+ };
+ Ok(Response::from_parts(parts, stream_body))
+ }
+ }
+
+ fn test_operator(transport: ScriptedTransport) -> Operator {
+ Operator::new(
+ AzblobBuilder::default()
+ .container("test")
+ .endpoint("https://myaccount.blob.core.windows.net")
+ .skip_signature(),
+ )
+ .expect("azblob operator must build")
+
.with_context(OperationContext::new().with_http_transport(HttpTransporter::new(transport)))
+ }
+
+ #[tokio::test]
+ async fn append_with_if_match_rejects_missing_blob_without_initializing() {
+ let transport = ScriptedTransport::new(vec![
+ Response::builder()
+ .status(StatusCode::NOT_FOUND)
+ .header("x-ms-error-code", "BlobNotFound")
+ .body(Bytes::new())
+ .unwrap(),
+ ]);
+ let requests = transport.requests.clone();
+ let op = test_operator(transport);
+
+ let err = op
+ .write_with("missing.log", "hello")
+ .append(true)
+ .if_match("\"etag-1\"")
+ .await
+ .expect_err("append with if_match on missing blob must fail");
+ assert_eq!(err.kind(), ErrorKind::ConditionNotMatch);
+
+ let recorded = requests.lock().unwrap();
+ assert_eq!(recorded.len(), 1);
+ assert_eq!(recorded[0].method, Method::HEAD);
+ }
+
+ #[tokio::test]
+ async fn
append_sends_conditions_only_on_first_chunk_and_checks_empty_append() {
+ let transport = ScriptedTransport::new(vec![
+ Response::builder()
+ .status(StatusCode::OK)
+ .header("x-ms-blob-type", "AppendBlob")
+ .header("content-length", "3")
+ .header("etag", "\"etag-1\"")
+ .body(Bytes::new())
+ .unwrap(),
+ Response::builder()
+ .status(StatusCode::CREATED)
+ .header("etag", "\"etag-2\"")
+ .body(Bytes::new())
+ .unwrap(),
+ Response::builder()
+ .status(StatusCode::CREATED)
+ .header("etag", "\"etag-3\"")
+ .body(Bytes::new())
+ .unwrap(),
+ ]);
+ let requests = transport.requests.clone();
+ let op = test_operator(transport);
+
+ let mut writer = op
+ .writer_with("existing.log")
+ .append(true)
+ .if_match("\"etag-1\"")
+ .await
+ .unwrap();
+ writer.write("hello").await.unwrap();
+ writer.write("world").await.unwrap();
+ writer.close().await.unwrap();
+
+ {
+ let recorded = requests.lock().unwrap();
+ assert_eq!(recorded.len(), 3);
+ assert_eq!(recorded[0].method, Method::HEAD);
+ assert_eq!(recorded[1].method, Method::PUT);
+ assert!(recorded[1].uri.contains("comp=appendblock"));
+ assert_eq!(
+ recorded[1].headers.get(IF_MATCH).map(|v| v.as_bytes()),
+ Some(b"\"etag-1\"".as_slice())
+ );
+ assert_eq!(recorded[2].method, Method::PUT);
+ assert!(recorded[2].uri.contains("comp=appendblock"));
+ assert!(recorded[2].headers.get(IF_MATCH).is_none());
+ }
+
+ // Empty append against an existing blob must still evaluate if_match.
+ let empty_transport = ScriptedTransport::new(vec![
+ Response::builder()
+ .status(StatusCode::OK)
+ .header("x-ms-blob-type", "AppendBlob")
+ .header("content-length", "3")
+ .header("etag", "\"etag-1\"")
+ .body(Bytes::new())
+ .unwrap(),
+ Response::builder()
+ .status(StatusCode::PRECONDITION_FAILED)
+ .header("x-ms-error-code", "ConditionNotMet")
+ .body(Bytes::new())
+ .unwrap(),
+ ]);
+ let empty_requests = empty_transport.requests.clone();
+ let op = test_operator(empty_transport);
+
+ let err = op
+ .write_with("existing.log", "")
+ .append(true)
+ .if_match("\"wrong-etag\"")
+ .await
+ .expect_err("empty append with wrong if_match must fail");
+ assert_eq!(err.kind(), ErrorKind::ConditionNotMatch);
+
+ let recorded = empty_requests.lock().unwrap();
+ assert_eq!(recorded.len(), 2);
+ assert_eq!(
+ recorded[1].headers.get(IF_MATCH).map(|v| v.as_bytes()),
+ Some(b"\"wrong-etag\"".as_slice())
+ );
+ }
+
+ #[tokio::test]
+ async fn
append_init_carries_user_metadata_and_does_not_repeat_if_not_exists_on_append_block()
{
+ let transport = ScriptedTransport::new(vec![
+ Response::builder()
+ .status(StatusCode::NOT_FOUND)
+ .header("x-ms-error-code", "BlobNotFound")
+ .body(Bytes::new())
+ .unwrap(),
+ Response::builder()
+ .status(StatusCode::CREATED)
+ .header("etag", "\"etag-0\"")
+ .body(Bytes::new())
+ .unwrap(),
+ Response::builder()
+ .status(StatusCode::CREATED)
+ .header("etag", "\"etag-1\"")
+ .body(Bytes::new())
+ .unwrap(),
+ ]);
+ let requests = transport.requests.clone();
+ let op = test_operator(transport);
+
+ op.write_with("new.log", "hello")
+ .append(true)
+ .if_not_exists(true)
+ .user_metadata([("env".to_string(), "prod".to_string())])
+ .await
+ .expect("conditional append creation must succeed");
+
+ let recorded = requests.lock().unwrap();
+ assert_eq!(recorded.len(), 3);
+ assert_eq!(recorded[0].method, Method::HEAD);
+ assert_eq!(recorded[1].method, Method::PUT);
+ assert_eq!(
+ recorded[1].headers.get(IF_NONE_MATCH).map(|v| v.as_bytes()),
+ Some(b"*".as_slice())
+ );
+ assert_eq!(
+ recorded[1]
+ .headers
+ .get("x-ms-meta-env")
+ .map(|v| v.as_bytes()),
+ Some(b"prod".as_slice())
+ );
+ assert_eq!(recorded[2].method, Method::PUT);
+ assert!(recorded[2].uri.contains("comp=appendblock"));
+ assert!(recorded[2].headers.get(IF_NONE_MATCH).is_none());
+ }
+}