Compare commits

..

1 Commits

Author SHA1 Message Date
GatewayJ c95022ce54 fix(table-catalog): retain a branch for published snapshot roots (#9766) 2026-12-03 13:53:24 +08:00
21 changed files with 2480 additions and 1837 deletions
File diff suppressed because it is too large Load Diff
+105 -79
View File
@@ -163,7 +163,7 @@ struct LockPeerChannelHealth {
request_backoff_until: Option<Instant>,
request_backoff: Duration,
request_probe_generation: Option<u64>,
request_generation: u64,
next_probe_generation: u64,
request_in_flight: usize,
late_release_in_flight: usize,
/// Timed-out RPCs still running in the background for this peer.
@@ -177,23 +177,13 @@ struct TimeoutLogHealth {
}
#[derive(Debug, Clone, Copy)]
enum LockRequestAdmission {
Normal(u64),
Probe(u64),
struct LockRequestAdmission {
probe_generation: Option<u64>,
}
impl LockPeerChannelHealth {
fn owns_probe(&self, admission: LockRequestAdmission) -> bool {
matches!(admission, LockRequestAdmission::Probe(generation) if self.request_probe_generation == Some(generation))
}
fn accepts_request_result(&self, admission: LockRequestAdmission) -> bool {
match admission {
LockRequestAdmission::Normal(generation) => {
self.request_backoff_until.is_none() && generation == self.request_generation
}
LockRequestAdmission::Probe(_) => self.owns_probe(admission),
}
impl LockRequestAdmission {
fn is_probe(self) -> bool {
self.probe_generation.is_some()
}
}
@@ -604,11 +594,16 @@ impl RemoteClient {
with_lock_peer_health(&self.addr, |health| {
health.last_success = Some(Instant::now());
health.consecutive_timeouts = 0;
if is_request_breaker_operation(op) && admission.is_some_and(|admission| health.accepts_request_result(admission)) {
health.request_consecutive_timeouts = 0;
health.request_backoff_until = None;
health.request_backoff = Duration::ZERO;
health.request_probe_generation = None;
if is_request_breaker_operation(op) {
let is_probe = admission.is_some_and(LockRequestAdmission::is_probe);
if health.request_backoff_until.is_none() || is_probe {
health.request_consecutive_timeouts = 0;
health.request_backoff_until = None;
health.request_backoff = Duration::ZERO;
}
if is_probe && admission.is_some_and(|admission| health.request_probe_generation == admission.probe_generation) {
health.request_probe_generation = None;
}
}
});
// A successful lock RPC over a cached or fresh channel proves the peer is
@@ -639,7 +634,7 @@ impl RemoteClient {
/// channel liveness and request admission are deliberately separate.
fn admit_lock_request(&self, op: &'static str) -> Option<LockRequestAdmission> {
if !is_request_breaker_operation(op) {
return Some(LockRequestAdmission::Normal(0));
return Some(LockRequestAdmission { probe_generation: None });
}
let now = Instant::now();
@@ -650,16 +645,21 @@ impl RemoteClient {
}
let Some(until) = health.request_backoff_until else {
health.request_in_flight += 1;
return (Some(LockRequestAdmission::Normal(health.request_generation)), "none");
return (Some(LockRequestAdmission { probe_generation: None }), "none");
};
if now < until || health.request_probe_generation.is_some() {
return (None, "breaker_open");
}
health.request_generation = health.request_generation.wrapping_add(1);
let generation = health.request_generation;
health.next_probe_generation = health.next_probe_generation.saturating_add(1);
let generation = health.next_probe_generation;
health.request_probe_generation = Some(generation);
health.request_in_flight += 1;
(Some(LockRequestAdmission::Probe(generation)), "none")
(
Some(LockRequestAdmission {
probe_generation: Some(generation),
}),
"none",
)
});
if admission.is_none() {
rustfs_io_metrics::lock_metrics::record_remote_lock_request_suppressed(&self.addr, op, suppression_reason);
@@ -679,7 +679,7 @@ impl RemoteClient {
if is_request_breaker_operation(op) && admission.is_some() {
with_lock_peer_health(&self.addr, |health| {
health.request_in_flight = health.request_in_flight.saturating_sub(1);
if admission.is_some_and(|admission| health.owns_probe(admission)) {
if admission.is_some_and(|admission| health.request_probe_generation == admission.probe_generation) {
health.request_probe_generation = None;
}
});
@@ -690,24 +690,30 @@ impl RemoteClient {
if !is_request_breaker_operation(op) {
return;
}
let Some(admission) = admission else {
return;
};
let now = Instant::now();
with_lock_peer_health(&self.addr, |health| {
// Once open, only the active probe may extend the backoff. Older
// RPCs may still complete after this probe recovers the breaker.
if !health.accepts_request_result(admission) {
return;
// Once request backoff is active (`request_backoff_until.is_some()`), only a timeout
// from the currently admitted half-open probe generation may escalate or re-arm the
// backoff window. Straggler timeouts from RPCs admitted before backoff opened
// (`probe_generation: None`) or from a superseded probe generation must not compound
// backoff even if they arrive after `until` has elapsed.
if health.request_backoff_until.is_some() {
let is_active_probe = admission
.and_then(|token| token.probe_generation)
.is_some_and(|generation| health.request_probe_generation == Some(generation));
if !is_active_probe {
return;
}
}
health.request_consecutive_timeouts = health.request_consecutive_timeouts.saturating_add(1);
if health.request_consecutive_timeouts < LOCK_RPC_REQUEST_BACKOFF_THRESHOLD {
return;
}
let initial = (deadline / 4).clamp(Duration::from_millis(1), Duration::from_millis(500));
let next = if health.request_backoff.is_zero() {
(deadline / 4).clamp(Duration::from_millis(1), Duration::from_millis(500))
initial
} else {
health.request_backoff.saturating_mul(2)
};
@@ -863,7 +869,7 @@ impl RemoteClient {
health.detached_rpcs = health.detached_rpcs.saturating_sub(1);
if is_request_breaker_operation(op) && admission.is_some() {
health.request_in_flight = health.request_in_flight.saturating_sub(1);
if admission.is_some_and(|admission| health.owns_probe(admission)) {
if admission.is_some_and(|admission| health.request_probe_generation == admission.probe_generation) {
health.request_probe_generation = None;
}
}
@@ -2209,72 +2215,54 @@ mod tests {
);
}
#[tokio::test(start_paused = true)]
async fn request_breaker_opens_after_three_timeouts_and_allows_one_probe() {
#[test]
fn request_breaker_opens_after_three_timeouts_and_allows_one_probe() {
let addr = "http://breaker-test";
let client = RemoteClient::new(addr.to_string());
reset_lock_peer_health_for_test(addr);
for _ in 0..LOCK_RPC_REQUEST_BACKOFF_THRESHOLD {
let admission = client.admit_lock_request("lock");
assert!(admission.is_some());
client.record_request_timeout("lock", Duration::from_millis(100), admission);
client.release_lock_request("lock", admission);
client.record_request_timeout("lock", Duration::from_millis(100), None);
}
assert!(
client.admit_lock_request("lock").is_none(),
"open breaker must reject requests during backoff"
);
tokio::time::advance(lock_peer_health_for_test(addr).request_backoff).await;
with_lock_peer_health(addr, |health| {
health.request_backoff_until = Some(Instant::now() - Duration::from_millis(1));
health.request_probe_generation = None;
health.request_in_flight = 0;
});
let probe = client
.admit_lock_request("lock")
.expect("half-open breaker must admit one probe");
assert!(matches!(probe, LockRequestAdmission::Probe(_)));
assert!(probe.is_probe());
assert!(client.admit_lock_request("lock").is_none(), "only one half-open probe may run");
client.release_lock_request("lock", Some(probe));
assert!(lock_peer_health_for_test(addr).request_probe_generation.is_none());
reset_lock_peer_health_for_test(addr);
}
#[tokio::test(start_paused = true)]
async fn only_active_probe_timeouts_extend_the_request_breaker() {
#[test]
fn old_request_completion_cannot_clear_a_new_probe() {
let addr = "http://breaker-token-test";
let client = RemoteClient::new(addr.to_string());
reset_lock_peer_health_for_test(addr);
let deadline = Duration::from_millis(100);
let old = client.admit_lock_request("lock").expect("closed breaker admits a request");
for _ in 0..LOCK_RPC_REQUEST_BACKOFF_THRESHOLD {
let admission = client.admit_lock_request("lock");
assert!(admission.is_some());
client.record_request_timeout("lock", deadline, admission);
client.release_lock_request("lock", admission);
}
let opened = lock_peer_health_for_test(addr);
client.record_request_timeout("lock", deadline, Some(old));
assert_eq!(lock_peer_health_for_test(addr).request_backoff_until, opened.request_backoff_until);
with_lock_peer_health(addr, |health| {
health.request_backoff_until = Some(Instant::now() - Duration::from_millis(1));
health.request_probe_generation = None;
health.request_in_flight = 1;
});
tokio::time::advance(opened.request_backoff).await;
client.record_request_timeout("lock", deadline, Some(old));
assert_eq!(lock_peer_health_for_test(addr).request_backoff_until, opened.request_backoff_until);
let probe = client.admit_lock_request("lock").expect("probe should be admitted");
client.record_rpc_success("lock", Some(old));
client.record_request_timeout("lock", deadline, Some(old));
assert_eq!(lock_peer_health_for_test(addr).request_backoff_until, opened.request_backoff_until);
client.record_request_timeout("lock", deadline, Some(probe));
assert_eq!(lock_peer_health_for_test(addr).request_backoff, opened.request_backoff * 2);
client.release_lock_request("lock", Some(LockRequestAdmission { probe_generation: None }));
assert!(lock_peer_health_for_test(addr).request_probe_generation.is_some());
client.record_rpc_success("lock", Some(LockRequestAdmission { probe_generation: None }));
assert!(lock_peer_health_for_test(addr).request_probe_generation.is_some());
client.release_lock_request("lock", Some(probe));
tokio::time::advance(opened.request_backoff * 2).await;
let recovery = client.admit_lock_request("lock").expect("next probe should be admitted");
client.record_rpc_success("lock", Some(recovery));
client.release_lock_request("lock", Some(recovery));
client.record_request_timeout("lock", deadline, Some(old));
client.release_lock_request("lock", Some(old));
let recovered = lock_peer_health_for_test(addr);
assert!(recovered.request_backoff_until.is_none());
assert_eq!(recovered.request_consecutive_timeouts, 0, "old wave cannot re-open recovered breaker");
assert!(lock_peer_health_for_test(addr).request_probe_generation.is_none());
reset_lock_peer_health_for_test(addr);
}
@@ -2296,16 +2284,54 @@ mod tests {
health.request_consecutive_timeouts = 0;
});
let second = client.admit_lock_request("lock").expect("second probe should be admitted");
assert!(!lock_peer_health_for_test(addr).owns_probe(first));
assert_ne!(first.probe_generation, second.probe_generation);
client.record_rpc_success("lock", Some(first));
client.release_lock_request("lock", Some(first));
assert!(lock_peer_health_for_test(addr).owns_probe(second));
assert!(lock_peer_health_for_test(addr).request_backoff_until.is_some());
assert_eq!(lock_peer_health_for_test(addr).request_probe_generation, second.probe_generation);
client.release_lock_request("lock", Some(second));
reset_lock_peer_health_for_test(addr);
}
#[test]
fn late_pre_backoff_timeout_after_expiry_does_not_escalate_without_failed_probe() {
let addr = "http://breaker-late-timeout-test";
let client = RemoteClient::new(addr.to_string());
reset_lock_peer_health_for_test(addr);
let pre_backoff = client
.admit_lock_request("lock")
.expect("normal pre-backoff RPC should be admitted");
assert!(!pre_backoff.is_probe());
for _ in 0..LOCK_RPC_REQUEST_BACKOFF_THRESHOLD {
client.record_request_timeout("lock", Duration::from_millis(100), None);
}
let initial_backoff = lock_peer_health_for_test(addr).request_backoff;
assert_eq!(initial_backoff, Duration::from_millis(25));
// Simulate backoff window expiry while the pre-backoff RPC is still finishing.
with_lock_peer_health(addr, |health| {
health.request_backoff_until = Some(Instant::now() - Duration::from_millis(5));
});
// A late timeout from a non-probe RPC (`probe_generation: None`) arriving after `until`
// must NOT double the backoff or block the upcoming half-open probe.
client.record_request_timeout("lock", Duration::from_millis(100), Some(pre_backoff));
client.release_lock_request("lock", Some(pre_backoff));
assert_eq!(lock_peer_health_for_test(addr).request_backoff, initial_backoff);
let probe = client
.admit_lock_request("lock")
.expect("expired backoff must still admit a half-open probe");
assert!(probe.is_probe());
// Only when the active probe itself times out does the backoff escalate.
client.record_request_timeout("lock", Duration::from_millis(100), Some(probe));
client.release_lock_request("lock", Some(probe));
assert_eq!(lock_peer_health_for_test(addr).request_backoff, initial_backoff * 2);
reset_lock_peer_health_for_test(addr);
}
#[test]
fn bounded_acquire_request_matches_transport_deadline() {
let request = test_lock_request(Duration::from_secs(30));
+13 -17
View File
@@ -798,7 +798,7 @@ pub struct DiskHealthTracker {
/// Atomic timestamp of last successful operation
pub last_success: AtomicI64,
/// Monotonic count of operations that completed successfully on this handle
completed_ops: AtomicU64,
pub completed_ops: AtomicU64,
/// Atomic timestamp of last operation start
pub last_started: AtomicI64,
/// Atomic disk status (OK or Faulty)
@@ -1264,15 +1264,11 @@ impl DiskHealthTracker {
/// Log a successful operation
pub fn log_success(&self) {
self.last_success.store(current_unix_nanos(), Ordering::Relaxed);
self.completed_ops.fetch_add(1, Ordering::Relaxed);
}
pub(crate) fn time_since_success(&self) -> Duration {
elapsed_since(self.last_success.load(Ordering::Relaxed), current_unix_nanos())
self.completed_ops.fetch_add(1, Ordering::AcqRel);
}
pub fn completed_ops(&self) -> u64 {
self.completed_ops.load(Ordering::Relaxed)
self.completed_ops.load(Ordering::Acquire)
}
pub fn record_capacity_probe(&self, total: u64, used: u64, free: u64) {
@@ -1377,14 +1373,7 @@ impl DiskHealthTracker {
}
pub fn mark_failure(&self, endpoint: &Endpoint, reason: &'static str) -> bool {
self.record_failure(endpoint, reason, None).unwrap_or(false)
}
fn record_failure(&self, endpoint: &Endpoint, reason: &'static str, completed_before: Option<u64>) -> Option<bool> {
let _guard = self.transition_lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
if completed_before.is_some_and(|before| self.completed_ops() != before) {
return None;
}
let current = self.runtime_state();
let now = current_unix_secs();
let next = match current {
@@ -1414,7 +1403,7 @@ impl DiskHealthTracker {
let became_offline = next == RuntimeDriveHealthState::Offline && current != RuntimeDriveHealthState::Offline;
self.transition_state(endpoint, current, next, reason);
Some(became_offline)
became_offline
}
/// Record a foreground timeout failure only when no sibling operation on this drive
@@ -1427,7 +1416,10 @@ impl DiskHealthTracker {
reason: &'static str,
completed_before: u64,
) -> Option<bool> {
self.record_failure(endpoint, reason, Some(completed_before))
if self.completed_ops() > completed_before {
return None;
}
Some(self.mark_failure(endpoint, reason))
}
#[allow(dead_code, reason = "asserted by this file's tests (backlog#1823)")]
@@ -1462,6 +1454,7 @@ impl DiskHealthTracker {
self.consecutive_successes.store(0, Ordering::Release);
self.offline_since_unix_secs.store(0, Ordering::Release);
self.waiting.store(0, Ordering::Release);
self.completed_ops.store(0, Ordering::Release);
self.last_success.store(now_nanos, Ordering::Relaxed);
self.last_started.store(now_nanos, Ordering::Relaxed);
self.last_transition_unix_secs.store(now_secs, Ordering::Release);
@@ -2126,7 +2119,10 @@ impl LocalDiskWrapper {
continue;
}
if health.time_since_success() < SKIP_IF_SUCCESS_BEFORE {
let last_success_nanos = health.last_success.load(Ordering::Relaxed);
let elapsed = elapsed_since(last_success_nanos, current_unix_nanos());
if elapsed < SKIP_IF_SUCCESS_BEFORE {
continue;
}
@@ -35,7 +35,6 @@ use crate::disk::disk_store::get_drive_metadata_timeout;
use crate::disk::{
self, BATCH_READ_VERSION_MAX_ITEMS, BatchReadVersionItem, BatchReadVersionReq, BatchReadVersionResp, Disk, DiskAPI,
};
use crate::layout::disks_layout::MAX_ERASURE_SET_DRIVE_COUNT;
use crate::set_disk::{
DiskError, DiskStore, FileInfo, ReadOptions, SetDisks, codec_streaming_rollout_applies,
collect_inline_data_shard_fileinfos_from_observations, file_info_is_valid_for_metadata, get_metadata_slowtail_fault_request,
@@ -1026,6 +1025,13 @@ impl SetDisks {
let diagnostic_context = crate::cluster::rpc::runtime_sources::ReadVersionDiagnosticContext::capture_entry(
rustfs_io_metrics::internode_metrics::ReadVersionEntrySource::MetadataRead,
);
let fanout_host_progress: Vec<u64> = disks
.iter()
.map(|disk| match disk.as_deref() {
Some(crate::disk::Disk::Remote(remote)) => remote.host_completed_ops(),
_ => 0,
})
.collect();
let futures = disks.iter().enumerate().map(|(disk_index, disk)| {
let disk = disk.clone();
let task_opts = opts;
@@ -1076,14 +1082,6 @@ impl SetDisks {
if bound_remote_stragglers {
use futures::stream::{FuturesUnordered, StreamExt};
let fanout_host_progress: smallvec::SmallVec<[u64; MAX_ERASURE_SET_DRIVE_COUNT]> = disks
.iter()
.map(|disk| match disk.as_deref() {
Some(Disk::Remote(remote)) => remote.host_completed_ops(),
_ => 0,
})
.collect();
let mut pending: FuturesUnordered<_> = futures
.into_iter()
.enumerate()
@@ -1164,7 +1162,7 @@ impl SetDisks {
for slot in &mut slots {
if slot.result.is_none() {
if let Some(Some(disk)) = disks.get(slot.disk_index)
&& let Disk::Remote(remote) = disk.as_ref()
&& let crate::disk::Disk::Remote(remote) = disk.as_ref()
{
remote.record_straggler_timeout_if_stalled(fanout_host_progress[slot.disk_index]);
}
@@ -1244,7 +1242,7 @@ impl SetDisks {
let stage_metrics_enabled = rustfs_io_metrics::get_stage_metrics_enabled();
let fanout_start = stage_metrics_enabled.then(Instant::now);
let mut slots = MetadataReadResult::pending(disks.len());
let mut tasks = vec![None; disks.len()];
let mut task_ids = vec![None; disks.len()];
let mut observations = Vec::with_capacity(disks.len());
let mut accumulator =
MetadataQuorumAccumulator::new(disks.len(), default_parity_count, true).with_requested_version_id(version_id);
@@ -1279,14 +1277,17 @@ impl SetDisks {
let diagnostic_context = crate::cluster::rpc::runtime_sources::ReadVersionDiagnosticContext::capture_entry(
rustfs_io_metrics::internode_metrics::ReadVersionEntrySource::MetadataRead,
);
let fanout_host_progress: Vec<u64> = disks
.iter()
.map(|disk| match disk.as_deref() {
Some(crate::disk::Disk::Remote(remote)) => remote.host_completed_ops(),
_ => 0,
})
.collect();
let spawn_read_version = |join_set: &mut JoinSet<(usize, disk::error::Result<FileInfo>, Duration)>,
tasks: &mut [Option<(tokio::task::Id, u64)>],
task_ids: &mut [Option<tokio::task::Id>],
index: usize,
disk: Option<DiskStore>| {
let host_completed_before = match disk.as_deref() {
Some(Disk::Remote(remote)) => remote.host_completed_ops(),
_ => 0,
};
let task_opts = opts;
let org_bucket = org_bucket.clone();
let bucket = bucket.clone();
@@ -1333,7 +1334,7 @@ impl SetDisks {
#[cfg(not(feature = "diagnostic-read-version-caller"))]
read.await
}));
tasks[index] = Some((task.id(), host_completed_before));
task_ids[index] = Some(task.id());
};
if bounded_fanout {
@@ -1341,14 +1342,14 @@ impl SetDisks {
while next_fanout_index < initial_target {
let disk_index = fanout_order[next_fanout_index];
if let Some(disk) = disks.get(disk_index).cloned() {
spawn_read_version(&mut join_set, &mut tasks, disk_index, disk);
spawn_read_version(&mut join_set, &mut task_ids, disk_index, disk);
scheduled_count = scheduled_count.saturating_add(1);
}
next_fanout_index = next_fanout_index.saturating_add(1);
}
} else {
for (index, disk) in disks.iter().cloned().enumerate() {
spawn_read_version(&mut join_set, &mut tasks, index, disk);
spawn_read_version(&mut join_set, &mut task_ids, index, disk);
scheduled_count = scheduled_count.saturating_add(1);
}
}
@@ -1407,7 +1408,7 @@ impl SetDisks {
let disk_index = fanout_order[next_fanout_index];
next_fanout_index = next_fanout_index.saturating_add(1);
if let Some(disk) = disks.get(disk_index).cloned() {
spawn_read_version(&mut join_set, &mut tasks, disk_index, disk);
spawn_read_version(&mut join_set, &mut task_ids, disk_index, disk);
scheduled_count = scheduled_count.saturating_add(1);
break;
}
@@ -1426,7 +1427,7 @@ impl SetDisks {
let disk_index = fanout_order[next_fanout_index];
next_fanout_index = next_fanout_index.saturating_add(1);
if let Some(disk) = disks.get(disk_index).cloned() {
spawn_read_version(&mut join_set, &mut tasks, disk_index, disk);
spawn_read_version(&mut join_set, &mut task_ids, disk_index, disk);
scheduled_count = scheduled_count.saturating_add(1);
}
}
@@ -1446,11 +1447,10 @@ impl SetDisks {
let elapsed = fanout_start.map_or(Duration::ZERO, |s| s.elapsed());
for slot in &mut slots {
if slot.result.is_none() {
if let Some((_, host_completed_before)) = tasks[slot.disk_index]
&& let Some(Some(disk)) = disks.get(slot.disk_index)
&& let Disk::Remote(remote) = disk.as_ref()
if let Some(Some(disk)) = disks.get(slot.disk_index)
&& let crate::disk::Disk::Remote(remote) = disk.as_ref()
{
remote.record_straggler_timeout_if_stalled(host_completed_before);
remote.record_straggler_timeout_if_stalled(fanout_host_progress[slot.disk_index]);
}
observations.push(MetadataFanoutObservation::from_error(&DiskError::Timeout, elapsed));
slot.result = Some(Err(DiskError::Timeout));
@@ -1524,10 +1524,7 @@ impl SetDisks {
&err,
fanout_start.map_or(Duration::ZERO, |s| s.elapsed()),
));
if let Some(index) = tasks
.iter()
.position(|task| task.is_some_and(|(id, _)| id == join_error.id()))
{
if let Some(index) = task_ids.iter().position(|id| *id == Some(join_error.id())) {
slots[index].result = Some(Err(err));
accumulator.observe(&slots[index]);
}
@@ -1662,7 +1659,7 @@ impl SetDisks {
{
let disk_index = fanout_order[next_fanout_index];
if let Some(disk) = disks.get(disk_index).cloned() {
spawn_read_version(&mut join_set, &mut tasks, disk_index, disk);
spawn_read_version(&mut join_set, &mut task_ids, disk_index, disk);
scheduled_count = scheduled_count.saturating_add(1);
}
next_fanout_index = next_fanout_index.saturating_add(1);
@@ -1670,7 +1667,7 @@ impl SetDisks {
while next_fanout_index < disks.len() {
let disk_index = fanout_order[next_fanout_index];
if let Some(disk) = disks.get(disk_index).cloned() {
spawn_read_version(&mut join_set, &mut tasks, disk_index, disk);
spawn_read_version(&mut join_set, &mut task_ids, disk_index, disk);
scheduled_count = scheduled_count.saturating_add(1);
}
next_fanout_index = next_fanout_index.saturating_add(1);
@@ -1682,7 +1679,7 @@ impl SetDisks {
{
let disk_index = fanout_order[next_fanout_index];
if let Some(disk) = disks.get(disk_index).cloned() {
spawn_read_version(&mut join_set, &mut tasks, disk_index, disk);
spawn_read_version(&mut join_set, &mut task_ids, disk_index, disk);
scheduled_count = scheduled_count.saturating_add(1);
}
next_fanout_index = next_fanout_index.saturating_add(1);
+12 -30
View File
@@ -132,7 +132,6 @@ tokio::task_local! {
struct RequestScopeState {
operation: usize,
entry_started: Option<Instant>,
subcause_503: Option<&'static str>,
}
impl RequestScopeState {
@@ -141,7 +140,6 @@ impl RequestScopeState {
Self {
operation,
entry_started: None,
subcause_503: None,
}
}
}
@@ -243,14 +241,18 @@ pub fn record_s3_http_lock_failure(resource_class: &'static str, mode: &'static
});
}
/// Capture a bounded 503 subcause while its typed error is still available.
pub fn observe_s3_http_503_subcause(classify: impl FnOnce() -> &'static str) {
let _ = CURRENT_OPERATION.try_with(|current| {
let subcause = classify();
let mut state = current.get();
state.subcause_503 = Some(subcause);
current.set(state);
});
/// Record an HTTP 503 S3 refusal classified by S3 error code and bounded subcause.
pub fn record_s3_http_503_response(s3_code: &'static str, subcause: &'static str) {
let op_label = CURRENT_OPERATION
.try_with(|current| operation_label(current.get().operation))
.unwrap_or("unknown");
metrics::counter!(
S3_503_RESPONSES_METRIC,
"op" => op_label,
"code" => s3_code,
"subcause" => subcause
)
.increment(1);
}
/// An external request is counted exactly once: at response headers, at a
@@ -262,7 +264,6 @@ pub struct S3HttpRequestGuard {
completion: Option<(S3HttpCompletionObserver, Instant)>,
finished: bool,
entry_started: Option<Instant>,
subcause_503: Option<&'static str>,
}
impl S3HttpRequestGuard {
@@ -285,7 +286,6 @@ impl S3HttpRequestGuard {
.and_then(|(enabled, observer)| enabled().then(|| (*observer, Instant::now()))),
finished: false,
entry_started: crate::metrics_enabled().then(Instant::now),
subcause_503: None,
}
}
@@ -307,13 +307,11 @@ impl S3HttpRequestGuard {
let state = CURRENT_OPERATION.with(Cell::get);
self.0.operation = state.operation;
self.0.entry_started = state.entry_started;
self.0.subcause_503 = state.subcause_503;
}
}
let state = RequestScopeState {
operation: self.operation,
entry_started: self.entry_started,
subcause_503: self.subcause_503,
};
CURRENT_OPERATION.sync_scope(Cell::new(state), || {
let _copy_back = CopyBack(self);
@@ -329,22 +327,6 @@ impl S3HttpRequestGuard {
self.finish(outcome);
}
/// The subcause observed before the gateway rendered the error.
pub fn subcause_503(&self) -> Option<&'static str> {
self.subcause_503
}
/// Record a final external S3 response with HTTP status 503.
pub fn record_503_response(&self, code: &'static str, subcause: &'static str) {
metrics::counter!(
S3_503_RESPONSES_METRIC,
"op" => operation_label(self.operation),
"code" => code,
"subcause" => subcause
)
.increment(1);
}
pub fn service_error(&mut self) {
self.finish(6);
}
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -73,7 +73,7 @@ pub const REQUEST_COMPAT_SEND_SITES: &[RequestCompatSendSite] = &[
json_field: "batch_read_version_req",
bin_field: "batch_read_version_req_bin",
},
json_encoder: "let batch_read_version_req = compat_json(&req, &policy)?;",
json_encoder: "let batch_read_version_req = compat_json(batch_rpc_req.as_ref(), &policy)?;",
policy: RequestJsonPolicy::MsgpackOnlyEligible,
},
RequestCompatSendSite {
+165 -146
View File
@@ -32,7 +32,7 @@ use std::ops::Not as _;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, LazyLock};
use std::task::{Context, Poll, ready};
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tokio::sync::mpsc;
@@ -829,8 +829,7 @@ fn internode_request_context(method: &Method, url: &str, operation: Option<&'sta
/// 3. Only for connect-phase failures with no typed kind do we consult the
/// DNS string heuristic, then default to `ConnectionRefused`.
/// 4. Body-phase failures map to `BodyStreamAborted`.
/// 5. A close before response headers maps to `ConnectionReset`.
/// 6. Anything else is `Unknown`.
/// 5. Anything else is `Unknown`.
fn classify_transport_error(
err: &(dyn std::error::Error + 'static),
is_timeout: bool,
@@ -841,7 +840,7 @@ fn classify_transport_error(
return InternodeHttpErrorKind::ConnectTimeout;
}
if let Some(kind) = find_transport_error_kind_in_chain(err, !is_connect && !is_body) {
if let Some(kind) = find_transport_error_kind_in_chain(err) {
return kind;
}
@@ -856,18 +855,17 @@ fn classify_transport_error(
return InternodeHttpErrorKind::BodyStreamAborted;
}
if let Some(kind) = find_request_phase_close_in_chain(err) {
return kind;
}
InternodeHttpErrorKind::Unknown
}
/// Map typed I/O failures and HTTP EOFs from the error source chain.
fn find_transport_error_kind_in_chain(
err: &(dyn std::error::Error + 'static),
before_headers: bool,
) -> Option<InternodeHttpErrorKind> {
let mut source = Some(err);
let mut request_closed = false;
for _ in 0..64 {
let Some(current) = source else { break };
fn find_transport_error_kind_in_chain(err: &(dyn std::error::Error + 'static)) -> Option<InternodeHttpErrorKind> {
let mut source: Option<&(dyn std::error::Error + 'static)> = Some(err);
while let Some(current) = source {
if let Some(io_err) = current.downcast_ref::<io::Error>() {
match io_err.kind() {
io::ErrorKind::ConnectionRefused | io::ErrorKind::AddrNotAvailable => {
@@ -880,7 +878,6 @@ fn find_transport_error_kind_in_chain(
return Some(InternodeHttpErrorKind::ConnectionReset);
}
io::ErrorKind::TimedOut => return Some(InternodeHttpErrorKind::ConnectTimeout),
io::ErrorKind::UnexpectedEof => request_closed |= before_headers,
io::ErrorKind::HostUnreachable | io::ErrorKind::NetworkUnreachable => {
return Some(InternodeHttpErrorKind::ConnectionRefused);
}
@@ -894,15 +891,30 @@ fn find_transport_error_kind_in_chain(
if hyper_err.is_incomplete_message() {
return Some(InternodeHttpErrorKind::ConnectionReset);
}
request_closed |= before_headers && (hyper_err.is_closed() || hyper_err.is_canceled());
}
source = current
.downcast_ref::<io::Error>()
.and_then(io::Error::get_ref)
.map(|inner| inner as &(dyn std::error::Error + 'static))
.or_else(|| current.source());
source = current.source();
}
request_closed.then_some(InternodeHttpErrorKind::ConnectionReset)
None
}
/// Map pooled HTTP/1.1 request-dispatch closes (`is_closed` / `is_canceled` / `UnexpectedEof`)
/// after `is_body` has been checked so response-body truncations retain `BodyStreamAborted`.
fn find_request_phase_close_in_chain(err: &(dyn std::error::Error + 'static)) -> Option<InternodeHttpErrorKind> {
let mut source: Option<&(dyn std::error::Error + 'static)> = Some(err);
while let Some(current) = source {
if let Some(io_err) = current.downcast_ref::<io::Error>()
&& io_err.kind() == io::ErrorKind::UnexpectedEof
{
return Some(InternodeHttpErrorKind::ConnectionReset);
}
if let Some(hyper_err) = current.downcast_ref::<hyper::Error>()
&& (hyper_err.is_closed() || hyper_err.is_canceled())
{
return Some(InternodeHttpErrorKind::ConnectionReset);
}
source = current.source();
}
None
}
/// The SOLE remaining string heuristic, gated behind `is_connect`: reqwest and
@@ -967,14 +979,9 @@ fn classify_http_response(
ClassifiedHttpResponse { kind, remote_disk_error }
}
fn internode_reqwest_error(
method: &Method,
url: &str,
operation: Option<&'static str>,
classified: InternodeHttpErrorKind,
err: reqwest::Error,
) -> io::Error {
fn internode_reqwest_error(method: &Method, url: &str, operation: Option<&'static str>, err: reqwest::Error) -> io::Error {
let context = internode_request_context(method, url, operation);
let classified = classify_reqwest_error(&err);
InternodeHttpError::with_source(classified, context, err).into_io_error()
}
@@ -1203,9 +1210,8 @@ impl HttpReader {
let resp = send_result.map_err(|e| {
record_internode_operation_duration(track_internode_metrics, internode_operation, request_started.elapsed());
record_internode_error(track_internode_metrics, internode_operation);
let classified = classify_reqwest_error(&e);
record_internode_classified_error(track_internode_metrics, internode_operation, classified);
internode_reqwest_error(method, url, internode_operation, classified, e)
record_internode_classified_error(track_internode_metrics, internode_operation, classify_reqwest_error(&e));
internode_reqwest_error(method, url, internode_operation, e)
})?;
record_internode_http_version(track_internode_metrics, internode_operation, http_version_metric_label(resp.version()));
@@ -1532,9 +1538,10 @@ pub struct HttpWriter {
url: String,
method: Method,
headers: HeaderMap,
err_rx: tokio::sync::oneshot::Receiver<std::io::Error>,
start_tx: Option<tokio::sync::oneshot::Sender<()>>,
sender: PollSender<Option<Bytes>>,
handle: Option<tokio::task::JoinHandle<io::Result<()>>>,
handle: tokio::task::JoinHandle<std::io::Result<()>>,
pending_chunk: BytesMut,
pending_reservation: Option<Arc<HttpWriterMemoryReservation>>,
memory_reserver: Option<HttpWriterMemoryReserver>,
@@ -1583,6 +1590,7 @@ impl HttpWriter {
let internode_operation = internode_rpc_operation(&url);
let (sender, receiver) = tokio::sync::mpsc::channel::<Option<Bytes>>(HTTP_WRITER_CHANNEL_CAPACITY);
let (err_tx, err_rx) = tokio::sync::oneshot::channel::<io::Error>();
let (start_tx, start_rx) = tokio::sync::oneshot::channel::<()>();
let handle = tokio::spawn(async move {
@@ -1605,12 +1613,13 @@ impl HttpWriter {
Ok(client) => client,
Err(err) => {
record_internode_error(track_internode_metrics, internode_operation);
let _ = err_tx.send(Error::new(err.kind(), err.to_string()));
return Err(err);
}
};
let request = client
.request(method_clone.clone(), url_clone.as_str())
.headers(headers_clone)
.request(method_clone.clone(), url_clone.clone())
.headers(headers_clone.clone())
.body(body);
// Hold the request until the shutdown signal is received
@@ -1635,7 +1644,9 @@ impl HttpWriter {
classify_http_status(resp.status()),
);
let status = resp.status();
return Err(internode_status_error(&method_clone, &url_clone, internode_operation, status));
let io_err = internode_status_error(&method_clone, &url_clone, internode_operation, status);
let _ = err_tx.send(internode_status_error(&method_clone, &url_clone, internode_operation, status));
return Err(io_err);
}
}
Err(e) => {
@@ -1643,7 +1654,9 @@ impl HttpWriter {
record_internode_error(track_internode_metrics, internode_operation);
let classified = classify_reqwest_error(&e);
record_internode_classified_error(track_internode_metrics, internode_operation, classified);
return Err(internode_reqwest_error(&method_clone, &url_clone, internode_operation, classified, e));
let _ = err_tx.send(internode_kind_error(&method_clone, &url_clone, internode_operation, classified));
let io_err = internode_reqwest_error(&method_clone, &url_clone, internode_operation, e);
return Err(io_err);
}
}
@@ -1656,9 +1669,10 @@ impl HttpWriter {
url,
method,
headers,
err_rx,
start_tx: Some(start_tx),
sender: PollSender::new(sender),
handle: Some(handle),
handle,
pending_chunk,
pending_reservation,
memory_reserver,
@@ -1847,6 +1861,14 @@ fn record_internode_write_shutdown_error(track: bool, operation: Option<&'static
}
}
fn poll_send_error_to_io<T>(err: tokio_util::sync::PollSendError<T>, context: &str) -> io::Error {
Error::other(format!("{context}: {err}"))
}
fn send_error_to_io<T>(err: tokio_util::sync::PollSendError<T>, context: &str) -> io::Error {
Error::other(format!("{context}: {err}"))
}
impl HttpWriter {
fn ensure_pending_capacity(&mut self) -> io::Result<()> {
if let Some(reserve) = &self.memory_reserver {
@@ -1898,20 +1920,11 @@ impl HttpWriter {
}
}
fn poll_upload_response(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
let Some(handle) = self.handle.as_mut() else {
return Poll::Ready(Ok(()));
};
let result = ready!(Pin::new(handle).poll(cx));
self.handle = None;
Poll::Ready(result.map_err(io::Error::other)?)
}
fn poll_upload_after_body_closed<T>(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<T>> {
// Hyper may drop the request body before the HTTP task publishes its
// response. Preserve the transport error or peer status for quorum.
ready!(self.poll_upload_response(cx))?;
Poll::Ready(Err(io::Error::new(io::ErrorKind::BrokenPipe, "peer closed the upload body early")))
fn take_background_error(&mut self) -> io::Result<()> {
match self.err_rx.try_recv() {
Ok(err) => Err(err),
Err(tokio::sync::oneshot::error::TryRecvError::Empty | tokio::sync::oneshot::error::TryRecvError::Closed) => Ok(()),
}
}
fn poll_send_pending_chunk(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
@@ -1922,12 +1935,12 @@ impl HttpWriter {
match self.sender.poll_reserve(cx) {
Poll::Ready(Ok(())) => {
let chunk = self.take_pending_chunk()?;
if self.sender.send_item(Some(chunk)).is_err() {
return self.poll_upload_after_body_closed(cx);
}
self.sender
.send_item(Some(chunk))
.map_err(|e| send_error_to_io(e, "HttpWriter send error"))?;
Poll::Ready(Ok(()))
}
Poll::Ready(Err(_)) => self.poll_upload_after_body_closed(cx),
Poll::Ready(Err(e)) => Poll::Ready(Err(poll_send_error_to_io(e, "HttpWriter send error"))),
Poll::Pending => Poll::Pending,
}
}
@@ -1942,6 +1955,9 @@ impl AsyncWrite for HttpWriter {
// buf.len()
// );
let this = self.as_mut().get_mut();
if let Err(err) = this.take_background_error() {
return Poll::Ready(Err(err));
}
if !this.pending_chunk.is_empty() && this.pending_chunk.len() >= this.pending_capacity() {
match this.poll_send_pending_chunk(cx) {
@@ -1965,13 +1981,13 @@ impl AsyncWrite for HttpWriter {
} else {
(Bytes::copy_from_slice(&buf[..HTTP_WRITER_BUFFER_SIZE]), HTTP_WRITER_BUFFER_SIZE)
};
if this.sender.send_item(Some(chunk)).is_err() {
return this.poll_upload_after_body_closed(cx);
}
this.sender
.send_item(Some(chunk))
.map_err(|e| send_error_to_io(e, "HttpWriter send error"))?;
this.start_request();
return Poll::Ready(Ok(written));
}
Poll::Ready(Err(_)) => return this.poll_upload_after_body_closed(cx),
Poll::Ready(Err(err)) => return Poll::Ready(Err(poll_send_error_to_io(err, "HttpWriter send error"))),
Poll::Pending => return Poll::Pending,
}
}
@@ -1991,6 +2007,9 @@ impl AsyncWrite for HttpWriter {
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
let this = self.as_mut().get_mut();
if let Err(err) = this.take_background_error() {
return Poll::Ready(Err(err));
}
this.poll_send_pending_chunk(cx)
}
@@ -2000,6 +2019,9 @@ impl AsyncWrite for HttpWriter {
return self.poll_write(cx, &bufs[0]);
}
let this = self.as_mut().get_mut();
if let Err(err) = this.take_background_error() {
return Poll::Ready(Err(err));
}
if !this.pending_chunk.is_empty() && this.pending_chunk.len() >= this.pending_capacity() {
match this.poll_send_pending_chunk(cx) {
@@ -2036,24 +2058,47 @@ impl AsyncWrite for HttpWriter {
true
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
let this = self.as_mut().get_mut();
this.start_request();
let result = ready!(this.poll_finish_upload(cx));
if result.is_err() {
record_internode_write_shutdown_error(this.track_internode_metrics, this.internode_operation);
}
Poll::Ready(result)
}
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
// let url = self.url.clone();
// let method = self.method.clone();
impl HttpWriter {
fn poll_finish_upload(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
ready!(self.poll_send_pending_chunk(cx))?;
if !self.finish {
if ready!(self.sender.poll_reserve(cx)).is_err() || self.sender.send_item(None).is_err() {
return self.poll_upload_after_body_closed(cx);
self.as_mut().get_mut().start_request();
if let Err(err) = self.as_mut().get_mut().take_background_error() {
record_internode_write_shutdown_error(self.track_internode_metrics, self.internode_operation);
return Poll::Ready(Err(err));
}
match self.as_mut().get_mut().poll_send_pending_chunk(cx) {
Poll::Ready(Ok(())) => {}
Poll::Ready(Err(err)) => {
record_internode_write_shutdown_error(self.track_internode_metrics, self.internode_operation);
return Poll::Ready(Err(err));
}
Poll::Pending => return Poll::Pending,
}
if !self.finish {
// http_log!("[HttpWriter::poll_shutdown] url: {}, method: {:?}", url, method);
let this = self.as_mut().get_mut();
match this.sender.poll_reserve(cx) {
Poll::Ready(Ok(())) => {
this.sender.send_item(None).map_err(|e| {
record_internode_write_shutdown_error(this.track_internode_metrics, this.internode_operation);
send_error_to_io(e, "HttpWriter shutdown error")
})?;
}
Poll::Ready(Err(err)) => {
record_internode_write_shutdown_error(this.track_internode_metrics, this.internode_operation);
return Poll::Ready(Err(poll_send_error_to_io(err, "HttpWriter shutdown error")));
}
Poll::Pending => return Poll::Pending,
}
// http_log!(
// "[HttpWriter::poll_shutdown] sent shutdown signal to HTTP request, url: {}, method: {:?}",
// url,
// method
// );
self.finish = true;
if self.memory_reserver.is_some() {
// EOF has been queued, so this writer no longer needs its tail.
@@ -2061,7 +2106,32 @@ impl HttpWriter {
self.pending_reservation = None;
}
}
self.poll_upload_response(cx)
// Wait for the HTTP request to complete
use futures::FutureExt;
match Pin::new(&mut self.as_mut().get_mut().handle).poll_unpin(cx) {
Poll::Ready(Ok(Ok(()))) => {
// http_log!(
// "[HttpWriter::poll_shutdown] HTTP request finished successfully, url: {}, method: {:?}",
// url,
// method
// );
}
Poll::Ready(Ok(Err(err))) => {
record_internode_write_shutdown_error(self.track_internode_metrics, self.internode_operation);
return Poll::Ready(Err(err));
}
Poll::Ready(Err(e)) => {
record_internode_write_shutdown_error(self.track_internode_metrics, self.internode_operation);
// http_log!("[HttpWriter::poll_shutdown] HTTP request failed: {e}, url: {}, method: {:?}", url, method);
return Poll::Ready(Err(Error::other(format!("HTTP request failed: {e}"))));
}
Poll::Pending => {
// http_log!("[HttpWriter::poll_shutdown] HTTP request pending, url: {}, method: {:?}", url, method);
return Poll::Pending;
}
}
Poll::Ready(Ok(()))
}
}
@@ -2075,9 +2145,7 @@ impl Drop for HttpWriter {
/// already handed to the transport: those land only in the upload's unique
/// tmp path and are reclaimed by tmp GC, never touching a committed object.
fn drop(&mut self) {
if let Some(handle) = &self.handle {
handle.abort();
}
self.handle.abort();
}
}
@@ -2171,51 +2239,6 @@ mod tests {
);
}
#[tokio::test]
async fn http_writer_waits_for_peer_status_after_upload_queue_closes() {
for operation in ["write", "flush", "shutdown"] {
let (mut writer, receiver) = paused_http_writer();
let (release, wait) = tokio::sync::oneshot::channel();
writer
.handle
.replace(tokio::spawn(async move {
wait.await.expect("test should release HTTP response");
Err(new_test_internode_http_io_error(InternodeHttpErrorKind::HttpStatus(
StatusCode::SERVICE_UNAVAILABLE,
)))
}))
.expect("paused writer task")
.abort();
if operation == "flush" {
writer
.write_all(b"buffered shard")
.await
.expect("small write should buffer bytes");
}
drop(receiver);
let payload = vec![0; HTTP_WRITER_BUFFER_SIZE];
let mut operation = Box::pin(async {
match operation {
"write" => writer.write_all(&payload).await,
"flush" => writer.flush().await,
"shutdown" => writer.shutdown().await,
_ => unreachable!(),
}
});
assert!(futures::poll!(&mut operation).is_pending());
release.send(()).expect("HTTP response task should be active");
let error = operation.await.expect_err("failed upload must surface the peer status");
assert_eq!(
error
.get_ref()
.and_then(|source| source.downcast_ref::<InternodeHttpError>())
.map(InternodeHttpError::kind),
Some(InternodeHttpErrorKind::HttpStatus(StatusCode::SERVICE_UNAVAILABLE))
);
}
}
#[tokio::test]
async fn early_503_during_streaming_upload_remains_retryable() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
@@ -2239,13 +2262,13 @@ mod tests {
.await
.expect("internode writer should be created");
let payload = vec![b'x'; 4 * 1024 * 1024];
let error = time::timeout(Duration::from_secs(5), async {
writer.write_all(&payload).await?;
writer.shutdown().await
})
.await
.expect("peer status should complete the upload")
.expect_err("early 503 close must fail streaming upload");
let mut final_err = None;
if let Err(err) = writer.write_all(&payload).await {
final_err = Some(err);
} else if let Err(err) = writer.shutdown().await {
final_err = Some(err);
}
let error = final_err.expect("early 503 close must fail streaming upload");
let source = error
.get_ref()
.and_then(|source| source.downcast_ref::<InternodeHttpError>())
@@ -3207,13 +3230,15 @@ mod tests {
.transpose()?
.map(Arc::new);
let (sender, receiver) = tokio::sync::mpsc::channel(HTTP_WRITER_CHANNEL_CAPACITY);
let (_, err_rx) = tokio::sync::oneshot::channel();
let writer = HttpWriter {
url: "http://127.0.0.1/paused".to_string(),
method: Method::PUT,
headers: HeaderMap::new(),
err_rx,
start_tx: None,
sender: PollSender::new(sender),
handle: Some(tokio::spawn(std::future::pending())),
handle: tokio::spawn(std::future::pending()),
pending_chunk: BytesMut::with_capacity(HTTP_WRITER_BUFFER_SIZE),
pending_reservation,
memory_reserver,
@@ -3431,15 +3456,12 @@ mod tests {
.expect("writer runtime");
let writer = runtime.block_on(async {
let (mut writer, receiver) = paused_http_writer_with_memory(Some(memory.reserver())).expect("reserved writer");
writer
.handle
.replace(tokio::spawn(async move {
std::future::pending::<()>().await;
drop(receiver);
Ok(())
}))
.expect("paused task")
.abort();
writer.handle.abort();
writer.handle = tokio::spawn(async move {
std::future::pending::<()>().await;
drop(receiver);
Ok(())
});
writer.write_all(b"queued").await.expect("pending bytes");
writer.flush().await.expect("queued allocation");
writer
@@ -3673,11 +3695,8 @@ mod tests {
let memory = HttpWriterTestMemory::new(HTTP_WRITER_BUFFER_SIZE);
let (mut writer, mut receiver) =
paused_http_writer_with_memory(Some(memory.reserver())).expect("reserve the shutdown body allocation");
writer
.handle
.replace(tokio::spawn(async { Ok(()) }))
.expect("paused task")
.abort();
writer.handle.abort();
writer.handle = tokio::spawn(async { Ok(()) });
writer.write_all(b"body").await.expect("buffer the final body bytes");
writer
.shutdown()
@@ -3915,7 +3934,7 @@ mod tests {
// Observe the background task via its abort handle; it must still be
// running before the drop, then be aborted (finished) after it.
let task = writer.handle.as_ref().expect("upload task should be active").abort_handle();
let task = writer.handle.abort_handle();
assert!(!task.is_finished(), "background task should still be running before drop");
drop(writer);
+1 -1
View File
@@ -17,7 +17,7 @@ A timed-out request is no longer cancelled. Cancelling sends `RST_STREAM`, and e
Three consecutive lock-acquisition timeouts open a request-level per-peer breaker. While open, new `lock` and `lock_batch` calls fail fast as retryable contention; after the backoff window one half-open probe is admitted. The breaker does not block release or refresh traffic, and it is separate from channel eviction. A per-peer in-flight admission limit also bounds requests that were already admitted before the breaker opened.
In multi-voter single-resource acquisition, the first round caps each peer's contention wait at one second. Exclusive retries allow a longer peer wait and give the first voter time to arbitrate before fanning out. If that voter stays silent, the coordinator contacts enough remaining voters in parallel, reserving at least half the round for fallback. If only the first voter refuses, the next retry uses ordinary parallel quorum so a stale or contended voter cannot block the remaining quorum. Each dispatch caps the peer wait at the remaining round budget. Pending responses and partial grants stay in the same round until a response proves that quorum is impossible or the caller's acquisition budget expires. A delayed response can still complete a healthy quorum; it does not restart acquisition with a fresh lock ID merely because delivery took longer than the peer's contention wait. Explicit contention failures retain rollback and retry behavior. Grants whose conservative lease deadline has expired before quorum are rolled back. Cancelling acquisition transfers both confirmed grants and pending replies to background cleanup. The caller's total deadline, read/write quorums, and fast quorum return remain unchanged.
Single-resource distributed acquisition bounds each peer's contention wait to one second, but keeps pending responses and partial grants in the same quorum round until a response proves that round cannot reach quorum or the caller's remaining acquisition budget expires. A delayed response can still complete a healthy quorum; it does not restart acquisition with a fresh lock ID merely because delivery took longer than the peer's contention wait. Explicit contention failures retain rollback and retry behavior. Grants whose conservative lease deadline has expired before quorum are rolled back. Cancelling acquisition transfers both confirmed grants and pending replies to background cleanup. The caller's total deadline, read/write quorums, and fast quorum return remain unchanged.
Unlock cleanup that remains unconfirmed after three quick retries continues in the background with a deferred schedule (1s, 2s, 4s, 8s, 16s). Exhausting that schedule means cleanup was not confirmed; it does not prove that the peer still holds the lock. A server-side lease bounds any grant that remains.
@@ -4468,6 +4468,7 @@ fn apply_table_updates_at(
}
}
snapshot_roots.validate_publication(&metadata)?;
prune_intermediate_snapshot_log_entries(&mut metadata, &snapshot_roots.added)?;
if metadata.get("format-version").is_some() {
@@ -5785,6 +5786,11 @@ struct SnapshotCommitRoots {
by_snapshot: BTreeMap<i64, SnapshotHistory>,
by_branch: BTreeMap<String, i64>,
added: BTreeSet<i64>,
// Branch targets assigned in this commit. A parentless snapshot may be staged with no ref.
// Once a branch points at that new history, or a tag names it, the final metadata must still
// have a branch on the same history. Removing or retargeting the only branch would leave the
// root detached on a populated table.
published_branch_snapshots: BTreeSet<i64>,
}
impl SnapshotCommitRoots {
@@ -5858,6 +5864,65 @@ impl SnapshotCommitRoots {
if is_branch || current.is_some() {
self.by_branch.insert(name.to_owned(), id);
}
if is_branch {
self.published_branch_snapshots.insert(id);
}
Ok(())
}
fn added_history_root(&self, snapshot_id: i64) -> Option<i64> {
let root = self.by_snapshot.get(&snapshot_id)?.root?;
self.added.contains(&root).then_some(root)
}
fn validate_publication(&self, metadata: &serde_json::Value) -> S3Result<()> {
let retained = metadata
.get("snapshots")
.and_then(serde_json::Value::as_array)
.map(|snapshots| {
snapshots
.iter()
.filter_map(|snapshot| snapshot.get("snapshot-id").and_then(serde_json::Value::as_i64))
.collect::<BTreeSet<_>>()
})
.unwrap_or_default();
let history_retained = |root: i64| {
self.by_snapshot
.iter()
.any(|(id, history)| history.root == Some(root) && self.added.contains(id) && retained.contains(id))
};
let mut surviving_branch_roots = BTreeSet::new();
let mut required_roots = BTreeSet::new();
if let Some(refs) = metadata.get("refs").and_then(serde_json::Value::as_object) {
for reference in refs.values() {
let Some(snapshot_id) = reference.get("snapshot-id").and_then(serde_json::Value::as_i64) else {
continue;
};
let Some(root) = self.added_history_root(snapshot_id) else {
continue;
};
match reference.get("type").and_then(serde_json::Value::as_str) {
Some("branch") => {
surviving_branch_roots.insert(root);
}
Some("tag") => {
required_roots.insert(root);
}
_ => {}
}
}
}
for snapshot_id in &self.published_branch_snapshots {
let Some(root) = self.added_history_root(*snapshot_id) else {
continue;
};
if history_retained(root) {
required_roots.insert(root);
}
}
if required_roots.iter().any(|root| !surviving_branch_roots.contains(root)) {
return Err(s3_error!(InvalidRequest, "cannot publish a snapshot history without a surviving branch"));
}
Ok(())
}
}
@@ -2,6 +2,8 @@
mod catalog_migration_scope;
#[path = "tests/real_catalog_failures.rs"]
mod real_catalog_failures;
#[path = "tests/row_level_snapshot_commits.rs"]
mod row_level_snapshot_commits;
use super::*;
use crate::admin::operation::test_support::TestRequest;
@@ -11908,7 +11910,11 @@ fn manifest_rewrite_metadata_bytes(bytes: Vec<u8>, case: &str) -> Vec<u8> {
{"name": "key", "type": "int"}, {"name": "value", "type": if is_bound { "bytes" } else { "long" }}
]
}}]),
Value::Union(1, Box::new(Value::Array(entries))),
match case {
"null_metrics" => Value::Union(0, Box::new(Value::Null)),
"append_empty_metrics" => Value::Union(1, Box::new(Value::Array(Vec::new()))),
_ => Value::Union(1, Box::new(Value::Array(entries))),
},
));
}
}
@@ -12116,6 +12122,7 @@ async fn manifest_rewrite_commit_preserves_live_files() {
"equality_ids",
"custom_metadata",
"missing_metric",
"append_empty_metrics",
"reordered_metadata",
"optional_null",
"duplicate_file",
@@ -12158,7 +12165,11 @@ async fn manifest_rewrite_commit_preserves_live_files() {
let manifest = format!("{location}/metadata/manifest-{snapshot_id}-{index}.avro");
let bytes = manifest_rewrite_metadata_bytes(
test_manifest_avro_bytes(&[(file, *file_content, *status, *entry_snapshot, *entry_sequence)]),
"unchanged",
if case == "append_empty_metrics" && *file == &added && *status == 1 {
"null_metrics"
} else {
"unchanged"
},
);
manifests.push((manifest.clone(), bytes.len(), i32::from(*file_content != 0), *entry_sequence));
backend
@@ -12251,6 +12262,10 @@ async fn manifest_rewrite_commit_preserves_live_files() {
"omitted_file" | "inherited_manifest" | "inherited_partition_spec" => {
rewritten.pop();
}
"append_empty_metrics" => {
seed_test_manifest_data_files(&backend, "warehouse", &[(&extra, 0, 1, 12, 3)]).await;
rewritten.push((extra.as_str(), 0, 1, 12, Some(3), Some(3)));
}
"extra_file" => {
backend
.put_bytes("warehouse", &test_snapshot_object_key("warehouse", &extra), b"extra".to_vec())
@@ -12346,6 +12361,9 @@ async fn manifest_rewrite_commit_preserves_live_files() {
{"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 12, "type": "branch"}
]
});
if case == "append_empty_metrics" {
request_json["updates"][0]["snapshot"]["summary"]["operation"] = "append".into();
}
if case == "intermediate_duplicate" {
let final_list = format!("{location}/metadata/snap-13.avro");
backend
@@ -12421,6 +12439,7 @@ async fn manifest_rewrite_commit_preserves_live_files() {
| "inherited_manifest"
| "staged_retry"
| "reordered_metadata"
| "append_empty_metrics"
| "optional_null"
| "format_case"
) {
@@ -12430,7 +12449,9 @@ async fn manifest_rewrite_commit_preserves_live_files() {
let live = load_snapshot_live_files(&backend, "warehouse", &after, &response.metadata, Some(12))
.await
.unwrap();
assert_eq!(live.data_files.len() + live.delete_files.len(), 2);
let is_append = case == "append_empty_metrics";
assert_eq!(live.data_files.len() + live.delete_files.len(), 2 + usize::from(is_append));
assert_eq!(live.data_files.contains_key(&extra), is_append);
assert_eq!(live.data_files[&retained].sequence_number, Some(1));
let kind = if content == 0 {
crate::table_catalog::TableMetadataMaintenanceObjectKind::DataFile
@@ -12975,6 +12996,176 @@ async fn row_level_conflict_allows_add_only_overwrite_snapshot() {
assert_eq!(commit.metadata["last-sequence-number"], 2);
}
#[tokio::test]
async fn noop_overwrite_snapshot_expiration_retains_shared_manifests_and_live_data_files() {
let backend = TestTableCatalogObjectBackend::content_addressed();
let store = crate::table_catalog::ObjectTableCatalogStore::new(backend.clone());
let bucket = "warehouse";
let namespace = crate::table_catalog::Namespace::parse("analytics").expect("namespace should parse");
let created = create_standard_events_table(&store, &backend, &namespace).await;
let location = created.metadata["location"].as_str().expect("table location");
let data_file = format!("{location}/data/part-10.parquet");
let manifest_10 = format!("{location}/metadata/manifest-10.avro");
let snap_10 = format!("{location}/metadata/snap-10.avro");
let snap_11 = format!("{location}/metadata/snap-11.avro");
seed_test_manifest(&backend, bucket, &manifest_10, &[(&data_file, 0, 1, 10, 1)]).await;
seed_test_manifest_list(&backend, bucket, &snap_10, &[&manifest_10], 1, 10).await;
commit_table_response(
&store,
&trusted_table_commit_backend(&backend),
bucket,
&namespace,
"events",
serde_json::from_value(serde_json::json!({
"updates": [
{
"action": "add-snapshot",
"snapshot": {
"snapshot-id": 10,
"sequence-number": 1,
"timestamp-ms": 1000,
"manifest-list": snap_10,
"summary": {"operation": "append"}
}
},
{"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 10, "type": "branch"}
]
}))
.expect("append request should parse"),
)
.await
.expect("append should commit");
seed_test_manifest_list_entries(&backend, bucket, &snap_11, &[(&manifest_10, 1, 10)]).await;
commit_table_response(
&store,
&trusted_table_commit_backend(&backend),
bucket,
&namespace,
"events",
serde_json::from_value(serde_json::json!({
"requirements": [{"type": "assert-ref-snapshot-id", "ref": "main", "snapshot-id": 10}],
"updates": [
{
"action": "add-snapshot",
"snapshot": {
"snapshot-id": 11,
"parent-snapshot-id": 10,
"sequence-number": 2,
"timestamp-ms": 2000,
"manifest-list": snap_11,
"summary": {"operation": "overwrite"}
}
},
{"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 11, "type": "branch"}
]
}))
.expect("no-op overwrite request should parse"),
)
.await
.expect("no-op overwrite should commit");
let expiration = table_metadata_maintenance_response(
&store,
&backend,
bucket,
&namespace,
"events",
TableMetadataMaintenanceRequest {
retain_recent_metadata_files: 0,
delete: false,
snapshot_expiration: Some(crate::table_catalog::TableSnapshotExpirationConfig {
min_snapshots_to_keep: 1,
max_snapshot_age_ms: 1,
}),
commit_snapshot_expiration: true,
compaction: None,
commit_compaction: false,
},
)
.await
.expect("snapshot expiration after no-op overwrite should succeed");
assert_eq!(
expiration
.snapshot_expiration
.as_ref()
.expect("expiration report")
.expired_snapshot_ids,
vec![10]
);
// Prune `metadata-log` on the current metadata (as `write.metadata.previous-versions-max` would)
// and backdate objects past the safety window so cleanup evaluates Snapshot 11's live graph alone.
let current_entry = store
.load_table(bucket, "analytics", "events")
.await
.expect("table lookup")
.expect("table exists");
let current_meta_obj = backend
.read_object(bucket, &current_entry.metadata_location)
.await
.expect("read current metadata")
.expect("current metadata exists");
let mut pruned_metadata: serde_json::Value = serde_json::from_slice(&current_meta_obj.data).expect("decode current metadata");
pruned_metadata["metadata-log"] = serde_json::json!([]);
backend
.put_json(bucket, &current_entry.metadata_location, pruned_metadata)
.await;
store
.put_table_maintenance_config(
bucket,
"analytics",
"events",
crate::table_catalog::TableMaintenanceConfig {
version: crate::table_catalog::TABLE_MAINTENANCE_CONFIG_VERSION,
retain_recent_metadata_files: 0,
delete_enabled: true,
..Default::default()
},
)
.await
.expect("maintenance delete config should persist");
for record in backend.state.lock().await.objects.values_mut() {
record.mod_time = Some(OffsetDateTime::UNIX_EPOCH);
}
let cleanup = table_metadata_maintenance_response(
&store,
&backend,
bucket,
&namespace,
"events",
TableMetadataMaintenanceRequest {
retain_recent_metadata_files: 0,
delete: true,
snapshot_expiration: None,
commit_snapshot_expiration: false,
compaction: None,
commit_compaction: false,
},
)
.await
.expect("metadata cleanup after parent snapshot expiration should succeed");
assert_eq!(cleanup.job.status, crate::table_catalog::TableMetadataMaintenanceJobStatus::Successful);
assert!(!cleanup.deletable_metadata_locations.is_empty());
let snap_10_key = test_snapshot_object_key(bucket, &snap_10);
let snap_11_key = test_snapshot_object_key(bucket, &snap_11);
let manifest_10_key = test_snapshot_object_key(bucket, &manifest_10);
let data_file_key = test_snapshot_object_key(bucket, &data_file);
assert_eq!(cleanup.deletable_object_locations, vec![snap_10_key.clone()]);
assert!(
!backend.object_exists(bucket, &snap_10_key).await.expect("snap-10 lookup"),
"expired parent snapshot's manifest-list should be reclaimed once unreferenced"
);
for retained_key in [&snap_11_key, &manifest_10_key, &data_file_key] {
assert!(
backend.object_exists(bucket, retained_key).await.expect("retained lookup"),
"shared object referenced by surviving no-op overwrite snapshot must remain retained: {retained_key}"
);
}
}
#[tokio::test]
async fn row_level_conflict_rejects_delete_of_non_current_file() {
let store = TestTableCatalogStore::default();
@@ -0,0 +1,246 @@
// 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 serde_json::{Value, json};
const DETACHED_HISTORY: &str = "cannot publish a snapshot history without a surviving branch";
const EXISTING_BRANCH: &str = "cannot publish a new snapshot history over an existing branch";
struct Table {
store: TestTableCatalogStore,
backend: TestTableCatalogObjectBackend,
namespace: crate::table_catalog::Namespace,
location: String,
}
impl Table {
async fn empty() -> Self {
let store = TestTableCatalogStore::default();
let backend = TestTableCatalogObjectBackend::content_addressed();
let namespace = crate::table_catalog::Namespace::parse("analytics").unwrap();
let created = create_standard_events_table(&store, &backend, &namespace).await;
Self {
location: created.metadata["location"].as_str().unwrap().to_owned(),
store,
backend,
namespace,
}
}
async fn populated() -> Self {
let table = Self::empty().await;
for name in ["a", "b"] {
seed_test_manifest(&table.backend, "warehouse", &table.manifest(name), &[(&table.data(name), 0, 1, 10, 1)]).await;
}
let list = table
.list("initial", &[(&table.manifest("a"), 1, 10), (&table.manifest("b"), 1, 10)])
.await;
table
.commit(json!({"updates": [snapshot("append", 10, 1, None, &list), branch("main", 10), branch("audit", 10)]}))
.await
.unwrap();
table
}
fn data(&self, name: &str) -> String {
format!("{}/data/{name}.parquet", self.location)
}
fn manifest(&self, name: &str) -> String {
format!("{}/metadata/manifest-{name}.avro", self.location)
}
async fn list(&self, name: &str, entries: &[(&str, i64, i64)]) -> String {
let location = format!("{}/metadata/snap-{name}.avro", self.location);
seed_test_manifest_list_entries(&self.backend, "warehouse", &location, entries).await;
location
}
async fn commit(&self, request: Value) -> S3Result<RestCommitTableResponse> {
commit_table_response(
&self.store,
&trusted_table_commit_backend(&self.backend),
"warehouse",
&self.namespace,
"events",
serde_json::from_value(request).unwrap(),
)
.await
}
async fn entry(&self) -> crate::table_catalog::TableEntry {
self.store
.load_table("warehouse", "analytics", "events")
.await
.unwrap()
.unwrap()
}
async fn reject(&self, updates: Value, message: &str) {
let before = self.entry().await;
let error = self
.commit(json!({"updates": updates}))
.await
.expect_err("commit should fail");
assert_eq!(error.code(), &S3ErrorCode::InvalidRequest);
assert_eq!(error.message(), Some(message));
let after = self.entry().await;
assert_eq!(after.metadata_location, before.metadata_location);
assert_eq!(after.version_token, before.version_token);
assert_eq!(after.generation, before.generation);
let metadata = read_persisted_table_metadata_for_entry(&self.backend, &after, &after.metadata_location, true)
.await
.unwrap();
assert_eq!(metadata["current-snapshot-id"], 10);
assert_eq!(metadata["refs"]["main"]["snapshot-id"], 10);
assert_eq!(metadata["refs"]["audit"]["snapshot-id"], 10);
assert!(metadata["refs"].get("temporary").is_none());
let live = load_snapshot_live_files(&self.backend, "warehouse", &after, &metadata, Some(10))
.await
.unwrap();
assert!(live.data_files.contains_key(&self.data("a")));
assert!(live.data_files.contains_key(&self.data("b")));
}
}
fn snapshot(operation: &str, id: i64, sequence: i64, parent: Option<i64>, list: &str) -> Value {
let mut snapshot = json!({
"snapshot-id": id,
"sequence-number": sequence,
"timestamp-ms": 1000 * sequence,
"manifest-list": list,
"summary": {"operation": operation}
});
if let Some(parent) = parent {
snapshot["parent-snapshot-id"] = parent.into();
}
json!({"action": "add-snapshot", "snapshot": snapshot})
}
fn branch(name: &str, id: i64) -> Value {
json!({"action": "set-snapshot-ref", "ref-name": name, "type": "branch", "snapshot-id": id})
}
fn tag(name: &str, id: i64) -> Value {
json!({"action": "set-snapshot-ref", "ref-name": name, "type": "tag", "snapshot-id": id})
}
fn remove_ref(name: &str) -> Value {
json!({"action": "remove-snapshot-ref", "ref-name": name})
}
#[tokio::test]
async fn temporary_branch_cannot_publish_a_root_on_a_populated_table() {
let table = Table::populated().await;
let list = table.list("empty", &[]).await;
let root = snapshot("overwrite", 11, 2, None, &list);
let child = snapshot("append", 12, 3, Some(11), &list);
table
.reject(json!([root, branch("temporary", 11), remove_ref("temporary")]), DETACHED_HISTORY)
.await;
table
.reject(json!([root, branch("temporary", 11), branch("temporary", 10)]), EXISTING_BRANCH)
.await;
table
.reject(json!([root, child, branch("temporary", 12), remove_ref("temporary")]), DETACHED_HISTORY)
.await;
// The same root may be staged with no ref, or published on a branch that survives.
let staged = table.commit(json!({"updates": [root]})).await.unwrap();
assert_eq!(staged.metadata["current-snapshot-id"], 10);
assert!(staged.metadata["refs"].get("temporary").is_none());
assert_eq!(staged.metadata["refs"]["main"]["snapshot-id"], 10);
let published = table
.commit(json!({"updates": [
snapshot("overwrite", 13, 3, None, &list),
tag("initial", 13),
snapshot("append", 14, 4, Some(13), &list),
branch("feature", 14),
tag("release", 14),
branch("temporary", 13),
remove_ref("temporary"),
]}))
.await
.unwrap();
assert_eq!(published.metadata["current-snapshot-id"], 10);
assert_eq!(published.metadata["refs"]["feature"]["snapshot-id"], 14);
assert_eq!(published.metadata["refs"]["initial"]["snapshot-id"], 13);
assert_eq!(published.metadata["refs"]["release"]["snapshot-id"], 14);
assert_eq!(published.metadata["refs"]["main"]["snapshot-id"], 10);
assert_eq!(published.metadata["refs"]["audit"]["snapshot-id"], 10);
}
#[tokio::test]
async fn a_tagged_root_requires_a_branch_for_its_own_history() {
let table = Table::empty().await;
let list = table.list("empty", &[]).await;
let root = snapshot("delete", 10, 1, None, &list);
for updates in [
json!([root, tag("release", 10)]),
json!([root, branch("temporary", 10), tag("release", 10), remove_ref("temporary")]),
json!([
root,
tag("release", 10),
snapshot("overwrite", 11, 2, None, &list),
branch("main", 11)
]),
] {
let before = table.entry().await;
let error = table
.commit(json!({"updates": updates}))
.await
.expect_err("commit should fail");
assert_eq!(error.code(), &S3ErrorCode::InvalidRequest);
assert_eq!(error.message(), Some(DETACHED_HISTORY));
let after = table.entry().await;
assert_eq!(after.metadata_location, before.metadata_location);
assert_eq!(after.version_token, before.version_token);
assert_eq!(after.generation, before.generation);
}
let committed = table
.commit(json!({"updates": [root, branch("main", 10), tag("release", 10)]}))
.await
.unwrap();
assert_eq!(committed.metadata["current-snapshot-id"], 10);
assert_eq!(committed.metadata["refs"]["release"]["snapshot-id"], 10);
assert_eq!(committed.metadata["refs"]["main"]["snapshot-id"], 10);
}
#[tokio::test]
async fn empty_inline_manifests_are_rejected_on_v2_tables() {
let table = Table::empty().await;
let before = table.entry().await;
let error = table
.commit(json!({"updates": [
{
"action": "add-snapshot",
"snapshot": {
"snapshot-id": 10,
"sequence-number": 1,
"timestamp-ms": 1000,
"manifests": [],
"summary": {"operation": "overwrite"}
}
},
branch("main", 10)
]}))
.await
.expect_err("v2 empty inline manifests should fail");
assert_eq!(error.code(), &S3ErrorCode::InvalidRequest);
assert_eq!(error.message(), Some("Iceberg v2 snapshots require manifest-list"));
let after = table.entry().await;
assert_eq!(after.metadata_location, before.metadata_location);
assert_eq!(after.generation, before.generation);
}
+45 -38
View File
@@ -15,7 +15,6 @@
use crate::storage_api::error::contract::{StorageErrorCode, range::HTTPRangeError};
use crate::storage_api::error::{PoolMetadataError, QuotaError, StorageError, unreadable_config_refusal};
use http::StatusCode;
use rustfs_io_metrics::internode_metrics::{INTERNODE_OPERATION_PUT_FILE_CAPABILITY, INTERNODE_OPERATION_PUT_FILE_STREAM};
use rustfs_kms::KmsUnavailableError;
use rustfs_lock::LockError;
use rustfs_s3_types::S3ErrorCode;
@@ -517,7 +516,6 @@ fn body_read_error_code(err: &(dyn std::error::Error + 'static)) -> Option<S3Err
let mut body_size_exceeded = false;
let mut incomplete_body = false;
let mut rpc_unavailable = false;
let mut inside_internode_http_error = false;
let digest = error_chain_find(err, |error| {
if error.is::<rustfs_rio::Sha256Mismatch>() {
return Some(S3ErrorCode::Custom(CONTENT_SHA256_MISMATCH_CODE.into()));
@@ -534,16 +532,11 @@ fn body_read_error_code(err: &(dyn std::error::Error + 'static)) -> Option<S3Err
.get(RPC_ADMISSION_METADATA_KEY)
.is_some_and(|value| value.as_encoded_bytes() == RPC_REPLAY_ADMISSION_METADATA_VALUE.as_bytes()))
});
if let Some(internode_error) = error.downcast_ref::<rustfs_rio::InternodeHttpError>() {
inside_internode_http_error = true;
rpc_unavailable |= is_unavailable_internode_http_error(internode_error);
}
upload_limit_exceeded |= error.is::<UploadLimitExceeded>();
server_source_failed |= error.is::<ServerSideSourceReadError>();
client_body_timed_out |= error.is::<ClientBodyReadTimeout>();
body_size_exceeded |= error.is::<rustfs_s3_types::BodyTooLarge>();
// A Hyper EOF beneath a peer HTTP failure describes the shard exchange.
incomplete_body |= error.is::<rustfs_rio::IncompleteBody>() || (!inside_internode_http_error && is_hyper_body_eof(error));
incomplete_body |= error.is::<rustfs_rio::IncompleteBody>() || is_hyper_body_eof(error);
None
});
digest.or({
@@ -568,7 +561,7 @@ fn body_read_error_code(err: &(dyn std::error::Error + 'static)) -> Option<S3Err
/// `io::Error::source` skips its custom payload itself. Visit that payload
/// explicitly at every level, then follow its source exactly once. The bound
/// also makes cyclic or excessively deep foreign error chains safe.
pub(crate) fn error_chain_find<T>(
fn error_chain_find<T>(
err: &(dyn std::error::Error + 'static),
mut classify: impl FnMut(&(dyn std::error::Error + 'static)) -> Option<T>,
) -> Option<T> {
@@ -602,9 +595,10 @@ fn is_unavailable_internode_http_error(err: &rustfs_rio::InternodeHttpError) ->
err.kind().is_retryable()
|| matches!(
err.kind(),
rustfs_rio::InternodeHttpErrorKind::HttpStatus(StatusCode::CONFLICT)
if err.context().operation() == Some(INTERNODE_OPERATION_PUT_FILE_STREAM)
rustfs_rio::InternodeHttpErrorKind::HttpStatus(status)
if status.is_server_error() || status.as_u16() == 409
)
|| (err.kind() == rustfs_rio::InternodeHttpErrorKind::Unknown && err.context().operation().is_some())
}
/// A nested lock timeout retains its retry advice even when an outer lock
@@ -629,10 +623,7 @@ fn service_unavailable_cause(source: &(dyn std::error::Error + 'static)) -> Opti
if cause.is_none()
&& let Some(internode_err) = error.downcast_ref::<rustfs_rio::InternodeHttpError>()
&& is_unavailable_internode_http_error(internode_err)
&& matches!(
internode_err.context().operation(),
Some(INTERNODE_OPERATION_PUT_FILE_STREAM | INTERNODE_OPERATION_PUT_FILE_CAPABILITY)
)
&& matches!(internode_err.context().operation(), Some("put_file_stream" | "put_file_capability"))
{
cause = Some("storage_write_quorum");
}
@@ -672,7 +663,10 @@ impl From<ApiError> for rustfs_s3_types::S3Error {
}
}
/// Classify a gateway refusal while its typed source is still available.
/// Fine-grained, bounded classification for every HTTP 503 response (`ServiceUnavailable`,
/// `SlowDown`, `SlowDownRead`, `Busy`), emitted via `x-rustfs-503-subcause` at the outer
/// gateway stack edge and counted under `rustfs_s3_503_responses_total` without expanding
/// `rustfs-gateway`'s closed inner `x-rustfs-error-cause` set.
pub(crate) fn classify_s3_503_subcause(
code: &S3ErrorCode,
message: Option<&str>,
@@ -690,6 +684,9 @@ pub(crate) fn classify_s3_503_subcause(
}
}
if matches!(code, S3ErrorCode::Custom(name) if &**name == SLOW_DOWN_READ_CODE) {
return "storage_read_quorum";
}
if code == &S3ErrorCode::Busy {
return "s3_select_busy";
}
@@ -700,22 +697,21 @@ pub(crate) fn classify_s3_503_subcause(
return sub;
}
if matches!(code, S3ErrorCode::Custom(name) if &**name == SLOW_DOWN_READ_CODE) {
return "storage_read_unavailable";
}
let msg = message.unwrap_or_default();
if code == &S3ErrorCode::SlowDown {
if msg.starts_with("foreground write concurrency limit reached") {
if msg.contains("write concurrency limit reached") || msg.contains("foreground write concurrency") {
return "foreground_write_admission";
}
if msg.starts_with("disk read concurrency limit reached") {
if msg.contains("disk read concurrency limit reached") {
return "disk_read_permit_exhausted";
}
if msg.starts_with("Table listing exceeded the protected scan limit") {
if msg.contains("Table listing exceeded") {
return "table_list_scan_limit";
}
if msg.ends_with(" queue is full; retry later") || msg.ends_with(" queue wait timed out; retry later") {
if msg.contains("cold-fill") || msg.contains("cache") {
return "object_cache_cold_fill_rejected";
}
if headers.and_then(|h| h.get(http::header::RETRY_AFTER)).is_some() {
return "bucket_operation_admission";
}
if msg.contains("Resource requested is unreadable") {
@@ -724,7 +720,7 @@ pub(crate) fn classify_s3_503_subcause(
return "slowdown_other";
}
if msg == "Bucket quota check temporarily unavailable, please retry" {
if msg.contains("quota") || msg.contains("Quota") {
return "quota_usage_unavailable";
}
if msg.contains("server context is not ready") || msg.contains("iam unavailable") {
@@ -734,6 +730,9 @@ pub(crate) fn classify_s3_503_subcause(
}
fn classify_503_source_chain(source: &(dyn std::error::Error + 'static)) -> Option<&'static str> {
if let Some(lock_or_write_cause) = service_unavailable_cause(source) {
return Some(lock_or_write_cause);
}
error_chain_find(source, |error| {
if let Some(status) = error.downcast_ref::<tonic::Status>() {
if status.code() == tonic::Code::ResourceExhausted
@@ -771,7 +770,6 @@ fn classify_503_source_chain(source: &(dyn std::error::Error + 'static)) -> Opti
}
return match storage_err {
StorageError::ErasureReadQuorum | StorageError::InsufficientReadQuorum(_, _) => Some("storage_read_quorum"),
StorageError::PartMissingOrCorrupt => Some("storage_part_unavailable"),
StorageError::ErasureWriteQuorum | StorageError::InsufficientWriteQuorum(_, _) => Some("storage_write_quorum"),
StorageError::DiskFull | StorageError::StorageFull => Some("disk_full"),
StorageError::TooManyOpenFiles => Some("too_many_open_files"),
@@ -961,6 +959,21 @@ impl From<StorageError> for ApiError {
source: Some(Box::new(err)),
};
}
if error_chain_find(inner, |cause| {
cause
.downcast_ref::<rustfs_rio::InternodeHttpError>()
.filter(|err| is_unavailable_internode_http_error(err))
.map(|_| ())
})
.is_some()
{
return ApiError {
code: S3ErrorCode::ServiceUnavailable,
message: ApiError::error_code_to_message(&S3ErrorCode::ServiceUnavailable),
source: Some(Box::new(err)),
};
}
}
let code = match &err {
@@ -2761,8 +2774,9 @@ mod tests {
for kind in [
ConnectionReset,
BodyStreamAborted,
HttpStatus(http::StatusCode::CONFLICT),
Unknown,
HttpStatus(http::StatusCode::SERVICE_UNAVAILABLE),
HttpStatus(http::StatusCode::INTERNAL_SERVER_ERROR),
] {
let errors = [
Some(DiskError::from(rustfs_rio::new_test_internode_http_io_error(kind))),
@@ -2782,17 +2796,10 @@ mod tests {
assert_eq!(response.status_code(), Some(http::StatusCode::SERVICE_UNAVAILABLE));
}
for kind in [
Unknown,
HttpStatus(http::StatusCode::BAD_REQUEST),
HttpStatus(http::StatusCode::INTERNAL_SERVER_ERROR),
] {
let err = DiskError::from(rustfs_rio::new_test_internode_http_io_error(kind));
let errors = [Some(err.clone()), Some(err.clone()), Some(err), None];
let reduced = reduce_write_quorum_errs(&errors, OBJECT_OP_IGNORED_ERRS, 3)
.expect("the peer failure must survive quorum reduction");
assert_eq!(ApiError::from(StorageError::from(reduced)).code, S3ErrorCode::InternalError, "{kind:?}");
}
let bad_req = DiskError::from(rustfs_rio::new_test_internode_http_io_error(HttpStatus(http::StatusCode::BAD_REQUEST)));
let errors = [Some(bad_req.clone()), Some(bad_req.clone()), Some(bad_req), None];
let reduced = reduce_write_quorum_errs(&errors, OBJECT_OP_IGNORED_ERRS, 3).unwrap();
assert_eq!(ApiError::from(StorageError::from(reduced)).code, S3ErrorCode::InternalError);
}
#[test]
+40 -10
View File
@@ -40,6 +40,36 @@ use rustfs_gateway::{
use rustfs_gateway_types::{ETag, ErrorCode, Timestamp, TimestampFormat};
use rustfs_s3_types::S3Error;
use std::borrow::Cow;
use std::cell::Cell;
use std::future::Future;
tokio::task_local! {
static CURRENT_503_SUBCAUSE: Cell<Option<&'static str>>;
}
/// Runs `future` with a task-local slot that captures the fine-grained subcause of any HTTP 503
/// rendered by [`handler_error`] so [`crate::server::gateway_stack::GatewayStack::call`] can
/// emit `x-rustfs-503-subcause` on the outer response without widening the gateway's closed
/// inner `x-rustfs-error-cause` set.
pub(in crate::server) async fn scope_503_subcause<F: Future>(future: F) -> (F::Output, Option<&'static str>) {
CURRENT_503_SUBCAUSE
.scope(Cell::new(None), async move {
let out = future.await;
let subcause = CURRENT_503_SUBCAUSE.try_with(Cell::get).ok().flatten();
(out, subcause)
})
.await
}
fn s3_code_metric_label(code: &rustfs_s3_types::S3ErrorCode) -> &'static str {
match code.as_str() {
"ServiceUnavailable" => "ServiceUnavailable",
"SlowDown" => "SlowDown",
"SlowDownRead" => "SlowDownRead",
"Busy" => "Busy",
_ => "Other503",
}
}
const LOG_COMPONENT_STORAGE: &str = "storage";
const LOG_SUBSYSTEM_OBJECT: &str = "object";
@@ -154,6 +184,16 @@ pub(crate) fn handler_error(error: S3Error) -> HandlerError {
.status
.or_else(|| parts.code.status_code())
.unwrap_or(http::StatusCode::INTERNAL_SERVER_ERROR);
if status == http::StatusCode::SERVICE_UNAVAILABLE {
let subcause = crate::error::classify_s3_503_subcause(
&parts.code,
parts.message.as_deref(),
parts.headers.as_ref(),
parts.source.as_deref().map(|err| err as &(dyn std::error::Error + 'static)),
);
rustfs_io_metrics::s3_http_metrics::record_s3_http_503_response(s3_code_metric_label(&parts.code), subcause);
let _ = CURRENT_503_SUBCAUSE.try_with(|slot| slot.set(Some(subcause)));
}
// A declared code compares equal to the custom code of the same spelling and status.
let code = ErrorCode::custom(parts.code.as_str().to_owned(), status);
let headers = parts.headers.unwrap_or_default();
@@ -176,16 +216,6 @@ pub(crate) fn handler_error(error: S3Error) -> HandlerError {
};
mapped = mapped.with_header(header);
}
if status == http::StatusCode::SERVICE_UNAVAILABLE {
rustfs_io_metrics::s3_http_metrics::observe_s3_http_503_subcause(|| {
crate::error::classify_s3_503_subcause(
&parts.code,
Some(mapped.message()),
Some(&headers),
parts.source.as_deref().map(|err| err as &(dyn std::error::Error + 'static)),
)
});
}
mapped
}
@@ -55,6 +55,7 @@ pub(crate) mod test_support;
pub(super) use self::access::verified_signature;
pub(crate) use self::error::handler_error;
pub(in crate::server) use self::error::scope_503_subcause;
use crate::app::{Answered, RequestEnvelope};
use crate::runtime_sources::{AppContext, ServerContextSlot};
use rustfs_gateway::{Handler, HandlerError, HandlerResult, OperationCodec, Req, Resp, ServiceBuilder};
+10 -1
View File
@@ -405,7 +405,16 @@ impl GatewayStack {
// left unread in a detached task of its own, which takes the body away from
// `EarlyResponseBodyService`, the drain the HTTP/1-2 shutdown accounting owns. The
// adapter's connection verdict is kept.
let mut response = service.call(request).await;
let (mut response, subcause_503) =
crate::server::gateway_handlers::scope_503_subcause(async move { service.call(request).await }).await;
if response.status() == http::StatusCode::SERVICE_UNAVAILABLE
&& let Some(subcause) = subcause_503
{
response.headers_mut().insert(
http::HeaderName::from_static("x-rustfs-503-subcause"),
http::HeaderValue::from_static(subcause),
);
}
if track_plaintext_post_ssec && is_plaintext_ssec_refusal_response(&response) {
report_plaintext_ssec();
}
-82
View File
@@ -1217,88 +1217,6 @@ impl rustfs_gateway::Handler<rustfs_gateway::dto::ListBuckets> for SigV4aProbe {
}
}
#[tokio::test]
async fn gateway_handler_503_is_attributed_at_external_response() {
use crate::server::layer::ExternalRequestContextLayer;
use metrics_util::debugging::{DebugValue, DebuggingRecorder};
use rustfs_gateway::{Handler, HandlerResult, Req, dto::ListBuckets};
use rustfs_s3_types::{S3Error, S3ErrorCode};
use tower::{Layer, ServiceExt};
struct UnavailableBucketListing;
impl Handler<ListBuckets> for UnavailableBucketListing {
async fn call(&self, _request: Req<ListBuckets>) -> HandlerResult<ListBuckets> {
rustfs_io_metrics::record_s3_op(rustfs_s3_ops::S3Operation::ListBuckets);
let mut error = S3Error::new(S3ErrorCode::ServiceUnavailable);
error.set_source(Box::new(crate::storage_api::error::StorageError::Timeout));
Err(crate::server::gateway_handlers::handler_error(error))
}
}
let a = assembly();
let builder = GatewayStack::configured_builder(
&a,
Arc::new(ScriptedIam { ready: true }),
root().source(),
decide_with(|_| Decision::Allow),
std::convert::identity,
)
.expect("assemble the gateway builder");
let stack = GatewayStack {
service: builder
.register::<ListBuckets, _>(Arc::new(UnavailableBucketListing))
.build()
.expect("register the failing handler"),
keystone_auth: None,
control_plane: false,
object_lambda_fallback: None,
};
let recorder = DebuggingRecorder::new();
let _recorder = metrics::set_default_local_recorder(&recorder);
let response = ExternalRequestContextLayer::default()
.layer(tower::service_fn(|request| {
let reply = stack.call(request);
async move { Ok::<_, std::convert::Infallible>(reply.await) }
}))
.oneshot(signed_request(Signed::Header, Method::GET, "/", "", ROOT_ACCESS_KEY, ROOT_SECRET_KEY))
.await
.expect("external S3 response");
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(response.headers()["x-rustfs-503-subcause"], "storage_timeout");
let gateway_error = response
.extensions()
.get::<rustfs_gateway::S3Error>()
.expect("rendered gateway error");
assert_eq!(gateway_error.code().expect("error code").as_str(), "ServiceUnavailable");
let body = response
.into_body()
.collect()
.await
.expect("read gateway response")
.to_bytes();
assert!(String::from_utf8_lossy(&body).contains("<Code>ServiceUnavailable</Code>"));
let entries = recorder.snapshotter().snapshot().into_vec();
let mut attributed = entries
.iter()
.filter(|(key, _, _, _)| key.key().name() == "rustfs_s3_503_responses_total");
let (key, _, _, value) = attributed
.next()
.expect("gateway refusal attributed at the external response");
let labels: std::collections::BTreeMap<_, _> = key.key().labels().map(|label| (label.key(), label.value())).collect();
assert_eq!(
labels,
std::collections::BTreeMap::from([
("op", "s3:ListBuckets"),
("code", "ServiceUnavailable"),
("subcause", "storage_timeout"),
])
);
assert_eq!(*value, DebugValue::Counter(1));
assert!(attributed.next().is_none(), "only the final S3 response is counted");
}
/// SigV4a header and presigned requests verify through `GatewayStack`, enforce signed
/// `x-rustfs-*` extension headers before reaching handlers, and reject tampered signatures.
#[tokio::test]
+90 -13
View File
@@ -82,16 +82,20 @@ pub(crate) async fn collect_probe_readiness(
}
fn apply_object_traffic_snapshot(report: &mut DependencyReadinessReport, probe: HealthProbe, snapshot: ObjectTrafficSnapshot) {
if snapshot.read_stalled && matches!(probe, HealthProbe::Readiness | HealthProbe::ClusterRead) {
if matches!(probe, HealthProbe::Readiness | HealthProbe::ClusterRead) && snapshot.read_stalled {
let reason = ReadinessDegradedReason::ObjectReadStalled;
report.degraded_reasons.push(reason);
if !report.degraded_reasons.contains(&reason) {
report.degraded_reasons.push(reason);
}
if probe == HealthProbe::Readiness {
record_readiness_overlay_reason(reason);
}
}
if snapshot.write_stalled && matches!(probe, HealthProbe::Readiness | HealthProbe::ClusterWrite) {
if matches!(probe, HealthProbe::Readiness | HealthProbe::ClusterWrite) && snapshot.write_stalled {
let reason = ReadinessDegradedReason::ObjectWriteStalled;
report.degraded_reasons.push(reason);
if !report.degraded_reasons.contains(&reason) {
report.degraded_reasons.push(reason);
}
if probe == HealthProbe::Readiness {
record_readiness_overlay_reason(reason);
}
@@ -323,21 +327,25 @@ pub(crate) fn build_health_response_parts(
),
};
let kms_overlay_degraded = probe == HealthProbe::Readiness && kms_ready == Some(false);
let readiness_overlay_degraded = kms_overlay_degraded
|| degraded_reasons.iter().any(|reason| match reason {
ReadinessDegradedReason::StartupFinalizationPending => probe == HealthProbe::Readiness,
ReadinessDegradedReason::ObjectReadStalled => matches!(probe, HealthProbe::Readiness | HealthProbe::ClusterRead),
ReadinessDegradedReason::ObjectWriteStalled => matches!(probe, HealthProbe::Readiness | HealthProbe::ClusterWrite),
_ => false,
});
let startup_pending = degraded_reasons.contains(&ReadinessDegradedReason::StartupFinalizationPending);
let write_stalled = degraded_reasons.contains(&ReadinessDegradedReason::ObjectWriteStalled);
let read_stalled = degraded_reasons.contains(&ReadinessDegradedReason::ObjectReadStalled);
let readiness_overlay_degraded = match probe {
HealthProbe::Readiness => startup_pending || write_stalled || read_stalled || matches!(kms_ready, Some(false)),
HealthProbe::ClusterWrite => write_stalled,
HealthProbe::ClusterRead => read_stalled,
HealthProbe::Liveness => false,
};
if readiness_overlay_degraded {
health = HealthCheckState {
status_code: StatusCode::SERVICE_UNAVAILABLE,
status: "degraded",
ready: false,
};
if kms_overlay_degraded && !degraded_reasons.contains(&ReadinessDegradedReason::KmsNotReady) {
if probe == HealthProbe::Readiness
&& matches!(kms_ready, Some(false))
&& !degraded_reasons.contains(&ReadinessDegradedReason::KmsNotReady)
{
degraded_reasons.push(ReadinessDegradedReason::KmsNotReady);
}
}
@@ -883,4 +891,73 @@ mod tests {
assert_eq!(payload["degradedReasons"], json!([]));
});
}
#[test]
#[serial]
fn cluster_probes_reflect_matching_traffic_stalls_without_startup_admission_overlay() {
with_var(rustfs_config::ENV_HEALTH_MINIMAL_RESPONSE_ENABLE, Some("false"), || {
let mut startup_report = ready_report();
startup_report
.degraded_reasons
.push(ReadinessDegradedReason::StartupFinalizationPending);
// Node readiness waits for S3 admission publication, while cluster probes continue
// reporting cluster quorum readiness before node-local publication.
let readiness = build_health_response_parts(
Method::GET,
HealthProbe::Readiness,
Some(&startup_report),
"rustfs-endpoint",
None,
None,
);
assert_eq!(readiness.status_code, StatusCode::SERVICE_UNAVAILABLE);
for probe in [HealthProbe::ClusterWrite, HealthProbe::ClusterRead] {
let parts = build_health_response_parts(Method::GET, probe, Some(&startup_report), "rustfs-endpoint", None, None);
assert_eq!(parts.status_code, StatusCode::OK, "{probe:?}");
}
let mut write_report = ready_report();
apply_object_traffic_snapshot(
&mut write_report,
HealthProbe::ClusterWrite,
ObjectTrafficSnapshot {
read_stalled: true,
write_stalled: true,
},
);
let write_parts = build_health_response_parts(
Method::GET,
HealthProbe::ClusterWrite,
Some(&write_report),
"rustfs-endpoint",
None,
None,
);
assert_eq!(write_parts.status_code, StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(
write_parts.payload.expect("cluster write payload")["degradedReasons"],
json!(["object_write_stalled"])
);
let mut read_report = ready_report();
apply_object_traffic_snapshot(
&mut read_report,
HealthProbe::ClusterRead,
ObjectTrafficSnapshot {
read_stalled: false,
write_stalled: true,
},
);
let read_parts = build_health_response_parts(
Method::GET,
HealthProbe::ClusterRead,
Some(&read_report),
"rustfs-endpoint",
None,
None,
);
assert_eq!(read_parts.status_code, StatusCode::OK);
});
}
}
+68 -145
View File
@@ -65,7 +65,6 @@ use tracing::{Level, debug, error, info, warn};
use url::form_urlencoded;
const HTTP_REQUEST_COMPLETED_EVENT: &str = "http_request_completed";
pub(super) const S3_503_SUBCAUSE_HEADER: http::HeaderName = http::HeaderName::from_static("x-rustfs-503-subcause");
const HTTP_REQUEST_FAILED_EVENT: &str = "http_request_failed";
@@ -424,32 +423,6 @@ where
};
if let Some(metrics) = this.metrics.as_mut() {
if response.status() == StatusCode::SERVICE_UNAVAILABLE {
let readiness_pending = response.headers().get(&S3_503_SUBCAUSE_HEADER)
== Some(&HeaderValue::from_static(super::readiness::READINESS_503_SUBCAUSE));
let code = match response
.extensions()
.get::<rustfs_gateway::S3Error>()
.and_then(|error| error.code())
.map(|code| code.as_str())
{
Some("ServiceUnavailable") => "ServiceUnavailable",
Some("SlowDown") => "SlowDown",
Some("SlowDownRead") => "SlowDownRead",
Some("Busy") => "Busy",
_ if readiness_pending => "ServiceUnavailable",
_ => "Other503",
};
let subcause = if readiness_pending {
super::readiness::READINESS_503_SUBCAUSE
} else {
metrics.subcause_503().unwrap_or("unclassified")
};
response
.headers_mut()
.insert(S3_503_SUBCAUSE_HEADER, HeaderValue::from_static(subcause));
metrics.record_503_response(code, subcause);
}
metrics.response(response.status().as_u16());
}
if let Some(request_id) = this.request_id.take() {
@@ -1078,17 +1051,6 @@ where
let response_parts =
build_health_response_parts(method, probe, readiness_report.as_ref(), "rustfs-endpoint", None, kms_ready);
if let Some(probe_label) = match probe {
HealthProbe::ClusterWrite => Some("write"),
HealthProbe::ClusterRead => Some("read"),
HealthProbe::Readiness | HealthProbe::Liveness => None,
} {
metrics::gauge!("rustfs_cluster_health_ready", "probe" => probe_label).set(if response_parts.status_code.is_success() {
1.0
} else {
0.0
});
}
let body = response_parts
.payload
.map(|payload| Bytes::from(serde_json::to_vec(&payload).unwrap_or_else(|_| b"{}".to_vec())))
@@ -2152,26 +2114,7 @@ pub(in crate::server) mod tests {
#[tokio::test]
async fn external_s3_http_outcomes_include_real_readiness_rejections() {
use metrics_util::debugging::{DebugValue, DebuggingRecorder};
use rustfs_io_metrics::s3_http_metrics::s3_http_metrics_snapshot;
let recorder = DebuggingRecorder::new();
let _recorder = metrics::set_default_local_recorder(&recorder);
let sts_response = tower::ServiceBuilder::new()
.layer(ExternalRequestContextLayer::default())
.layer(crate::server::ReadinessGateLayer::new(Arc::new(GlobalReadiness::new())))
.service(StatusService::new(StatusCode::OK))
.call(
Request::builder()
.method(Method::POST)
.uri("/")
.header(http::header::CONTENT_TYPE, "application/x-www-form-urlencoded")
.body(Full::new(Bytes::from_static(b"Action=AssumeRole")))
.expect("STS request"),
)
.await
.expect("STS readiness response");
assert_eq!(sts_response.status(), StatusCode::SERVICE_UNAVAILABLE);
assert!(!sts_response.headers().contains_key(AMZ_REQUEST_ID));
let rejected = || {
s3_http_metrics_snapshot()
.into_iter()
@@ -2212,35 +2155,12 @@ pub(in crate::server) mod tests {
.expect("readiness response");
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
assert!(response.headers().contains_key(AMZ_REQUEST_ID));
assert_eq!(response.headers()[S3_503_SUBCAUSE_HEADER], "readiness_pending");
let _body = response.bytes().await.expect("readiness body");
tokio::time::timeout(Duration::from_secs(5), server)
.await
.expect("bounded HTTP server shutdown")
.expect("server task");
assert_eq!(rejected() - before, 1, "rejection is counted before the inner trace layer");
let series = recorder
.snapshotter()
.snapshot()
.into_vec()
.into_iter()
.find(|(key, _, _, _)| key.key().name() == "rustfs_s3_503_responses_total")
.expect("the final HTTP 503 is attributed");
assert_eq!(series.3, DebugValue::Counter(1));
for (key, value) in [
("op", "unknown"),
("code", "ServiceUnavailable"),
("subcause", "readiness_pending"),
] {
assert!(
series
.0
.key()
.labels()
.any(|label| label.key() == key && label.value() == value),
"{key}"
);
}
}
async fn public_health_layer_with_tracker(object_traffic_health: Arc<ObjectTrafficHealth>) -> PublicHealthEndpointLayer {
@@ -2891,20 +2811,45 @@ pub(in crate::server) mod tests {
let mut service =
crate::server::ReadinessGateLayer::new(Arc::clone(&readiness)).layer(public_health.layer(inner));
// Cluster quorum can recover before this node publishes S3 admission.
for method in [Method::GET, Method::HEAD] {
for path in [
MINIO_HEALTH_CLUSTER_PATH,
MINIO_HEALTH_CLUSTER_READ_PATH,
HEALTH_COMPAT_LIVE_PATH,
] {
let response = service
.call(
Request::builder()
.method(method.clone())
.uri(path)
.body(Full::<Bytes>::from(Bytes::new()))
.expect("probe request before admission publication"),
)
.await
.expect("probe response before admission publication");
assert_eq!(response.status(), StatusCode::OK, "{method} {path}");
let body = BodyExt::collect(response.into_body()).await.expect("probe body").to_bytes();
if method == Method::HEAD {
assert!(body.is_empty(), "HEAD {path}");
} else {
let payload: serde_json::Value = serde_json::from_slice(&body).expect("probe JSON");
if path == HEALTH_COMPAT_LIVE_PATH {
assert_eq!(payload["status"], "ok");
assert!(payload.get("ready").is_none());
} else {
assert_eq!(payload["ready"], true, "{path}");
}
}
}
}
for published in [false, true] {
if published {
readiness.mark_stage(rustfs_common::SystemStage::FullReady);
}
for method in [Method::GET, Method::HEAD] {
for path in [
HEALTH_READY_PATH,
MINIO_HEALTH_READY_PATH,
MINIO_HEALTH_CLUSTER_PATH,
MINIO_HEALTH_CLUSTER_READ_PATH,
HEALTH_COMPAT_LIVE_PATH,
] {
let liveness = path == HEALTH_COMPAT_LIVE_PATH;
let ready = published || !matches!(path, HEALTH_READY_PATH | MINIO_HEALTH_READY_PATH);
for path in [HEALTH_READY_PATH, MINIO_HEALTH_READY_PATH] {
let response = service
.call(
Request::builder()
@@ -2915,7 +2860,7 @@ pub(in crate::server) mod tests {
)
.await
.expect("node readiness response");
let expected = if ready {
let expected = if published {
StatusCode::OK
} else {
StatusCode::SERVICE_UNAVAILABLE
@@ -2929,16 +2874,11 @@ pub(in crate::server) mod tests {
assert!(body.is_empty(), "HEAD {path}");
} else {
let payload: serde_json::Value = serde_json::from_slice(&body).expect("readiness JSON");
if liveness {
assert_eq!(payload["status"], "ok");
assert!(payload.get("ready").is_none());
continue;
}
assert_eq!(payload["ready"], ready);
assert_eq!(payload["ready"], published);
for component in ["storage", "iam", "lock"] {
assert_eq!(payload["details"][component]["ready"], true, "{component}");
}
let reasons = if ready {
let reasons = if published {
serde_json::json!([])
} else {
serde_json::json!(["startup_finalization_pending"])
@@ -2977,8 +2917,6 @@ pub(in crate::server) mod tests {
#[tokio::test]
#[serial]
async fn public_readiness_aliases_use_the_installed_object_progress() {
use metrics_util::debugging::{DebugValue, DebuggingRecorder};
async_with_vars(
[
(rustfs_config::ENV_HEALTH_ENDPOINT_ENABLE, Some("true")),
@@ -3033,6 +2971,37 @@ pub(in crate::server) mod tests {
.is_empty()
);
let response = service
.call(
Request::builder()
.method(Method::GET)
.uri(MINIO_HEALTH_CLUSTER_READ_PATH)
.body(Full::<Bytes>::from(Bytes::new()))
.expect("cluster read request"),
)
.await
.expect("cluster read response");
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
let body = BodyExt::collect(response.into_body())
.await
.expect("cluster read body")
.to_bytes();
let payload: serde_json::Value = serde_json::from_slice(&body).expect("cluster read JSON");
assert_eq!(payload["ready"], false);
assert_eq!(payload["degradedReasons"], serde_json::json!(["object_read_stalled"]));
let response = service
.call(
Request::builder()
.method(Method::GET)
.uri(MINIO_HEALTH_CLUSTER_PATH)
.body(Full::<Bytes>::from(Bytes::new()))
.expect("cluster write request"),
)
.await
.expect("cluster write response");
assert_eq!(response.status(), StatusCode::OK);
let response = service
.call(
Request::builder()
@@ -3054,53 +3023,7 @@ pub(in crate::server) mod tests {
assert!(payload.get("degradedReasons").is_none());
assert_eq!(calls.load(Ordering::SeqCst), 0);
let recorder = DebuggingRecorder::new();
let _recorder = metrics::set_default_local_recorder(&recorder);
drop(stalled);
for (read_stall, write_stall) in [(true, false), (false, true), (false, false)] {
let read_stall = read_stall.then(|| object_traffic_health.track_read_storage().expect("read tracking"));
let write_stall = write_stall.then(|| object_traffic_health.track_write_storage().expect("write tracking"));
for (path, probe, stalled) in [
(MINIO_HEALTH_CLUSTER_READ_PATH, "read", read_stall.is_some()),
(MINIO_HEALTH_CLUSTER_PATH, "write", write_stall.is_some()),
] {
let response = service
.call(
Request::builder()
.method(Method::HEAD)
.uri(path)
.body(Full::<Bytes>::from(Bytes::new()))
.expect("cluster probe"),
)
.await
.expect("cluster health response");
let status = if stalled {
StatusCode::SERVICE_UNAVAILABLE
} else {
StatusCode::OK
};
assert_eq!(response.status(), status, "{path}");
let gauge = recorder
.snapshotter()
.snapshot()
.into_vec()
.into_iter()
.find_map(|(key, _, _, value)| {
(key.key().name() == "rustfs_cluster_health_ready"
&& key
.key()
.labels()
.any(|label| label.key() == "probe" && label.value() == probe))
.then_some(value)
});
let ready = if stalled { 0.0 } else { 1.0 };
assert!(
matches!(gauge, Some(DebugValue::Gauge(value)) if value.into_inner() == ready),
"{path} returned {status}, cluster health gauge was {gauge:?}"
);
}
}
let response = service
.call(
Request::builder()
+54 -6
View File
@@ -81,6 +81,7 @@ const LOG_COMPONENT_SERVER: &str = "server";
const LOG_SUBSYSTEM_READINESS: &str = "readiness";
const METRIC_RUNTIME_READINESS_READY: &str = "rustfs_runtime_readiness_ready";
const METRIC_RUNTIME_READINESS_DEGRADED_TOTAL: &str = "rustfs_runtime_readiness_degraded_total";
const METRIC_CLUSTER_HEALTH_READY: &str = "rustfs_cluster_health_ready";
const METRIC_CLUSTER_HEALTH_DURATION_SECONDS: &str = "rustfs_cluster_health_duration_seconds";
pub use crate::shared_types::{
@@ -166,7 +167,6 @@ type BoxBody = http_body_util::combinators::UnsyncBoxBody<Bytes, BoxError>;
/// Header exposing which startup dependency the readiness gate is waiting
/// on, so operators can diagnose a 503 without shell access (rustfs#4304).
const READINESS_PENDING_HEADER: &str = "x-rustfs-readiness-pending";
pub(super) const READINESS_503_SUBCAUSE: &str = "readiness_pending";
/// Maps the current startup stage to the dependency the gate is waiting on.
fn readiness_pending_dependency(stage: rustfs_common::SystemStage) -> &'static str {
@@ -179,6 +179,7 @@ fn readiness_pending_dependency(stage: rustfs_common::SystemStage) -> &'static s
fn service_not_ready_response(stage: rustfs_common::SystemStage) -> Response<BoxBody> {
let pending = readiness_pending_dependency(stage);
rustfs_io_metrics::s3_http_metrics::record_s3_http_503_response("ServiceUnavailable", "readiness_pending");
let body: BoxBody = Full::new(Bytes::from(format!("Service not ready: waiting for {pending}")))
.map_err(|never| match never {})
.boxed_unsync();
@@ -197,9 +198,10 @@ fn service_not_ready_response(stage: rustfs_common::SystemStage) -> Response<Box
response
.headers_mut()
.insert(READINESS_PENDING_HEADER, HeaderValue::from_static(pending));
response
.headers_mut()
.insert(super::layer::S3_503_SUBCAUSE_HEADER, HeaderValue::from_static(READINESS_503_SUBCAUSE));
response.headers_mut().insert(
http::HeaderName::from_static("x-rustfs-503-subcause"),
HeaderValue::from_static("readiness_pending"),
);
response
}
@@ -1047,6 +1049,12 @@ where
ClusterHealthProbeKind::Write => "write",
ClusterHealthProbeKind::Read => "read",
};
let ready = report.degraded_reasons.is_empty()
&& report.readiness.storage_ready
&& report.readiness.iam_ready
&& report.readiness.lock_quorum_ready
&& report.readiness.peer_health_ready;
gauge!(METRIC_CLUSTER_HEALTH_READY, "probe" => probe).set(if ready { 1.0 } else { 0.0 });
let wait_duration = collection_started.unwrap_or_else(tokio::time::Instant::now) - started_at;
histogram!(METRIC_CLUSTER_HEALTH_DURATION_SECONDS, "probe" => probe, "phase" => "wait").record(wait_duration.as_secs_f64());
if let Some(collection_started) = collection_started {
@@ -2165,6 +2173,17 @@ mod tests {
.then_some(value)
});
assert!(matches!(timeout_count, Some(DebugValue::Counter(1))));
for (probe, expected) in [("write", 0.0), ("read", 1.0)] {
let ready = entries.iter().find_map(|(key, _, _, value)| {
(key.key().name() == METRIC_CLUSTER_HEALTH_READY
&& key
.key()
.labels()
.any(|label| label.key() == "probe" && label.value() == probe))
.then_some(value)
});
assert!(matches!(ready, Some(DebugValue::Gauge(value)) if value.into_inner() == expected));
}
reset_cluster_health_report_caches().await;
}
@@ -2525,10 +2544,12 @@ mod tests {
#[tokio::test]
async fn service_not_ready_response_preserves_observable_contract() {
let response = service_not_ready_response(rustfs_common::SystemStage::Booting);
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
let response =
metrics::with_local_recorder(&recorder, || service_not_ready_response(rustfs_common::SystemStage::Booting));
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(response.headers()[super::super::layer::S3_503_SUBCAUSE_HEADER], READINESS_503_SUBCAUSE);
assert_eq!(
response
.headers()
@@ -2557,6 +2578,33 @@ mod tests {
.and_then(|value| value.to_str().ok()),
Some("storage_quorum")
);
assert_eq!(
response
.headers()
.get("x-rustfs-503-subcause")
.and_then(|value| value.to_str().ok()),
Some("readiness_pending")
);
let counted = snapshotter
.snapshot()
.into_vec()
.into_iter()
.find_map(|(composite, _, _, value)| {
(composite.key().name() == "rustfs_s3_503_responses_total"
&& composite
.key()
.labels()
.any(|label| label.key() == "code" && label.value() == "ServiceUnavailable")
&& composite
.key()
.labels()
.any(|label| label.key() == "subcause" && label.value() == "readiness_pending"))
.then_some(value)
});
assert!(
matches!(counted, Some(DebugValue::Counter(1))),
"service_not_ready_response must increment rustfs_s3_503_responses_total once"
);
let body = match response.into_body().collect().await {
Ok(body) => body.to_bytes(),
Err(err) => panic!("not-ready body should collect: {err}"),
+117 -136
View File
@@ -314,6 +314,55 @@ macro_rules! log_internode_rpc_response_failure {
}};
}
macro_rules! log_internode_put_file_stage_failure {
($stage:expr, $query:expr, $err:expr) => {{
let err_ref: &(dyn std::error::Error + 'static) = $err;
let status = classify_put_file_stage_status($stage, err_ref);
if status == StatusCode::BAD_REQUEST {
tracing::debug!(
event = EVENT_RPC_REQUEST_FAILED,
component = LOG_COMPONENT_INTERNODE_RPC,
subsystem = LOG_SUBSYSTEM_FILE_TRANSFER,
operation = INTERNODE_OPERATION_PUT_FILE_STREAM,
result = "aborted_by_sender",
status_code = status.as_u16(),
rpc_path = PUT_FILE_STREAM_PATH,
method = %Method::PUT,
reason = "put_file_body_aborted",
stage = $stage,
disk = %$query.disk,
volume = %$query.volume,
path = %$query.path,
append = $query.append,
size = $query.size,
error = %err_ref,
"internode put_file stream aborted by sender"
);
} else {
error!(
event = EVENT_RPC_REQUEST_FAILED,
component = LOG_COMPONENT_INTERNODE_RPC,
subsystem = LOG_SUBSYSTEM_FILE_TRANSFER,
operation = INTERNODE_OPERATION_PUT_FILE_STREAM,
result = "failed",
status_code = status.as_u16(),
rpc_path = PUT_FILE_STREAM_PATH,
method = %Method::PUT,
reason = "put_file_stage_failed",
stage = $stage,
disk = %$query.disk,
volume = %$query.volume,
path = %$query.path,
append = $query.append,
size = $query.size,
error = %err_ref,
"internode rpc request failed"
);
}
status
}};
}
/// Answers the internode rpc paths itself and hands every other request to
/// `inner`. Its own responses are built as [`Body`] and converted into the
/// wrapped service's response body type, so both leave as one type.
@@ -2056,7 +2105,13 @@ where
#[cfg(feature = "internode-transport")]
let size_mismatch = size_mismatch || append_size.is_some_and(|size| size != copied);
if size_mismatch {
return Err(("verify_size", Box::new(incomplete_put_file_body(query.size, copied)) as BoxError));
return Err((
"verify_size",
Box::new(io::Error::new(
io::ErrorKind::UnexpectedEof,
format!("body size mismatch: expected {} bytes, received {copied}", query.size),
)) as BoxError,
));
}
file.shutdown().await.map_err(|err| ("shutdown", Box::new(err) as BoxError))?;
drop(file);
@@ -2080,13 +2135,7 @@ where
cleanup.downcast_ref::<DiskError>(),
Some(DiskError::FileNotFound | DiskError::VolumeNotFound)
) {
log_put_file_failure(
StatusCode::INTERNAL_SERVER_ERROR,
PUT_FILE_AUTH_STREAM_PATH,
"cleanup_staging",
query,
cleanup.as_ref(),
);
let _ = log_internode_put_file_stage_failure!("cleanup_staging", query, cleanup.as_ref());
}
return Err((stage, primary));
}
@@ -2198,7 +2247,9 @@ async fn handle_put_file(req: Request<Incoming>, require_auth: bool) -> Response
let copied = match write_authenticated_put_file(&disk, req.into_body().into_data_stream(), &query, nonce, &url).await {
Ok(copied) => copied,
Err((stage, e)) => {
return put_file_failure_response(&path, stage, &query, e.as_ref());
let message = put_file_stage_error_message(stage, &query, e.as_ref());
let status = log_internode_put_file_stage_failure!(stage, query, e.as_ref());
return response_with_status(status, message);
}
};
record_put_file_metrics(copied);
@@ -2212,14 +2263,18 @@ async fn handle_put_file(req: Request<Incoming>, require_auth: bool) -> Response
match disk.append_file(&query.volume, &query.path).await {
Ok(file) => file,
Err(e) => {
return put_file_failure_response(&path, "append", &query, &e);
let message = put_file_stage_error_message("append", &query, &e);
let status = log_internode_put_file_stage_failure!("append", query, &e);
return response_with_status(status, message);
}
}
} else {
match disk.create_file("", &query.volume, &query.path, query.size).await {
Ok(file) => file,
Err(e) => {
return put_file_failure_response(&path, "create", &query, &e);
let message = put_file_stage_error_message("create", &query, &e);
let status = log_internode_put_file_stage_failure!("create", query, &e);
return response_with_status(status, message);
}
}
};
@@ -2229,19 +2284,28 @@ async fn handle_put_file(req: Request<Incoming>, require_auth: bool) -> Response
{
Ok(copied) => copied,
Err(e) => {
return put_file_failure_response(&path, "write_body", &query, &e);
let message = put_file_stage_error_message("write_body", &query, &e);
let status = log_internode_put_file_stage_failure!("write_body", query, &e);
return response_with_status(status, message);
}
};
record_put_file_metrics(copied);
if put_body_size_mismatch(&query, copied) {
let err = incomplete_put_file_body(query.size, copied);
return put_file_failure_response(&path, "verify_size", &query, &err);
let err = std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
format!("body size mismatch: expected {} bytes, received {copied}", query.size),
);
let message = put_file_stage_error_message("verify_size", &query, &err);
let status = log_internode_put_file_stage_failure!("verify_size", query, &err);
return response_with_status(status, message);
}
if let Err(e) = file.flush().await {
return put_file_failure_response(&path, "flush", &query, &e);
let message = put_file_stage_error_message("flush", &query, &e);
let status = log_internode_put_file_stage_failure!("flush", query, &e);
return response_with_status(status, message);
}
empty_ok()
@@ -2260,24 +2324,6 @@ fn record_put_file_metrics(copied: u64) {
);
}
#[derive(thiserror::Error, Debug)]
enum PutFileBodyError {
#[error("{0}")]
Receive(#[source] BoxError),
#[error("body size mismatch: expected {expected} bytes, received {received}")]
Short { expected: i64, received: u64 },
#[error("put_file auth trailer is incomplete")]
IncompleteAuthTrailer,
}
fn incomplete_put_file_body(expected: i64, received: u64) -> io::Error {
io::Error::new(io::ErrorKind::UnexpectedEof, PutFileBodyError::Short { expected, received })
}
fn put_file_body_receive_error(error: impl Into<BoxError>) -> io::Error {
io::Error::other(PutFileBodyError::Receive(error.into()))
}
async fn write_body_chunks_to_writer<S, E, W>(body: S, writer: &mut W) -> io::Result<u64>
where
S: futures::TryStream<Ok = Bytes, Error = E> + Unpin,
@@ -2288,7 +2334,7 @@ where
let mut copied = 0_u64;
let mut pending = BytesMut::with_capacity(DEFAULT_READ_BUFFER_SIZE);
while let Some(bytes) = body.try_next().await.map_err(put_file_body_receive_error)? {
while let Some(bytes) = body.try_next().await.map_err(io::Error::other)? {
copied = copied.saturating_add(u64::try_from(bytes.len()).unwrap_or(u64::MAX));
pending.extend_from_slice(&bytes);
@@ -2333,7 +2379,7 @@ where
let mut trailer = Vec::with_capacity(PUT_FILE_AUTH_TRAILER_LEN);
let mut hasher = Sha256::new();
while let Some(bytes) = body.try_next().await.map_err(put_file_body_receive_error)? {
while let Some(bytes) = body.try_next().await.map_err(io::Error::other)? {
if let Some(remaining) = remaining.as_mut() {
let chunk_len = u64::try_from(bytes.len()).unwrap_or(u64::MAX);
let data_len = usize::try_from((*remaining).min(chunk_len))
@@ -2394,10 +2440,13 @@ where
}
if remaining.is_some_and(|remaining| remaining != 0) {
return Err(incomplete_put_file_body(query.size, copied));
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
format!("body size mismatch: expected {} bytes, received {copied}", query.size),
));
}
if trailer.len() != PUT_FILE_AUTH_TRAILER_LEN {
return Err(io::Error::new(io::ErrorKind::UnexpectedEof, PutFileBodyError::IncompleteAuthTrailer));
return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "put_file auth trailer is incomplete"));
}
let expected = verify_put_file_auth_trailer(url, &Method::PUT, nonce, &trailer)?;
@@ -2481,14 +2530,12 @@ fn put_body_size_mismatch(query: &PutFileQuery, copied: u64) -> bool {
!query.append && query.size > 0 && copied != u64::try_from(query.size).unwrap_or(u64::MAX)
}
fn classify_put_file_stage_status(err: &(dyn std::error::Error + 'static)) -> StatusCode {
crate::error::error_chain_find(err, |cause| {
if cause.is::<PutFileBodyError>() {
return Some(StatusCode::BAD_REQUEST);
}
if matches!(
cause.downcast_ref::<DiskError>(),
Some(
fn classify_put_file_stage_status(stage: &str, err: &(dyn std::error::Error + 'static)) -> StatusCode {
let mut current: Option<&(dyn std::error::Error + 'static)> = Some(err);
while let Some(cause) = current {
if let Some(disk_err) = cause.downcast_ref::<DiskError>()
&& matches!(
disk_err,
DiskError::Timeout
| DiskError::FaultyDisk
| DiskError::FaultyRemoteDisk
@@ -2497,74 +2544,33 @@ fn classify_put_file_stage_status(err: &(dyn std::error::Error + 'static)) -> St
| DiskError::TooManyOpenFiles
| DiskError::DiskOngoingReq
)
) {
return Some(StatusCode::SERVICE_UNAVAILABLE);
{
return StatusCode::SERVICE_UNAVAILABLE;
}
cause
.downcast_ref::<io::Error>()
.is_some_and(|err| matches!(err.kind(), io::ErrorKind::TimedOut | io::ErrorKind::StorageFull))
.then_some(StatusCode::SERVICE_UNAVAILABLE)
})
.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)
}
fn log_put_file_failure(
status: StatusCode,
path: &str,
stage: &str,
query: &PutFileQuery,
err: &(dyn std::error::Error + 'static),
) {
macro_rules! log_failure {
($level:expr, $result:literal, $reason:literal, $message:literal) => {
tracing::event!(
$level,
event = EVENT_RPC_REQUEST_FAILED,
component = LOG_COMPONENT_INTERNODE_RPC,
subsystem = LOG_SUBSYSTEM_FILE_TRANSFER,
operation = INTERNODE_OPERATION_PUT_FILE_STREAM,
result = $result,
status_code = status.as_u16(),
rpc_path = path,
method = %Method::PUT,
reason = $reason,
stage,
disk = %query.disk,
volume = %query.volume,
path = %query.path,
append = query.append,
size = query.size,
error = %err,
$message
)
};
if matches!(stage, "write_body" | "verify_size") {
if let Some(io_err) = cause.downcast_ref::<io::Error>()
&& matches!(
io_err.kind(),
io::ErrorKind::UnexpectedEof
| io::ErrorKind::ConnectionReset
| io::ErrorKind::BrokenPipe
| io::ErrorKind::ConnectionAborted
)
{
return StatusCode::BAD_REQUEST;
}
if let Some(hyper_err) = cause.downcast_ref::<hyper::Error>()
&& (hyper_err.is_body_write_aborted()
|| hyper_err.is_incomplete_message()
|| hyper_err.is_closed()
|| hyper_err.is_canceled())
{
return StatusCode::BAD_REQUEST;
}
}
current = cause.source();
}
match status {
StatusCode::BAD_REQUEST => log_failure!(
tracing::Level::DEBUG,
"aborted_by_sender",
"put_file_body_aborted",
"internode put_file stream aborted by sender"
),
StatusCode::SERVICE_UNAVAILABLE => log_failure!(
tracing::Level::WARN,
"unavailable",
"put_file_stage_failed",
"internode storage unavailable"
),
_ => log_failure!(tracing::Level::ERROR, "failed", "put_file_stage_failed", "internode rpc request failed"),
}
}
fn put_file_failure_response(
path: &str,
stage: &str,
query: &PutFileQuery,
err: &(dyn std::error::Error + 'static),
) -> Response<Body> {
let status = classify_put_file_stage_status(err);
log_put_file_failure(status, path, stage, query, err);
response_with_status(status, put_file_stage_error_message(stage, query, err))
StatusCode::INTERNAL_SERVER_ERROR
}
fn put_file_stage_error_message(stage: &str, query: &PutFileQuery, err: &dyn std::fmt::Display) -> String {
@@ -3095,31 +3101,6 @@ mod tests {
assert!(labels.get("server").is_some_and(|value| !value.is_empty()));
}
#[tokio::test]
async fn put_file_failure_http_status_distinguishes_peer_body_and_disk_errors() {
let query = PutFileQuery::default();
let input = futures_util::stream::iter([Err::<Bytes, _>(io::Error::from(io::ErrorKind::BrokenPipe))]);
let peer_error = write_put_file_body_chunks_to_writer(input, &mut tokio::io::sink(), &query, None, "")
.await
.expect_err("peer ended the request body");
let response = super::put_file_failure_response(PUT_FILE_STREAM_PATH, "write_body", &query, &peer_error);
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
let input = futures_util::stream::iter([Ok::<_, io::Error>(Bytes::from_static(b"shard"))]);
let (mut writer, closed_disk) = tokio::io::duplex(8);
drop(closed_disk);
let disk_error = write_put_file_body_chunks_to_writer(input, &mut writer, &query, None, "")
.await
.expect_err("the disk writer failed");
assert_eq!(disk_error.kind(), io::ErrorKind::BrokenPipe);
let response = super::put_file_failure_response(PUT_FILE_STREAM_PATH, "write_body", &query, &disk_error);
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
let unavailable_disk = io::Error::other(DiskError::DiskOngoingReq);
let response = super::put_file_failure_response(PUT_FILE_AUTH_STREAM_PATH, "write_body", &query, &unavailable_disk);
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
}
#[test]
fn put_file_stage_error_message_includes_stage_and_request_context() {
let query = PutFileQuery {