Compare commits

...

12 Commits

Author SHA1 Message Date
Hauser Zhi 04f94189f5 test(server): cover health gauge and gateway 503 attribution
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Signed-off-by: Hauser Zhi <housemecn@gmail.com>
2026-12-03 10:56:11 +08:00
Hauser Zhi 803e4d26bd Merge branch 'main' into houseme/fix-3402-saturation-followup 2026-12-03 10:44:28 +08:00
Hauser Zhi 175a90efd6 Merge remote main into the S3 saturation follow-up
Preserve write-vote tracking in the direct grant path. Align batch read policy and JSON encoder checks with the borrowed-request implementation.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Signed-off-by: Hauser Zhi <housemecn@gmail.com>
2026-12-03 09:13:43 +08:00
Hauser Zhi bb7e5c0bd1 Merge remote main into the S3 saturation follow-up
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-02 23:41:13 +08:00
Hauser Zhi 7dce7b84a0 fix(ecstore): preserve drive health on metadata batch fallback
Keep Unimplemented as a typed RPC failure through drive health accounting. Resolve fallback after the batch attempt and its permit end. Borrow the original request and encode only after bulk admission.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Signed-off-by: Hauser Zhi <housemecn@gmail.com>
2026-12-02 23:31:17 +08:00
Hauser Zhi 0a1431d651 fix(ecstore): count negative gRPC reads as peer progress
Record peer liveness from a complete error reply independently of drive recovery. Apply the shared reply path to unary metadata reads and recovery probes. Refresh existing timeout keys in place.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Signed-off-by: Hauser Zhi <housemecn@gmail.com>
2026-12-02 23:05:46 +08:00
Hauser Zhi bccaacff27 fix(ecstore): require drive RPC evidence for remote recovery
Keep TCP probe cadence and peer reachability separate from disk I/O progress. Use the existing single-flight recovery monitor for degraded disks and discard a connectivity failure overtaken by successful drive I/O.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Signed-off-by: Hauser Zhi <housemecn@gmail.com>
2026-12-02 22:36:56 +08:00
Hauser Zhi db4baa3b76 Merge remote main into the S3 saturation follow-up
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-02 22:19:44 +08:00
Hauser Zhi 275f5a20e3 perf(lock): transfer quorum grants directly to guards
Return granted leases directly and keep only diagnostic data on failure. Centralize rollback and pending-reply ownership in the quorum round and carry one absolute deadline across retries and peer dispatch.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Signed-off-by: Hauser Zhi <housemecn@gmail.com>
2026-12-02 22:05:50 +08:00
Hauser Zhi 77443d53fa perf(lock): give exclusive retries a bounded anchor wait
Let a responsive anchor settle contention before asking other voters. Try parallel quorum after an anchor-only refusal and dispatch the remaining quorum together if the anchor stays silent. Clip each voter wait at dispatch and allocate retry state on contention. Retain merged transport, admission, and breaker timing defaults.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Signed-off-by: Hauser Zhi <housemecn@gmail.com>
2026-12-02 21:53:36 +08:00
Hauser Zhi 7adffeff02 Merge remote main into the S3 saturation follow-up
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-12-02 21:38:03 +08:00
Hauser Zhi 75ea68f11b fix(s3): unify saturation handling and response attribution
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Signed-off-by: Hauser Zhi <housemecn@gmail.com>
2026-12-02 21:01:13 +08:00
18 changed files with 1830 additions and 1971 deletions
File diff suppressed because it is too large Load Diff
+79 -105
View File
@@ -163,7 +163,7 @@ struct LockPeerChannelHealth {
request_backoff_until: Option<Instant>,
request_backoff: Duration,
request_probe_generation: Option<u64>,
next_probe_generation: u64,
request_generation: u64,
request_in_flight: usize,
late_release_in_flight: usize,
/// Timed-out RPCs still running in the background for this peer.
@@ -177,13 +177,23 @@ struct TimeoutLogHealth {
}
#[derive(Debug, Clone, Copy)]
struct LockRequestAdmission {
probe_generation: Option<u64>,
enum LockRequestAdmission {
Normal(u64),
Probe(u64),
}
impl LockRequestAdmission {
fn is_probe(self) -> bool {
self.probe_generation.is_some()
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),
}
}
}
@@ -594,16 +604,11 @@ 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) {
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;
}
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;
}
});
// A successful lock RPC over a cached or fresh channel proves the peer is
@@ -634,7 +639,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 { probe_generation: None });
return Some(LockRequestAdmission::Normal(0));
}
let now = Instant::now();
@@ -645,21 +650,16 @@ impl RemoteClient {
}
let Some(until) = health.request_backoff_until else {
health.request_in_flight += 1;
return (Some(LockRequestAdmission { probe_generation: None }), "none");
return (Some(LockRequestAdmission::Normal(health.request_generation)), "none");
};
if now < until || health.request_probe_generation.is_some() {
return (None, "breaker_open");
}
health.next_probe_generation = health.next_probe_generation.saturating_add(1);
let generation = health.next_probe_generation;
health.request_generation = health.request_generation.wrapping_add(1);
let generation = health.request_generation;
health.request_probe_generation = Some(generation);
health.request_in_flight += 1;
(
Some(LockRequestAdmission {
probe_generation: Some(generation),
}),
"none",
)
(Some(LockRequestAdmission::Probe(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.request_probe_generation == admission.probe_generation) {
if admission.is_some_and(|admission| health.owns_probe(admission)) {
health.request_probe_generation = None;
}
});
@@ -690,30 +690,24 @@ 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 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;
}
// 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;
}
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() {
initial
(deadline / 4).clamp(Duration::from_millis(1), Duration::from_millis(500))
} else {
health.request_backoff.saturating_mul(2)
};
@@ -869,7 +863,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.request_probe_generation == admission.probe_generation) {
if admission.is_some_and(|admission| health.owns_probe(admission)) {
health.request_probe_generation = None;
}
}
@@ -2215,54 +2209,72 @@ mod tests {
);
}
#[test]
fn request_breaker_opens_after_three_timeouts_and_allows_one_probe() {
#[tokio::test(start_paused = true)]
async 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 {
client.record_request_timeout("lock", Duration::from_millis(100), None);
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);
}
assert!(
client.admit_lock_request("lock").is_none(),
"open breaker must reject requests during backoff"
);
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;
});
tokio::time::advance(lock_peer_health_for_test(addr).request_backoff).await;
let probe = client
.admit_lock_request("lock")
.expect("half-open breaker must admit one probe");
assert!(probe.is_probe());
assert!(matches!(probe, LockRequestAdmission::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);
}
#[test]
fn old_request_completion_cannot_clear_a_new_probe() {
#[tokio::test(start_paused = true)]
async fn only_active_probe_timeouts_extend_the_request_breaker() {
let addr = "http://breaker-token-test";
let client = RemoteClient::new(addr.to_string());
reset_lock_peer_health_for_test(addr);
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;
});
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);
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.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.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(probe));
assert!(lock_peer_health_for_test(addr).request_probe_generation.is_none());
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");
reset_lock_peer_health_for_test(addr);
}
@@ -2284,54 +2296,16 @@ mod tests {
health.request_consecutive_timeouts = 0;
});
let second = client.admit_lock_request("lock").expect("second probe should be admitted");
assert_ne!(first.probe_generation, second.probe_generation);
assert!(!lock_peer_health_for_test(addr).owns_probe(first));
client.record_rpc_success("lock", Some(first));
client.release_lock_request("lock", Some(first));
assert_eq!(lock_peer_health_for_test(addr).request_probe_generation, second.probe_generation);
assert!(lock_peer_health_for_test(addr).owns_probe(second));
assert!(lock_peer_health_for_test(addr).request_backoff_until.is_some());
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));
+17 -13
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
pub completed_ops: AtomicU64,
completed_ops: AtomicU64,
/// Atomic timestamp of last operation start
pub last_started: AtomicI64,
/// Atomic disk status (OK or Faulty)
@@ -1264,11 +1264,15 @@ 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::AcqRel);
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())
}
pub fn completed_ops(&self) -> u64 {
self.completed_ops.load(Ordering::Acquire)
self.completed_ops.load(Ordering::Relaxed)
}
pub fn record_capacity_probe(&self, total: u64, used: u64, free: u64) {
@@ -1373,7 +1377,14 @@ 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 {
@@ -1403,7 +1414,7 @@ impl DiskHealthTracker {
let became_offline = next == RuntimeDriveHealthState::Offline && current != RuntimeDriveHealthState::Offline;
self.transition_state(endpoint, current, next, reason);
became_offline
Some(became_offline)
}
/// Record a foreground timeout failure only when no sibling operation on this drive
@@ -1416,10 +1427,7 @@ impl DiskHealthTracker {
reason: &'static str,
completed_before: u64,
) -> Option<bool> {
if self.completed_ops() > completed_before {
return None;
}
Some(self.mark_failure(endpoint, reason))
self.record_failure(endpoint, reason, Some(completed_before))
}
#[allow(dead_code, reason = "asserted by this file's tests (backlog#1823)")]
@@ -1454,7 +1462,6 @@ 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);
@@ -2119,10 +2126,7 @@ impl LocalDiskWrapper {
continue;
}
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 {
if health.time_since_success() < SKIP_IF_SUCCESS_BEFORE {
continue;
}
@@ -35,6 +35,7 @@ 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,
@@ -1025,13 +1026,6 @@ 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;
@@ -1082,6 +1076,14 @@ 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()
@@ -1162,7 +1164,7 @@ impl SetDisks {
for slot in &mut slots {
if slot.result.is_none() {
if let Some(Some(disk)) = disks.get(slot.disk_index)
&& let crate::disk::Disk::Remote(remote) = disk.as_ref()
&& let Disk::Remote(remote) = disk.as_ref()
{
remote.record_straggler_timeout_if_stalled(fanout_host_progress[slot.disk_index]);
}
@@ -1242,7 +1244,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 task_ids = vec![None; disks.len()];
let mut tasks = 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);
@@ -1277,17 +1279,14 @@ 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)>,
task_ids: &mut [Option<tokio::task::Id>],
tasks: &mut [Option<(tokio::task::Id, u64)>],
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();
@@ -1334,7 +1333,7 @@ impl SetDisks {
#[cfg(not(feature = "diagnostic-read-version-caller"))]
read.await
}));
task_ids[index] = Some(task.id());
tasks[index] = Some((task.id(), host_completed_before));
};
if bounded_fanout {
@@ -1342,14 +1341,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 task_ids, disk_index, disk);
spawn_read_version(&mut join_set, &mut tasks, 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 task_ids, index, disk);
spawn_read_version(&mut join_set, &mut tasks, index, disk);
scheduled_count = scheduled_count.saturating_add(1);
}
}
@@ -1408,7 +1407,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 task_ids, disk_index, disk);
spawn_read_version(&mut join_set, &mut tasks, disk_index, disk);
scheduled_count = scheduled_count.saturating_add(1);
break;
}
@@ -1427,7 +1426,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 task_ids, disk_index, disk);
spawn_read_version(&mut join_set, &mut tasks, disk_index, disk);
scheduled_count = scheduled_count.saturating_add(1);
}
}
@@ -1447,10 +1446,11 @@ 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(Some(disk)) = disks.get(slot.disk_index)
&& let crate::disk::Disk::Remote(remote) = disk.as_ref()
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()
{
remote.record_straggler_timeout_if_stalled(fanout_host_progress[slot.disk_index]);
remote.record_straggler_timeout_if_stalled(host_completed_before);
}
observations.push(MetadataFanoutObservation::from_error(&DiskError::Timeout, elapsed));
slot.result = Some(Err(DiskError::Timeout));
@@ -1524,7 +1524,10 @@ impl SetDisks {
&err,
fanout_start.map_or(Duration::ZERO, |s| s.elapsed()),
));
if let Some(index) = task_ids.iter().position(|id| *id == Some(join_error.id())) {
if let Some(index) = tasks
.iter()
.position(|task| task.is_some_and(|(id, _)| id == join_error.id()))
{
slots[index].result = Some(Err(err));
accumulator.observe(&slots[index]);
}
@@ -1659,7 +1662,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 task_ids, disk_index, disk);
spawn_read_version(&mut join_set, &mut tasks, disk_index, disk);
scheduled_count = scheduled_count.saturating_add(1);
}
next_fanout_index = next_fanout_index.saturating_add(1);
@@ -1667,7 +1670,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 task_ids, disk_index, disk);
spawn_read_version(&mut join_set, &mut tasks, disk_index, disk);
scheduled_count = scheduled_count.saturating_add(1);
}
next_fanout_index = next_fanout_index.saturating_add(1);
@@ -1679,7 +1682,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 task_ids, disk_index, disk);
spawn_read_version(&mut join_set, &mut tasks, disk_index, disk);
scheduled_count = scheduled_count.saturating_add(1);
}
next_fanout_index = next_fanout_index.saturating_add(1);
+30 -12
View File
@@ -132,6 +132,7 @@ tokio::task_local! {
struct RequestScopeState {
operation: usize,
entry_started: Option<Instant>,
subcause_503: Option<&'static str>,
}
impl RequestScopeState {
@@ -140,6 +141,7 @@ impl RequestScopeState {
Self {
operation,
entry_started: None,
subcause_503: None,
}
}
}
@@ -241,18 +243,14 @@ pub fn record_s3_http_lock_failure(resource_class: &'static str, mode: &'static
});
}
/// 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);
/// 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);
});
}
/// An external request is counted exactly once: at response headers, at a
@@ -264,6 +262,7 @@ pub struct S3HttpRequestGuard {
completion: Option<(S3HttpCompletionObserver, Instant)>,
finished: bool,
entry_started: Option<Instant>,
subcause_503: Option<&'static str>,
}
impl S3HttpRequestGuard {
@@ -286,6 +285,7 @@ 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,11 +307,13 @@ 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);
@@ -327,6 +329,22 @@ 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(batch_rpc_req.as_ref(), &policy)?;",
json_encoder: "let batch_read_version_req = compat_json(&req, &policy)?;",
policy: RequestJsonPolicy::MsgpackOnlyEligible,
},
RequestCompatSendSite {
+144 -163
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};
use std::task::{Context, Poll, ready};
use std::time::{Duration, Instant};
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tokio::sync::mpsc;
@@ -829,7 +829,8 @@ 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. Anything else is `Unknown`.
/// 5. A close before response headers maps to `ConnectionReset`.
/// 6. Anything else is `Unknown`.
fn classify_transport_error(
err: &(dyn std::error::Error + 'static),
is_timeout: bool,
@@ -840,7 +841,7 @@ fn classify_transport_error(
return InternodeHttpErrorKind::ConnectTimeout;
}
if let Some(kind) = find_transport_error_kind_in_chain(err) {
if let Some(kind) = find_transport_error_kind_in_chain(err, !is_connect && !is_body) {
return kind;
}
@@ -855,17 +856,18 @@ 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)) -> Option<InternodeHttpErrorKind> {
let mut source: Option<&(dyn std::error::Error + 'static)> = Some(err);
while let Some(current) = source {
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 };
if let Some(io_err) = current.downcast_ref::<io::Error>() {
match io_err.kind() {
io::ErrorKind::ConnectionRefused | io::ErrorKind::AddrNotAvailable => {
@@ -878,6 +880,7 @@ fn find_transport_error_kind_in_chain(err: &(dyn std::error::Error + 'static)) -
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);
}
@@ -891,30 +894,15 @@ fn find_transport_error_kind_in_chain(err: &(dyn std::error::Error + 'static)) -
if hyper_err.is_incomplete_message() {
return Some(InternodeHttpErrorKind::ConnectionReset);
}
request_closed |= before_headers && (hyper_err.is_closed() || hyper_err.is_canceled());
}
source = current.source();
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());
}
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
request_closed.then_some(InternodeHttpErrorKind::ConnectionReset)
}
/// The SOLE remaining string heuristic, gated behind `is_connect`: reqwest and
@@ -979,9 +967,14 @@ fn classify_http_response(
ClassifiedHttpResponse { kind, remote_disk_error }
}
fn internode_reqwest_error(method: &Method, url: &str, operation: Option<&'static str>, err: reqwest::Error) -> io::Error {
fn internode_reqwest_error(
method: &Method,
url: &str,
operation: Option<&'static str>,
classified: InternodeHttpErrorKind,
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()
}
@@ -1210,8 +1203,9 @@ 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);
record_internode_classified_error(track_internode_metrics, internode_operation, classify_reqwest_error(&e));
internode_reqwest_error(method, url, internode_operation, e)
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_http_version(track_internode_metrics, internode_operation, http_version_metric_label(resp.version()));
@@ -1538,10 +1532,9 @@ 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: tokio::task::JoinHandle<std::io::Result<()>>,
handle: Option<tokio::task::JoinHandle<io::Result<()>>>,
pending_chunk: BytesMut,
pending_reservation: Option<Arc<HttpWriterMemoryReservation>>,
memory_reserver: Option<HttpWriterMemoryReserver>,
@@ -1590,7 +1583,6 @@ 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 {
@@ -1613,13 +1605,12 @@ 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.clone())
.headers(headers_clone.clone())
.request(method_clone.clone(), url_clone.as_str())
.headers(headers_clone)
.body(body);
// Hold the request until the shutdown signal is received
@@ -1644,9 +1635,7 @@ impl HttpWriter {
classify_http_status(resp.status()),
);
let status = resp.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);
return Err(internode_status_error(&method_clone, &url_clone, internode_operation, status));
}
}
Err(e) => {
@@ -1654,9 +1643,7 @@ 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);
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);
return Err(internode_reqwest_error(&method_clone, &url_clone, internode_operation, classified, e));
}
}
@@ -1669,10 +1656,9 @@ impl HttpWriter {
url,
method,
headers,
err_rx,
start_tx: Some(start_tx),
sender: PollSender::new(sender),
handle,
handle: Some(handle),
pending_chunk,
pending_reservation,
memory_reserver,
@@ -1861,14 +1847,6 @@ 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 {
@@ -1920,11 +1898,20 @@ impl HttpWriter {
}
}
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_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 poll_send_pending_chunk(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
@@ -1935,12 +1922,12 @@ impl HttpWriter {
match self.sender.poll_reserve(cx) {
Poll::Ready(Ok(())) => {
let chunk = self.take_pending_chunk()?;
self.sender
.send_item(Some(chunk))
.map_err(|e| send_error_to_io(e, "HttpWriter send error"))?;
if self.sender.send_item(Some(chunk)).is_err() {
return self.poll_upload_after_body_closed(cx);
}
Poll::Ready(Ok(()))
}
Poll::Ready(Err(e)) => Poll::Ready(Err(poll_send_error_to_io(e, "HttpWriter send error"))),
Poll::Ready(Err(_)) => self.poll_upload_after_body_closed(cx),
Poll::Pending => Poll::Pending,
}
}
@@ -1955,9 +1942,6 @@ 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) {
@@ -1981,13 +1965,13 @@ impl AsyncWrite for HttpWriter {
} else {
(Bytes::copy_from_slice(&buf[..HTTP_WRITER_BUFFER_SIZE]), HTTP_WRITER_BUFFER_SIZE)
};
this.sender
.send_item(Some(chunk))
.map_err(|e| send_error_to_io(e, "HttpWriter send error"))?;
if this.sender.send_item(Some(chunk)).is_err() {
return this.poll_upload_after_body_closed(cx);
}
this.start_request();
return Poll::Ready(Ok(written));
}
Poll::Ready(Err(err)) => return Poll::Ready(Err(poll_send_error_to_io(err, "HttpWriter send error"))),
Poll::Ready(Err(_)) => return this.poll_upload_after_body_closed(cx),
Poll::Pending => return Poll::Pending,
}
}
@@ -2007,9 +1991,6 @@ 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)
}
@@ -2019,9 +2000,6 @@ 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) {
@@ -2058,47 +2036,24 @@ impl AsyncWrite for HttpWriter {
true
}
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();
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,
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)
}
}
impl HttpWriter {
fn poll_finish_upload(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
ready!(self.poll_send_pending_chunk(cx))?;
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,
if ready!(self.sender.poll_reserve(cx)).is_err() || self.sender.send_item(None).is_err() {
return self.poll_upload_after_body_closed(cx);
}
// 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.
@@ -2106,32 +2061,7 @@ impl AsyncWrite for HttpWriter {
self.pending_reservation = None;
}
}
// 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(()))
self.poll_upload_response(cx)
}
}
@@ -2145,7 +2075,9 @@ 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) {
self.handle.abort();
if let Some(handle) = &self.handle {
handle.abort();
}
}
}
@@ -2239,6 +2171,51 @@ 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};
@@ -2262,13 +2239,13 @@ mod tests {
.await
.expect("internode writer should be created");
let payload = vec![b'x'; 4 * 1024 * 1024];
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 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 source = error
.get_ref()
.and_then(|source| source.downcast_ref::<InternodeHttpError>())
@@ -3230,15 +3207,13 @@ 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: tokio::spawn(std::future::pending()),
handle: Some(tokio::spawn(std::future::pending())),
pending_chunk: BytesMut::with_capacity(HTTP_WRITER_BUFFER_SIZE),
pending_reservation,
memory_reserver,
@@ -3456,12 +3431,15 @@ 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.abort();
writer.handle = tokio::spawn(async move {
std::future::pending::<()>().await;
drop(receiver);
Ok(())
});
writer
.handle
.replace(tokio::spawn(async move {
std::future::pending::<()>().await;
drop(receiver);
Ok(())
}))
.expect("paused task")
.abort();
writer.write_all(b"queued").await.expect("pending bytes");
writer.flush().await.expect("queued allocation");
writer
@@ -3695,8 +3673,11 @@ 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.abort();
writer.handle = tokio::spawn(async { Ok(()) });
writer
.handle
.replace(tokio::spawn(async { Ok(()) }))
.expect("paused task")
.abort();
writer.write_all(b"body").await.expect("buffer the final body bytes");
writer
.shutdown()
@@ -3934,7 +3915,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.abort_handle();
let task = writer.handle.as_ref().expect("upload task should be active").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.
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.
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.
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.
+38 -45
View File
@@ -15,6 +15,7 @@
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;
@@ -516,6 +517,7 @@ 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()));
@@ -532,11 +534,16 @@ 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>();
incomplete_body |= error.is::<rustfs_rio::IncompleteBody>() || is_hyper_body_eof(error);
// 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));
None
});
digest.or({
@@ -561,7 +568,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.
fn error_chain_find<T>(
pub(crate) fn error_chain_find<T>(
err: &(dyn std::error::Error + 'static),
mut classify: impl FnMut(&(dyn std::error::Error + 'static)) -> Option<T>,
) -> Option<T> {
@@ -595,10 +602,9 @@ fn is_unavailable_internode_http_error(err: &rustfs_rio::InternodeHttpError) ->
err.kind().is_retryable()
|| matches!(
err.kind(),
rustfs_rio::InternodeHttpErrorKind::HttpStatus(status)
if status.is_server_error() || status.as_u16() == 409
rustfs_rio::InternodeHttpErrorKind::HttpStatus(StatusCode::CONFLICT)
if err.context().operation() == Some(INTERNODE_OPERATION_PUT_FILE_STREAM)
)
|| (err.kind() == rustfs_rio::InternodeHttpErrorKind::Unknown && err.context().operation().is_some())
}
/// A nested lock timeout retains its retry advice even when an outer lock
@@ -623,7 +629,10 @@ 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("put_file_stream" | "put_file_capability"))
&& matches!(
internode_err.context().operation(),
Some(INTERNODE_OPERATION_PUT_FILE_STREAM | INTERNODE_OPERATION_PUT_FILE_CAPABILITY)
)
{
cause = Some("storage_write_quorum");
}
@@ -663,10 +672,7 @@ impl From<ApiError> for rustfs_s3_types::S3Error {
}
}
/// 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.
/// Classify a gateway refusal while its typed source is still available.
pub(crate) fn classify_s3_503_subcause(
code: &S3ErrorCode,
message: Option<&str>,
@@ -684,9 +690,6 @@ 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";
}
@@ -697,21 +700,22 @@ 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.contains("write concurrency limit reached") || msg.contains("foreground write concurrency") {
if msg.starts_with("foreground write concurrency limit reached") {
return "foreground_write_admission";
}
if msg.contains("disk read concurrency limit reached") {
if msg.starts_with("disk read concurrency limit reached") {
return "disk_read_permit_exhausted";
}
if msg.contains("Table listing exceeded") {
if msg.starts_with("Table listing exceeded the protected scan limit") {
return "table_list_scan_limit";
}
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() {
if msg.ends_with(" queue is full; retry later") || msg.ends_with(" queue wait timed out; retry later") {
return "bucket_operation_admission";
}
if msg.contains("Resource requested is unreadable") {
@@ -720,7 +724,7 @@ pub(crate) fn classify_s3_503_subcause(
return "slowdown_other";
}
if msg.contains("quota") || msg.contains("Quota") {
if msg == "Bucket quota check temporarily unavailable, please retry" {
return "quota_usage_unavailable";
}
if msg.contains("server context is not ready") || msg.contains("iam unavailable") {
@@ -730,9 +734,6 @@ 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
@@ -770,6 +771,7 @@ 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"),
@@ -959,21 +961,6 @@ 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 {
@@ -2774,9 +2761,8 @@ mod tests {
for kind in [
ConnectionReset,
BodyStreamAborted,
Unknown,
HttpStatus(http::StatusCode::CONFLICT),
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))),
@@ -2796,10 +2782,17 @@ mod tests {
assert_eq!(response.status_code(), Some(http::StatusCode::SERVICE_UNAVAILABLE));
}
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);
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:?}");
}
}
#[test]
+10 -40
View File
@@ -40,36 +40,6 @@ 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";
@@ -184,16 +154,6 @@ 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();
@@ -216,6 +176,16 @@ 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,7 +55,6 @@ 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};
+1 -10
View File
@@ -405,16 +405,7 @@ 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, 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),
);
}
let mut response = service.call(request).await;
if track_plaintext_post_ssec && is_plaintext_ssec_refusal_response(&response) {
report_plaintext_ssec();
}
+82
View File
@@ -1217,6 +1217,88 @@ 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]
+13 -90
View File
@@ -82,20 +82,16 @@ pub(crate) async fn collect_probe_readiness(
}
fn apply_object_traffic_snapshot(report: &mut DependencyReadinessReport, probe: HealthProbe, snapshot: ObjectTrafficSnapshot) {
if matches!(probe, HealthProbe::Readiness | HealthProbe::ClusterRead) && snapshot.read_stalled {
if snapshot.read_stalled && matches!(probe, HealthProbe::Readiness | HealthProbe::ClusterRead) {
let reason = ReadinessDegradedReason::ObjectReadStalled;
if !report.degraded_reasons.contains(&reason) {
report.degraded_reasons.push(reason);
}
report.degraded_reasons.push(reason);
if probe == HealthProbe::Readiness {
record_readiness_overlay_reason(reason);
}
}
if matches!(probe, HealthProbe::Readiness | HealthProbe::ClusterWrite) && snapshot.write_stalled {
if snapshot.write_stalled && matches!(probe, HealthProbe::Readiness | HealthProbe::ClusterWrite) {
let reason = ReadinessDegradedReason::ObjectWriteStalled;
if !report.degraded_reasons.contains(&reason) {
report.degraded_reasons.push(reason);
}
report.degraded_reasons.push(reason);
if probe == HealthProbe::Readiness {
record_readiness_overlay_reason(reason);
}
@@ -327,25 +323,21 @@ pub(crate) fn build_health_response_parts(
),
};
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,
};
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,
});
if readiness_overlay_degraded {
health = HealthCheckState {
status_code: StatusCode::SERVICE_UNAVAILABLE,
status: "degraded",
ready: false,
};
if probe == HealthProbe::Readiness
&& matches!(kms_ready, Some(false))
&& !degraded_reasons.contains(&ReadinessDegradedReason::KmsNotReady)
{
if kms_overlay_degraded && !degraded_reasons.contains(&ReadinessDegradedReason::KmsNotReady) {
degraded_reasons.push(ReadinessDegradedReason::KmsNotReady);
}
}
@@ -891,73 +883,4 @@ 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);
});
}
}
+145 -68
View File
@@ -65,6 +65,7 @@ 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";
@@ -423,6 +424,32 @@ 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() {
@@ -1051,6 +1078,17 @@ 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())))
@@ -2114,7 +2152,26 @@ 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()
@@ -2155,12 +2212,35 @@ 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 {
@@ -2811,45 +2891,20 @@ 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] {
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);
let response = service
.call(
Request::builder()
@@ -2860,7 +2915,7 @@ pub(in crate::server) mod tests {
)
.await
.expect("node readiness response");
let expected = if published {
let expected = if ready {
StatusCode::OK
} else {
StatusCode::SERVICE_UNAVAILABLE
@@ -2874,11 +2929,16 @@ 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");
assert_eq!(payload["ready"], published);
if liveness {
assert_eq!(payload["status"], "ok");
assert!(payload.get("ready").is_none());
continue;
}
assert_eq!(payload["ready"], ready);
for component in ["storage", "iam", "lock"] {
assert_eq!(payload["details"][component]["ready"], true, "{component}");
}
let reasons = if published {
let reasons = if ready {
serde_json::json!([])
} else {
serde_json::json!(["startup_finalization_pending"])
@@ -2917,6 +2977,8 @@ 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")),
@@ -2971,37 +3033,6 @@ 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()
@@ -3023,7 +3054,53 @@ 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()
+6 -54
View File
@@ -81,7 +81,6 @@ 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::{
@@ -167,6 +166,7 @@ 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,7 +179,6 @@ 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();
@@ -198,10 +197,9 @@ 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(
http::HeaderName::from_static("x-rustfs-503-subcause"),
HeaderValue::from_static("readiness_pending"),
);
response
.headers_mut()
.insert(super::layer::S3_503_SUBCAUSE_HEADER, HeaderValue::from_static(READINESS_503_SUBCAUSE));
response
}
@@ -1049,12 +1047,6 @@ 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 {
@@ -2173,17 +2165,6 @@ 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;
}
@@ -2544,12 +2525,10 @@ mod tests {
#[tokio::test]
async fn service_not_ready_response_preserves_observable_contract() {
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
let response =
metrics::with_local_recorder(&recorder, || service_not_ready_response(rustfs_common::SystemStage::Booting));
let response = 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()
@@ -2578,33 +2557,6 @@ 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}"),
+136 -117
View File
@@ -314,55 +314,6 @@ 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.
@@ -2105,13 +2056,7 @@ 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(io::Error::new(
io::ErrorKind::UnexpectedEof,
format!("body size mismatch: expected {} bytes, received {copied}", query.size),
)) as BoxError,
));
return Err(("verify_size", Box::new(incomplete_put_file_body(query.size, copied)) as BoxError));
}
file.shutdown().await.map_err(|err| ("shutdown", Box::new(err) as BoxError))?;
drop(file);
@@ -2135,7 +2080,13 @@ where
cleanup.downcast_ref::<DiskError>(),
Some(DiskError::FileNotFound | DiskError::VolumeNotFound)
) {
let _ = log_internode_put_file_stage_failure!("cleanup_staging", query, cleanup.as_ref());
log_put_file_failure(
StatusCode::INTERNAL_SERVER_ERROR,
PUT_FILE_AUTH_STREAM_PATH,
"cleanup_staging",
query,
cleanup.as_ref(),
);
}
return Err((stage, primary));
}
@@ -2247,9 +2198,7 @@ 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)) => {
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);
return put_file_failure_response(&path, stage, &query, e.as_ref());
}
};
record_put_file_metrics(copied);
@@ -2263,18 +2212,14 @@ 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) => {
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);
return put_file_failure_response(&path, "append", &query, &e);
}
}
} else {
match disk.create_file("", &query.volume, &query.path, query.size).await {
Ok(file) => file,
Err(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);
return put_file_failure_response(&path, "create", &query, &e);
}
}
};
@@ -2284,28 +2229,19 @@ async fn handle_put_file(req: Request<Incoming>, require_auth: bool) -> Response
{
Ok(copied) => copied,
Err(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);
return put_file_failure_response(&path, "write_body", &query, &e);
}
};
record_put_file_metrics(copied);
if put_body_size_mismatch(&query, copied) {
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);
let err = incomplete_put_file_body(query.size, copied);
return put_file_failure_response(&path, "verify_size", &query, &err);
}
if let Err(e) = file.flush().await {
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);
return put_file_failure_response(&path, "flush", &query, &e);
}
empty_ok()
@@ -2324,6 +2260,24 @@ 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,
@@ -2334,7 +2288,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(io::Error::other)? {
while let Some(bytes) = body.try_next().await.map_err(put_file_body_receive_error)? {
copied = copied.saturating_add(u64::try_from(bytes.len()).unwrap_or(u64::MAX));
pending.extend_from_slice(&bytes);
@@ -2379,7 +2333,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(io::Error::other)? {
while let Some(bytes) = body.try_next().await.map_err(put_file_body_receive_error)? {
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))
@@ -2440,13 +2394,10 @@ where
}
if remaining.is_some_and(|remaining| remaining != 0) {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
format!("body size mismatch: expected {} bytes, received {copied}", query.size),
));
return Err(incomplete_put_file_body(query.size, copied));
}
if trailer.len() != PUT_FILE_AUTH_TRAILER_LEN {
return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "put_file auth trailer is incomplete"));
return Err(io::Error::new(io::ErrorKind::UnexpectedEof, PutFileBodyError::IncompleteAuthTrailer));
}
let expected = verify_put_file_auth_trailer(url, &Method::PUT, nonce, &trailer)?;
@@ -2530,12 +2481,14 @@ 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(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,
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(
DiskError::Timeout
| DiskError::FaultyDisk
| DiskError::FaultyRemoteDisk
@@ -2544,33 +2497,74 @@ fn classify_put_file_stage_status(stage: &str, err: &(dyn std::error::Error + 's
| DiskError::TooManyOpenFiles
| DiskError::DiskOngoingReq
)
{
return StatusCode::SERVICE_UNAVAILABLE;
) {
return Some(StatusCode::SERVICE_UNAVAILABLE);
}
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();
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
)
};
}
StatusCode::INTERNAL_SERVER_ERROR
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))
}
fn put_file_stage_error_message(stage: &str, query: &PutFileQuery, err: &dyn std::fmt::Display) -> String {
@@ -3101,6 +3095,31 @@ 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 {