Compare commits

...

3 Commits

Author SHA1 Message Date
cxymds 5278eba93c fix(s3): restore 1.0.7 compatibility and batch delete correctness (#9622)
* fix(s3): restore release compatibility and batch delete preparation

* fix(ecstore): isolate batch delete metadata and receipt staging

* fix(lock): coordinate contended distributed PUT quorum retries

* fix(ecstore): sync finished local delete receipts before proof retirement

* test(ecstore): exercise local retirement through the batch entry point

* fix(ecstore): return the committed batch delete action to duplicate entries

* fix(ecstore): preserve child objects on failed delete preparation

* fix(ecstore): retain delete proofs after ambiguous head changes

* fix(ecstore): durably recertify retried delete decisions

* fix(ecstore): sync prepared directory ancestry before voting

* fix(ecstore): recheck delete decisions under the metadata lease

* Complete batch namespace acquisition once every key has a write quorum

* Keep partial batch grant cleanup alive after caller cancellation

* fix(s3): retain the verified batch delete and lock fixes

Restore the previously verified storage and locking changes alongside the S3 compatibility fixes. Track the outstanding four-node timeout and the experimental XFS writeback approach separately in rustfs/backlog#3308.
2026-11-25 16:15:59 +08:00
cxymds 1eee967c7c fix(replication): verify probe cleanup against target versions (#9624) 2026-11-25 13:55:28 +08:00
cxymds 95b43154f2 fix(scanner): walk directories with an explicit stack (#9623) 2026-11-25 10:00:19 +08:00
31 changed files with 4026 additions and 2066 deletions
@@ -159,6 +159,17 @@ mod tests {
"PutBucketAccelerateConfiguration should return success for existing bucket, got: {:?}",
put_accelerate.err()
);
let invalid = client
.put_bucket_accelerate_configuration()
.bucket(bucket)
.accelerate_configuration(
AccelerateConfiguration::builder()
.status(BucketAccelerateStatus::from("Bogus"))
.build(),
)
.send()
.await;
assert_s3_error(invalid, 400, "MalformedXML", "unknown acceleration status");
let put_request_payment = client
.put_bucket_request_payment()
@@ -176,6 +187,18 @@ mod tests {
"PutBucketRequestPayment should return success for existing bucket, got: {:?}",
put_request_payment.err()
);
let invalid = client
.put_bucket_request_payment()
.bucket(bucket)
.request_payment_configuration(
RequestPaymentConfiguration::builder()
.payer(Payer::from("Nobody"))
.build()
.expect("build request with an unknown payer"),
)
.send()
.await;
assert_s3_error(invalid, 400, "InvalidArgument", "unknown request payer");
let accelerate_after_put = client
.get_bucket_accelerate_configuration()
@@ -562,11 +562,11 @@ mod tests {
multipart_body
);
assert_versioned_content_language_round_trip(&client, bucket).await;
assert_versioned_response_headers_round_trip(&client, bucket).await;
env.stop_server();
}
async fn assert_versioned_content_language_round_trip(client: &aws_sdk_s3::Client, bucket: &str) {
async fn assert_versioned_response_headers_round_trip(client: &aws_sdk_s3::Client, bucket: &str) {
let http = reqwest::Client::builder()
.no_proxy()
.no_gzip()
@@ -583,7 +583,11 @@ mod tests {
original.to_vec()
};
let mut versions = Vec::new();
for language in [Some("zh-CN"), None, Some("en-US")] {
for (language, expires) in [
(Some("zh-CN"), Some(1_893_456_000)),
(None, Some(1_924_992_000)),
(Some("en-US"), None),
] {
let put = client
.put_object()
.bucket(bucket)
@@ -591,18 +595,27 @@ mod tests {
.content_type("application/octet-stream")
.set_content_encoding(encoding.map(str::to_string))
.set_content_language(language.map(str::to_string))
.set_expires(expires.map(DateTime::from_secs))
.metadata("content-language", "user-language")
.body(ByteStream::from(payload.clone()))
.send()
.await
.expect("Failed to write versioned language fixture");
versions.push((put.version_id().expect("PUT must return a version ID").to_string(), language));
versions.push((put.version_id().expect("PUT must return a version ID").to_string(), language, expires));
}
let current_version = &versions.last().expect("Fixture has three versions").0;
let reads = std::iter::once((None, Some("en-US")))
.chain(versions.iter().map(|(version, language)| (Some(version.as_str()), *language)));
for (version, language) in reads {
let reads = std::iter::once((None, Some("en-US"), None)).chain(
versions
.iter()
.map(|(version, language, expires)| (Some(version.as_str()), *language, *expires)),
);
for (version, language, expires) in reads {
let expected_expires = expires.map(|secs| {
DateTime::from_secs(secs)
.fmt(DateTimeFormat::HttpDate)
.expect("valid HTTP date")
});
let expected_version = version.unwrap_or(current_version);
let head = client
.head_object()
@@ -613,6 +626,7 @@ mod tests {
.await
.expect("HEAD failed for language fixture");
assert_eq!(head.content_language(), language);
assert_eq!(head.expires_string(), expected_expires.as_deref());
assert_eq!(head.version_id(), Some(expected_version));
for range in [None, Some("bytes=1-7")] {
@@ -626,6 +640,7 @@ mod tests {
.set_range(range.map(str::to_string));
let get = request.clone().send().await.expect("GET failed for language fixture");
assert_eq!(get.content_language(), language);
assert_eq!(get.expires_string(), expected_expires.as_deref());
assert_eq!(get.content_type(), Some("application/octet-stream"));
assert_eq!(get.content_encoding(), encoding);
assert_eq!(
+43 -7
View File
@@ -649,9 +649,19 @@ async fn write_delete_rollback_file(
data: &[u8],
namespace_owner: Option<Arc<dyn Send + Sync>>,
) -> Result<()> {
write_delete_rollback_files(io_root, volume, object_dir, rollback_dir, &[], &[(name, data)], None, namespace_owner)
.await
.map(|_| ())
write_delete_rollback_files(
io_root,
volume,
object_dir,
rollback_dir,
&[],
&[(name, data)],
None,
None,
namespace_owner,
)
.await
.map(|_| ())
}
#[allow(clippy::too_many_arguments)]
@@ -663,6 +673,7 @@ async fn write_delete_rollback_files(
remove_before_publish: &[&'static str],
files: &[(&'static str, &[u8])],
inspect_object: Option<&str>,
sync_preparation_through: Option<&Path>,
namespace_owner: Option<Arc<dyn Send + Sync>>,
) -> Result<Option<crate::disk::DeleteRecoveryInspection>> {
let backup_dir = object_dir.join(rollback_dir.to_string());
@@ -695,6 +706,7 @@ async fn write_delete_rollback_files(
let staging_root = io_root.join(RUSTFS_META_TMP_BUCKET);
let io_root = io_root.to_path_buf();
let object_dir_buf = object_dir.to_path_buf();
let sync_preparation_through = sync_preparation_through.map(Path::to_owned);
let volume_str = volume.to_owned();
let inspect_object = inspect_object.map(str::to_owned);
let recovery_scope = delete_recovery::recovery_operation_scope();
@@ -706,6 +718,11 @@ async fn write_delete_rollback_files(
reject_local_disk_symlink_components(&io_root, path).map_err(std::io::Error::from)?;
}
reject_local_disk_symlink_components(&io_root, &staging_root).map_err(std::io::Error::from)?;
let backup_dir_existed = backup_dir.is_dir();
std::fs::create_dir_all(&backup_dir)?;
if sync && let Some(through) = sync_preparation_through.as_deref() {
delete_recovery::sync_preparation_parents(&object_dir_buf, through)?;
}
for (path, _) in &removed_entries {
#[cfg(all(any(test, feature = "test-util"), not(windows)))]
os::prepared_publication_test_hooks::run(os::prepared_publication_test_hooks::Stage::Remove, path);
@@ -715,8 +732,6 @@ async fn write_delete_rollback_files(
Err(err) => return Err(err),
}
}
let backup_dir_existed = backup_dir.is_dir();
std::fs::create_dir_all(&backup_dir)?;
std::fs::create_dir_all(&staging_root)?;
// tempfile's Windows `persist` hands both the staged and the final path
// straight to `MoveFileExW`, bypassing std's long-path handling, so a
@@ -751,7 +766,10 @@ async fn write_delete_rollback_files(
}
if sync {
os::fsync_dir_std(&backup_dir)?;
if !backup_dir_existed && let Some(parent) = backup_dir.parent() {
if !backup_dir_existed
&& sync_preparation_through.is_none()
&& let Some(parent) = backup_dir.parent()
{
os::fsync_dir_std(parent)?;
}
}
@@ -9345,7 +9363,7 @@ impl LocalDisk {
.try_fused_recoverable_delete_version_with_paths(
volume,
path,
&fi,
delete_recovery::FusedDeleteRequest::Single(&fi),
&opts,
rollback_dir,
namespace_owner.clone(),
@@ -10968,6 +10986,24 @@ impl LocalDisk {
.await;
}
if let [fi] = fis
&& expected_current.is_none()
&& let Some(transaction) = opts.old_data_dir
&& let Some(()) = self
.try_fused_recoverable_delete_version_with_paths(
volume,
path,
delete_recovery::FusedDeleteRequest::BatchEntry(fi),
opts,
transaction,
namespace_owner.clone(),
Some((object_path, volume_dir.clone(), object_dir.to_path_buf())),
)
.await?
{
return Ok(());
}
let (data, _) = match self
.read_all_data_with_dmtime(volume, volume_dir.as_path(), &xlpath, None)
.await
File diff suppressed because it is too large Load Diff
+52
View File
@@ -7163,6 +7163,58 @@ mod multipart_orphan_control_probe_tests {
}
}
/// Reclaim the named files from a published staging directory. Other entries
/// can be live child objects. Leave the directory in place when it is nonempty.
pub(in crate::disk) fn discard_staged_files(
parent: &Path,
base: &Path,
publication_root: &PublicationRoot,
directory_name: &str,
files: &[&str],
) -> io::Result<()> {
#[cfg(unix)]
{
use rustix::fs::{AtFlags, Mode, OFlags, openat, unlinkat};
let parents = open_existing_directory_below_base_std(parent, base, publication_root)?;
let parent = parents.last().ok_or_else(|| io::Error::other("missing staging parent"))?;
let directory = openat(
parent,
directory_name,
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::empty(),
)?;
for &name in files {
match unlinkat(&directory, name, AtFlags::empty()) {
Ok(()) | Err(rustix::io::Errno::NOENT) => {}
Err(error) => return Err(error.into()),
}
}
unlinkat(parent, directory_name, AtFlags::REMOVEDIR)?;
Ok(())
}
#[cfg(windows)]
{
existing_base_directory_suffix(parent, base)?;
let _parent = lock_windows_directory_tree(parent, publication_root)?;
let path = parent.join(directory_name);
let directory = lock_windows_directory_tree(&path, publication_root)?;
for &name in files {
match std::fs::remove_file(path.join(name)) {
Ok(()) => {}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(error),
}
}
drop(directory);
std::fs::remove_dir(path)
}
#[cfg(not(any(unix, windows)))]
{
let _ = (parent, base, publication_root, directory_name, files);
Err(io::ErrorKind::Unsupported.into())
}
}
/// Pin an existing MPU tree without creating any missing source directory.
pub(crate) fn pin_multipart_source_directory(
directory: &Path,
+10 -2
View File
@@ -5333,10 +5333,18 @@ impl SetDisks {
.with_attempt(attempt))
}
async fn namespace_lock_for_write(&self, op: &str, bucket: &str, object: &str) -> Result<NamespaceLockWrapper> {
let mut lock = self.new_ns_lock(bucket, object).await?;
if op == "put_object_commit" {
lock.prefer_first_voter_on_contention();
}
Ok(lock)
}
async fn acquire_write_lock_diag(&self, op: &'static str, bucket: &str, object: &str) -> Result<ObjectLockDiagGuard> {
crate::hp_guard!("SetDisks::acquire_write_lock");
let diag_enabled = is_object_lock_diag_enabled();
let ns_lock = self.new_ns_lock(bucket, object).await?;
let ns_lock = self.namespace_lock_for_write(op, bucket, object).await?;
let acquire_start = Instant::now();
let acquire_timeout = get_put_object_commit_lock_acquire_timeout(op);
let mut attempt = ObjectLockAttempt::start(op, bucket, object, None, &ns_lock, "write", acquire_timeout);
@@ -5379,7 +5387,7 @@ impl SetDisks {
) -> Result<ObjectLockDiagGuard> {
crate::hp_guard!("SetDisks::acquire_write_lock");
let diag_enabled = is_object_lock_diag_enabled();
let ns_lock = self.new_ns_lock(bucket, object).await?;
let ns_lock = self.namespace_lock_for_write(op, bucket, object).await?;
let acquire_start = Instant::now();
let acquire_timeout = get_put_object_commit_lock_acquire_timeout(op);
let mut attempt = ObjectLockAttempt::start(op, bucket, object, None, &ns_lock, "write", acquire_timeout);
+86 -81
View File
@@ -2065,10 +2065,6 @@ fn batch_delete_creates_latest_marker(object: &ObjectToDelete, delete_config_sna
versioned || version_suspended
}
fn batch_delete_action_key(object: &ObjectToDelete) -> (&str, Option<Uuid>) {
(object.object_name.as_str(), object.version_id)
}
fn batch_delete_targets_pool(creates_latest_marker: bool, marker_target_pool_idx: Option<usize>, pool_idx: usize) -> bool {
!creates_latest_marker || marker_target_pool_idx == Some(pool_idx)
}
@@ -6523,34 +6519,15 @@ impl ECStore {
#[cfg(test)]
inject_conditional_delete_post_admission_mutations(self, bucket).await;
if !has_conditions {
// Keys whose write lock failed are already reported in `del_errs`;
// the phase only runs for the keys this batch actually holds, and
// only its outcomes replace the outer per-key state.
let indices = (0..objects.len()).filter(|idx| del_errs[*idx].is_none()).collect::<Vec<_>>();
let (phase_deleted, mut phase_errors, mut phase_accounting) = self
.run_batch_delete_phase(
bucket,
&objects,
&opts,
BatchDeletePhasePlan {
indices: &indices,
pool_generations,
marker_targets: &conditional_marker_targets,
},
)
.await;
for idx in indices {
del_objects[idx] = phase_deleted[idx].clone();
del_errs[idx] = phase_errors[idx].take();
accounting[idx] = phase_accounting[idx].take();
}
} else {
let mut conditional_actions = HashMap::with_capacity(objects.len());
// Conditions have already been evaluated per input. Equal remaining actions
// include the version, synthetic null semantics, identity guard and replication
// fields. Run each action once and return its committed result to every alias.
let mut actions = HashMap::with_capacity(objects.len());
if has_conditions {
let mut conditional_indices = Vec::with_capacity(objects.len());
for (idx, object) in objects.iter().enumerate() {
if admitted_conditions[idx] && del_errs[idx].is_none() {
let representative = *conditional_actions.entry(batch_delete_action_key(object)).or_insert(idx);
let representative = *actions.entry(object).or_insert(idx);
representatives[idx] = representative;
if representative == idx {
conditional_indices.push(idx);
@@ -6576,66 +6553,54 @@ impl ECStore {
accounting[*idx] = receipts[*idx].take();
}
}
let successful_conditional_actions = conditional_actions
.into_iter()
.filter(|(_, idx)| del_errs[*idx].is_none())
.collect::<HashMap<_, _>>();
let mut ordinary_actions = HashMap::with_capacity(objects.len());
let mut ordinary_indices = Vec::with_capacity(objects.len());
for (idx, object) in objects.iter().enumerate() {
if requested_conditions[idx] || del_errs[idx].is_some() {
continue;
}
let action = batch_delete_action_key(object);
if object.expected_identity.is_none()
&& let Some(representative) = successful_conditional_actions.get(&action)
{
// Only a committed conditional action can satisfy its
// unconditional alias. A CAS failure grants no deletion.
representatives[idx] = *representative;
continue;
}
let representative = *ordinary_actions.entry(action).or_insert(idx);
representatives[idx] = representative;
if representative == idx {
ordinary_indices.push(idx);
}
// Only a successful guarded mutation can satisfy an ordinary alias.
// Callers providing their own generation guard still get an independent check.
actions.retain(|object, index| object.expected_identity.is_none() && del_errs[*index].is_none());
}
let mut ordinary_indices = Vec::with_capacity(objects.len());
for (idx, object) in objects.iter().enumerate() {
if requested_conditions[idx] || del_errs[idx].is_some() {
continue;
}
if !ordinary_indices.is_empty() {
// The guarded phase has finished all rollback/receipt work.
// These actions receive neither its CAS nor its transaction.
let (deleted, mut errors, mut receipts) = self
.run_batch_delete_phase(
bucket,
&objects,
&opts,
BatchDeletePhasePlan {
indices: &ordinary_indices,
pool_generations: HashMap::new(),
marker_targets: &HashMap::new(),
},
)
.await;
for idx in ordinary_indices {
del_objects[idx] = deleted[idx].clone();
del_errs[idx] = errors[idx].take();
accounting[idx] = receipts[idx].take();
}
let representative = *actions.entry(object).or_insert(idx);
representatives[idx] = representative;
if representative == idx {
ordinary_indices.push(idx);
}
}
if !ordinary_indices.is_empty() {
// The guarded phase has finished all rollback/receipt work.
// These actions receive neither its CAS nor its transaction.
let (deleted, mut errors, mut receipts) = self
.run_batch_delete_phase(
bucket,
&objects,
&opts,
BatchDeletePhasePlan {
indices: &ordinary_indices,
pool_generations: HashMap::new(),
marker_targets: &HashMap::new(),
},
)
.await;
for idx in ordinary_indices {
del_objects[idx] = deleted[idx].clone();
del_errs[idx] = errors[idx].take();
accounting[idx] = receipts[idx].take();
}
}
if has_conditions {
for (idx, representative) in representatives.into_iter().enumerate() {
if representative != idx {
del_objects[idx] = del_objects[representative].clone();
del_errs[idx] = del_errs[representative].clone();
accounting[idx] = None;
}
for (idx, representative) in representatives.into_iter().enumerate() {
if representative != idx {
del_objects[idx] = del_objects[representative].clone();
del_errs[idx] = del_errs[representative].clone();
}
}
if has_conditions {
let mut first_successes = HashMap::with_capacity(objects.len());
for (idx, object) in objects.iter().enumerate() {
if del_errs[idx].is_none() {
let first = *first_successes.entry(batch_delete_action_key(object)).or_insert(idx);
let first = *first_successes.entry(object).or_insert(idx);
if first != idx && accounting[idx].is_some() {
accounting[first] = accounting[idx].take();
}
@@ -11047,6 +11012,46 @@ mod tests {
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn ordinary_batch_delete_returns_the_stored_marker_to_every_duplicate() {
let bucket = "ordinary-duplicate-markers";
let key = "target";
let (_dirs, store) = multipool_delete_test_store(bucket, true).await;
let options = ObjectOptions {
versioned: true,
..Default::default()
};
let original = store.pools[1]
.put_object(bucket, key, &mut PutObjReader::from_vec(b"original".to_vec()), &options)
.await
.expect("write version before marker");
let action = ObjectToDelete {
object_name: key.to_owned(),
..Default::default()
};
let (deleted, errors) = store.handle_delete_objects(bucket, vec![action; 16], options).await;
assert!(errors.iter().all(Option::is_none), "all input slots succeed: {errors:?}");
let versions = store
.inner_list_object_versions(bucket, key, None, None, None, 20)
.await
.expect("list actual marker and retained version");
let markers: Vec<_> = versions.objects.iter().filter(|entry| entry.delete_marker).collect();
assert_eq!(markers.len(), 1);
let marker = markers[0].version_id.expect("stored marker has an ID");
assert!(
versions
.objects
.iter()
.any(|entry| !entry.delete_marker && entry.version_id == original.version_id)
);
assert_eq!(deleted.len(), 16);
assert!(
deleted
.iter()
.all(|row| row.object_name == key && row.delete_marker_version_id == Some(marker))
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn conditional_batch_delete_success_reuses_unconditional_current_alias_once() {
use crate::storage_api_contracts::object::DeleteObjectCondition;
+1 -1
View File
@@ -119,7 +119,7 @@ impl From<VersionPurgeStatusType> for ReplicationStatusType {
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub enum VersionPurgeStatusType {
Pending,
Complete,
+380 -58
View File
@@ -19,6 +19,7 @@ use crate::{
types::{LockId, LockInfo, LockRequest, LockResponse, LockStatus, LockType},
};
use futures::{
FutureExt,
future::join_all,
stream::{FuturesUnordered, StreamExt},
};
@@ -249,6 +250,52 @@ impl HeldLockEntry {
}
}
/// A peer may finish after the coordinator returns or its caller disconnects.
/// Each positive vote stays owned here until a guard or quorum rollback takes it.
struct BatchPeerReply {
client: Arc<dyn LockClient>,
requests: Arc<[LockRequest]>,
responses: Result<Vec<LockResponse>>,
}
impl BatchPeerReply {
fn take_vote(&mut self, index: usize) -> std::result::Result<LockId, String> {
let response = self
.responses
.as_mut()
.map_err(|error| error.to_string())?
.get_mut(index)
.ok_or_else(|| "client returned incomplete batch lock response".to_owned())?;
if !std::mem::take(&mut response.success) {
return Err(response
.error
.take()
.unwrap_or_else(|| "distributed lock acquisition failed".to_owned()));
}
Ok(response
.lock_info
.take()
.map_or_else(|| self.requests[index].lock_id.clone(), |info| info.id))
}
}
impl Drop for BatchPeerReply {
fn drop(&mut self) {
if let Ok(responses) = &mut self.responses {
let unused = responses
.iter_mut()
.zip(self.requests.iter())
.filter(|(reply, _)| reply.success)
.map(|(reply, request)| {
let id = reply.lock_info.take().map_or_else(|| request.lock_id.clone(), |info| info.id);
(id, self.client.clone())
})
.collect();
DistributedLock::spawn_release_cleanup(unused, "distributed_lock_surplus_batch_votes");
}
}
}
/// Own grants and pending replies until normal completion transfers their cleanup.
/// Cancelling the caller must not abort a reply that can still carry a grant.
struct LockAcquireRound {
@@ -542,6 +589,7 @@ pub struct DistributedLock {
namespace: Arc<str>,
/// Quorum size for exclusive/write operations
quorum: usize,
prefer_first_voter_on_contention: bool,
}
type LockAcquireTaskResult = (usize, Result<LockResponse>);
@@ -572,9 +620,14 @@ impl DistributedLock {
clients,
namespace,
quorum: q,
prefer_first_voter_on_contention: false,
}
}
pub(super) fn prefer_first_voter_on_contention(&mut self) {
self.prefer_first_voter_on_contention = true;
}
/// Get namespace identifier
pub fn namespace(&self) -> &str {
&self.namespace
@@ -773,7 +826,7 @@ impl DistributedLock {
let required_quorum = self.required_quorum(LockType::Exclusive);
let attempt_started = Instant::now();
let requests: Vec<LockRequest> = resources
let requests: Arc<[LockRequest]> = resources
.iter()
.map(|resource| {
LockRequest::new(resource.clone(), LockType::Exclusive, owner)
@@ -782,48 +835,67 @@ impl DistributedLock {
})
.collect();
// One batched round per client; a client-level failure is a per-key
// failure for every key that still needed that client's vote.
let rounds = join_all(self.clients.iter().map(|client| {
let requests = requests.clone();
async move { client.acquire_locks_batch(&requests).await }
}))
.await;
// Keep each reply drainable after an early quorum or cancellation. Dropping a
// JoinHandle detaches the peer request. Its reply releases any unclaimed votes.
let mut pending: FuturesUnordered<_> = self
.clients
.iter()
.map(|client| {
let client = Arc::clone(client);
let requests = Arc::clone(&requests);
tokio::spawn(async move {
let responses = client.acquire_locks_batch(&requests).await;
BatchPeerReply {
client,
requests,
responses,
}
})
})
.collect();
let mut counts = vec![0; resources.len()];
let mut unconfirmed = resources.len();
let mut rounds = Vec::with_capacity(self.clients.len());
while let Some(completed) = pending.next().await {
let Ok(reply) = completed else { continue };
if let Ok(responses) = &reply.responses {
for (count, response) in counts.iter_mut().zip(responses) {
if response.success {
*count += 1;
if *count == required_quorum {
unconfirmed -= 1;
}
}
}
}
rounds.push(reply);
if unconfirmed == 0 {
// Retain already available spare votes without holding the majority
// hostage to a contended voter, including for a one-key batch.
while let Some(Some(completed)) = pending.next().now_or_never() {
if let Ok(reply) = completed {
rounds.push(reply);
}
}
break;
}
}
drop(pending);
let mut results: Vec<Result<DistributedLockGuard>> = Vec::with_capacity(resources.len());
let mut orphaned_entries: Vec<(LockId, Arc<dyn LockClient>)> = Vec::new();
for (key_idx, resource) in resources.iter().enumerate() {
let mut entries: Vec<HeldLockEntry> = Vec::new();
let mut failure: Option<String> = None;
for (client_idx, client) in self.clients.iter().enumerate() {
match &rounds[client_idx] {
Ok(responses) => match responses.get(key_idx) {
Some(response) if response.success => {
let lock_id = response
.lock_info
.as_ref()
.map(|info| info.id.clone())
.unwrap_or_else(|| LockId::new_unique(resource));
entries.push(HeldLockEntry {
lock_id,
client: client.clone(),
valid_until: attempt_started.checked_add(ttl).unwrap_or(attempt_started),
});
}
Some(response) => {
failure.get_or_insert_with(|| {
response
.error
.clone()
.unwrap_or_else(|| "distributed lock acquisition failed".to_string())
});
}
None => {
failure.get_or_insert_with(|| "client returned incomplete batch lock response".to_string());
}
},
Err(err) => {
failure.get_or_insert_with(|| err.to_string());
for reply in &mut rounds {
match reply.take_vote(key_idx) {
Ok(lock_id) => entries.push(HeldLockEntry {
lock_id,
client: reply.client.clone(),
valid_until: attempt_started.checked_add(ttl).unwrap_or(attempt_started),
}),
Err(error) => {
failure.get_or_insert(error);
}
}
}
@@ -860,7 +932,11 @@ impl DistributedLock {
// keeps retrying in the background instead of parking the request
// on the deferred unlock schedule.
if !orphaned_entries.is_empty() {
Self::release_entries_bounded(orphaned_entries, "distributed_lock_batch_quorum_rollback").await;
// The caller waits for the first pass. If it disconnects during an
// unlock, the task still owns every minority vote until cleanup finishes.
let rollback =
tokio::spawn(Self::release_entries_bounded(orphaned_entries, "distributed_lock_batch_quorum_rollback"));
let _ = rollback.await;
}
results
}
@@ -1187,7 +1263,18 @@ impl DistributedLock {
// A peer may grant promptly but deliver its response after its local
// contention budget. Keep this round's owners until a response proves
// quorum impossible or the caller's remaining budget expires.
let result = self.acquire_lock_quorum_once(&attempt_request, remaining).await?;
let contention_retry = self.prefer_first_voter_on_contention
&& self.clients.len() > 1
&& request.lock_type == LockType::Exclusive
&& last_result.as_ref().is_some_and(|previous| !previous.quorum_impossible);
// Split votes can repeatedly occupy different peers without any writer
// reaching quorum. On a contention retry let one voter order the
// competing writers before fanning out; reserve at least half the
// remaining budget for a quorum that can exclude a silent first voter.
let first_vote_wait = contention_retry.then_some(remaining / 2);
let result = self
.acquire_lock_quorum_once(&attempt_request, remaining, first_vote_wait)
.await?;
if !result.response.success {
tracing::trace!(
target: "rustfs_lock::namespace_owner",
@@ -1273,7 +1360,12 @@ impl DistributedLock {
/// Quorum-based lock acquisition: success if at least the required quorum succeeds.
/// Collects all individual lock_ids from successful clients and creates an aggregate lock_id.
/// Returns the LockResponse with aggregate lock_id and individual lock mappings.
async fn acquire_lock_quorum_once(&self, request: &LockRequest, quorum_timeout: Duration) -> Result<LockAcquireQuorumResult> {
async fn acquire_lock_quorum_once(
&self,
request: &LockRequest,
quorum_timeout: Duration,
first_vote_wait: Option<Duration>,
) -> Result<LockAcquireQuorumResult> {
let voter_count =
u32::try_from(self.clients.len().max(1)).map_err(|_| LockError::internal("lock voter count exceeds u32"))?;
let required_quorum = self.required_quorum(request.lock_type);
@@ -1287,14 +1379,16 @@ impl DistributedLock {
fallback_lock_id: request.lock_id.clone(),
};
let mut next_client_index = 0usize;
self.spawn_lock_requests_until(
&mut round.pending,
request,
&mut next_client_index,
required_quorum
.saturating_add(LOCK_ACQUIRE_SPARE_HEDGES)
.min(self.clients.len()),
);
let initial_width = required_quorum
.saturating_add(LOCK_ACQUIRE_SPARE_HEDGES)
.min(self.clients.len());
if let Some(first_vote_budget) = first_vote_wait {
let mut first = request.clone();
first.acquire_timeout = first_vote_budget;
self.spawn_lock_requests_until(&mut round.pending, &first, &mut next_client_index, 1);
} else {
self.spawn_lock_requests_until(&mut round.pending, request, &mut next_client_index, initial_width);
}
let mut last_failure = None;
let mut last_failure_kind = None;
let mut last_hard_failure_kind = None;
@@ -1306,7 +1400,7 @@ impl DistributedLock {
// Spread additional hedges across the existing attempt budget; fast
// quorums still use only the initial quorum-plus-spare requests.
let hedge_interval = request.acquire_timeout / voter_count;
let hedge_timer = tokio::time::sleep(hedge_interval);
let hedge_timer = tokio::time::sleep(first_vote_wait.unwrap_or(hedge_interval));
tokio::pin!(hedge_timer);
while !round.pending.is_empty() {
@@ -1351,7 +1445,11 @@ impl DistributedLock {
}
_ = &mut hedge_timer, if next_client_index < self.clients.len() => {
if start.elapsed() < quorum_timeout {
let target_in_flight = round.pending.len().saturating_add(1);
let target_in_flight = if first_vote_wait.is_some() && next_client_index == 1 {
initial_width
} else {
round.pending.len().saturating_add(1)
};
self.spawn_lock_requests_until(
&mut round.pending, request, &mut next_client_index, target_in_flight,
);
@@ -1382,6 +1480,9 @@ impl DistributedLock {
}
};
if first_vote_wait.is_some() && next_client_index == 1 {
hedge_timer.set(tokio::time::sleep(hedge_interval));
}
match join_result {
Ok((idx, Ok(resp))) => {
if resp.success {
@@ -3286,7 +3387,7 @@ mod tests {
let request = LockRequest::new(ObjectKey::new("bucket", "partial-grants"), LockType::Shared, "owner")
.with_acquire_timeout(Duration::from_secs(1));
let result = lock
.acquire_lock_quorum_once(&request, request.acquire_timeout)
.acquire_lock_quorum_once(&request, request.acquire_timeout, None)
.await
.expect("partial quorum should return a timeout response");
assert!(!result.response.success);
@@ -3476,7 +3577,7 @@ mod tests {
let request = LockRequest::new(ObjectKey::new("bucket", "object"), LockType::Exclusive, "owner")
.with_acquire_timeout(Duration::from_secs(2));
let result = lock
.acquire_lock_quorum_once(&request, request.acquire_timeout)
.acquire_lock_quorum_once(&request, request.acquire_timeout, None)
.await
.expect("round result");
assert!(!result.response.success);
@@ -3498,7 +3599,7 @@ mod tests {
.with_acquire_timeout(Duration::from_secs(2));
let started = Instant::now();
let result = lock
.acquire_lock_quorum_once(&request, request.acquire_timeout)
.acquire_lock_quorum_once(&request, request.acquire_timeout, None)
.await
.expect("round result");
assert!(!result.response.success);
@@ -3535,7 +3636,7 @@ mod tests {
.with_acquire_timeout(Duration::from_secs(2));
let started = Instant::now();
let result = lock
.acquire_lock_quorum_once(&request, request.acquire_timeout)
.acquire_lock_quorum_once(&request, request.acquire_timeout, None)
.await
.expect("round result");
assert!(!result.response.success);
@@ -3563,7 +3664,7 @@ mod tests {
let request = LockRequest::new(ObjectKey::new("bucket", "object"), LockType::Exclusive, "owner")
.with_acquire_timeout(Duration::from_secs(1));
let result = lock
.acquire_lock_quorum_once(&request, request.acquire_timeout)
.acquire_lock_quorum_once(&request, request.acquire_timeout, None)
.await
.expect("round result");
assert!(!result.response.success);
@@ -3676,9 +3777,11 @@ mod tests {
);
let request = LockRequest::new(ObjectKey::new("bucket", "ready-after-deadline"), LockType::Shared, "owner")
.with_acquire_timeout(Duration::from_secs(5));
let mut attempt = Box::pin(tokio::task::unconstrained(
lock.acquire_lock_quorum_once(&request, request.acquire_timeout),
));
let mut attempt = Box::pin(tokio::task::unconstrained(lock.acquire_lock_quorum_once(
&request,
request.acquire_timeout,
None,
)));
assert!(matches!(poll!(&mut attempt), Poll::Pending));
tokio::time::timeout(Duration::from_secs(1), async {
while clients
@@ -3746,6 +3849,108 @@ mod tests {
wait_for_acquisition_cleanup(&clients).await;
}
#[tokio::test(start_paused = true)]
async fn contended_write_retry_continues_hedging_past_a_silent_prefix() {
let clients: Vec<_> = (0..7)
.map(|_| {
Arc::new(SequencedClient::new(
vec![AcquirePlan::Success {
delay: Duration::from_secs(2),
}],
Arc::new(Mutex::new(Vec::new())),
))
})
.collect();
let lock = DistributedLock::new(
"put-commit".to_owned(),
clients.iter().map(|client| client.clone() as Arc<dyn LockClient>).collect(),
4,
);
let timeout = Duration::from_secs(1);
let request =
LockRequest::new(ObjectKey::new("bucket", "hot-key"), LockType::Exclusive, "writer").with_acquire_timeout(timeout);
let task = tokio::spawn(async move {
lock.acquire_lock_quorum_once(&request, timeout, Some(Duration::from_millis(100)))
.await
});
tokio::time::timeout(Duration::from_millis(700), async {
while clients[6].requested_acquires.load(Ordering::SeqCst) == 0 {
tokio::time::advance(Duration::from_millis(10)).await;
}
})
.await
.expect("every voter must be tried even if the initial quorum plus spare is silent");
let result = task.await.expect("retry task").expect("retry round");
assert!(result.attempt_timed_out);
wait_for_acquisition_cleanup(&clients).await;
}
#[tokio::test(start_paused = true)]
async fn contended_write_retry_can_use_or_bypass_the_first_voter_and_clean_up() {
use crate::{NamespaceLock, NamespaceLockWrapper};
for (first_vote_delay, cancel) in [
(Duration::from_millis(100), false),
(Duration::from_secs(4), false),
(Duration::from_millis(100), true),
] {
let clients: Vec<_> = (0..4)
.map(|index| {
Arc::new(SequencedClient::new(
vec![
AcquirePlan::Failure {
error: "Lock acquisition timeout",
delay: Duration::ZERO,
},
AcquirePlan::Success {
delay: if index == 0 { first_vote_delay } else { Duration::ZERO },
},
],
Arc::new(Mutex::new(Vec::new())),
))
})
.collect();
let mut lock = NamespaceLockWrapper::new(
NamespaceLock::with_clients_and_quorum(
"put-commit".to_owned(),
clients.iter().map(|client| client.clone() as Arc<dyn LockClient>).collect(),
3,
),
ObjectKey::new("bucket", "hot-key"),
"writer".to_owned(),
);
lock.prefer_first_voter_on_contention();
let timeout = Duration::from_secs(5);
let start = Instant::now();
let acquisition = tokio::spawn(async move { lock.get_write_lock(timeout).await });
tokio::time::timeout(Duration::from_secs(1), async {
while clients[0].requested_acquires.load(Ordering::SeqCst) < 2 {
tokio::time::advance(Duration::from_millis(5)).await;
}
})
.await
.expect("reach preferred-voter retry");
assert!(
clients[1..]
.iter()
.all(|client| client.requested_acquires.load(Ordering::SeqCst) == 1),
"other writers must not be able to split retry votes while waiting for the first voter",
);
if cancel {
acquisition.abort();
assert!(acquisition.await.expect_err("cancelled acquire").is_cancelled());
} else {
let guard = acquisition.await.expect("acquire task").expect("three responsive voters");
assert!(start.elapsed() < timeout);
if first_vote_delay >= timeout / 2 {
assert_eq!(clients[0].completed_acquires.load(Ordering::SeqCst), 1, "silent voter is optional");
}
drop(guard);
}
wait_for_acquisition_cleanup(&clients).await;
}
}
#[tokio::test(start_paused = true)]
async fn cancelling_acquisition_cleans_confirmed_and_pending_grants() {
let clients = (0..4)
@@ -4033,14 +4238,28 @@ mod tests {
struct ScriptedBatchClient {
grants: Vec<String>,
releases: Arc<Mutex<Vec<String>>>,
gate: Option<Arc<tokio::sync::Semaphore>>,
cleanup_gate: Option<(Arc<tokio::sync::Notify>, Arc<tokio::sync::Semaphore>)>,
grants_returned: Arc<std::sync::atomic::AtomicUsize>,
}
impl ScriptedBatchClient {
fn build(grants: &[&str]) -> (Arc<dyn LockClient>, Arc<Mutex<Vec<String>>>) {
Self::controlled(grants, None, Arc::default())
}
fn controlled(
grants: &[&str],
gate: Option<Arc<tokio::sync::Semaphore>>,
grants_returned: Arc<std::sync::atomic::AtomicUsize>,
) -> (Arc<dyn LockClient>, Arc<Mutex<Vec<String>>>) {
let releases = Arc::new(Mutex::new(Vec::new()));
let client = Arc::new(Self {
grants: grants.iter().map(|object| (*object).to_string()).collect(),
releases: Arc::clone(&releases),
gate,
cleanup_gate: None,
grants_returned,
}) as Arc<dyn LockClient>;
(client, releases)
}
@@ -4049,7 +4268,11 @@ mod tests {
#[async_trait::async_trait]
impl LockClient for ScriptedBatchClient {
async fn acquire_lock(&self, request: &LockRequest) -> crate::Result<LockResponse> {
if let Some(gate) = &self.gate {
drop(gate.acquire().await.expect("gate stays open"));
}
if self.grants.iter().any(|object| object == request.resource.object.as_ref()) {
self.grants_returned.fetch_add(1, Ordering::Release);
let info = LockInfo {
id: request.lock_id.clone(),
resource: request.resource.clone(),
@@ -4070,6 +4293,10 @@ mod tests {
}
async fn release(&self, lock_id: &LockId) -> crate::Result<bool> {
if let Some((entered, resume)) = &self.cleanup_gate {
entered.notify_one();
drop(resume.acquire().await.expect("rollback gate stays open"));
}
self.releases
.lock()
.expect("release log")
@@ -4106,6 +4333,101 @@ mod tests {
}
}
#[tokio::test]
async fn cancelling_a_batch_during_quorum_rollback_still_returns_the_partial_vote() {
let entered = Arc::new(tokio::sync::Notify::new());
let resume = Arc::new(tokio::sync::Semaphore::new(0));
let releases = Arc::new(Mutex::new(Vec::new()));
let voter = Arc::new(ScriptedBatchClient {
grants: vec!["lost".to_string()],
releases: Arc::clone(&releases),
gate: None,
grants_returned: Arc::default(),
cleanup_gate: Some((Arc::clone(&entered), Arc::clone(&resume))),
}) as Arc<dyn LockClient>;
let (denied, _) = ScriptedBatchClient::build(&[]);
let lock = DistributedLock::new("batch-rollback-cancel".into(), vec![voter, denied], 2);
let task = tokio::spawn(async move {
lock.acquire_guard_batch(
&[ObjectKey::new("bucket", "lost")],
"owner",
Duration::from_secs(5),
Duration::from_secs(30),
)
.await
});
tokio::time::timeout(Duration::from_secs(2), entered.notified())
.await
.expect("the partial vote must reach rollback");
task.abort();
assert!(task.await.unwrap_err().is_cancelled());
resume.add_permits(1);
tokio::time::timeout(Duration::from_secs(2), async {
while releases.lock().unwrap().is_empty() {
tokio::task::yield_now().await;
}
})
.await
.expect("cancelling the caller must not abandon the only owner of a partial vote");
assert_eq!(*releases.lock().unwrap(), ["lost"]);
}
#[tokio::test]
async fn acquire_guard_batch_returns_a_complete_quorum_and_releases_late_votes() {
for cancel_before_quorum in [false, true] {
let gate = Arc::new(tokio::sync::Semaphore::new(0));
let granted = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let immediate = if cancel_before_quorum { 2 } else { 3 };
let keys = ["hot", "cold"];
let (clients, releases): (Vec<_>, Vec<_>) = (0..4)
.map(|peer| ScriptedBatchClient::controlled(&keys, (peer >= immediate).then(|| gate.clone()), granted.clone()))
.unzip();
let lock = DistributedLock::new("batch-quorum".into(), clients, 3);
let task = tokio::spawn(async move {
let keys = keys.map(|key| ObjectKey::new("bucket", key));
lock.acquire_guard_batch(&keys, "owner", Duration::from_secs(5), Duration::from_secs(30))
.await
});
tokio::time::timeout(Duration::from_secs(2), async {
while granted.load(Ordering::Acquire) < immediate * keys.len() {
tokio::task::yield_now().await;
}
})
.await
.expect("reachable peers granted both keys");
let guards = if cancel_before_quorum {
assert!(!task.is_finished());
task.abort();
assert!(task.await.unwrap_err().is_cancelled());
None
} else {
let results = tokio::time::timeout(Duration::from_secs(2), task)
.await
.expect("three votes suffice even if the fourth peer is waiting")
.unwrap();
Some(results.into_iter().collect::<crate::Result<Vec<_>>>().unwrap())
};
gate.add_permits(1);
tokio::time::timeout(Duration::from_secs(2), async {
for (peer, releases) in releases.iter().enumerate() {
if !cancel_before_quorum && peer < immediate {
assert!(releases.lock().unwrap().is_empty(), "the live guards retain their majority");
continue;
}
while releases.lock().unwrap().len() < keys.len() {
tokio::task::yield_now().await;
}
let mut objects = releases.lock().unwrap().clone();
objects.sort();
assert_eq!(objects, ["cold", "hot"]);
}
})
.await
.expect("every unclaimed vote is released");
drop(guards);
}
}
/// A batch key granted by fewer than quorum clients fails alone, and its
/// partial grants are released synchronously before the call returns
/// (PR9155 review coverage for the distributed rollback path).
+8
View File
@@ -67,6 +67,14 @@ impl NamespaceLockWrapper {
self.lock.namespace()
}
/// Let contended distributed writers retry through the first voter in
/// topology order. Other voters can still form quorum without that voter.
pub fn prefer_first_voter_on_contention(&mut self) {
if let NamespaceLock::Distributed(lock) = &mut self.lock {
lock.prefer_first_voter_on_contention();
}
}
/// Acquire write lock (exclusive lock) with timeout
/// Returns the guard if acquisition succeeds, or an error if it fails
pub async fn get_write_lock(&self, timeout: Duration) -> std::result::Result<NamespaceLockGuard, crate::error::LockError> {
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,257 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use super::*;
/// The current folder owns its accumulator even when its parent lent it a compacted total.
pub(super) struct FolderFrame {
pub(super) folder: CachedFolder,
pub(super) mode: FolderScanMode,
pub(super) hash: DataUsageHash,
pub(super) entry: DataUsageEntry,
pub(super) was_compacted: bool,
pub(super) completed_budgeted_object: bool,
pub(super) started: Instant,
pub(super) trace_started_at: Option<Instant>,
}
impl FolderFrame {
fn new(folder: CachedFolder, entry: DataUsageEntry, mode: FolderScanMode) -> Self {
Self {
mode,
hash: hash_path(&folder.name),
folder,
was_compacted: entry.compacted,
entry,
completed_budgeted_object: false,
started: Instant::now(),
trace_started_at: trace_start_instant(),
}
}
}
pub(super) struct FolderListing {
pub(super) dir_reader: Option<ScannerDirectory>,
pub(super) queued_folders: std::vec::IntoIter<QueuedFolder>,
pub(super) acknowledge_previous: Option<(String, bool)>,
pub(super) force_compact: bool,
pub(super) isolate_compacted_children: bool,
pub(super) found_object_metadata: bool,
pub(super) forward_sweep: bool,
pub(super) object_to_finish: Option<(ScannerItem, Option<u64>)>,
pub(super) abandoned_children: DataUsageHashMap,
pub(super) healing: Option<AbandonedFolders>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum ChildAccounting {
Linked,
Shared,
Summary { isolated: bool },
}
pub(super) enum ChildOrigin {
Queued,
Abandoned(tokio_util::sync::DropGuard),
}
pub(super) struct ChildRequest {
pub(super) folder: CachedFolder,
pub(super) mode: FolderScanMode,
pub(super) accounting: ChildAccounting,
pub(super) origin: ChildOrigin,
}
pub(super) enum WalkAction {
Enter(bool),
Advance(Box<FolderListing>),
Descend(Box<FolderListing>, ChildRequest),
Finish,
Return(Result<FolderScanOutcome, ScannerError>),
}
struct SuspendedFolder {
frame: FolderFrame,
listing: Box<FolderListing>,
accounting: ChildAccounting,
origin: ChildOrigin,
checkpointed: bool,
suspended_updates: Option<ScannerUsageUpdates>,
}
impl FolderScanner {
pub(super) fn suspend_checkpoint_parent(
&mut self,
hash: &mut DataUsageHash,
entry: &mut DataUsageEntry,
) -> Result<bool, ScannerError> {
if self.checkpoint_tx.is_none() || self.old_cache.info.scan_progress.is_none() {
return Ok(false);
}
let depth = self.checkpoint_depth;
if depth >= MAX_DATA_USAGE_CACHE_DEPTH {
return Err(ScannerError::Other("scanner checkpoint ancestor depth limit exceeded".to_string()));
}
if self.checkpoint_ancestors.len() == depth {
self.checkpoint_ancestors.push(ScannerCheckpointAncestor::default());
}
let slot = &mut self.checkpoint_ancestors[depth];
std::mem::swap(hash, &mut slot.hash);
std::mem::swap(entry, &mut slot.entry);
self.checkpoint_depth += 1;
Ok(true)
}
async fn advance_folder(
&mut self,
ctx: &CancellationToken,
frame: &mut FolderFrame,
mut listing: Box<FolderListing>,
) -> Result<WalkAction, ScannerError> {
if listing.healing.is_none() {
if let Some(child) = self.next_queued_child(ctx, frame, &mut listing).await? {
return Ok(WalkAction::Descend(listing, child));
}
if !self.prepare_abandoned_children(ctx, frame, &mut listing).await? {
return Ok(WalkAction::Finish);
}
}
if let Some(abandoned) = &mut listing.healing
&& let Some((folder, guard)) = self.next_abandoned_child(ctx, frame, abandoned).await?
{
let accounting = if frame.entry.compacted {
ChildAccounting::Shared
} else {
ChildAccounting::Linked
};
return Ok(WalkAction::Descend(
listing,
ChildRequest {
folder,
mode: FolderScanMode::Namespace,
accounting,
origin: ChildOrigin::Abandoned(guard),
},
));
}
Ok(WalkAction::Finish)
}
pub(super) async fn scan_folder_inner(
&mut self,
ctx: CancellationToken,
folder: CachedFolder,
into: &mut DataUsageEntry,
mode: FolderScanMode,
isolate_compacted_namespace_errors: bool,
) -> Result<FolderScanOutcome, ScannerError> {
let mut parents = Vec::<SuspendedFolder>::new();
// A compacted child borrows the entire parent accumulator. Reuse the
// empty replacement across siblings, including its histogram allocations.
let mut shared_slots = Vec::new();
let mut current = FolderFrame::new(folder, std::mem::take(into), mode);
let mut action = WalkAction::Enter(isolate_compacted_namespace_errors);
loop {
#[cfg(test)]
tests::checkpoint_fixture::deep_compacted::observe_folder_frame_depth(parents.len() + 1);
action = match action {
WalkAction::Enter(isolate) => self.enumerate_folder(&ctx, &mut current, isolate).await,
WalkAction::Advance(listing) => self.advance_folder(&ctx, &mut current, listing).await,
WalkAction::Finish => Ok(WalkAction::Return(self.finish_folder(&ctx, &mut current).await)),
WalkAction::Descend(listing, child) => {
let checkpoint = if child.accounting == ChildAccounting::Linked {
self.suspend_checkpoint_parent(&mut current.hash, &mut current.entry)
} else {
Ok(false)
};
let isolated = child.accounting == ChildAccounting::Summary { isolated: true };
let suspended_updates = if isolated { self.usage_updates.take() } else { None };
let entry = match child.accounting {
ChildAccounting::Shared => std::mem::replace(&mut current.entry, shared_slots.pop().unwrap_or_default()),
ChildAccounting::Linked => DataUsageEntry::default(),
ChildAccounting::Summary { .. } => DataUsageEntry {
compacted: true,
..Default::default()
},
};
parents.push(SuspendedFolder {
frame: current,
listing,
accounting: child.accounting,
origin: child.origin,
checkpointed: matches!(checkpoint, Ok(true)),
suspended_updates,
});
current = FolderFrame::new(child.folder, entry, child.mode);
checkpoint.map(|_| WalkAction::Enter(isolated))
}
WalkAction::Return(result) => {
let Some(mut parent) = parents.pop() else {
*into = current.entry;
return result;
};
if parent.checkpointed {
self.checkpoint_depth -= 1;
let slot = &mut self.checkpoint_ancestors[self.checkpoint_depth];
std::mem::swap(&mut parent.frame.hash, &mut slot.hash);
std::mem::swap(&mut parent.frame.entry, &mut slot.entry);
}
if parent.accounting == ChildAccounting::Shared {
std::mem::swap(&mut parent.frame.entry, &mut current.entry);
}
if parent.accounting == (ChildAccounting::Summary { isolated: true }) {
self.usage_updates = parent.suspended_updates;
}
// Settle even errors from entering a child: the parent owns the
// decision to propagate a partial result or isolate a coverage gap.
let resume = match parent.origin {
ChildOrigin::Queued => {
self.accept_queued_child(
&ctx,
&mut parent.frame,
&mut parent.listing,
&current,
parent.accounting,
result,
)
.await
}
ChildOrigin::Abandoned(_cancel_on_exit) => self
.accept_abandoned_child(
&ctx,
&mut parent.frame,
&current,
result,
parent.accounting == ChildAccounting::Shared,
)
.await
.map(|()| true),
};
if parent.accounting == ChildAccounting::Shared {
shared_slots.push(current.entry);
}
current = parent.frame;
resume.map(|more| {
if more {
WalkAction::Advance(parent.listing)
} else {
WalkAction::Finish
}
})
}
}
.unwrap_or_else(|error| WalkAction::Return(Err(error)));
}
}
}
@@ -0,0 +1,451 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use super::*;
use tokio_util::sync::DropGuard;
pub(super) struct AbandonedFolders {
names: std::collections::hash_set::IntoIter<String>,
previous_bucket: String,
}
impl AbandonedFolders {
pub(super) fn new(names: HashSet<String>) -> Self {
Self {
names: names.into_iter(),
previous_bucket: String::new(),
}
}
}
impl FolderScanner {
pub(super) async fn next_abandoned_child(
&mut self,
ctx: &CancellationToken,
frame: &FolderFrame,
abandoned: &mut AbandonedFolders,
) -> Result<Option<(CachedFolder, DropGuard)>, ScannerError> {
for name in abandoned.names.by_ref() {
if !self.try_should_heal().await? {
break;
}
let (bucket, prefix) = path2_bucket_object(&name);
if bucket != abandoned.previous_bucket {
self.send_required_scanner_heal_request(
PendingScannerHealKind::Bucket,
bucket.clone(),
None,
None,
build_bucket_heal_request(bucket.clone(), HealChannelPriority::High),
)
.await?;
abandoned.previous_bucket.clone_from(&bucket);
}
let child_ctx = ctx.child_token();
let cancel_on_exit = child_ctx.clone().drop_guard();
if self.discover_abandoned_child(ctx, child_ctx, bucket, prefix).await? {
let child = CachedFolder {
name,
parent: Some(frame.hash.clone()),
object_heal_prob_div: 1,
};
return Ok(Some((child, cancel_on_exit)));
}
}
Ok(None)
}
pub(super) async fn accept_abandoned_child(
&mut self,
ctx: &CancellationToken,
frame: &mut FolderFrame,
child: &FolderFrame,
result: Result<FolderScanOutcome, ScannerError>,
shared: bool,
) -> Result<(), ScannerError> {
if shared {
result?;
self.send_update_for_entry(&frame.hash, &frame.folder.parent, &frame.entry)
.await;
tokio::task::yield_now().await;
return Ok(());
}
if let Err(error) = result {
if matches!(&error, ScannerError::DirectoryChanged | ScannerError::AbandonedChildUnverified) {
return Err(error);
}
if ctx.is_cancelled() || matches!(&error, ScannerError::SourceUnavailable(_) | ScannerError::ResourceDeferred) {
self.preserve_partial_child_progress(&child.folder.parent, &child.hash, &mut frame.entry, &child.entry)
.await;
return Err(error);
}
warn!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
folder = %frame.folder.name,
child_folder = %child.folder.name,
state = "heal_child_scan_failed",
error = %error,
"Scanner heal child folder scan failed"
);
return Err(ScannerError::AbandonedChildUnverified);
}
tokio::task::yield_now().await;
frame.entry.add_child(&child.hash);
self.refresh_usage_subtree(&child.hash, &child.folder.parent);
self.send_update().await;
self.maybe_send_checkpoint(&frame.folder, &frame.hash, &frame.entry);
Ok(())
}
async fn discover_abandoned_child(
&mut self,
ctx: &CancellationToken,
child_ctx: CancellationToken,
bucket: String,
prefix: String,
) -> Result<bool, ScannerError> {
let (agreed_tx, mut agreed_rx) = mpsc::channel::<String>(1);
let (partial_tx, mut partial_rx) = mpsc::channel::<MetaCacheEntries>(1);
let (finished_tx, mut finished_rx) = mpsc::channel::<Vec<Option<DiskError>>>(1);
let disks = self.disks.iter().cloned().map(Some).collect();
let disks_quorum = self.disks_quorum;
let bucket_clone = bucket.clone();
let child_ctx_clone = child_ctx.clone();
#[cfg(test)]
let list_path_raw_options_observer = self.list_path_raw_options_observer.clone();
let listing = tokio::spawn(async move {
let options = ListPathRawOptions {
disks,
bucket: bucket_clone.clone(),
path: prefix.clone(),
recursive: true,
// Each absent copy contributes an empty stream to this union.
report_not_found: false,
min_disks: disks_quorum,
agreed: Some(Box::new(move |entry: MetaCacheEntry| {
let entry_name = entry.name.clone();
let agreed_tx = agreed_tx.clone();
Box::pin(async move {
if let Err(e) = agreed_tx.send(entry_name).await {
error!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
entry = %entry.name,
state = "list_path_agreed_send_failed",
error = %e,
"Scanner list_path_raw agreed callback failed"
);
}
Ok(())
})
})),
partial: Some(Box::new(move |entries: MetaCacheEntries, _: &[Option<DiskError>]| {
let partial_tx = partial_tx.clone();
Box::pin(async move {
if let Err(e) = partial_tx.send(entries).await {
error!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
state = "list_path_partial_send_failed",
error = %e,
"Scanner list_path_raw partial callback failed"
);
}
})
})),
finished: Some(Box::new(move |errs: &[Option<DiskError>]| {
let finished_tx = finished_tx.clone();
let errs_clone = errs.to_vec();
Box::pin(async move {
if let Err(e) = finished_tx.send(errs_clone).await {
error!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
state = "list_path_finished_send_failed",
error = %e,
"Scanner list_path_raw finished callback failed"
);
}
})
})),
..scanner_abandoned_child_list_options()
};
#[cfg(test)]
if let Some(observer) = list_path_raw_options_observer {
let _ =
observer.send((options.skip_walkdir_total_timeout, options.walkdir_timeout, options.walkdir_stall_timeout));
}
let result = crate::storage_api::ecstore_with_background_disk_io(
child_ctx_clone.clone(),
list_path_raw(child_ctx_clone.clone(), options),
)
.await;
if let Err(e) = &result {
if is_missing_path_disk_error(e) {
debug!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
bucket = %bucket_clone,
prefix = %prefix,
state = "list_path_missing",
error = %e,
"Scanner list_path_raw missing path skipped"
);
} else {
error!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
bucket = %bucket_clone,
prefix = %prefix,
state = "list_path_failed",
error = %e,
"Scanner list_path_raw failed"
);
}
}
result
});
let mut found_objects = false;
let mut agreed_closed = false;
let mut partial_closed = false;
let mut finished_closed = false;
loop {
if child_ctx.is_cancelled() || (agreed_closed && partial_closed && finished_closed) {
break;
}
#[cfg(test)]
let defer_entries = self.defer_abandoned_entries_until_finished && !finished_closed;
#[cfg(not(test))]
let defer_entries = false;
select! {
entry_name = agreed_rx.recv(), if !agreed_closed && !defer_entries => {
let Some(entry_name) = entry_name else {
agreed_closed = true;
continue;
};
(self.update_current_path)(&entry_name).await;
}
entries = partial_rx.recv(), if !partial_closed && !defer_entries => {
let Some(entries) = entries else {
partial_closed = true;
continue;
};
if !self.try_should_heal().await? {
child_ctx.cancel();
break;
}
#[cfg(test)]
let candidate_limit = self.partial_heal_candidate_limit.unwrap_or(MAX_META_CACHE_HEAL_CANDIDATES);
#[cfg(not(test))]
let candidate_limit = MAX_META_CACHE_HEAL_CANDIDATES;
let discovery = entries.discover_heal_candidates(&bucket, candidate_limit);
#[cfg(test)]
if let Some(observer) = &self.partial_heal_discovery_observer {
let _ = observer.send((discovery.candidates.len(), discovery.truncated_candidates.len()));
}
counter!(METRIC_SCANNER_HEAL_DISCOVERY_CANDIDATES_TOTAL)
.increment(u64::try_from(discovery.candidates.len()).unwrap_or(u64::MAX));
counter!(METRIC_SCANNER_HEAL_DISCOVERY_SUB_QUORUM_TOTAL).increment(
u64::try_from(
discovery
.candidates
.iter()
.filter(|candidate| candidate.replica_count < disks_quorum)
.count(),
)
.unwrap_or(u64::MAX),
);
counter!(METRIC_SCANNER_HEAL_DISCOVERY_UNVERIFIED_TOTAL).increment(
u64::try_from(discovery.unverified_count).unwrap_or(u64::MAX),
);
if discovery.truncated {
counter!(METRIC_SCANNER_HEAL_DISCOVERY_TRUNCATED_TOTAL).increment(1);
}
// The merge emits one key per partial frame, with all its replicas.
// Deduplicate overflow versions within that key, never across the subtree.
let mut seen_heal_candidates: HashSet<(String, Option<String>, MetaCacheHealCandidateKind)> = HashSet::new();
for candidate in discovery.candidates {
let sub_quorum_candidate = candidate.replica_count < disks_quorum;
let version_id = candidate.validated_version().map(|id| id.to_string());
let identity = (candidate.object.clone(), version_id.clone(), candidate.kind.clone());
if !seen_heal_candidates.insert(identity) {
continue;
}
let request = if candidate.is_unversioned() {
build_non_destructive_object_heal_request(
bucket.clone(),
candidate.object.clone(),
self.scan_mode,
HealChannelPriority::High,
)
} else {
build_object_heal_request(
bucket.clone(),
candidate.object.clone(),
version_id.clone(),
self.scan_mode,
HealChannelPriority::High,
)
};
(self.update_current_path)(&candidate.object).await;
let admission = self.send_required_scanner_heal_request(
PendingScannerHealKind::Object,
bucket.clone(),
Some(candidate.object.clone()),
version_id.clone(),
request,
)
.await?;
if admission.is_admitted() {
counter!(METRIC_SCANNER_HEAL_DISCOVERY_QUEUED_TOTAL).increment(1);
} else if sub_quorum_candidate {
self.mark_pending_scanner_heal_reason(
PendingScannerHealKind::Object,
&bucket,
Some(&candidate.object),
version_id.as_deref(),
"sub_quorum_metadata",
);
}
found_objects = true;
}
// Candidates beyond the main cap remain exact
// version requests; never downgrade them to a
// latest-version (version_id=None) heal.
for candidate in discovery.truncated_candidates {
let version_id = candidate.validated_version().map(|id| id.to_string());
let identity = (candidate.object.clone(), version_id.clone(), candidate.kind.clone());
if !seen_heal_candidates.insert(identity) {
continue;
}
let request = if candidate.is_unversioned() {
build_non_destructive_object_heal_request(
bucket.clone(),
candidate.object.clone(),
self.scan_mode,
HealChannelPriority::High,
)
} else {
build_object_heal_request(
bucket.clone(),
candidate.object.clone(),
version_id.clone(),
self.scan_mode,
HealChannelPriority::High,
)
};
(self.update_current_path)(&candidate.object).await;
let admission = self
.send_required_scanner_heal_request(
PendingScannerHealKind::Object,
bucket.clone(),
Some(candidate.object.clone()),
version_id,
request,
)
.await?;
if admission.is_admitted() {
counter!(METRIC_SCANNER_HEAL_DISCOVERY_QUEUED_TOTAL).increment(1);
}
found_objects = true;
}
}
errs = finished_rx.recv(), if !finished_closed => {
let Some(errs) = errs else {
finished_closed = true;
continue;
};
finished_closed = true;
// The callback preserves the input disk order. A failing sibling does
// not invalidate this walk, but the selected source's rejection does.
if let Some(error) = self.disks.iter().position(|disk| Arc::ptr_eq(disk, &self.local_disk))
.and_then(|idx| errs.get(idx)).and_then(Option::as_ref)
{
let error = StorageError::from(error.clone());
if is_scanner_source_unavailable(&error) {
return Err(ScannerError::source_unavailable(error));
}
}
if disk_errors_are_only_missing_paths(&errs) {
debug!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
state = "list_path_finished_missing_paths",
errors = ?errs,
"Scanner list_path_raw finished with missing paths"
);
} else {
error!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
state = "list_path_finished_with_errors",
errors = ?errs,
"Scanner list_path_raw finished with disk errors"
);
}
// The producer awaited callback sends, not their
// consumption. Drain the remaining candidate and
// agreed frames before closing this child walk.
}
_ = child_ctx.cancelled() => {
break;
}
}
}
if ctx.is_cancelled() {
return Err(ScannerError::Other("Operation cancelled".to_owned()));
}
if child_ctx.is_cancelled() {
return Err(ScannerError::AbandonedChildUnverified);
}
match listing.await {
Ok(Ok(())) => {}
Ok(Err(error)) if is_missing_path_disk_error(&error) => {}
_ => return Err(ScannerError::AbandonedChildUnverified),
}
Ok(found_objects)
}
}
@@ -0,0 +1,293 @@
// Copyright 2026 RustFS Team
// Licensed under the Apache License, Version 2.0.
use super::*;
impl FolderScanner {
pub(super) async fn next_queued_child(
&mut self,
ctx: &CancellationToken,
frame: &mut FolderFrame,
listing: &mut FolderListing,
) -> Result<Option<ChildRequest>, ScannerError> {
let folder = &frame.folder;
let this_hash = &frame.hash;
let into = &mut frame.entry;
let mut work = listing.dir_reader.as_mut().and_then(ScannerDirectory::work);
loop {
if let Some(work) = &mut work
&& let Some((name, linked)) = listing.acknowledge_previous.take()
{
work.gap |= self.coverage_gap;
work.acknowledge(&name, linked, into.compacted);
}
if ctx.is_cancelled() {
return Err(ScannerError::Other("Operation cancelled".to_string()));
}
let queued_folder = if let Some(work) = &mut work {
let Some(name) =
wait_for_scanner_io(ctx, run_scanner_node_operation(self.node_admission.as_ref(), ctx, work.next_name()))
.await???
else {
return Ok(None);
};
let name = path_join_buf(&[&folder.name, &name]);
let source = if !listing.force_compact && self.old_cache.find(&name).is_some() {
FolderScanSource::Existing
} else {
FolderScanSource::New
};
let h = hash_path(&name);
if source == FolderScanSource::Existing
&& let Some(updates) = &mut self.usage_updates
{
updates
.cache
.copy_with_children(&self.old_cache, &h, &Some(this_hash.clone()));
}
QueuedFolder {
folder: CachedFolder {
name,
parent: Some(this_hash.clone()),
object_heal_prob_div: folder.object_heal_prob_div,
},
source,
}
} else {
let Some(queued) = listing.queued_folders.next() else { return Ok(None) };
queued
};
let mut folder_item = queued_folder.folder;
let h = hash_path(&folder_item.name);
if work.is_some() {
listing.acknowledge_previous = Some((folder_item.name.clone(), false));
}
if work.is_some()
&& queued_folder.source == FolderScanSource::Existing
&& self.can_reuse_scoped_child(folder, into, &folder_item.name, &h)
{
self.reuse_clean_root_child(&folder_item, &h, into);
if let Some((_, linked)) = &mut listing.acknowledge_previous {
*linked = true;
}
continue;
}
let reuse_covered = self.can_reuse_covered_namespace(&folder_item.name, into.compacted);
let mut child_mode = if self.is_erasure_mode && is_erasure_candidate(&folder_item.name) {
FolderScanMode::ErasureCandidate {
reuse_namespace: reuse_covered,
parent_has_metadata: listing.found_object_metadata,
}
} else {
FolderScanMode::Namespace
};
if child_mode == FolderScanMode::Namespace && reuse_covered {
let started = Instant::now();
self.new_cache.copy_with_children(&self.old_cache, &h, &folder_item.parent);
into.add_child(&h);
global_metrics()
.scan_observation()
.record_cache_reuse(ScannerCacheReuseKind::CoveredNamespace, started.elapsed());
if let Some((_, linked)) = &mut listing.acknowledge_previous {
*linked = true;
}
continue;
}
match queued_folder.source {
FolderScanSource::New => {
// Add new folders to the update tree so totals update for these.
if !into.compacted
&& let Some(updates) = &mut self.usage_updates
{
let mut found_any = false;
let mut parent = clone_cache_value(this_hash);
let update_root_hash = hash_path(&updates.cache.info.name);
while parent != update_root_hash {
let parent_key = clone_cache_value(&parent.0);
let e = updates.cache.find(&parent_key);
if e.is_none_or(|v| v.compacted) {
found_any = true;
break;
}
if let Some(next) = updates.cache.search_parent(&parent) {
parent = next;
} else {
found_any = true;
break;
}
}
if !found_any {
// Add non-compacted empty entry.
updates
.cache
.replace_hashed(&h, &Some(clone_cache_value(this_hash)), &DataUsageEntry::default());
}
}
}
FolderScanSource::Existing => {
// Usage sampling is not proof that a Deep check ran.
if let Some(reuse) = self.sampled_namespace_reuse(&h, into.compacted, listing.forward_sweep) {
if reuse {
if child_mode == FolderScanMode::Namespace {
let started = Instant::now();
self.new_cache.copy_with_children(&self.old_cache, &h, &folder_item.parent);
into.add_child(&h);
global_metrics()
.scan_observation()
.record_cache_reuse(ScannerCacheReuseKind::SampledNamespace, started.elapsed());
self.record_scan_resume_hint(&folder_item.name);
continue;
}
// Sampling may skip namespace work, never the
// classification that protects its parent object.
child_mode = FolderScanMode::ErasureCandidate {
reuse_namespace: true,
parent_has_metadata: listing.found_object_metadata,
};
} else {
folder_item.object_heal_prob_div = data_usage_update_dir_cycles();
}
}
}
}
(self.update_current_path)(&folder_item.name).await;
// Keep a compacted namespace child's accounting local until it
// succeeds. Ordinary child errors can then discard it without
// rolling back totals already committed by healthy siblings.
let isolate_compacted_child =
into.compacted && listing.isolate_compacted_children && child_mode == FolderScanMode::Namespace;
// A parked queue owns only committed subtree totals. Run the
// active child in its own accumulator so cancellation cannot
// count a partial child twice at the next admission.
let child_summary = isolate_compacted_child || (into.compacted && work.is_some());
let accounting = if child_summary {
ChildAccounting::Summary {
isolated: isolate_compacted_child,
}
} else if into.compacted {
ChildAccounting::Shared
} else {
ChildAccounting::Linked
};
return Ok(Some(ChildRequest {
folder: folder_item,
mode: child_mode,
accounting,
origin: ChildOrigin::Queued,
}));
}
}
pub(super) async fn accept_queued_child(
&mut self,
ctx: &CancellationToken,
frame: &mut FolderFrame,
listing: &mut FolderListing,
child: &FolderFrame,
accounting: ChildAccounting,
result: Result<FolderScanOutcome, ScannerError>,
) -> Result<bool, ScannerError> {
let mut work = listing.dir_reader.as_mut().and_then(ScannerDirectory::work);
let into = &mut frame.entry;
let folder = &child.folder;
let hash = &child.hash;
let outcome = match (accounting, result) {
(ChildAccounting::Shared, result) => result?,
(ChildAccounting::Summary { .. }, Ok(outcome)) => {
into.merge(&child.entry);
if let Some(work) = &mut work {
if outcome == FolderScanOutcome::Namespace && !self.coverage_gap && child.entry.failed_objects == 0 {
work.compacted_total.merge(&child.entry);
work.acknowledge(&folder.name, false, true);
} else if child.entry.failed_objects != 0 {
self.coverage_gap = true;
}
}
outcome
}
(ChildAccounting::Linked, Ok(outcome)) => outcome,
(accounting, Err(error)) => {
if matches!(&error, ScannerError::DirectoryChanged | ScannerError::AbandonedChildUnverified) {
return Err(error);
}
if ctx.is_cancelled() || matches!(&error, ScannerError::SourceUnavailable(_) | ScannerError::ResourceDeferred) {
if matches!(accounting, ChildAccounting::Summary { .. }) {
// Propagate the counted prefix before yielding the source.
into.merge(&child.entry);
} else {
self.preserve_partial_child_progress(&folder.parent, hash, into, &child.entry)
.await;
}
return Err(error);
}
if child.mode != FolderScanMode::Namespace
|| (into.compacted && !matches!(accounting, ChildAccounting::Summary { isolated: true }))
{
return Err(error);
}
warn!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
state = "child_scan_failed",
folder = %frame.folder.name,
child_folder = %folder.name,
error = %error,
"Scanner child folder scan failed"
);
// A skipped namespace is a gap even outside a checkpointed sweep.
self.coverage_gap = true;
self.finish_raw_enumeration_parent(&folder.name);
return Ok(true);
}
};
self.finish_raw_enumeration_parent(&folder.name);
if outcome == FolderScanOutcome::Vanished || outcome == FolderScanOutcome::ErasureData {
self.new_cache.delete_recursive(hash);
if let Some(updates) = &mut self.usage_updates {
updates.cache.delete_recursive(hash);
}
into.children.remove(&clone_cache_value(&hash.0));
if outcome == FolderScanOutcome::Vanished || listing.found_object_metadata {
return Ok(true);
}
// Siblings that completed cannot certify an unresolved parent object.
self.coverage_gap |= listing.forward_sweep;
if self.coverage_frontier.as_deref().is_some_and(|frontier| {
frontier
.strip_prefix(&frame.folder.name)
.is_some_and(|suffix| suffix.starts_with('/'))
}) {
self.coverage_frontier = None;
}
self.record_missing_erasure_metadata(&frame.folder, into).await?;
return Ok(false);
}
if into.compacted {
self.record_completed_child(&folder.name);
if !frame.was_compacted && work.is_some() {
self.maybe_send_owned_checkpoint(&frame.folder, &frame.hash, into, work.as_deref());
}
self.send_update_for_entry(&frame.hash, &frame.folder.parent, into).await;
tokio::task::yield_now().await;
} else {
into.add_child(hash);
if let Some(work) = &mut work {
work.acknowledge(&folder.name, true, false);
}
self.record_completed_child(&folder.name);
tokio::task::yield_now().await;
self.maybe_send_checkpoint(&frame.folder, &frame.hash, into);
self.refresh_usage_subtree(hash, &folder.parent);
self.send_update().await;
}
Ok(true)
}
}
+2 -15
View File
@@ -617,22 +617,9 @@ async fn checkpoint_ancestor_depth_limit_preserves_suspended_accounting() {
size: 7,
..Default::default()
};
let mut child = DataUsageEntry::default();
let error = scanner
.scan_child_folder(
CancellationToken::new(),
CachedFolder {
name: "bucket/parent/child".to_string(),
parent: Some(hash.clone()),
object_heal_prob_div: 1,
},
&mut hash,
&mut parent,
&mut child,
FolderScanMode::Namespace,
)
.await
.expect_err("unsupported depth must stop before recursion");
.suspend_checkpoint_parent(&mut hash, &mut parent)
.expect_err("unsupported checkpoint depth must preserve the parent");
assert!(matches!(error, ScannerError::Other(message) if message.contains("depth limit")));
assert_eq!(hash, hash_path("bucket/parent"));
assert_eq!((parent.objects, parent.size), (3, 7));
@@ -225,6 +225,105 @@ async fn large_prefix_deep_resumes_after_budget_across_cycles_and_leaders() {
check_large_prefix_resumption(HealScanMode::Deep).await;
}
tokio::task_local! {
static MAX_FOLDER_FRAMES: std::cell::Cell<usize>;
}
pub(in crate::scanner_folder) fn observe_folder_frame_depth(depth: usize) {
let _ = MAX_FOLDER_FRAMES.try_with(|peak| peak.set(peak.get().max(depth)));
}
#[test]
#[serial]
fn nested_folder_sweep_resumes_with_exact_usage() {
// Match the Linux server profiles even when nextest sets a larger libtest stack.
let stack_size = if cfg!(debug_assertions) {
8 * rustfs_config::DEFAULT_THREAD_STACK_SIZE
} else {
rustfs_config::DEFAULT_THREAD_STACK_SIZE
};
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.thread_stack_size(stack_size)
.enable_all()
.build()
.expect("build scanner worker runtime");
let worker = runtime.spawn(MAX_FOLDER_FRAMES.scope(std::cell::Cell::new(0), check_nested_folder_sweep()));
runtime
.block_on(worker)
.expect("scanner worker must complete the folder sweep");
}
async fn check_nested_folder_sweep() {
let (scanner, root) = build_test_scanner().await;
let _cleanup = TestGuard {
temp_dir: Some(root.clone()),
};
write_checkpoint_object(
&root,
"documents/archive/2024/quarter-1/finance/receipts/first",
&[(Some(Uuid::from_u128(1)), 3), (Some(Uuid::from_u128(2)), 7)],
)
.await;
for (key, bytes) in [
("documents/archive/2024/quarter-1/finance/receipts/second", 11),
("documents/archive/2025/quarter-2/finance/reports/first", 13),
("pictures/archive/2024/quarter-2/projects/meeting/first", 17),
] {
write_checkpoint_object(&root, key, &[(None, bytes)]).await;
}
let identity = crate::DataUsageScanIdentity {
tier_registry_generation: crate::runtime_tier_registry_for_cycle(11, 7).await.generation,
..bound_checkpoint().1
};
let mut initial = DataUsageCache::default();
initial.prepare_bucket_checkpoint("bucket", 11, 7, SOURCE, PLAN, identity);
initial.info.skip_healing = true;
let mode = HealScanMode::Normal;
let (fresh, visits) = scan(&scanner.local_disk, initial.clone(), mode, 5).await;
let ScannerDiskScanOutcome::Complete(fresh) = fresh else {
panic!("the uninterrupted sweep must visit all sibling prefixes");
};
assert!(
MAX_FOLDER_FRAMES.with(|peak| peak.replace(0)) >= 8,
"the driver must own all ancestor frames"
);
assert_eq!(visits.progress().0, 4);
let expected = (4, 2, 51);
let totals = fresh.checked_flatten("bucket").expect("complete fresh bucket tree");
assert_eq!((totals.objects, totals.versions, totals.size), expected);
let (interrupted, visits) = scan(&scanner.local_disk, initial, mode, 2).await;
let ScannerDiskScanOutcome::Partial(partial) = interrupted else {
panic!("the two-object budget must stop inside the folder walk");
};
assert!(
MAX_FOLDER_FRAMES.with(|peak| peak.replace(0)) >= 8,
"the budget must interrupt a nested walk"
);
assert_eq!(visits.reason(), Some(ScannerCycleBudgetReason::Objects));
let store = FixtureStore::new();
let mut resumed = save_reload(&store, &partial).await;
assert!(!resumed.info.snapshot_complete);
assert!(resumed.has_scan_position());
resumed.prepare_bucket_checkpoint("bucket", 12, 8, SOURCE, PLAN, identity);
resumed.info.skip_healing = true;
let (finished, _) = scan(&scanner.local_disk, resumed, mode, 5).await;
let ScannerDiskScanOutcome::Complete(finished) = finished else {
panic!("the resumed walk must finish the remaining sibling prefixes");
};
assert!(
MAX_FOLDER_FRAMES.with(|peak| peak.get()) >= 8,
"the driver must revisit nested work after reload"
);
let persisted = save_reload(&store, &finished).await;
assert!(persisted.info.snapshot_complete);
assert!(persisted.info.scan_checkpoint.is_none());
let totals = persisted.checked_flatten("bucket").expect("complete resumed bucket tree");
assert_eq!((totals.objects, totals.versions, totals.size), expected);
}
async fn check_large_prefix_resumption(mode: HealScanMode) {
let (scanner, root) = build_test_scanner().await;
let _cleanup = TestGuard {
+2 -2
View File
@@ -192,7 +192,7 @@ pub enum WalkVersionsSortOrder {
/// `version_id` identifies the S3 version while these fields identify the
/// concrete generation observed before the delete was queued. This matters for
/// the reusable null version ID in versioning-suspended buckets.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ObjectToDeleteIdentity {
pub data_dir: Option<Uuid>,
pub mod_time: Option<OffsetDateTime>,
@@ -267,7 +267,7 @@ impl DeleteObjectCondition {
}
}
#[derive(Debug, Default, Clone)]
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
pub struct ObjectToDelete {
pub object_name: String,
pub version_id: Option<Uuid>,
+10 -3
View File
@@ -32,7 +32,7 @@ The route returns HTTP 200 with JSON after all configured targets have been chec
"Arn": "arn:minio:replication::target",
"Bucket": "replica",
"Status": "FAILED",
"Error": "probe cleanup failed: target delete object version check failed: AccessDenied",
"Error": "probe cleanup failed: delete probe object version: HTTP 403 AccessDenied",
"Phases": {
"Bucket": { "Status": "OK" },
"Versioning": { "Status": "OK" },
@@ -43,7 +43,7 @@ The route returns HTTP 200 with JSON after all configured targets have been chec
"VersionDelete": { "Status": "OK" },
"Cleanup": {
"Status": "FAILED",
"Error": "target delete object version check failed: AccessDenied"
"Error": "delete probe object version: HTTP 403 AccessDenied"
}
}
}
@@ -55,9 +55,16 @@ The route returns HTTP 200 with JSON after all configured targets have been chec
| --- | --- |
| `Phases.*.Status` | `OK`, `FAILED`, or `SKIPPED`. |
| `Error` | Single line, bounded to `REPLICATION_CHECK_ERROR_MAX_BYTES` (512 bytes); omits remote messages, endpoints, credentials, signatures, and authorization material. |
| `Cleanup` | A cleanup failure is always explicit; it is never reported as a successful check. |
| `ActiveMutation` | Always `true` for this check, including when cleanup succeeds. The probe writes to the target. |
| `Cleanup` | Reports whether the probe could account for its writes and verify that its exact key has no remaining versions or delete markers. |
| `Code` | Appears only on failures callers are expected to branch on (currently `BucketRemoteTargetVersionMismatch`). Go decoders ignore the unknown key. |
## Cleanup phase
If a version DELETE loses its response, the target may already have removed that version. Cleanup lists versions and delete markers for the exact probe key. It can retry a version still present once and verifies the result with a fresh listing. A definitive rejection such as HTTP 403, a listing that cannot be completed, or a remaining artifact makes cleanup fail.
When investigating a failure, capture the target's DELETE responses and list both versions and delete markers before an external test or operator removes the test bucket. Keep the request times and target request IDs so they can be matched to the target service log.
## VersionFidelity phase
`VersionFidelity` pins the version-identity contract on both write paths. The probe PUT carries a source version id (header plus `?versionId=` query, the exact shape live replication uses) and the target must answer with the same id; a second probe repeats the check through CreateMultipartUpload -> UploadPart -> CompleteMultipartUpload, where the target fixes the version at initiate and only reports it on completion. A target can adopt PutObject ids and still mint its own for multipart; the failure message names the path that drifted.
+3 -112
View File
@@ -12,6 +12,9 @@
// See the License for the specific language governing permissions and
// limitations under the License.
mod replication_probe_cleanup;
use self::replication_probe_cleanup::cleanup_replication_probe;
use super::storage_api::bucket::bandwidth::monitor::BandwidthDetails;
use super::storage_api::bucket::metadata_sys;
use super::storage_api::bucket::replication::{self, BucketReplicationResyncStatus, BucketStats, ReplicationStatusType};
@@ -3004,118 +3007,6 @@ async fn delete_replication_probe_object(
.map_err(S3ClientError::from)
}
async fn delete_replication_probe_version(
target_client: &TargetClient,
target_bucket: &str,
probe_key: &str,
version_id: &str,
) -> Result<(), S3ClientError> {
target_client
.client
.delete_object()
.bucket(target_bucket)
.key(probe_key)
.version_id(version_id)
.send()
.await
.map(|_| ())
.map_err(S3ClientError::from)
}
/// The VersionDelete phase already removed the probe version the cleanup is
/// handed, and a strict S3 target (Wasabi) answers a second DELETE of that
/// id with `NoSuchVersion` where RustFS/MinIO answer 204: the goal is met
/// either way.
fn probe_version_already_gone(err: &S3ClientError) -> bool {
matches!(err.code.as_deref(), Some("NoSuchKey" | "NoSuchVersion"))
}
async fn cleanup_replication_probe<'a>(
target_client: &TargetClient,
target_bucket: &str,
probe_key: &str,
known_version_ids: impl IntoIterator<Item = Option<&'a str>>,
) -> Result<(), String> {
let mut errors = Vec::new();
let mut deleted_ids = HashSet::new();
for version_id in known_version_ids.into_iter().flatten() {
if deleted_ids.insert(version_id.to_string())
&& let Err(err) = delete_replication_probe_version(target_client, target_bucket, probe_key, version_id).await
&& !probe_version_already_gone(&err)
{
errors.push(format_replication_check_client_error(
&err,
ReplicationCheckFailureContext::DeleteObjectVersion,
));
}
}
let mut key_marker = None;
let mut version_id_marker = None;
loop {
let output = target_client
.client
.list_object_versions()
.bucket(target_bucket)
.prefix(probe_key)
.set_key_marker(key_marker.clone())
.set_version_id_marker(version_id_marker.clone())
.send()
.await
.map_err(|err| {
format_replication_check_client_error(
&S3ClientError::from(err),
ReplicationCheckFailureContext::DeleteObjectVersion,
)
})?;
let mut discovered_ids = Vec::new();
discovered_ids.extend(
output
.versions()
.iter()
.filter(|version| version.key() == Some(probe_key))
.filter_map(|version| version.version_id().map(ToOwned::to_owned)),
);
discovered_ids.extend(
output
.delete_markers()
.iter()
.filter(|marker| marker.key() == Some(probe_key))
.filter_map(|marker| marker.version_id().map(ToOwned::to_owned)),
);
for version_id in discovered_ids {
if deleted_ids.insert(version_id.clone())
&& let Err(err) = delete_replication_probe_version(target_client, target_bucket, probe_key, &version_id).await
&& !probe_version_already_gone(&err)
{
errors.push(format_replication_check_client_error(
&err,
ReplicationCheckFailureContext::DeleteObjectVersion,
));
}
}
if output.is_truncated() != Some(true) {
break;
}
let next_key_marker = output.next_key_marker().map(ToOwned::to_owned);
let next_version_id_marker = output.next_version_id_marker().map(ToOwned::to_owned);
if next_key_marker.is_none() || next_key_marker == key_marker {
errors.push("target returned an invalid cleanup pagination marker".to_string());
break;
}
key_marker = next_key_marker;
version_id_marker = next_version_id_marker;
}
if errors.is_empty() {
Ok(())
} else {
Err(bound_replication_check_error(errors.join("; ")))
}
}
async fn source_bucket_requires_object_lock(bucket: &str) -> S3Result<bool> {
match metadata_sys::get_object_lock_config(bucket).await {
Ok((config, _)) => Ok(config
@@ -0,0 +1,267 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#[cfg(test)]
mod tests;
use super::{TargetClient, bound_replication_check_error};
use aws_sdk_s3::error::{ProvideErrorMetadata, SdkError};
use std::collections::{BTreeMap, BTreeSet, HashSet};
// A fresh probe creates at most four distinct versions. Allow for ambiguous writes and
// small target page sizes, but never traverse an unbounded response from a remote target.
// This bounds both tracked IDs and pages even if a target returns a single entry per page.
const PROBE_CLEANUP_LIMIT: usize = 64;
// S3 object keys and version IDs are each limited to 1,024 bytes.
const PROBE_CLEANUP_MAX_TOKEN_BYTES: usize = 1024;
struct ProbeCleanupError {
detail: String,
reconcilable: bool,
}
fn probe_cleanup_error<E: ProvideErrorMetadata>(operation: &str, err: &SdkError<E>) -> ProbeCleanupError {
let status = err.raw_response().map(|response| response.status().as_u16());
let code = err.code();
// Keep remote messages, endpoint URLs, and arbitrary remote codes out of admin responses.
let safe_code = code.filter(|code| {
matches!(
*code,
"AccessDenied"
| "InvalidAccessKeyId"
| "SignatureDoesNotMatch"
| "InvalidToken"
| "ExpiredToken"
| "InvalidRequest"
| "NoSuchBucket"
| "NoSuchKey"
| "NoSuchVersion"
| "RequestTimeout"
| "SlowDown"
| "ServiceUnavailable"
| "InternalError"
| "InternalServerError"
)
});
let category = match err {
SdkError::ConstructionFailure(_) => "request construction failure",
SdkError::TimeoutError(_) => "timeout",
SdkError::DispatchFailure(error) if error.is_timeout() => "timeout",
SdkError::DispatchFailure(_) => "transport failure",
SdkError::ResponseError(_) => "invalid response",
_ => "remote request failed",
};
let detail = match (status, safe_code) {
(Some(status), Some(code)) => format!("{operation}: HTTP {status} {code}"),
(Some(status), None) => format!("{operation}: HTTP {status} ({category})"),
(None, Some(code)) => format!("{operation}: {code}"),
(None, None) => format!("{operation}: {category}"),
};
let reconcilable = match (code, status) {
(_, Some(401 | 403)) => false,
(Some("RequestTimeout" | "SlowDown" | "ServiceUnavailable" | "InternalError" | "InternalServerError"), _) => true,
(Some(_), _) => false,
(None, Some(408 | 429 | 500 | 502 | 503 | 504)) => true,
// An unreadable success response can follow a committed DELETE.
(None, Some(200..=299)) => true,
(None, None) => match err {
SdkError::TimeoutError(_) | SdkError::ResponseError(_) => true,
SdkError::DispatchFailure(error) => !error.is_user(),
_ => false,
},
_ => false,
};
ProbeCleanupError { detail, reconcilable }
}
#[derive(Default)]
struct ProbeVersionCleanup {
attempts: u8,
error: Option<ProbeCleanupError>,
}
impl ProbeVersionCleanup {
fn can_delete(&self) -> bool {
self.attempts < 2 && self.error.as_ref().is_none_or(|error| error.reconcilable)
}
async fn delete(&mut self, client: &TargetClient, bucket: &str, key: &str, version_id: &str) {
self.attempts += 1;
self.error = match client
.client
.delete_object()
.bucket(bucket)
.key(key)
.version_id(version_id)
.send()
.await
{
// A strict target may reject the repeat of the VersionDelete phase with NoSuchVersion.
Ok(_) => None,
Err(err)
if matches!(err.code(), Some("NoSuchKey" | "NoSuchVersion"))
&& err.raw_response().is_some_and(|response| response.status().as_u16() == 404) =>
{
None
}
Err(err) => Some(probe_cleanup_error("delete probe object version", &err)),
};
}
}
async fn list_replication_probe_versions(client: &TargetClient, bucket: &str, key: &str) -> Result<BTreeSet<String>, String> {
let mut ids = BTreeSet::new();
let mut cursor: (Option<String>, Option<String>) = (None, None);
let mut seen_cursors = HashSet::new();
for _ in 0..PROBE_CLEANUP_LIMIT {
let output = client
.client
.list_object_versions()
.bucket(bucket)
.prefix(key)
.max_keys(PROBE_CLEANUP_LIMIT as i32)
.set_key_marker(cursor.0.clone())
.set_version_id_marker(cursor.1.clone())
.send()
.await
.map_err(|err| probe_cleanup_error("list probe object versions", &err).detail)?;
if output.name().is_some_and(|name| name != bucket)
|| output.prefix().is_some_and(|prefix| prefix != key)
|| output
.key_marker()
.is_some_and(|marker| marker != cursor.0.as_deref().unwrap_or_default())
|| output
.version_id_marker()
.is_some_and(|marker| marker != cursor.1.as_deref().unwrap_or_default())
{
return Err("target returned a different probe cleanup listing than requested".to_string());
}
let entry_count = output.versions().len() + output.delete_markers().len();
if entry_count > PROBE_CLEANUP_LIMIT {
return Err("target exceeded the probe cleanup page entry limit".to_string());
}
let versions = output.versions().iter().map(|version| (version.key(), version.version_id()));
let markers = output
.delete_markers()
.iter()
.map(|marker| (marker.key(), marker.version_id()));
for (entry_key, id) in versions.chain(markers) {
if entry_key.ok_or("target listed a probe cleanup entry without a key")? == key {
let id = id
.filter(|value| !value.is_empty() && value.len() <= PROBE_CLEANUP_MAX_TOKEN_BYTES)
.ok_or("target listed a probe entry without a valid version ID")?;
ids.insert(id.to_owned());
if ids.len() > PROBE_CLEANUP_LIMIT {
return Err("target exceeded the probe cleanup version limit".to_string());
}
}
}
let next_key = output.next_key_marker().filter(|value| !value.is_empty());
let next_version = output.next_version_id_marker().filter(|value| !value.is_empty());
let has_cursor = next_key.is_some() || next_version.is_some();
match output.is_truncated() {
Some(false) if !has_cursor => return Ok(ids),
// Some compatible targets omit IsTruncated on a short terminal page. Require
// their bucket identity so an empty or unrelated response cannot certify absence.
None if !has_cursor && entry_count < PROBE_CLEANUP_LIMIT && output.name() == Some(bucket) => return Ok(ids),
Some(true) => {}
_ => return Err("target returned inconsistent probe cleanup pagination status".to_string()),
}
let next_key = next_key
.filter(|value| value.len() <= PROBE_CLEANUP_MAX_TOKEN_BYTES)
.ok_or("target returned an invalid cleanup pagination marker")?;
if next_version.is_some_and(|value| value.len() > PROBE_CLEANUP_MAX_TOKEN_BYTES) {
return Err("target returned an invalid cleanup pagination marker".to_string());
}
cursor = (Some(next_key.to_owned()), next_version.map(str::to_owned));
if !seen_cursors.insert(cursor.clone()) {
return Err("target repeated a cleanup pagination marker pair".to_string());
}
}
Err("target exceeded the probe cleanup page limit".to_string())
}
pub(super) async fn cleanup_replication_probe<'a>(
target_client: &TargetClient,
target_bucket: &str,
probe_key: &str,
known_version_ids: impl IntoIterator<Item = Option<&'a str>>,
) -> Result<(), String> {
let mut versions = BTreeMap::<String, ProbeVersionCleanup>::new();
for id in known_version_ids.into_iter().flatten() {
// Only address valid target-reported IDs; enumeration recovers unknown versions.
if id.is_empty() || id.len() > PROBE_CLEANUP_MAX_TOKEN_BYTES {
continue;
}
let version = versions.entry(id.to_owned()).or_default();
if version.attempts == 0 {
version.delete(target_client, target_bucket, probe_key, id).await;
}
}
// List before mutating a page's cursor. A version first discovered by listing can
// need its initial delete, one retry, and a final read to establish the outcome.
let mut verification_error = None;
for pass in 0..=2 {
let remaining = match list_replication_probe_versions(target_client, target_bucket, probe_key).await {
Ok(ids) => ids,
Err(error) => {
verification_error = Some(error);
break;
}
};
// Absence resolves an ambiguous commit, but cannot erase an explicit denial.
for (id, version) in &mut versions {
if !remaining.contains(id) && version.error.as_ref().is_some_and(|err| err.reconcilable) {
version.error = None;
}
}
if remaining.is_empty() {
break;
}
let new_ids = remaining.iter().filter(|id| !versions.contains_key(*id)).count();
if versions.len() + new_ids > PROBE_CLEANUP_LIMIT {
verification_error = Some("target exceeded the probe cleanup version limit".to_string());
break;
}
let mut attempted = false;
if pass < 2 {
for id in &remaining {
let version = versions.entry(id.clone()).or_default();
if version.can_delete() {
version.delete(target_client, target_bucket, probe_key, id).await;
attempted = true;
}
}
}
if !attempted {
verification_error = Some(format!("target still lists {} probe object versions or delete markers", remaining.len()));
break;
}
}
let errors: Vec<_> = verification_error
.into_iter()
.chain(
versions
.into_values()
.filter_map(|version| version.error.map(|error| error.detail)),
)
.collect();
if errors.is_empty() {
Ok(())
} else {
Err(bound_replication_check_error(errors.join("; ")))
}
}
@@ -0,0 +1,398 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use super::{TargetClient, cleanup_replication_probe};
use aws_sdk_s3::config::{Credentials, Region, retry::RetryConfig};
use http::StatusCode;
use reqwest::Url;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpListener;
const BUCKET: &str = "test-bucket";
const KEY: &str = "probe";
const VERSION: &str = "<Version><Key>probe</Key><VersionId>v1</VersionId></Version>";
#[derive(Debug)]
enum Call {
Delete(String),
List(Option<String>),
}
enum Reply {
Disconnect,
Http(StatusCode, String),
}
fn page(entries: &str, next_version: Option<&str>) -> Reply {
let cursor = match next_version {
Some(version) => format!(
"<IsTruncated>true</IsTruncated><NextKeyMarker>{KEY}</NextKeyMarker><NextVersionIdMarker>{version}</NextVersionIdMarker>"
),
None => "<IsTruncated>false</IsTruncated>".to_owned(),
};
Reply::Http(StatusCode::OK, format!("<ListVersionsResult>{entries}{cursor}</ListVersionsResult>"))
}
fn decode_request(line: &str) -> Call {
let mut parts = line.split_whitespace();
let method = parts.next().expect("HTTP method");
let uri = parts.next().expect("HTTP request target");
let url = Url::parse(&format!("http://localhost{uri}")).expect("relative request URI");
let params: HashMap<_, _> = url.query_pairs().collect();
match method {
"DELETE" => {
assert_eq!(url.path(), format!("/{BUCKET}/{KEY}"));
Call::Delete(params.get("versionId").expect("explicit version").to_string())
}
"GET" => {
assert_eq!(url.path().trim_end_matches('/'), format!("/{BUCKET}"));
assert!(params.contains_key("versions"));
assert_eq!(params.get("prefix").map(|value| value.as_ref()), Some(KEY));
let version_marker = params.get("version-id-marker").map(ToString::to_string);
assert_eq!(params.get("key-marker").map(|value| value.as_ref()), version_marker.as_ref().map(|_| KEY));
Call::List(version_marker)
}
_ => panic!("unexpected cleanup request: {line}"),
}
}
async fn run_cleanup(known: &[&str], mut respond: impl FnMut(Call) -> Reply) -> Result<(), String> {
temp_env::async_with_vars([("NO_PROXY", Some("127.0.0.1")), ("no_proxy", Some("127.0.0.1"))], async {
let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind fake S3");
let endpoint = format!("http://{}", listener.local_addr().expect("bound address"));
let target = TargetClient {
client: Arc::new(aws_sdk_s3::Client::from_conf(
aws_sdk_s3::Config::builder()
.behavior_version_latest()
.region(Region::new("us-east-1"))
.credentials_provider(Credentials::new("fixture", "fixture-secret", None, None, "cleanup-test"))
.endpoint_url(&endpoint)
.force_path_style(true)
.retry_config(RetryConfig::disabled())
.build(),
)),
endpoint,
credentials: None,
bucket: BUCKET.to_owned(),
storage_class: String::new(),
disable_proxy: true,
arn: String::new(),
reset_id: String::new(),
site_peer_deployment_id: String::new(),
secure: false,
health_check_duration: Duration::ZERO,
replicate_sync: false,
timeouts: Default::default(),
};
let serve = async {
loop {
let (stream, _) = listener.accept().await.expect("accept SDK connection");
let mut reader = BufReader::new(stream);
let mut line = String::new();
reader.read_line(&mut line).await.expect("request line");
let call = decode_request(&line);
loop {
line.clear();
assert_ne!(reader.read_line(&mut line).await.expect("request header"), 0, "incomplete SDK headers");
if line == "\r\n" {
break;
}
}
if let Reply::Http(status, body) = respond(call) {
let response = format!(
"HTTP/1.1 {}\r\nContent-Length: {}\r\nContent-Type: application/xml\r\nConnection: close\r\n\r\n{body}",
status,
body.len()
);
reader.get_mut().write_all(response.as_bytes()).await.expect("reply to SDK");
}
}
};
tokio::time::timeout(Duration::from_secs(10), async {
tokio::select! {
result = cleanup_replication_probe(&target, BUCKET, KEY, known.iter().copied().map(Some)) => result,
() = serve => unreachable!("fake S3 should serve until cleanup completes"),
}
})
.await
.expect("cleanup must terminate")
})
.await
}
#[tokio::test]
async fn replication_probe_cleanup_lost_delete_response_confirmed_absent() {
let mut deletes = 0;
let mut confirmed = false;
let outcome = run_cleanup(&["v1"], |call| match call {
Call::Delete(id) => {
assert_eq!(id, "v1");
deletes += 1;
Reply::Disconnect
}
Call::List(None) => {
assert_eq!(deletes, 1);
confirmed = true;
page("", None)
}
other => panic!("unexpected {other:?}"),
})
.await;
assert_eq!(outcome, Ok(()));
assert_eq!(deletes, 1);
assert!(confirmed);
}
#[tokio::test]
async fn replication_probe_cleanup_retries_listed_version_and_confirms_removal() {
let mut deletes = 0;
let mut confirmed = false;
let outcome = run_cleanup(&["v1"], |call| match call {
Call::Delete(id) => {
assert_eq!(id, "v1");
deletes += 1;
match deletes {
1 => Reply::Disconnect,
2 => Reply::Http(StatusCode::NO_CONTENT, String::new()),
_ => panic!("version already removed"),
}
}
Call::List(None) if deletes == 1 => page(VERSION, None),
Call::List(None) if deletes == 2 => {
confirmed = true;
page("", None)
}
other => panic!("unexpected {other:?}"),
})
.await;
assert_eq!(outcome, Ok(()));
assert!(confirmed);
}
#[tokio::test]
async fn replication_probe_cleanup_keeps_forbidden_delete_with_empty_listing() {
let denied = "<Error><Code>AccessDenied</Code><Message>private-upstream-detail</Message></Error>";
for body in [denied, ""] {
let mut deletes = 0;
let error = run_cleanup(&["v1"], |call| match call {
Call::Delete(id) => {
assert_eq!(id, "v1");
deletes += 1;
Reply::Http(StatusCode::FORBIDDEN, body.to_owned())
}
Call::List(None) => page("", None),
other => panic!("unexpected {other:?}"),
})
.await
.expect_err("explicit rejection must survive an empty listing");
let description = error.to_ascii_lowercase();
assert!(description.contains("delete"), "{error}");
assert!(
["403", "forbidden", "permission", "accessdenied", "access denied"]
.iter()
.any(|word| description.contains(word)),
"{error}"
);
assert!(!error.contains("private-upstream-detail"), "{error}");
assert_eq!(deletes, 1);
}
}
#[tokio::test]
async fn replication_probe_cleanup_requires_readable_confirmation() {
let error = run_cleanup(&["v1"], |call| match call {
Call::Delete(_) => Reply::Disconnect,
Call::List(None) => Reply::Http(
StatusCode::FORBIDDEN,
"<Error><Code>AccessDenied</Code><Message>private-upstream-detail</Message></Error>".to_owned(),
),
other => panic!("unexpected {other:?}"),
})
.await
.expect_err("cannot certify the target without a complete list");
assert!(error.to_ascii_lowercase().contains("list"), "{error}");
assert!(!error.contains("private-upstream-detail"), "{error}");
}
#[tokio::test]
async fn replication_probe_cleanup_still_listed_after_successful_deletes_fails() {
let mut deletes = 0;
let mut checked_after_repair = false;
let error = run_cleanup(&["v1"], |call| match call {
Call::Delete(id) => {
assert_eq!(id, "v1");
deletes += 1;
Reply::Http(StatusCode::NO_CONTENT, String::new())
}
Call::List(None) => {
checked_after_repair |= deletes == 2;
page(VERSION, None)
}
other => panic!("unexpected {other:?}"),
})
.await
.expect_err("target kept the version despite successful DELETE responses");
assert!(!error.is_empty());
assert_eq!(deletes, 2);
assert!(checked_after_repair);
}
#[tokio::test]
async fn replication_probe_cleanup_pages_same_key_and_preserves_neighboring_versions() {
const NEIGHBORS: &str = "<Version><Key>probe-neighbor</Key><VersionId>other-data</VersionId></Version><DeleteMarker><Key>probe-neighbor</Key><VersionId>other-marker</VersionId></DeleteMarker>";
let last_page = format!("<Version><Key>probe</Key><VersionId>v3</VersionId></Version>{NEIGHBORS}");
let mut deleted = Vec::new();
let mut confirmed = false;
let outcome = run_cleanup(&[], |call| match call {
Call::Delete(id) => {
assert!(matches!(id.as_str(), "v1" | "v2" | "v3"));
deleted.push(id);
Reply::Http(StatusCode::NO_CONTENT, String::new())
}
Call::List(None) if deleted.len() == 3 => {
confirmed = true;
page(NEIGHBORS, None)
}
Call::List(None) => page(VERSION, Some("v1")),
Call::List(Some(cursor)) if cursor == "v1" => {
page("<DeleteMarker><Key>probe</Key><VersionId>v2</VersionId></DeleteMarker>", Some("v2"))
}
Call::List(Some(cursor)) if cursor == "v2" => page(&last_page, None),
other => panic!("unexpected {other:?}"),
})
.await;
assert_eq!(outcome, Ok(()));
deleted.sort();
assert_eq!(deleted, ["v1", "v2", "v3"]);
assert!(confirmed);
}
#[tokio::test]
async fn replication_probe_cleanup_rejects_cycling_pagination_cursor() {
let mut reached_cycle = false;
let error = run_cleanup(&[], |call| match call {
Call::List(None) => page("", Some("first")),
Call::List(Some(cursor)) if cursor == "first" => page("", Some("second")),
Call::List(Some(cursor)) if cursor == "second" => {
reached_cycle = true;
page("", Some("first"))
}
other => panic!("unexpected {other:?}"),
})
.await
.expect_err("cyclic version listing cannot certify cleanup");
assert!(reached_cycle);
let description = error.to_ascii_lowercase();
assert!(
["pagination", "cursor", "marker"]
.iter()
.any(|word| description.contains(word)),
"{error}"
);
}
#[tokio::test]
async fn replication_probe_cleanup_accepts_absent_key_and_version() {
for code in ["NoSuchKey", "NoSuchVersion"] {
let outcome = run_cleanup(&["v1"], |call| match call {
Call::Delete(_) => Reply::Http(StatusCode::NOT_FOUND, format!("<Error><Code>{code}</Code></Error>")),
Call::List(None) => page("", None),
other => panic!("unexpected {other:?}"),
})
.await;
assert_eq!(outcome, Ok(()));
}
}
#[tokio::test]
async fn replication_probe_cleanup_validates_the_entire_listing_before_deleting() {
let name = format!("<Name>{BUCKET}</Name><Prefix>{KEY}</Prefix>");
let too_many = (0..65)
.map(|id| format!("<Version><Key>{KEY}</Key><VersionId>overflow-{id}</VersionId></Version>"))
.collect::<Vec<_>>()
.join("");
let terminal = |contents: &str| format!("<ListVersionsResult>{contents}</ListVersionsResult>");
let cases = [
("error payload with HTTP 200", "<Error><Code>AccessDenied</Code></Error>".to_owned()),
("unidentified terminal page", terminal("")),
(
"wrong bucket",
terminal(&format!("<Name>other-bucket</Name><Prefix>{KEY}</Prefix>{VERSION}")),
),
(
"wrong prefix",
terminal(&format!(
"<Name>{BUCKET}</Name><Prefix>another-key</Prefix><IsTruncated>false</IsTruncated>"
)),
),
(
"wrong starting key",
terminal(&format!("{name}<KeyMarker>other</KeyMarker><IsTruncated>false</IsTruncated>")),
),
(
"wrong starting version",
terminal(&format!(
"{name}<VersionIdMarker>wrong-cursor</VersionIdMarker><IsTruncated>false</IsTruncated>"
)),
),
(
"version missing its ID",
terminal(&format!("{name}<IsTruncated>false</IsTruncated><Version><Key>{KEY}</Key></Version>")),
),
(
"delete marker with empty ID",
terminal(&format!(
"{name}<IsTruncated>false</IsTruncated><DeleteMarker><Key>{KEY}</Key><VersionId/></DeleteMarker>"
)),
),
("overlong page", terminal(&format!("{name}<IsTruncated>false</IsTruncated>{too_many}"))),
];
for (case, invalid_page) in cases {
let mut saw_invalid_page = false;
let result = run_cleanup(&[], |call| match call {
Call::List(None) => Reply::Http(StatusCode::OK, terminal(&format!(
"{name}{VERSION}<IsTruncated>true</IsTruncated><NextKeyMarker>{KEY}</NextKeyMarker><NextVersionIdMarker>v1</NextVersionIdMarker>"
))),
Call::List(Some(marker)) if marker == "v1" => {
saw_invalid_page = true;
Reply::Http(StatusCode::OK, invalid_page.clone())
}
other => panic!("{case}: unexpected {other:?} before completion of the scan"),
})
.await;
assert!(saw_invalid_page, "{case}: the scan never reached the terminal page");
assert!(result.is_err(), "{case}: invalid list certified cleanup");
}
}
#[tokio::test]
async fn replication_probe_cleanup_accepts_legacy_short_page_with_bucket_identity() {
let mut listed = false;
let outcome = run_cleanup(&[], |call| match call {
Call::List(None) => {
listed = true;
Reply::Http(
StatusCode::OK,
format!("<ListVersionsResult><Name>{BUCKET}</Name><Prefix>{KEY}</Prefix></ListVersionsResult>"),
)
}
other => panic!("unexpected {other:?} for an empty short page"),
})
.await;
assert_eq!(outcome, Ok(()));
assert!(listed);
}
+41 -34
View File
@@ -1273,22 +1273,25 @@ fn build_list_objects_v2_metadata_output(
}
}
/// Answer a `CreateBucket` for a bucket that already exists.
///
/// A deployment owns one bucket namespace, so every requester that passed
/// authorization belongs to the same owner as the bucket's creator; there is no
/// second account that could trigger `BucketAlreadyExists`. That leaves the AWS
/// account-owner semantics: the default region returns the legacy idempotent
/// `200 OK`, any other region returns `BucketAlreadyOwnedByYou`.
fn create_bucket_exists_response(region: &str) -> S3Result<S3Response<CreateBucketOutput>> {
if region == RUSTFS_REGION {
return Ok(S3Response::new(CreateBucketOutput::default()));
fn create_bucket_response(
region: &str,
bucket: &str,
path: &str,
already_exists: bool,
) -> S3Result<S3Response<CreateBucketOutput>> {
// A deployment has one bucket owner. Only the default region treats a repeated create as idempotent.
if already_exists && region != RUSTFS_REGION {
return Err(S3Error::with_message(
S3ErrorCode::BucketAlreadyOwnedByYou,
"The requested bucket already exists.",
));
}
Err(S3Error::with_message(
S3ErrorCode::BucketAlreadyOwnedByYou,
"The requested bucket already exists.",
))
// On a bucket-level request the virtual-hosted form has an empty path after the leading slash.
let location = (region == RUSTFS_REGION && !path.trim_matches('/').is_empty()).then(|| format!("/{bucket}"));
Ok(S3Response::new(CreateBucketOutput {
location,
..Default::default()
}))
}
fn resolve_notification_region(global_region: Option<Region>, request_region: Option<Region>) -> String {
@@ -1489,12 +1492,9 @@ impl DefaultBucketUsecase {
current_object_store_handle_for_context(self.context.as_deref())
}
fn create_bucket_exists_result(&self) -> S3Result<S3Response<CreateBucketOutput>> {
let region = self
.global_region()
.map(|region| region.to_string())
.unwrap_or_else(|| RUSTFS_REGION.to_string());
create_bucket_exists_response(&region)
fn create_bucket_result(&self, bucket: &str, path: &str, already_exists: bool) -> S3Result<S3Response<CreateBucketOutput>> {
let region = self.global_region();
create_bucket_response(region.as_ref().map_or(RUSTFS_REGION, Region::as_str), bucket, path, already_exists)
}
#[instrument(
@@ -1532,7 +1532,7 @@ impl DefaultBucketUsecase {
.is_ok()
{
let helper = OperationHelper::new(&req, EventName::BucketCreated, S3Operation::CreateBucket);
let result = self.create_bucket_exists_result();
let result = self.create_bucket_result(&req.input.bucket, req.uri.path(), true);
let _ = helper.complete(&result);
return result;
}
@@ -1612,16 +1612,15 @@ impl DefaultBucketUsecase {
.await;
}
Err(StorageError::BucketExists(_)) => {
let result = self.create_bucket_exists_result();
let result = self.create_bucket_result(&bucket, req.uri.path(), true);
let _ = helper.complete(&result);
return result;
}
Err(e) => return Err(ApiError::from(e).into()),
}
let output = CreateBucketOutput::default();
counter!("rustfs_create_bucket_total").increment(1);
let result = Ok(S3Response::new(output));
let result = self.create_bucket_result(&bucket, req.uri.path(), false);
let _ = helper.complete(&result);
rustfs_scanner::record_dirty_usage_bucket_from_producer(
&bucket,
@@ -4500,14 +4499,20 @@ mod tests {
}
#[test]
fn create_bucket_exists_response_returns_ok_in_default_region() {
let response = create_bucket_exists_response(RUSTFS_REGION).expect("recreate in us-east-1 should succeed");
assert_eq!(response.output.location, None);
}
fn create_bucket_location_preserves_region_and_addressing_style() {
for already_exists in [false, true] {
for path in ["/bucket-name", "/bucket-name/"] {
let response = create_bucket_response(RUSTFS_REGION, "bucket-name", path, already_exists).unwrap();
assert_eq!(response.output.location.as_deref(), Some("/bucket-name"));
}
let response = create_bucket_response(RUSTFS_REGION, "bucket-name", "/", already_exists).unwrap();
assert_eq!(response.output.location, None);
}
#[test]
fn create_bucket_exists_response_returns_owned_by_you_outside_default_region() {
let err = create_bucket_exists_response("eu-west-1").expect_err("recreate outside us-east-1 should report ownership");
let response = create_bucket_response("eu-west-1", "bucket-name", "/bucket-name", false).unwrap();
assert_eq!(response.output.location, None);
let err = create_bucket_response("eu-west-1", "bucket-name", "/bucket-name", true)
.expect_err("recreate outside us-east-1 should report ownership");
assert_eq!(err.code(), &S3ErrorCode::BucketAlreadyOwnedByYou);
}
@@ -4627,7 +4632,7 @@ mod tests {
let store = crate::app::gating_test_env::shared_gating_ecstore().await;
let bucket = format!("create-missing-{}", uuid::Uuid::new_v4().simple());
let input = CreateBucketInput::builder().bucket(bucket.clone()).build().unwrap();
let req = build_request_with_req_info(
let mut req = build_request_with_req_info(
input,
Method::PUT,
ReqInfo {
@@ -4635,8 +4640,10 @@ mod tests {
..Default::default()
},
);
req.uri = format!("/{bucket}").parse().unwrap();
let usecase = DefaultBucketUsecase::with_context(Some(context));
usecase.execute_create_bucket(req).await.expect("create a missing bucket");
let response = usecase.execute_create_bucket(req).await.expect("create a missing bucket");
assert_eq!(response.output.location, Some(format!("/{bucket}")));
let info = store
.get_bucket_info(&bucket, &BucketOptions::default())
.await
+12 -23
View File
@@ -74,8 +74,9 @@ use super::storage_api::multipart_usecase::{
};
use super::trailer_adapter::trailer_source;
use crate::app::object::{
ConcurrencyManager, ForegroundWriteAdmission, get_concurrency_manager, put_object_body_read_timeout,
reject_non_wildcard_write_if_none_match, reject_oversize_single_upload, reject_veeam_sosapi_mutation,
ConcurrencyManager, ForegroundWriteAdmission, check_copy_source_preconditions, get_concurrency_manager,
put_object_body_read_timeout, reject_non_wildcard_write_if_none_match, reject_oversize_single_upload,
reject_veeam_sosapi_mutation,
};
use crate::app::object_data_cache::{
ObjectDataCacheAdapter, invalidate_object_data_cache_after_complete_multipart_success,
@@ -1749,7 +1750,9 @@ impl DefaultMultipartUsecase {
part_number,
upload_id,
copy_source_if_match,
copy_source_if_unmodified_since,
copy_source_if_none_match,
copy_source_if_modified_since,
sse_customer_algorithm,
sse_customer_key,
sse_customer_key_md5,
@@ -1892,27 +1895,13 @@ impl DefaultMultipartUsecase {
let resolved_src_version_id = format_copy_source_version_id(src_info.version_id, src_versioned, src_version_suspended);
if let Some(if_match) = copy_source_if_match {
if let Some(ref etag) = src_info.etag {
if let Some(strong_etag) = if_match.into_etag() {
if ETag::Strong(etag.clone()) != strong_etag {
return Err(s3_error!(PreconditionFailed));
}
} else {
return Err(s3_error!(PreconditionFailed));
}
} else {
return Err(s3_error!(PreconditionFailed));
}
}
if let Some(if_none_match) = copy_source_if_none_match
&& let Some(ref etag) = src_info.etag
&& let Some(strong_etag) = if_none_match.into_etag()
&& ETag::Strong(etag.clone()) == strong_etag
{
return Err(s3_error!(PreconditionFailed));
}
check_copy_source_preconditions(
src_info,
copy_source_if_match,
copy_source_if_unmodified_since,
copy_source_if_none_match,
copy_source_if_modified_since,
)?;
let source_actual_size = src_info.get_actual_size().ok().filter(|size| *size >= 0);
let source_logical_size = match source_actual_size {
@@ -74,6 +74,12 @@ fn upload_part_copy_shares_foreground_admission_with_upload_part() {
.any(|label| label.key() == "size_bucket" && label.value() == source_size_bucket)
})
};
let mut guarded = input.clone();
guarded.copy_source_if_unmodified_since = Some(Timestamp::from(time::OffsetDateTime::UNIX_EPOCH));
let error = Box::pin(usecase.execute_upload_part_copy(build_request(guarded, Method::PUT)))
.await
.expect_err("source date must be evaluated before admitting the write");
assert_eq!(error.code(), &S3ErrorCode::PreconditionFailed);
let error = Box::pin(usecase.execute_upload_part_copy(build_request(input.clone(), Method::PUT)))
.await
.expect_err("copy must not bypass the occupied UploadPart pool");
+102 -29
View File
@@ -18,6 +18,7 @@ use super::*;
use crate::app::storage_api::object_usecase::object_utils::to_s3s_xml_etag;
use futures::FutureExt;
use rustfs_utils::path::fold_object_name_path_separators;
use s3s::dto::ETagCondition;
use tracing::Instrument;
use crate::auth::{VerifiedPresignedRequest, reject_presigned_put_max_content_length_for_other_operation};
@@ -110,6 +111,41 @@ fn copy_namespace_lock_object(key: &str, backslash_is_separator: bool) -> String
fold_object_name_path_separators(&encode_dir_object(key), backslash_is_separator).into_owned()
}
pub(crate) fn check_copy_source_preconditions(
source: &ObjectInfo,
if_match: Option<ETagCondition>,
if_unmodified_since: Option<Timestamp>,
if_none_match: Option<ETagCondition>,
if_modified_since: Option<Timestamp>,
) -> S3Result<()> {
// The caller has resolved the source version. Each ETag condition takes
// precedence over its paired date; HTTP dates have whole-second precision.
let etag_matches = |condition: &ETagCondition, compare: fn(&ETag, &ETag) -> bool| match condition {
ETagCondition::Any => true,
ETagCondition::ETag(expected) => source.etag.as_deref().is_some_and(|raw| compare(&to_s3s_etag(raw), expected)),
};
let modified = source.mod_time.map(OffsetDateTime::unix_timestamp);
if let Some(condition) = if_match {
if !etag_matches(&condition, ETag::strong_cmp) {
return Err(s3_error!(PreconditionFailed));
}
} else if let (Some(actual), Some(limit)) = (modified, if_unmodified_since)
&& actual > OffsetDateTime::from(limit).unix_timestamp()
{
return Err(s3_error!(PreconditionFailed));
}
if let Some(condition) = if_none_match {
if etag_matches(&condition, ETag::weak_cmp) {
return Err(s3_error!(PreconditionFailed));
}
} else if let (Some(actual), Some(limit)) = (modified, if_modified_since)
&& actual <= OffsetDateTime::from(limit).unix_timestamp()
{
return Err(s3_error!(PreconditionFailed));
}
Ok(())
}
async fn acquire_self_copy_namespace_lock<S>(
store: &S,
bucket: &str,
@@ -173,7 +209,9 @@ impl DefaultObjectUsecase {
tagging,
tagging_directive,
copy_source_if_match,
copy_source_if_unmodified_since,
copy_source_if_none_match,
copy_source_if_modified_since,
cache_control,
content_disposition,
content_encoding,
@@ -502,6 +540,14 @@ impl DefaultObjectUsecase {
// happens here.
authorize_sse_kms_object_read(copy_principal.as_ref(), &src_info.user_defined).await?;
check_copy_source_preconditions(
&src_info,
copy_source_if_match,
copy_source_if_unmodified_since,
copy_source_if_none_match,
copy_source_if_modified_since,
)?;
// Capture the version actually read from the source before src_info is mutated/consumed
// below. This is the exact source version copied (issue #4976): the response must echo it
// via x-amz-copy-source-version-id, distinct from the destination version_id.
@@ -518,30 +564,6 @@ impl DefaultObjectUsecase {
.find_map(|(k, v)| rustfs_rio::Checksum::new_from_string(&k, &v))
});
// Validate copy source conditions
if let Some(if_match) = copy_source_if_match {
if let Some(ref etag) = src_info.etag {
if let Some(strong_etag) = if_match.into_etag() {
if ETag::Strong(etag.clone()) != strong_etag {
return Err(s3_error!(PreconditionFailed));
}
} else {
// Weak ETag or Any (*) in If-Match should fail per RFC 9110
return Err(s3_error!(PreconditionFailed));
}
} else {
return Err(s3_error!(PreconditionFailed));
}
}
if let Some(if_none_match) = copy_source_if_none_match
&& let Some(ref etag) = src_info.etag
&& let Some(strong_etag) = if_none_match.into_etag()
&& ETag::Strong(etag.clone()) == strong_etag
{
return Err(s3_error!(PreconditionFailed));
}
// A same-name copy is normally serviced as a metadata-only update: the store layer
// rewrites xl.meta in place and leaves the data blocks alone. That shortcut is only sound
// when the destination's physical bytes are identical to the source's, and encryption
@@ -940,6 +962,47 @@ mod tests {
use std::sync::Arc;
use tokio::io::AsyncReadExt;
#[test]
fn copy_source_preconditions_use_http_seconds_and_paired_etag_precedence() {
let source = ObjectInfo {
etag: Some("\"source\"".to_owned()),
mod_time: Some(
OffsetDateTime::UNIX_EPOCH
.replace_nanosecond(750_000_000)
.expect("valid nanoseconds"),
),
..Default::default()
};
let date = |second| Timestamp::from(OffsetDateTime::from_unix_timestamp(second).expect("valid test timestamp"));
let etag = |value: &str| value.parse::<ETagCondition>().expect("valid test ETag");
for (if_match, unmodified, if_none_match, modified, allowed) in [
(None, Some(-1), None, None, false),
(None, Some(0), None, Some(-1), true),
(None, None, None, Some(0), false),
(Some("\"source\""), Some(-1), None, None, true),
(Some("\"other\""), Some(1), None, None, false),
(Some("W/\"source\""), None, None, None, false),
(None, None, Some("W/\"source\""), Some(-1), false),
(None, None, Some("\"other\""), Some(1), true),
(Some("*"), None, None, Some(1), false),
(Some("*"), None, None, None, true),
(None, None, Some("*"), None, false),
] {
let result = check_copy_source_preconditions(
&source,
if_match.map(etag),
unmodified.map(date),
if_none_match.map(etag),
modified.map(date),
);
assert_eq!(
result.err().as_ref().map(S3Error::code),
(!allowed).then_some(&S3ErrorCode::PreconditionFailed),
"{if_match:?}, {unmodified:?}, {if_none_match:?}, {modified:?}",
);
}
}
#[test]
fn copy_namespace_lock_object_folds_backslash_spellings_only_as_separators() {
// `a\b\` is not a same-object copy of `a/b` by `path_join_buf` (the
@@ -1321,16 +1384,29 @@ mod tests {
let source_version_id = old.version_id.expect("historical source should have a version id");
let current_version_id = current.version_id.expect("current destination should have a version id");
let input = CopyObjectInput::builder()
let mut input = CopyObjectInput::builder()
.copy_source(CopySource::Bucket {
bucket: bucket.clone().into(),
key: object.to_string().into(),
version_id: Some(source_version_id.to_string().into()),
})
.copy_source_if_unmodified_since(Some(Timestamp::from(OffsetDateTime::UNIX_EPOCH)))
.bucket(bucket.clone())
.key(object.to_string())
.build()
.expect("expected-current historical copy input should build");
let usecase = DefaultObjectUsecase::with_context(Some(context));
let error = usecase
.execute_copy_object(build_request(input.clone(), Method::PUT))
.await
.expect_err("a stale source date must reject the copy");
assert_eq!(error.code(), &S3ErrorCode::PreconditionFailed);
let after = store
.get_object_info(&bucket, object, &ObjectOptions::default())
.await
.expect("current version");
assert_eq!(after.version_id, Some(current_version_id), "rejected copy must not create a version");
input.copy_source_if_match = Some(ETagCondition::ETag(to_s3s_etag(old.etag.as_deref().expect("source ETag"))));
let mut req = build_request(input, Method::PUT);
req.headers.insert(
RUSTFS_EXPECTED_CURRENT_VERSION_ID,
@@ -1338,10 +1414,7 @@ mod tests {
);
let response = temp_env::async_with_vars(
[(rustfs_config::ENV_OBJECT_LOCK_OPTIMIZATION_ENABLE, Some("false"))],
tokio::time::timeout(
Duration::from_secs(10),
DefaultObjectUsecase::with_context(Some(context)).execute_copy_object(req),
),
tokio::time::timeout(Duration::from_secs(10), usecase.execute_copy_object(req)),
)
.await
.expect("nonbuffered source reader must not deadlock behind the self-copy write lock")
+11 -6
View File
@@ -4133,6 +4133,7 @@ impl DefaultObjectUsecase {
content_encoding: info.content_encoding.clone(),
content_language: info.user_defined.get("content-language").cloned(),
cache_control,
expires: info.expires.map(|value| format_expires_header(&value.into())).transpose()?,
content_disposition,
content_range,
parts_count,
@@ -4236,6 +4237,7 @@ impl DefaultObjectUsecase {
content_disposition: remote.content_disposition,
content_language: remote.content_language,
cache_control: remote.cache_control,
expires: remote.expires_string,
e_tag: remote.e_tag.as_deref().and_then(|v| ETag::from_str(v).ok()),
last_modified: remote
.last_modified
@@ -12107,12 +12109,13 @@ mod tests {
#[tokio::test]
async fn build_get_object_output_context_returns_standard_headers() {
for (content_language, user_language) in [
(Some("zh-CN"), None),
(None, None),
(Some(""), None),
(Some("zh-CN"), Some("fr-FR")),
(None, Some("fr-FR")),
let stored_expires = time::macros::datetime!(2030-01-01 0:00 UTC);
for (content_language, user_language, expires) in [
(Some("zh-CN"), None, Some(stored_expires)),
(None, None, None),
(Some(""), None, None),
(Some("zh-CN"), Some("fr-FR"), None),
(None, Some("fr-FR"), None),
] {
let mut metadata = HashMap::new();
metadata.insert("cache-control".to_string(), "public, max-age=259200".to_string());
@@ -12128,6 +12131,7 @@ mod tests {
bucket: "test-bucket".to_string(),
name: "path/raw".to_string(),
user_defined: Arc::new(metadata),
expires,
..Default::default()
};
@@ -12178,6 +12182,7 @@ mod tests {
assert_eq!(context.output.cache_control.as_deref(), Some("public, max-age=259200"));
assert_eq!(context.output.content_disposition.as_deref(), Some("attachment; filename=\"demo.png\""));
assert_eq!(context.output.content_language.as_deref(), content_language);
assert_eq!(context.output.expires.as_deref(), expires.map(|_| "Tue, 01 Jan 2030 00:00:00 GMT"));
assert_eq!(
context
.output
+1
View File
@@ -306,6 +306,7 @@ impl DefaultObjectUsecase {
content_disposition: remote.content_disposition,
content_language: remote.content_language,
cache_control: remote.cache_control,
expires: remote.expires_string,
accept_ranges: Some(ACCEPT_RANGES_BYTES.to_string()),
e_tag: remote.e_tag.as_deref().and_then(|v| ETag::from_str(v).ok()),
last_modified: remote
+2
View File
@@ -226,6 +226,8 @@ pub(crate) mod shared;
mod test_support;
mod veeam_sosapi;
pub(crate) use self::copy::check_copy_source_preconditions;
#[cfg(test)]
pub(crate) use self::delete::*;
pub(crate) use self::extract::*;
+14 -4
View File
@@ -1585,8 +1585,14 @@ impl S3 for FS {
.await
.map_err(crate::error::ApiError::from)?;
let accelerate_config = serialize(&req.input.accelerate_configuration)
.map_err(|err| S3Error::with_message(S3ErrorCode::MalformedXML, format!("{err}")))?;
let config = &req.input.accelerate_configuration;
if let Some(status) = &config.status
&& !matches!(status.as_str(), BucketAccelerateStatus::ENABLED | BucketAccelerateStatus::SUSPENDED)
{
return Err(s3_error!(MalformedXML, "Invalid bucket acceleration status"));
}
let accelerate_config =
serialize(config).map_err(|err| S3Error::with_message(S3ErrorCode::MalformedXML, format!("{err}")))?;
update_bucket_metadata_config_if_incarnation(
&req.input.bucket,
BUCKET_ACCELERATE_CONFIG,
@@ -1684,8 +1690,12 @@ impl S3 for FS {
.await
.map_err(crate::error::ApiError::from)?;
let payment_config = serialize(&req.input.request_payment_configuration)
.map_err(|err| S3Error::with_message(S3ErrorCode::MalformedXML, format!("{err}")))?;
let config = &req.input.request_payment_configuration;
if !matches!(config.payer.as_str(), Payer::BUCKET_OWNER | Payer::REQUESTER) {
return Err(s3_error!(InvalidArgument, "Invalid request payer"));
}
let payment_config =
serialize(config).map_err(|err| S3Error::with_message(S3ErrorCode::MalformedXML, format!("{err}")))?;
update_bucket_metadata_config_if_incarnation(
&req.input.bucket,
BUCKET_REQUEST_PAYMENT_CONFIG,
+18 -16
View File
@@ -13,15 +13,15 @@
// limitations under the License.
use crate::storage::s3_api::common::rustfs_owner;
use s3s::dto::{GetBucketAclOutput, GetObjectAclOutput, Grant, Grantee, Permission, Type};
use s3s::dto::{GetBucketAclOutput, GetObjectAclOutput, Grant, Grantee, Owner, Permission, Type};
fn full_control_grants() -> Vec<Grant> {
fn full_control_grants(owner: &Owner) -> Vec<Grant> {
vec![Grant {
grantee: Some(Grantee {
type_: Type::from_static(Type::CANONICAL_USER),
display_name: None,
display_name: owner.display_name.clone(),
email_address: None,
id: None,
id: owner.id.clone(),
uri: None,
}),
permission: Some(Permission::from_static(Permission::FULL_CONTROL)),
@@ -29,16 +29,18 @@ fn full_control_grants() -> Vec<Grant> {
}
pub(crate) fn build_get_bucket_acl_output() -> GetBucketAclOutput {
let owner = rustfs_owner();
GetBucketAclOutput {
grants: Some(full_control_grants()),
owner: Some(rustfs_owner()),
grants: Some(full_control_grants(&owner)),
owner: Some(owner),
}
}
pub(crate) fn build_get_object_acl_output() -> GetObjectAclOutput {
let owner = rustfs_owner();
GetObjectAclOutput {
grants: Some(full_control_grants()),
owner: Some(rustfs_owner()),
grants: Some(full_control_grants(&owner)),
owner: Some(owner),
..Default::default()
}
}
@@ -57,10 +59,10 @@ mod tests {
assert_eq!(grants.len(), 1);
assert_eq!(grants[0].permission.as_ref().map(Permission::as_str), Some(Permission::FULL_CONTROL));
assert_eq!(
grants[0].grantee.as_ref().map(|grantee| grantee.type_.as_str()),
Some(Type::CANONICAL_USER)
);
let grantee = grants[0].grantee.as_ref().expect("owner grant must identify its grantee");
assert_eq!(grantee.type_.as_str(), Type::CANONICAL_USER);
assert_eq!(grantee.id, owner.id);
assert_eq!(grantee.display_name, owner.display_name);
let expected_owner = rustfs_owner();
assert_eq!(owner.display_name, expected_owner.display_name);
@@ -75,10 +77,10 @@ mod tests {
assert_eq!(grants.len(), 1);
assert_eq!(grants[0].permission.as_ref().map(Permission::as_str), Some(Permission::FULL_CONTROL));
assert_eq!(
grants[0].grantee.as_ref().map(|grantee| grantee.type_.as_str()),
Some(Type::CANONICAL_USER)
);
let grantee = grants[0].grantee.as_ref().expect("owner grant must identify its grantee");
assert_eq!(grantee.type_.as_str(), Type::CANONICAL_USER);
assert_eq!(grantee.id, owner.id);
assert_eq!(grantee.display_name, owner.display_name);
let expected_owner = rustfs_owner();
assert_eq!(owner.display_name, expected_owner.display_name);
+2
View File
@@ -86,6 +86,8 @@ checked_files=(
"crates/scanner/src/scanner.rs"
"crates/scanner/src/scanner_io.rs"
"crates/scanner/src/scanner_folder.rs"
"crates/scanner/src/scanner_folder/heal_walk.rs"
"crates/scanner/src/scanner_folder/queue_walk.rs"
"crates/concurrency/src/workers.rs"
"crates/concurrency/src/deadlock.rs"
"crates/trusted-proxies/src/global.rs"