From 75ea68f11b0a857aa4ae494acc2bffc5b65facaa Mon Sep 17 00:00:00 2001 From: Hauser Zhi Date: Wed, 2 Dec 2026 20:47:32 +0800 Subject: [PATCH] fix(s3): unify saturation handling and response attribution Co-Authored-By: heihutu Co-Authored-By: zhi22915 Co-Authored-By: qunjiazhu Signed-off-by: Hauser Zhi --- crates/config/src/constants/internode.rs | 36 +- crates/config/src/constants/object.rs | 2 +- crates/ecstore/src/cluster/rpc/remote_disk.rs | 595 ++++++++---------- .../ecstore/src/cluster/rpc/remote_locker.rs | 184 +++--- crates/ecstore/src/disk/disk_store.rs | 47 +- .../src/set_disk/core/metadata_read.rs | 61 +- crates/io-metrics/src/s3_http_metrics.rs | 42 +- crates/lock/src/distributed_lock.rs | 286 +++------ crates/protos/src/channel_reset_tests.rs | 25 +- crates/protos/src/lib.rs | 25 +- crates/rio/src/http_reader.rs | 307 +++++---- rustfs/src/error.rs | 83 ++- rustfs/src/server/gateway_handlers/error.rs | 50 +- rustfs/src/server/gateway_handlers/mod.rs | 1 - rustfs/src/server/gateway_stack.rs | 11 +- rustfs/src/server/health.rs | 103 +-- rustfs/src/server/layer.rs | 191 ++++-- rustfs/src/server/readiness.rs | 60 +- rustfs/src/storage/rpc/http_service.rs | 253 ++++---- 19 files changed, 1027 insertions(+), 1335 deletions(-) diff --git a/crates/config/src/constants/internode.rs b/crates/config/src/constants/internode.rs index 187b871d4f..a9687ebe6e 100644 --- a/crates/config/src/constants/internode.rs +++ b/crates/config/src/constants/internode.rs @@ -71,15 +71,15 @@ const _: () = assert!(DEFAULT_INTERNODE_RPC_TCP_NODELAY); /// unary responses such as `ReadMultiple` and `BatchReadVersion`. Set to 0 to use the /// `tonic`/`hyper` default. Defaults to 1MiB. pub const ENV_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE: &str = "RUSTFS_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE"; -pub const DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE: u32 = 4 * 1024 * 1024; +pub const DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE: u32 = 1024 * 1024; /// HTTP/2 initial connection window size (bytes) for internode gRPC client channels. /// /// Should be >= the stream window so multiple concurrent streams are not starved by the /// connection-level flow-control window. Set to 0 to fall back to the library default. -/// Defaults to 16MiB. +/// Defaults to 2MiB. pub const ENV_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE: &str = "RUSTFS_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE"; -pub const DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE: u32 = 16 * 1024 * 1024; +pub const DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE: u32 = 2 * 1024 * 1024; // Compile-time invariant: the connection-level window must be >= the per-stream window, or // concurrent streams would be starved by the connection-level flow-control budget. @@ -284,23 +284,23 @@ pub const DEFAULT_INTERNODE_IDEMPOTENT_READ_RETRIES: usize = 1; /// Enable control/bulk internode gRPC channel isolation. /// -/// Defaults to `true` so bulk `ReadAll`/`WriteAll`/`ReadMultiple`/`BatchReadVersion` transfers -/// use dedicated bulk HTTP/2 channels instead of head-of-line blocking latency-sensitive -/// `Lock`/`UnLock`/`Refresh`/`DiskInfo` control RPCs under high concurrency. Set -/// `RUSTFS_INTERNODE_CHANNEL_ISOLATION=false` for single-env rollback to legacy shared-channel behavior. +/// Defaults to `false`: this touches lock-RPC transport routing (consistency-sensitive), so it +/// is opt-in and validated against a baseline before rollout. When `false`, bulk RPCs reuse the +/// control channel exactly as before, so the switch is a single-env rollback. pub const ENV_INTERNODE_CHANNEL_ISOLATION: &str = "RUSTFS_INTERNODE_CHANNEL_ISOLATION"; -pub const DEFAULT_INTERNODE_CHANNEL_ISOLATION: bool = true; +pub const DEFAULT_INTERNODE_CHANNEL_ISOLATION: bool = false; -// Compile-time invariant: channel isolation defaults on so bulk data RPCs cannot starve lock/quorum RPCs. -const _: () = assert!(DEFAULT_INTERNODE_CHANNEL_ISOLATION); +// Compile-time invariant: isolation is opt-in so the default build behaves exactly as before P1. +const _: () = assert!(!DEFAULT_INTERNODE_CHANNEL_ISOLATION); /// Number of bulk channels maintained per peer when channel isolation is enabled. /// /// A tonic `Channel` is a single TCP/HTTP2 connection; multiple bulk channels are round-robined -/// to relieve the single-connection throughput ceiling for large transfers. Defaults to 4 (matching -/// typical 4-drive-per-node stripes); clamped to at least 1. +/// to relieve the single-connection throughput ceiling for large transfers. Kept small (default +/// 2) to avoid a connection storm; clamped to at least 1. Set to 1 to isolate bulk onto a single +/// dedicated connection (still separate from control). pub const ENV_INTERNODE_BULK_CHANNELS: &str = "RUSTFS_INTERNODE_BULK_CHANNELS"; -pub const DEFAULT_INTERNODE_BULK_CHANNELS: usize = 4; +pub const DEFAULT_INTERNODE_BULK_CHANNELS: usize = 2; /// Optional receive-window overrides for isolated bulk channels. When unset, inherit the /// corresponding `RUSTFS_INTERNODE_RPC_HTTP2_*` setting. Zero selects the library default. @@ -310,7 +310,7 @@ pub const ENV_INTERNODE_BULK_HTTP2_CONN_WINDOW_SIZE: &str = "RUSTFS_INTERNODE_BU /// Transport admission and pending-buffer limits for isolated bulk channels. These limits /// apply to the tonic service; complete unary bodies are observed separately by RPC metrics. pub const ENV_INTERNODE_BULK_CONCURRENCY_LIMIT: &str = "RUSTFS_INTERNODE_BULK_CONCURRENCY_LIMIT"; -pub const DEFAULT_INTERNODE_BULK_CONCURRENCY_LIMIT: usize = 128; +pub const DEFAULT_INTERNODE_BULK_CONCURRENCY_LIMIT: usize = 64; pub const ENV_INTERNODE_BULK_BUFFER_SIZE: &str = "RUSTFS_INTERNODE_BULK_BUFFER_SIZE"; pub const DEFAULT_INTERNODE_BULK_BUFFER_SIZE: usize = 1024; @@ -501,8 +501,8 @@ mod tests { #[test] fn internode_rpc_channel_tuning_defaults() { - assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE, 4 * 1024 * 1024); - assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE, 16 * 1024 * 1024); + assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE, 1024 * 1024); + assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE, 2 * 1024 * 1024); // The nodelay-on and connection-window >= stream-window invariants are enforced at // compile time next to the constant definitions. } @@ -525,8 +525,8 @@ mod tests { #[test] fn internode_channel_isolation_defaults_and_env_names() { - // The isolation-on default is asserted at compile time next to the constant definition. - assert_eq!(DEFAULT_INTERNODE_BULK_CHANNELS, 4); + // The isolation-off default is asserted at compile time next to the constant definition. + assert_eq!(DEFAULT_INTERNODE_BULK_CHANNELS, 2); assert_eq!(DEFAULT_INTERNODE_BULK_BODY_CONCURRENCY_LIMIT, 0); assert_eq!(DEFAULT_INTERNODE_BULK_BODY_WAIT_TIMEOUT_MS, 1_000); assert_eq!(ENV_INTERNODE_CHANNEL_ISOLATION, "RUSTFS_INTERNODE_CHANNEL_ISOLATION"); diff --git a/crates/config/src/constants/object.rs b/crates/config/src/constants/object.rs index 0b427dc673..f1b3680a8b 100644 --- a/crates/config/src/constants/object.rs +++ b/crates/config/src/constants/object.rs @@ -482,7 +482,7 @@ pub const DEFAULT_PUT_MULTIPART_FOREGROUND_ADMISSION_MIN_SIZE_BYTES: usize = 0; /// A short wait smooths transient bursts while still returning S3 /// `SlowDown`/503 before body ingest when the node is already saturated. pub const ENV_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS: &str = "RUSTFS_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS"; -pub const DEFAULT_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS: u64 = 2_000; +pub const DEFAULT_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS: u64 = 250; /// Time in milliseconds a multipart UploadPart waits for a foreground write permit. /// diff --git a/crates/ecstore/src/cluster/rpc/remote_disk.rs b/crates/ecstore/src/cluster/rpc/remote_disk.rs index fb51f8b8bc..e3114c5d69 100644 --- a/crates/ecstore/src/cluster/rpc/remote_disk.rs +++ b/crates/ecstore/src/cluster/rpc/remote_disk.rs @@ -91,7 +91,7 @@ use std::{ pin::Pin, sync::{ Arc, Mutex as StdMutex, Weak, - atomic::{AtomicBool, AtomicU32, Ordering}, + atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}, }, task::{Context, Poll}, time::{Duration, Instant}, @@ -1030,6 +1030,7 @@ pub struct RemoteDisk { health_monitor_started: AtomicBool, /// Health tracker for connection monitoring health: Arc, + host_rpc_health: Arc, /// Cancellation token for monitoring tasks cancel_token: CancellationToken, recovery_monitor_active: Arc, @@ -1463,13 +1464,18 @@ fn internode_idempotent_read_retries() -> usize { static PREWARMED_PEERS: std::sync::LazyLock>> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashSet::new())); -/// Tracks multi-disk timeout bursts per peer `addr` so that when a single host -/// stops answering across multiple drives (e.g. `SIGSTOP` grey failure in 3x4), -/// sibling drives on that host fast-fail instead of each paying independent 5-10s -/// timeouts. A single disk timing out never triggers host-level fast-fail, and -/// any successful RPC or periodic re-probe clears degradation immediately. -#[derive(Default)] +/// Success advances a generation without taking the timeout lock. Only timeouts from the +/// same generation contribute to host degradation. +#[derive(Debug, Default)] +struct HostRpcHealth { + completed: AtomicU64, + may_be_degraded: AtomicBool, + timeouts: StdMutex, +} + +#[derive(Debug, Default)] struct HostTimeoutDegradationState { + completed_at_failure: u64, timed_out_endpoints: std::collections::HashMap, degraded_until: Option, last_probe_allowed: Option, @@ -1480,95 +1486,77 @@ const HOST_TIMEOUT_DEGRADATION_TTL: Duration = Duration::from_secs(5); const HOST_TIMEOUT_REPROBE_INTERVAL: Duration = Duration::from_secs(2); const HOST_TIMEOUT_MIN_DISTINCT_DISKS: usize = 2; -static HOST_TIMEOUT_DEGRADATION: std::sync::LazyLock< - std::sync::Mutex>, -> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new())); +type HostRpcHealthRegistry = StdMutex>>; -static HOST_RPC_PROGRESS: std::sync::LazyLock< - std::sync::Mutex>>, -> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new())); - -fn host_progress_counter(addr: &str) -> Arc { - let mut map = HOST_RPC_PROGRESS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - if let Some(counter) = map.get(addr) { - return Arc::clone(counter); +fn host_rpc_health(addr: &str) -> Arc { + static PEERS: std::sync::LazyLock = std::sync::LazyLock::new(HostRpcHealthRegistry::default); + let mut peers = PEERS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if let Some(health) = peers.get(addr).and_then(Weak::upgrade) { + return health; } - let counter = Arc::new(std::sync::atomic::AtomicU64::new(0)); - map.insert(addr.to_owned(), Arc::clone(&counter)); - counter + peers.retain(|_, health| health.strong_count() != 0); + let health = Arc::new(HostRpcHealth::default()); + peers.insert(addr.to_owned(), Arc::downgrade(&health)); + health } -pub(crate) fn host_completed_ops(addr: &str) -> u64 { - let Ok(map) = HOST_RPC_PROGRESS.lock() else { - return 0; - }; - map.get(addr) - .map_or(0, |counter| counter.load(std::sync::atomic::Ordering::Acquire)) -} - -fn record_host_rpc_success(addr: &str) { - host_progress_counter(addr).fetch_add(1, std::sync::atomic::Ordering::AcqRel); - clear_host_timeout_degradation(addr); -} - -fn record_host_disk_timeout(addr: &str, endpoint: &str) { - let now = tokio::time::Instant::now(); - let Ok(mut map) = HOST_TIMEOUT_DEGRADATION.lock() else { - return; - }; - let state = map.entry(addr.to_owned()).or_default(); - state - .timed_out_endpoints - .retain(|_, ts| now.saturating_duration_since(*ts) <= HOST_TIMEOUT_CORRELATION_WINDOW); - state.timed_out_endpoints.insert(endpoint.to_owned(), now); - if state.timed_out_endpoints.len() >= HOST_TIMEOUT_MIN_DISTINCT_DISKS { - state.degraded_until = Some(now + HOST_TIMEOUT_DEGRADATION_TTL); - state.last_probe_allowed.get_or_insert(now); +impl HostRpcHealth { + fn completed_ops(&self) -> u64 { + self.completed.load(Ordering::Relaxed) } -} -fn is_host_timeout_degraded(addr: &str) -> bool { - let now = tokio::time::Instant::now(); - let Ok(map) = HOST_TIMEOUT_DEGRADATION.lock() else { - return false; - }; - map.get(addr) - .and_then(|state| state.degraded_until) - .is_some_and(|until| now < until) -} - -fn clear_host_timeout_degradation(addr: &str) { - if let Ok(mut map) = HOST_TIMEOUT_DEGRADATION.lock() { - map.remove(addr); + fn record_success(&self) { + self.completed.fetch_add(1, Ordering::Relaxed); } -} -fn host_timeout_fast_fail_should_bypass(addr: &str) -> bool { - let now = tokio::time::Instant::now(); - let Ok(mut map) = HOST_TIMEOUT_DEGRADATION.lock() else { - return false; - }; - let Some(state) = map.get_mut(addr) else { - return false; - }; - let Some(until) = state.degraded_until else { - return false; - }; - if now >= until { - state.degraded_until = None; + fn record_disk_timeout(&self, endpoint: &Endpoint, completed_before: u64) { + if self.completed_ops() != completed_before { + return; + } + let now = time::Instant::now(); + let mut state = self.timeouts.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if self.completed_ops() != completed_before { + return; + } + if state.completed_at_failure != completed_before { + *state = HostTimeoutDegradationState { + completed_at_failure: completed_before, + ..HostTimeoutDegradationState::default() + }; + self.may_be_degraded.store(false, Ordering::Relaxed); + } state .timed_out_endpoints .retain(|_, ts| now.saturating_duration_since(*ts) <= HOST_TIMEOUT_CORRELATION_WINDOW); - return false; + state.timed_out_endpoints.insert(endpoint.to_string(), now); + if state.timed_out_endpoints.len() >= HOST_TIMEOUT_MIN_DISTINCT_DISKS { + state.degraded_until = Some(now + HOST_TIMEOUT_DEGRADATION_TTL); + state.last_probe_allowed.get_or_insert(now); + self.may_be_degraded.store(true, Ordering::Relaxed); + } } - if state - .last_probe_allowed - .is_none_or(|last| now.saturating_duration_since(last) >= HOST_TIMEOUT_REPROBE_INTERVAL) - { - state.last_probe_allowed = Some(now); - return false; + + fn should_bypass(&self, allow_probe: bool) -> bool { + if !self.may_be_degraded.load(Ordering::Relaxed) { + return false; + } + let now = time::Instant::now(); + let mut state = self.timeouts.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if self.completed_ops() != state.completed_at_failure || state.degraded_until.is_none_or(|until| now >= until) { + state.degraded_until = None; + self.may_be_degraded.store(false, Ordering::Relaxed); + return false; + } + if allow_probe + && state + .last_probe_allowed + .is_none_or(|last| now.saturating_duration_since(last) >= HOST_TIMEOUT_REPROBE_INTERVAL) + { + state.last_probe_allowed = Some(now); + return false; + } + true } - true } fn claim_control_channel_prewarm(addr: &str) -> bool { @@ -1952,6 +1940,7 @@ impl RemoteDisk { let disk = Self { handle_id: Uuid::new_v4(), id: Mutex::new(None), + host_rpc_health: host_rpc_health(&addr), addr, endpoint: ep.clone(), scanning: Arc::new(AtomicU32::new(0)), @@ -2294,10 +2283,6 @@ impl RemoteDisk { rx } - fn mark_suspect_or_offline(&self, reason: &'static str) -> bool { - self.health.mark_failure(&self.endpoint, reason) - } - /// Enable health monitoring after disk creation. /// Used to defer health checks until after startup format loading completes, /// so that remote peers have time to come online. @@ -2341,10 +2326,11 @@ impl RemoteDisk { ) { let mut interval = time::interval(get_drive_active_check_interval()); - // Perform basic connectivity check + // A TCP handshake detects reachability. Only an RPC response can prove progress + // when a process has stopped servicing requests but the kernel still accepts TCP. let initial_probe_ok = Self::perform_connectivity_check(&addr).await.is_ok(); if initial_probe_ok { - health.record_operation_success(&endpoint, "connectivity_probe_success"); + health.record_connectivity_success(&endpoint, "connectivity_probe_success"); rustfs_io_metrics::internode_metrics::record_peer_reachable_if_offline(&addr); } else if health.mark_failure(&endpoint, "connectivity_probe_failed") { warn!( @@ -2416,7 +2402,7 @@ impl RemoteDisk { // Perform basic connectivity check if Self::perform_connectivity_check(&addr).await.is_ok() { - health.record_operation_success(&endpoint, "connectivity_probe_success"); + health.record_connectivity_success(&endpoint, "connectivity_probe_success"); rustfs_io_metrics::internode_metrics::record_peer_reachable_if_offline(&addr); } else if health.mark_failure(&endpoint, "connectivity_probe_failed") { warn!( @@ -2461,6 +2447,7 @@ impl RemoteDisk { health: Arc, cancel_token: CancellationToken, ) { + let host_rpc_health = host_rpc_health(&addr); let mut interval = time::interval(get_drive_returning_probe_interval()); let initial_boot_epoch = crate::cluster::rpc::client::peer_authenticated_boot_epoch_for_addr(&addr); debug!( @@ -2488,8 +2475,7 @@ impl RemoteDisk { return; } _ = interval.tick() => { - if Self::perform_recovery_probe(&addr, &endpoint).await.is_ok() { - clear_host_timeout_degradation(&addr); + if Self::perform_recovery_probe(&addr, &endpoint, &host_rpc_health).await.is_ok() { rustfs_io_metrics::internode_metrics::record_peer_reachable(&addr); let current_boot_epoch = crate::cluster::rpc::client::peer_authenticated_boot_epoch_for_addr(&addr); let peer_restarted = current_boot_epoch.is_some() && current_boot_epoch != initial_boot_epoch; @@ -2534,14 +2520,12 @@ impl RemoteDisk { /// never engages host-level fast-fail while a `SIGSTOP`'d peer holding 4 /// drives fast-fails immediately on subsequent requests. pub(crate) fn record_straggler_timeout_if_stalled(&self, host_completed_before: u64) { - if host_completed_ops(&self.addr) > host_completed_before { - return; - } - record_host_disk_timeout(&self.addr, &self.endpoint.to_string()); + self.host_rpc_health + .record_disk_timeout(&self.endpoint, host_completed_before); } pub(crate) fn host_completed_ops(&self) -> u64 { - host_completed_ops(&self.addr) + self.host_rpc_health.completed_ops() } /// On-demand bounded recovery probe used only when a read is about to fail read quorum due to @@ -2550,17 +2534,21 @@ impl RemoteDisk { if !self.health.is_faulty() { return false; } - let Ok(Ok(())) = timeout(Duration::from_millis(1000), Self::perform_recovery_probe(&self.addr, &self.endpoint)).await + let Ok(Ok(())) = timeout( + Duration::from_millis(1000), + Self::perform_recovery_probe(&self.addr, &self.endpoint, &self.host_rpc_health), + ) + .await else { return false; }; - record_host_rpc_success(&self.addr); rustfs_io_metrics::internode_metrics::record_peer_reachable(&self.addr); self.health .mark_peer_restarted_online(&self.endpoint, "on_demand_quorum_recovery_probe_success") } - async fn perform_recovery_probe(addr: &str, endpoint: &Endpoint) -> Result<()> { + async fn perform_recovery_probe(addr: &str, endpoint: &Endpoint, host_rpc_health: &HostRpcHealth) -> Result<()> { + let host_completed_before = host_rpc_health.completed_ops(); let mut evict_cached_connection = false; let result = match timeout(get_drive_active_check_timeout(), async { let opts = serde_json::to_string(&DiskInfoOptions { @@ -2588,7 +2576,10 @@ impl RemoteDisk { }) .await { - Ok(Ok(())) => Ok(()), + Ok(Ok(())) => { + host_rpc_health.record_success(); + Ok(()) + } Ok(Err((err, should_evict))) => { evict_cached_connection = should_evict; Err(err) @@ -2599,7 +2590,7 @@ impl RemoteDisk { } }; - if evict_cached_connection { + if evict_cached_connection && host_rpc_health.completed_ops() == host_completed_before { // Cache contention must not hold the recovery lease indefinitely. let _ = timeout( get_drive_active_check_timeout(), @@ -2678,13 +2669,11 @@ impl RemoteDisk { .await { Err(err) if attempt < max_retries && is_network_like_disk_error(&err) => { - if matches!(err, DiskError::Timeout) && is_host_timeout_degraded(&self.addr) { + if matches!(err, DiskError::Timeout) && self.host_rpc_health.should_bypass(false) { return Err(err); } if matches!(err, DiskError::Timeout) && deadline.is_some_and(|deadline| time::Instant::now() >= deadline) { - if self.health.completed_ops() == drive_completed_before { - self.mark_faulty("read_operation_deadline"); - } + self.mark_faulty("read_operation_deadline", drive_completed_before); return Err(err); } attempt += 1; @@ -2763,7 +2752,7 @@ impl RemoteDisk { // same peer host recently timed out, short-circuit sibling drives (including // idempotent read attempts whose attempt-0 health action is IgnoreFailure) // so quorum operations stay sub-second while allowing periodic self-healing probes. - if host_timeout_fast_fail_should_bypass(&self.addr) { + if self.host_rpc_health.should_bypass(true) { return Err(DiskError::Timeout); } @@ -2775,62 +2764,41 @@ impl RemoteDisk { self.health.last_started.store(now, std::sync::atomic::Ordering::Relaxed); let _waiting_guard = self.health.waiting_guard(); - if timeout_duration == Duration::ZERO { - let drive_completed_before = self.health.completed_ops(); - let host_completed_before = host_completed_ops(&self.addr); - let operation_result = operation().await; - if operation_result.is_ok() { - record_host_rpc_success(&self.addr); + let drive_completed_before = self.health.completed_ops(); + let host_completed_before = self.host_completed_ops(); + let timed_result = if timeout_duration.is_zero() { + Ok(operation().await) + } else { + time::timeout(timeout_duration, operation()).await + }; + + match timed_result { + Ok(Ok(value)) => { + self.host_rpc_health.record_success(); self.health.record_operation_success(&self.endpoint, "operation_success"); rustfs_io_metrics::internode_metrics::record_peer_reachable_if_offline(&self.addr); + Ok(value) } - let drive_stalled = self.health.completed_ops() == drive_completed_before; - let host_stalled = host_completed_ops(&self.addr) == host_completed_before; - self.handle_network_like_error( - op, - timeout_duration, - &operation_result, - failure_health_action, - drive_stalled, - host_stalled, - ) - .await; - return operation_result; - } - - // Execute operation with timeout - let drive_completed_before = self.health.completed_ops(); - let host_completed_before = host_completed_ops(&self.addr); - let result = time::timeout(timeout_duration, operation()).await; - - match result { - Ok(operation_result) => { - // Log success; the waiting guard balances every exit path. - if operation_result.is_ok() { - record_host_rpc_success(&self.addr); - self.health.record_operation_success(&self.endpoint, "operation_success"); - rustfs_io_metrics::internode_metrics::record_peer_reachable_if_offline(&self.addr); + Ok(Err(error)) => { + if self.record_network_like_error(op, timeout_duration, &error) + && failure_health_action == FailureHealthAction::MarkFailure + { + self.mark_faulty_and_evict_if_stalled( + "operation_network_error", + drive_completed_before, + host_completed_before, + ) + .await; } - let drive_stalled = self.health.completed_ops() == drive_completed_before; - let host_stalled = host_completed_ops(&self.addr) == host_completed_before; - self.handle_network_like_error( - op, - timeout_duration, - &operation_result, - failure_health_action, - drive_stalled, - host_stalled, - ) - .await; - operation_result + Err(error) } Err(_) => { self.record_timeout(op, timeout_duration); - let drive_stalled = self.health.completed_ops() == drive_completed_before; - let host_stalled = host_completed_ops(&self.addr) == host_completed_before; - if failure_health_action == FailureHealthAction::MarkFailure && drive_stalled { - record_host_disk_timeout(&self.addr, &self.endpoint.to_string()); - self.mark_faulty_with_eviction("operation_timeout", host_stalled).await; + if failure_health_action == FailureHealthAction::MarkFailure { + self.host_rpc_health + .record_disk_timeout(&self.endpoint, host_completed_before); + self.mark_faulty_and_evict_if_stalled("operation_timeout", drive_completed_before, host_completed_before) + .await; } Err(DiskError::Timeout) } @@ -2847,61 +2815,34 @@ impl RemoteDisk { F: FnOnce() -> Fut, Fut: std::future::Future>, { - if timeout_duration == Duration::ZERO { + if timeout_duration.is_zero() { self.record_timeout(op, timeout_duration); return Err(DiskError::Timeout); } - let drive_completed_before = self.health.completed_ops(); - let host_completed_before = host_completed_ops(&self.addr); - match time::timeout(timeout_duration, operation()).await { - Ok(operation_result) => { - if operation_result.is_ok() { - record_host_rpc_success(&self.addr); - self.health.record_operation_success(&self.endpoint, "operation_success"); - rustfs_io_metrics::internode_metrics::record_peer_reachable_if_offline(&self.addr); + let host_completed_before = self.host_completed_ops(); + let (error, rebuild_reason) = match time::timeout(timeout_duration, operation()).await { + Ok(Ok(value)) => { + // Initial response headers establish peer reachability. Individual results + // arrive on the stream and cannot recover the representative drive here. + self.host_rpc_health.record_success(); + rustfs_io_metrics::internode_metrics::record_peer_reachable_if_offline(&self.addr); + return Ok(value); + } + Ok(Err(error)) => { + if !self.record_network_like_error(op, timeout_duration, &error) { + return Err(error); } - let drive_stalled = self.health.completed_ops() == drive_completed_before; - let host_stalled = host_completed_ops(&self.addr) == host_completed_before; - let evict = drive_stalled - && host_stalled - && operation_result - .as_ref() - .err() - .is_some_and(|error| !error.is_metacache_output_stream_closed() && is_network_like_disk_error(error)); - self.handle_network_like_error( - op, - timeout_duration, - &operation_result, - FailureHealthAction::IgnoreFailure, - drive_stalled, - host_stalled, - ) - .await; - if evict { - evict_failed_connection_with_reason( - &self.addr, - ChannelRebuildReason::RpcFailure, - ConnectionEvictionLogLevel::Debug, - ) - .await; - } - operation_result + (error, ChannelRebuildReason::RpcFailure) } Err(_) => { self.record_timeout(op, timeout_duration); - if self.health.completed_ops() == drive_completed_before - && host_completed_ops(&self.addr) == host_completed_before - { - evict_failed_connection_with_reason( - &self.addr, - ChannelRebuildReason::OperationTimeout, - ConnectionEvictionLogLevel::Debug, - ) - .await; - } - Err(DiskError::Timeout) + (DiskError::Timeout, ChannelRebuildReason::OperationTimeout) } + }; + if self.host_completed_ops() == host_completed_before { + evict_failed_connection_with_reason(&self.addr, rebuild_reason, ConnectionEvictionLogLevel::Debug).await; } + Err(error) } fn record_timeout(&self, op: &'static str, timeout_duration: Duration) { @@ -2927,48 +2868,41 @@ impl RemoteDisk { } } - async fn handle_network_like_error( - &self, - op: &'static str, - timeout_duration: Duration, - operation_result: &Result, - failure_health_action: FailureHealthAction, - drive_stalled: bool, - host_stalled: bool, - ) { - if let Err(err) = operation_result - && !err.is_metacache_output_stream_closed() - && is_network_like_disk_error(err) - { - counter!( - "rustfs_drive_op_network_error_total", - "endpoint" => self.endpoint.to_string(), - "op" => op.to_string() - ) - .increment(1); - if let Some(suppressed) = self.network_error_logs.claim() { - warn!( - event = EVENT_REMOTE_DISK_RPC, - component = LOG_COMPONENT_ECSTORE, - subsystem = LOG_SUBSYSTEM_REMOTE_DISK, - endpoint = %self.endpoint, - addr = %self.addr, - op, - timeout_ms = timeout_duration.as_millis(), - suppressed, - state = "network_like_error", - "Remote disk operation returned network-like error" - ); - } - if failure_health_action == FailureHealthAction::MarkFailure && drive_stalled { - self.mark_faulty_with_eviction("operation_network_error", host_stalled).await; - } + fn record_network_like_error(&self, op: &'static str, timeout_duration: Duration, error: &Error) -> bool { + if error.is_metacache_output_stream_closed() || !is_network_like_disk_error(error) { + return false; } + counter!( + "rustfs_drive_op_network_error_total", + "endpoint" => self.endpoint.to_string(), + "op" => op.to_string() + ) + .increment(1); + if let Some(suppressed) = self.network_error_logs.claim() { + warn!( + event = EVENT_REMOTE_DISK_RPC, + component = LOG_COMPONENT_ECSTORE, + subsystem = LOG_SUBSYSTEM_REMOTE_DISK, + state = "network_like_error", + endpoint = %self.endpoint, + addr = %self.addr, + op, + timeout_ms = timeout_duration.as_millis(), + suppressed, + "Remote disk operation returned network-like error" + ); + } + true } - fn mark_faulty(&self, reason: &'static str) -> bool { + fn mark_faulty(&self, reason: &'static str, drive_completed_before: u64) -> bool { let previous_state = self.runtime_state(); - let transitioned_to_offline = self.mark_suspect_or_offline(reason); + let Some(transitioned_to_offline) = + self.health + .mark_failure_unless_progressed(&self.endpoint, reason, drive_completed_before) + else { + return false; + }; let state = self.runtime_state(); if state != previous_state { @@ -3007,8 +2941,13 @@ impl RemoteDisk { state != previous_state } - async fn mark_faulty_with_eviction(&self, reason: &'static str, evict_connection: bool) { - if self.mark_faulty(reason) && evict_connection { + async fn mark_faulty_and_evict_if_stalled( + &self, + reason: &'static str, + drive_completed_before: u64, + host_completed_before: u64, + ) { + if self.mark_faulty(reason, drive_completed_before) && self.host_completed_ops() == host_completed_before { counter!( "rustfs_drive_connection_evict_total", "endpoint" => self.endpoint.to_string(), @@ -13905,6 +13844,65 @@ mod tests { remote_disk.cancel_token.cancel(); } + #[tokio::test(start_paused = true)] + async fn sibling_remote_drive_progress_preserves_channel_but_faults_stalled_drive() { + let addr = "http://sibling-drive-progress:9000"; + let stalled = remote_disk_for_addr(addr).await; + let mut sibling_endpoint = stalled.endpoint.clone(); + sibling_endpoint.url.set_path("/data/rustfs1"); + let sibling = RemoteDisk::new( + &sibling_endpoint, + &DiskOption { + cleanup: false, + health_check: false, + }, + Arc::new(TcpHttpInternodeDataTransport), + ) + .await + .expect("construct sibling drive on the same peer"); + + let channel = TonicEndpoint::from_static(addr).connect_lazy(); + runtime_sources::cache_test_node_channel(addr.to_owned(), channel).await; + let (started, wait_for_start) = tokio::sync::oneshot::channel(); + let (result, ()) = tokio::join!( + stalled.execute_with_timeout( + || async { + started.send(()).expect("signal starting disk operation"); + std::future::pending::>().await + }, + Duration::from_secs(1), + ), + async { + wait_for_start.await.expect("stalled operation began"); + sibling + .execute_with_timeout(|| async { Ok(()) }, Duration::ZERO) + .await + .expect("sibling operation completed"); + }, + ); + + assert_eq!(result, Err(DiskError::Timeout)); + assert_eq!(stalled.runtime_state(), RuntimeDriveHealthState::Suspect); + assert_eq!(sibling.runtime_state(), RuntimeDriveHealthState::Online); + assert!(runtime_sources::test_node_channel_is_cached(addr).await); + evict_failed_connection_with_reason(addr, ChannelRebuildReason::RpcFailure, ConnectionEvictionLogLevel::Debug).await; + } + + #[tokio::test] + async fn peer_batch_response_does_not_recover_representative_drive() { + let drive = remote_disk_for_addr("http://peer-batch-drive-health:9000").await; + drive.health.mark_failure(&drive.endpoint, "test_disk_timeout"); + let peer_before = drive.host_completed_ops(); + + drive + .execute_peer_batch_with_timeout("rename_data_batch", || async { Ok(()) }, Duration::from_secs(1)) + .await + .expect("peer returned batch response headers"); + + assert_ne!(drive.host_completed_ops(), peer_before); + assert_eq!(drive.runtime_state(), RuntimeDriveHealthState::Suspect); + } + #[tokio::test] async fn test_execute_with_timeout_evicts_cached_connection() { let addr = "http://127.0.0.1:59991".to_string(); @@ -15088,104 +15086,23 @@ mod tests { #[test] fn host_timeout_fast_fail_requires_two_distinct_disks_and_clears_on_success() { - let addr = "http://127.0.0.1:19390"; - clear_host_timeout_degradation(addr); + let host = HostRpcHealth::default(); + let first = Endpoint::try_from("http://127.0.0.1:19390/data1").expect("first disk endpoint"); + let second = Endpoint::try_from("http://127.0.0.1:19390/data2").expect("second disk endpoint"); + let before = host.completed_ops(); + host.record_disk_timeout(&first, before); + host.record_disk_timeout(&first, before); + assert!(!host.should_bypass(true), "a single timed-out drive does not degrade its host"); - // Single disk timing out once (or repeatedly) must NOT engage host-level fast-fail. - record_host_disk_timeout(addr, "http://127.0.0.1:19390/data1"); - record_host_disk_timeout(addr, "http://127.0.0.1:19390/data1"); - assert!( - !host_timeout_fast_fail_should_bypass(addr), - "single timed-out disk must not trip host-level fast-fail" - ); + host.record_disk_timeout(&second, before); + assert!(host.should_bypass(false), "two distinct drives degrade the host"); + assert!(host.should_bypass(true), "the host immediately bypasses sibling operations"); - // Second distinct disk on the same host timing out engages host-level fast-fail - // immediately until the periodic re-probe interval elapses. - record_host_disk_timeout(addr, "http://127.0.0.1:19390/data2"); - assert!(is_host_timeout_degraded(addr)); - assert!( - host_timeout_fast_fail_should_bypass(addr), - "sibling requests during degradation window must fast-fail immediately" - ); - - // Any single successful RPC on the host clears degradation immediately. - clear_host_timeout_degradation(addr); - assert!(!is_host_timeout_degraded(addr)); - assert!( - !host_timeout_fast_fail_should_bypass(addr), - "host degradation must clear immediately after a successful RPC" - ); - } - - #[tokio::test] - async fn sibling_drive_progress_preserves_host_channel_without_suppressing_stalled_drive_fault() { - async fn make_drive(port: u16, disk_idx: i32) -> RemoteDisk { - let url = url::Url::parse(&format!("http://127.0.0.1:{port}/data{disk_idx}")).expect("endpoint url"); - let endpoint = Endpoint { - url, - is_local: false, - pool_idx: 0, - set_idx: 0, - disk_idx, - }; - RemoteDisk::new( - &endpoint, - &DiskOption { - cleanup: false, - health_check: false, - }, - Arc::new(TcpHttpInternodeDataTransport), - ) - .await - .expect("remote disk handle") - } - - let stalled_drive = make_drive(59985, 0).await; - let sibling_drive = make_drive(59985, 1).await; - let addr = stalled_drive.addr.clone(); - clear_host_timeout_degradation(&addr); - - let dummy_channel = tonic::transport::Endpoint::from_static("http://127.0.0.1:59985").connect_lazy(); - rustfs_common::cache_connection(addr.clone(), dummy_channel).await; - assert!(rustfs_common::has_cached_connection(&addr).await); - - // Start a slow operation on `stalled_drive` while `sibling_drive` on the same host - // completes an RPC before `stalled_drive` times out. - let sibling_ref = &sibling_drive; - let err = stalled_drive - .execute_with_timeout_for_op_and_health_action( - "write_all", - || async move { - sibling_ref - .execute_with_timeout_for_op_and_health_action( - "read_all", - || async { Ok::<(), Error>(()) }, - Duration::from_secs(1), - FailureHealthAction::MarkFailure, - ) - .await - .expect("sibling drive RPC succeeds"); - tokio::time::sleep(Duration::from_millis(80)).await; - Ok::<(), Error>(()) - }, - Duration::from_millis(20), - FailureHealthAction::MarkFailure, - ) - .await - .expect_err("stalled drive must time out"); - - assert!(matches!(err, DiskError::Timeout)); - assert_ne!( - stalled_drive.runtime_state(), - RuntimeDriveHealthState::Online, - "sibling drive progress must not suppress mark_faulty on the drive that actually timed out" - ); - assert!( - rustfs_common::has_cached_connection(&addr).await, - "host-level progress from sibling drive must suppress shared-channel eviction" - ); - - rustfs_protos::evict_failed_connection(&addr).await; - clear_host_timeout_degradation(&addr); + host.record_success(); + host.record_disk_timeout(&first, before); + host.record_disk_timeout(&second, before); + assert!(!host.should_bypass(true), "stale timeouts cannot reopen a recovered host"); + host.record_disk_timeout(&first, host.completed_ops()); + assert!(!host.should_bypass(true), "a fresh timeout must not combine with a stale sibling"); } } diff --git a/crates/ecstore/src/cluster/rpc/remote_locker.rs b/crates/ecstore/src/cluster/rpc/remote_locker.rs index c39aed67e0..2fdba588f0 100644 --- a/crates/ecstore/src/cluster/rpc/remote_locker.rs +++ b/crates/ecstore/src/cluster/rpc/remote_locker.rs @@ -163,7 +163,7 @@ struct LockPeerChannelHealth { request_backoff_until: Option, request_backoff: Duration, request_probe_generation: Option, - 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, +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 { 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 / 2).max(Duration::from_millis(1)) } 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)); diff --git a/crates/ecstore/src/disk/disk_store.rs b/crates/ecstore/src/disk/disk_store.rs index 2ea57bf4b5..fbd219b4e9 100644 --- a/crates/ecstore/src/disk/disk_store.rs +++ b/crates/ecstore/src/disk/disk_store.rs @@ -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) @@ -1263,12 +1263,18 @@ impl DiskHealthTracker { /// Log a successful operation pub fn log_success(&self) { + self.record_success_time(true); + } + + fn record_success_time(&self, drive_progress: bool) { self.last_success.store(current_unix_nanos(), Ordering::Relaxed); - self.completed_ops.fetch_add(1, Ordering::AcqRel); + if drive_progress { + self.completed_ops.fetch_add(1, Ordering::Relaxed); + } } 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 +1379,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) -> Option { 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 +1416,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 +1429,7 @@ impl DiskHealthTracker { reason: &'static str, completed_before: u64, ) -> Option { - 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 +1464,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); @@ -1462,6 +1471,10 @@ impl DiskHealthTracker { } pub fn mark_recovery_success(&self, endpoint: &Endpoint, reason: &'static str) -> bool { + self.recover_after_success(endpoint, reason, true) + } + + fn recover_after_success(&self, endpoint: &Endpoint, reason: &'static str, drive_progress: bool) -> bool { #[cfg(test)] if self.test_forced_offline.load(Ordering::Acquire) { return false; @@ -1492,7 +1505,7 @@ impl DiskHealthTracker { } self.transition_state(endpoint, current, next, reason); if became_online { - self.log_success(); + self.record_success_time(drive_progress); } became_online } @@ -1522,6 +1535,14 @@ impl DiskHealthTracker { } } + pub(crate) fn record_connectivity_success(&self, endpoint: &Endpoint, reason: &'static str) { + if self.runtime_state() == RuntimeDriveHealthState::Online { + self.record_success_time(false); + } else { + self.recover_after_success(endpoint, reason, false); + } + } + fn transition_state( &self, endpoint: &Endpoint, @@ -6926,6 +6947,12 @@ mod tests { let health = DiskHealthTracker::new(); let before = health.completed_ops(); + assert!(!health.mark_failure(&endpoint, "operation_timeout")); + assert_eq!(health.runtime_state(), RuntimeDriveHealthState::Suspect); + health.record_connectivity_success(&endpoint, "connectivity_probe_success"); + assert_eq!(health.runtime_state(), RuntimeDriveHealthState::Online); + assert_eq!(health.completed_ops(), before, "a TCP handshake does not complete drive I/O"); + // Sibling operation completes while a queued operation is waiting. health.record_operation_success(&endpoint, "operation_success"); assert!(health.completed_ops() > before); diff --git a/crates/ecstore/src/set_disk/core/metadata_read.rs b/crates/ecstore/src/set_disk/core/metadata_read.rs index 78e11ef65a..6be0c104c6 100644 --- a/crates/ecstore/src/set_disk/core/metadata_read.rs +++ b/crates/ecstore/src/set_disk/core/metadata_read.rs @@ -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 = 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 = 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, Duration)>, - task_ids: &mut [Option], + tasks: &mut [Option<(tokio::task::Id, u64)>], index: usize, disk: Option| { + 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); diff --git a/crates/io-metrics/src/s3_http_metrics.rs b/crates/io-metrics/src/s3_http_metrics.rs index cb13cd6b1e..d798ab2992 100644 --- a/crates/io-metrics/src/s3_http_metrics.rs +++ b/crates/io-metrics/src/s3_http_metrics.rs @@ -132,6 +132,7 @@ tokio::task_local! { struct RequestScopeState { operation: usize, entry_started: Option, + 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, + 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); } diff --git a/crates/lock/src/distributed_lock.rs b/crates/lock/src/distributed_lock.rs index 983066eab6..ae4f605ada 100644 --- a/crates/lock/src/distributed_lock.rs +++ b/crates/lock/src/distributed_lock.rs @@ -1841,8 +1841,8 @@ impl DistributedLock { ); } - fn log_failed_lock_response(&self, request: &LockRequest, idx: usize, error: String) { - if request.suppress_contention_logs || !should_warn_lock_failure(&error) { + fn log_failed_lock_response(&self, request: &LockRequest, idx: usize, error: &str) { + if request.suppress_contention_logs || !should_warn_lock_failure(error) { tracing::debug!( resource = %request.resource, owner = %request.owner, @@ -1887,13 +1887,11 @@ impl DistributedLock { // A peer may grant promptly but deliver its response after its local // contention budget. Keep this round's owners until a response proves // quorum impossible or the caller's remaining budget expires. - // On Exclusive contention retries (`attempt > 1`), serialize on the - // canonical anchor voter (`clients[0]`) before fanning out to remaining - // voters so N-node local-first split-votes do not livelock across rounds - // while preserving 1-RTT initial fanout and 2s reader-outlast queue time. + // Give the first voter a chance to arbitrate competing writers on retry. + // The normal hedge still covers a silent voter. let serialize_on_anchor = request.lock_type == LockType::Exclusive && attempt > 1; let result = self - .acquire_lock_quorum_once_inner(&attempt_request, remaining, serialize_on_anchor) + .acquire_lock_quorum_once(&attempt_request, remaining, serialize_on_anchor) .await?; if !result.response.success { tracing::trace!( @@ -1980,12 +1978,7 @@ impl DistributedLock { /// Quorum-based lock acquisition: success if at least the required quorum succeeds. /// Collects all individual lock_ids from successful clients and creates an aggregate lock_id. /// Returns the LockResponse with aggregate lock_id and individual lock mappings. - #[cfg_attr(not(test), allow(dead_code))] - async fn acquire_lock_quorum_once(&self, request: &LockRequest, quorum_timeout: Duration) -> Result { - self.acquire_lock_quorum_once_inner(request, quorum_timeout, false).await - } - - async fn acquire_lock_quorum_once_inner( + async fn acquire_lock_quorum_once( &self, request: &LockRequest, quorum_timeout: Duration, @@ -2017,7 +2010,6 @@ impl DistributedLock { let mut last_failure_kind = None; let mut last_hard_failure_kind = None; let mut hard_failures = 0usize; - let mut anchor_definitive_contention = false; let mut retry_at = vec![None; self.clients.len()]; let mut contention_retries = vec![0usize; self.clients.len()]; let start = attempt_started; @@ -2123,11 +2115,20 @@ impl DistributedLock { } } else { let error = resp.error.unwrap_or_else(|| "unknown error".to_string()); + self.log_failed_lock_response(request, idx, &error); // Only an authoritative no-grant response is safe to retry under // the same ID. A successful or still-pending voter is never retried. if is_definitive_lock_contention(&error) { - if idx == 0 { - anchor_definitive_contention = true; + // Before a hedge starts, let the anchor arbitrate contention + // without acquiring partial votes at the remaining peers. + if anchor_serialized && idx == 0 && next_client_index == 1 { + return Ok(LockAcquireQuorumResult { + response: LockResponse::failure(error, resp.wait_time), + individual_locks: Vec::new(), + failure_kind: Some(LockAcquireFailureKind::RetryableContention), + quorum_impossible: false, + attempt_timed_out: false, + }); } contention_retries[idx] = contention_retries[idx].saturating_add(1); let backoff = LOCK_ACQUIRE_RETRY_INITIAL_BACKOFF @@ -2141,7 +2142,6 @@ impl DistributedLock { hard_failures += 1; last_hard_failure_kind = Some(failure_kind); } - self.log_failed_lock_response(request, idx, error.clone()); last_failure = Some(error); last_failure_kind = Some(failure_kind); } @@ -2285,34 +2285,6 @@ impl DistributedLock { }); } - // When serializing a contended Exclusive retry on the healthy anchor voter - // (`clients[0]`), yield immediately only if `clients[0]` rejected due to definitive - // lock contention rather than fanning out and split-voting on `clients[1..]`. If - // `clients[0]` granted (`!round.grants.is_empty()`), returned a timeout/backoff/breaker - // failure (`!anchor_definitive_contention`), failed with an RPC error (`hard_failures > 0`), - // or timed out its silent-prefix hedge (`next_client_index > 1`), fall through and fan out - // normally so offline, degraded, or hung anchor nodes never block quorum. - if anchor_serialized - && anchor_definitive_contention - && round.grants.is_empty() - && hard_failures == 0 - && next_client_index == 1 - && round.pending.is_empty() - { - let mut error = format!("Anchor voter contended: 0/{required_quorum} required"); - if let Some(last_failure) = last_failure { - error.push_str("; last failure: "); - error.push_str(&last_failure); - } - return Ok(LockAcquireQuorumResult { - response: LockResponse::failure(error, Duration::ZERO), - individual_locks: Vec::new(), - failure_kind: Some(LockAcquireFailureKind::RetryableContention), - quorum_impossible: false, - attempt_timed_out: false, - }); - } - let needed = required_quorum.saturating_sub(round.grants.len()); self.spawn_lock_requests_until( &mut round.pending, @@ -3840,6 +3812,61 @@ mod tests { ); } + #[tokio::test(start_paused = true)] + async fn exclusive_retry_skips_unresponsive_anchor_without_skipping_quorum() { + for error in [ + "Remote lock RPC timed out: peer request breaker is open", + "Remote lock RPC timed out: transport deadline exceeded", + ] { + let anchor = Arc::new(SequencedClient::new( + vec![AcquirePlan::Failure { + error, + delay: Duration::ZERO, + }], + Arc::default(), + )); + let clients = std::iter::once(anchor.clone() as Arc) + .chain((0..3).map(|_| Arc::new(SequencedClient::new(Vec::new(), Arc::default())) as Arc)) + .collect(); + let lock = DistributedLock::new("test".to_owned(), clients, 3); + let request = LockRequest::new(ObjectKey::new("bucket", "object"), LockType::Exclusive, "owner") + .with_acquire_timeout(Duration::from_secs(2)); + + let result = lock + .acquire_lock_quorum_once(&request, request.acquire_timeout, true) + .await + .expect("the three remaining peers can form quorum"); + + assert!(result.response.success, "anchor returned {error}: {:?}", result.response.error); + assert_eq!(result.individual_locks.len(), 3); + assert_eq!(anchor.requested_acquires.load(Ordering::SeqCst), 1); + } + } + + #[tokio::test(start_paused = true)] + async fn exclusive_retry_avoids_fanout_after_definitive_anchor_contention() { + let anchor = Arc::new(SequencedClient::new( + vec![AcquirePlan::Failure { + error: "Lock acquisition timeout", + delay: Duration::ZERO, + }], + Arc::default(), + )); + let other = Arc::new(SequencedClient::new(Vec::new(), Arc::default())); + let lock = DistributedLock::new("test".to_owned(), vec![anchor, other.clone()], 2); + let request = LockRequest::new(ObjectKey::new("bucket", "object"), LockType::Exclusive, "owner") + .with_acquire_timeout(Duration::from_secs(2)); + + let result = lock + .acquire_lock_quorum_once(&request, request.acquire_timeout, true) + .await + .expect("the first voter can report definitive contention"); + + assert!(!result.response.success); + assert!(matches!(result.failure_kind, Some(LockAcquireFailureKind::RetryableContention))); + assert_eq!(other.requested_acquires.load(Ordering::SeqCst), 0); + } + fn clients_with_initial_quorum_loss(retries: &[AcquirePlan]) -> Vec> { (0..4) .map(|index| { @@ -4161,7 +4188,7 @@ mod tests { let request = LockRequest::new(ObjectKey::new("bucket", "partial-grants"), LockType::Shared, "owner") .with_acquire_timeout(Duration::from_secs(1)); let result = lock - .acquire_lock_quorum_once(&request, request.acquire_timeout) + .acquire_lock_quorum_once(&request, request.acquire_timeout, false) .await .expect("partial quorum should return a timeout response"); assert!(!result.response.success); @@ -4371,7 +4398,7 @@ mod tests { let request = LockRequest::new(ObjectKey::new("bucket", "object"), LockType::Exclusive, "owner") .with_acquire_timeout(Duration::from_secs(2)); let result = lock - .acquire_lock_quorum_once(&request, request.acquire_timeout) + .acquire_lock_quorum_once(&request, request.acquire_timeout, false) .await .expect("round result"); assert!(!result.response.success); @@ -4393,7 +4420,7 @@ mod tests { .with_acquire_timeout(Duration::from_secs(2)); let started = Instant::now(); let result = lock - .acquire_lock_quorum_once(&request, request.acquire_timeout) + .acquire_lock_quorum_once(&request, request.acquire_timeout, false) .await .expect("round result"); assert!(!result.response.success); @@ -4430,7 +4457,7 @@ mod tests { .with_acquire_timeout(Duration::from_secs(2)); let started = Instant::now(); let result = lock - .acquire_lock_quorum_once(&request, request.acquire_timeout) + .acquire_lock_quorum_once(&request, request.acquire_timeout, false) .await .expect("round result"); assert!(!result.response.success); @@ -4458,7 +4485,7 @@ mod tests { let request = LockRequest::new(ObjectKey::new("bucket", "object"), LockType::Exclusive, "owner") .with_acquire_timeout(Duration::from_secs(1)); let result = lock - .acquire_lock_quorum_once(&request, request.acquire_timeout) + .acquire_lock_quorum_once(&request, request.acquire_timeout, false) .await .expect("round result"); assert!(!result.response.success); @@ -4571,9 +4598,11 @@ mod tests { ); let request = LockRequest::new(ObjectKey::new("bucket", "ready-after-deadline"), LockType::Shared, "owner") .with_acquire_timeout(Duration::from_secs(5)); - let mut attempt = Box::pin(tokio::task::unconstrained( - lock.acquire_lock_quorum_once(&request, request.acquire_timeout), - )); + let mut attempt = Box::pin(tokio::task::unconstrained(lock.acquire_lock_quorum_once( + &request, + request.acquire_timeout, + false, + ))); assert!(matches!(poll!(&mut attempt), Poll::Pending)); tokio::time::timeout(Duration::from_secs(1), async { while clients @@ -5103,155 +5132,4 @@ mod tests { ); drop(results); } - - #[tokio::test] - async fn exclusive_retry_fans_out_to_remaining_voters_when_anchor_times_out_or_breaker_opens() { - #[derive(Debug)] - struct FixedResponseClient { - calls: Arc, - response: LockResponse, - } - - #[async_trait::async_trait] - impl LockClient for FixedResponseClient { - async fn acquire_lock(&self, request: &LockRequest) -> crate::Result { - self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - if self.response.success { - Ok(LockResponse::success( - LockInfo { - id: request.lock_id.clone(), - resource: request.resource.clone(), - lock_type: request.lock_type, - status: crate::LockStatus::Acquired, - owner: request.owner.clone(), - acquired_at: std::time::SystemTime::now(), - expires_at: std::time::SystemTime::now() + request.ttl, - last_refreshed: std::time::SystemTime::now(), - metadata: request.metadata.clone(), - priority: request.priority, - wait_start_time: None, - }, - Duration::ZERO, - )) - } else { - Ok(self.response.clone()) - } - } - - async fn release(&self, _lock_id: &LockId) -> crate::Result { - Ok(true) - } - - async fn refresh(&self, _lock_id: &LockId) -> crate::Result { - Ok(true) - } - - async fn force_release(&self, _lock_id: &LockId) -> crate::Result { - Ok(true) - } - - async fn check_status(&self, _lock_id: &LockId) -> crate::Result> { - Ok(None) - } - - async fn get_stats(&self) -> crate::Result { - Ok(LockStats::default()) - } - - async fn close(&self) -> crate::Result<()> { - Ok(()) - } - - async fn is_online(&self) -> bool { - true - } - - async fn is_local(&self) -> bool { - false - } - } - - for anchor_error in [ - "RPC request backoff active for lock on http://127.0.0.1:9000", - "remote lock RPC lock on http://127.0.0.1:9000 timed out after 1s", - ] { - let c0_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); - let c1_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); - let c2_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); - let c0: Arc = Arc::new(FixedResponseClient { - calls: Arc::clone(&c0_calls), - response: LockResponse::failure(anchor_error, Duration::ZERO), - }); - let grant_template = LockResponse::success( - LockInfo { - id: LockId::new(ObjectKey::new("bucket", "key")), - resource: ObjectKey::new("bucket", "key"), - lock_type: LockType::Exclusive, - status: crate::LockStatus::Acquired, - owner: "owner".to_string(), - acquired_at: std::time::SystemTime::now(), - expires_at: std::time::SystemTime::now() + Duration::from_secs(30), - last_refreshed: std::time::SystemTime::now(), - metadata: Default::default(), - priority: Default::default(), - wait_start_time: None, - }, - Duration::ZERO, - ); - let c1: Arc = Arc::new(FixedResponseClient { - calls: Arc::clone(&c1_calls), - response: grant_template.clone(), - }); - let c2: Arc = Arc::new(FixedResponseClient { - calls: Arc::clone(&c2_calls), - response: grant_template, - }); - - let lock = DistributedLock::new("anchor-breaker-test".to_string(), vec![c0, c1, c2], 2); - let request = LockRequest::new(ObjectKey::new("bucket", "key"), LockType::Exclusive, "owner") - .with_acquire_timeout(Duration::from_millis(500)) - .with_ttl(Duration::from_secs(30)); - - let outcome = lock - .acquire_lock_quorum_once_inner(&request, Duration::from_millis(500), true) - .await - .expect("quorum attempt must complete"); - assert!( - outcome.response.is_success(), - "anchor error `{anchor_error}` must fall through to remaining voters and reach 2/3 quorum" - ); - assert_eq!(c0_calls.load(std::sync::atomic::Ordering::SeqCst), 1); - assert_eq!(c1_calls.load(std::sync::atomic::Ordering::SeqCst), 1); - assert_eq!(c2_calls.load(std::sync::atomic::Ordering::SeqCst), 1); - } - - // Conversely, definitive contention on the anchor must still short-circuit without - // contacting the remaining voters. - let c0_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); - let c1_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); - let c0: Arc = Arc::new(FixedResponseClient { - calls: Arc::clone(&c0_calls), - response: LockResponse::failure("Lock conflict: resource held by other", Duration::ZERO), - }); - let c1: Arc = Arc::new(FixedResponseClient { - calls: Arc::clone(&c1_calls), - response: LockResponse::failure("unused", Duration::ZERO), - }); - let c2: Arc = Arc::new(FixedResponseClient { - calls: Arc::new(std::sync::atomic::AtomicUsize::new(0)), - response: LockResponse::failure("unused", Duration::ZERO), - }); - let lock = DistributedLock::new("anchor-contention-test".to_string(), vec![c0, c1, c2], 2); - let request = LockRequest::new(ObjectKey::new("bucket", "key"), LockType::Exclusive, "owner") - .with_acquire_timeout(Duration::from_millis(500)) - .with_ttl(Duration::from_secs(30)); - let outcome = lock - .acquire_lock_quorum_once_inner(&request, Duration::from_millis(500), true) - .await - .expect("contention attempt must complete"); - assert!(!outcome.response.is_success()); - assert!(matches!(outcome.failure_kind, Some(LockAcquireFailureKind::RetryableContention))); - assert_eq!(c0_calls.load(std::sync::atomic::Ordering::SeqCst), 1); - assert_eq!(c1_calls.load(std::sync::atomic::Ordering::SeqCst), 0); - } } diff --git a/crates/protos/src/channel_reset_tests.rs b/crates/protos/src/channel_reset_tests.rs index 67217d8323..1b6e25c294 100644 --- a/crates/protos/src/channel_reset_tests.rs +++ b/crates/protos/src/channel_reset_tests.rs @@ -102,14 +102,9 @@ async fn accept_peer(listener: TcpListener) -> io::Result { Ok(socket) } -async fn delayed_response_peer( - listener: TcpListener, - ready: mpsc::Sender<()>, - error_resets: Arc, - concurrency_limit: usize, -) -> io::Result<()> { +async fn delayed_response_peer(listener: TcpListener, ready: mpsc::Sender<()>, error_resets: Arc) -> io::Result<()> { let mut socket = accept_peer(listener).await?; - let mut cancelled = Vec::with_capacity(concurrency_limit); + let mut cancelled = Vec::with_capacity(INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT); let mut resets = HashSet::new(); let mut probe = None; loop { @@ -123,9 +118,9 @@ async fn delayed_response_peer( let credit = u32::try_from(frame.payload.len()).expect("bounded DATA frame").to_be_bytes(); write_frame(&mut socket, WINDOW_UPDATE, 0, 0, &credit).await?; } - HEADERS if cancelled.len() < concurrency_limit => { + HEADERS if cancelled.len() < INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT => { cancelled.push(frame.stream); - if cancelled.len() == concurrency_limit { + if cancelled.len() == INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT { ready.send(()).await.map_err(|_| io::Error::other("test driver stopped"))?; } } @@ -145,7 +140,7 @@ async fn delayed_response_peer( _ => {} } if let Some(stream) = probe - && resets.len() == concurrency_limit + && resets.len() == INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT { // A raw peer controls bytes already in flight at cancellation. A normal // server would consume RST_STREAM and suppress these delayed responses. @@ -160,12 +155,12 @@ async fn delayed_response_peer( } } -async fn assert_cancelled_responses_are_ignored(bulk: bool, concurrency_limit: usize) { +async fn assert_cancelled_responses_are_ignored(bulk: bool) { let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind isolated peer"); let address = format!("http://{}", listener.local_addr().expect("peer address")); let (ready_tx, mut ready_rx) = mpsc::channel(1); let error_resets = Arc::new(AtomicUsize::new(0)); - let peer = tokio::spawn(delayed_response_peer(listener, ready_tx, error_resets.clone(), concurrency_limit)); + let peer = tokio::spawn(delayed_response_peer(listener, ready_tx, error_resets.clone())); let cache_key = if bulk { super::bulk_cache_key(&address, 0) } else { @@ -178,7 +173,7 @@ async fn assert_cancelled_responses_are_ignored(bulk: bool, concurrency_limit: u let mut client = node_service::node_service_client::NodeServiceClient::new(channel); for batch in 0..BATCHES { let mut requests = JoinSet::new(); - for _ in 0..concurrency_limit { + for _ in 0..INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT { let mut pending_client = client.clone(); requests.spawn(async move { pending_client.read_version(node_service::ReadVersionRequest::default()).await }); } @@ -208,14 +203,14 @@ async fn assert_cancelled_responses_are_ignored(bulk: bool, concurrency_limit: u #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn cancelled_metadata_responses_keep_the_shared_channel_usable() { - assert_cancelled_responses_are_ignored(false, INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT).await; + assert_cancelled_responses_are_ignored(false).await; } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn cancelled_metadata_responses_keep_the_bulk_channel_usable() { temp_env::async_with_vars( [(rustfs_config::ENV_INTERNODE_BULK_CONCURRENCY_LIMIT, Some("64"))], - assert_cancelled_responses_are_ignored(true, 64), + assert_cancelled_responses_are_ignored(true), ) .await; } diff --git a/crates/protos/src/lib.rs b/crates/protos/src/lib.rs index a2fc8616f6..1cc951293f 100644 --- a/crates/protos/src/lib.rs +++ b/crates/protos/src/lib.rs @@ -3836,7 +3836,7 @@ fn complete_pending_rebuild_on_cache_hit(dial_addr: &str, cache_key: &str) -> bo } // Limits transport response futures; client RPC metrics separately cover unary body decoding. -pub const INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT: usize = 256; +pub const INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT: usize = 64; // Quorum reads cancel surplus metadata RPCs in bursts. Keep bounded reset state // for their in-flight replies through the HTTP/2 grace period without spending @@ -5929,7 +5929,7 @@ mod tests { ); assert_eq!( checked_rpc_window(internode_rpc_http2_stream_window()).expect("control setting"), - Some(rustfs_config::DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE) + Some(1024 * 1024) ); }, ) @@ -6024,20 +6024,17 @@ mod tests { #[tokio::test] async fn get_channel_for_class_bulk_reuses_control_cache_when_isolation_disabled() { let _test_guard = TLS02_TEST_LOCK.lock().await; - temp_env::async_with_vars([(rustfs_config::ENV_INTERNODE_CHANNEL_ISOLATION, Some("false"))], async { - // When isolation is explicitly disabled, a Bulk request must reuse the control channel - // keyed by the bare address and must NOT create a separate bulk-keyed entry. - let addr = "http://get-channel-isolation-off-test"; - let channel = Endpoint::from_static("http://127.0.0.1:1").connect_lazy(); - cache_connection(addr.to_string(), channel).await; + // Isolation defaults off, so a Bulk request must reuse the control channel keyed by the + // bare address and must NOT create a separate bulk-keyed entry (zero behavior change). + let addr = "http://get-channel-isolation-off-test"; + let channel = Endpoint::from_static("http://127.0.0.1:1").connect_lazy(); + cache_connection(addr.to_string(), channel).await; - let acquired = get_channel_for_class(addr, ChannelClass::Bulk).await; - assert!(acquired.is_ok()); - assert!(!rustfs_common::has_cached_connection(&bulk_cache_key(addr, 0)).await); + let acquired = get_channel_for_class(addr, ChannelClass::Bulk).await; + assert!(acquired.is_ok()); + assert!(!rustfs_common::has_cached_connection(&bulk_cache_key(addr, 0)).await); - evict_failed_connection_with_log_level(addr, ConnectionEvictionLogLevel::Debug).await; - }) - .await; + evict_failed_connection_with_log_level(addr, ConnectionEvictionLogLevel::Debug).await; } } diff --git a/crates/rio/src/http_reader.rs b/crates/rio/src/http_reader.rs index 9a2f85e08a..d8643eb7fc 100644 --- a/crates/rio/src/http_reader.rs +++ b/crates/rio/src/http_reader.rs @@ -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 { - 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 { + 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::() { 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::() + .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 { - 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_err.kind() == io::ErrorKind::UnexpectedEof - { - return Some(InternodeHttpErrorKind::ConnectionReset); - } - if let Some(hyper_err) = current.downcast_ref::() - && (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, start_tx: Option>, sender: PollSender>, - handle: tokio::task::JoinHandle>, + handle: Option>>, pending_chunk: BytesMut, pending_reservation: Option>, memory_reserver: Option, @@ -1590,7 +1583,6 @@ impl HttpWriter { let internode_operation = internode_rpc_operation(&url); let (sender, receiver) = tokio::sync::mpsc::channel::>(HTTP_WRITER_CHANNEL_CAPACITY); - let (err_tx, err_rx) = tokio::sync::oneshot::channel::(); 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(err: tokio_util::sync::PollSendError, context: &str) -> io::Error { - Error::other(format!("{context}: {err}")) -} - -fn send_error_to_io(err: tokio_util::sync::PollSendError, 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> { + 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(&mut self, cx: &mut Context<'_>) -> Poll> { + // 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> { @@ -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> { 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> { - // 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> { + 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> { + 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::()) + .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::()) @@ -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); diff --git a/rustfs/src/error.rs b/rustfs/src/error.rs index 80e9740153..ea09d23ad5 100644 --- a/rustfs/src/error.rs +++ b/rustfs/src/error.rs @@ -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() { 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() { + inside_internode_http_error = true; + rpc_unavailable |= is_unavailable_internode_http_error(internode_error); + } upload_limit_exceeded |= error.is::(); server_source_failed |= error.is::(); client_body_timed_out |= error.is::(); body_size_exceeded |= error.is::(); - incomplete_body |= error.is::() || is_hyper_body_eof(error); + // A Hyper EOF beneath a peer HTTP failure describes the shard exchange. + incomplete_body |= error.is::() || (!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( +pub(crate) fn error_chain_find( err: &(dyn std::error::Error + 'static), mut classify: impl FnMut(&(dyn std::error::Error + 'static)) -> Option, ) -> Option { @@ -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::() && 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 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::() { 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 for ApiError { source: Some(Box::new(err)), }; } - - if error_chain_find(inner, |cause| { - cause - .downcast_ref::() - .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] diff --git a/rustfs/src/server/gateway_handlers/error.rs b/rustfs/src/server/gateway_handlers/error.rs index d605163d15..9f8ba8c0fe 100644 --- a/rustfs/src/server/gateway_handlers/error.rs +++ b/rustfs/src/server/gateway_handlers/error.rs @@ -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>; -} - -/// 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(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 } diff --git a/rustfs/src/server/gateway_handlers/mod.rs b/rustfs/src/server/gateway_handlers/mod.rs index cc4d261a9d..c3edebac46 100644 --- a/rustfs/src/server/gateway_handlers/mod.rs +++ b/rustfs/src/server/gateway_handlers/mod.rs @@ -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}; diff --git a/rustfs/src/server/gateway_stack.rs b/rustfs/src/server/gateway_stack.rs index ba4692f142..aafd6386e3 100644 --- a/rustfs/src/server/gateway_stack.rs +++ b/rustfs/src/server/gateway_stack.rs @@ -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(); } diff --git a/rustfs/src/server/health.rs b/rustfs/src/server/health.rs index eed21009ab..b2d59e91ed 100644 --- a/rustfs/src/server/health.rs +++ b/rustfs/src/server/health.rs @@ -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); - }); - } } diff --git a/rustfs/src/server/layer.rs b/rustfs/src/server/layer.rs index 4d3ab14866..0b91be0b7c 100644 --- a/rustfs/src/server/layer.rs +++ b/rustfs/src/server/layer.rs @@ -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::() + .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) -> 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::::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"]) @@ -2971,37 +3031,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::::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::::from(Bytes::new())) - .expect("cluster write request"), - ) - .await - .expect("cluster write response"); - assert_eq!(response.status(), StatusCode::OK); - let response = service .call( Request::builder() @@ -3024,6 +3053,32 @@ pub(in crate::server) mod tests { assert_eq!(calls.load(Ordering::SeqCst), 0); 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, stalled) in [ + (MINIO_HEALTH_CLUSTER_READ_PATH, read_stall.is_some()), + (MINIO_HEALTH_CLUSTER_PATH, write_stall.is_some()), + ] { + let response = service + .call( + Request::builder() + .method(Method::HEAD) + .uri(path) + .body(Full::::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 response = service .call( Request::builder() diff --git a/rustfs/src/server/readiness.rs b/rustfs/src/server/readiness.rs index 9274b94599..3e615d5979 100644 --- a/rustfs/src/server/readiness.rs +++ b/rustfs/src/server/readiness.rs @@ -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; /// 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 { 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 "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}"), diff --git a/rustfs/src/storage/rpc/http_service.rs b/rustfs/src/storage/rpc/http_service.rs index c8f5f4ff06..9ab0bfefd1 100644 --- a/rustfs/src/storage/rpc/http_service.rs +++ b/rustfs/src/storage/rpc/http_service.rs @@ -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::(), 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, 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, 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, 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) -> io::Error { + io::Error::other(PutFileBodyError::Receive(error.into())) +} + async fn write_body_chunks_to_writer(body: S, writer: &mut W) -> io::Result where S: futures::TryStream + 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::() - && 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::() { + return Some(StatusCode::BAD_REQUEST); + } + if matches!( + cause.downcast_ref::(), + 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::() - && 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_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::() + .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 { + 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::(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 {