Files
rustfs/crates/io-metrics/src/collector.rs
T
houseme 1553dc3f62 Address P2 follow-ups from the 2026-07-10..12 merged-PR review (backlog#1210-1220) (#4783)
* fix(obs): open cleaner compression source with O_NOFOLLOW

The compressor opened the source log via File::open, which follows a
symlink at the final path component. Between the scanner selecting a
regular file and this open, an attacker with write access to the log
directory could swap the entry for a symlink (TOCTOU) pointing at, say,
/etc/shadow, whose contents would then be copied into an archive. Open
the source with O_NOFOLLOW on Unix so such a swap fails with ELOOP; the
temp/archive path already refused symlinks, this closes the source side.

Refs rustfs/backlog#1210
Co-Authored-By: heihutu <heihutu@gmail.com>

* fix(obs): recompress instead of trusting leftover cleaner archives

archive_header_ok only checked the first 2-4 magic bytes before treating
an existing .gz/.zst as a completed prior result and letting the caller
delete the source log. A file with valid magic but a truncated or forged
body passes that check, so an attacker with write access to the log
directory (or a crashed prior run) could plant such a stub and make the
cleaner delete the real log without ever producing a usable archive —
silent audit-data loss.

Chosen fix: stop trusting cross-process leftovers entirely and always
recompress the source in this pass, rather than fully decoding every
leftover to validate it. Full-decode validation would add real CPU cost
and decode-bug surface for a rare crash-recovery case; the existing
atomic create_new+rename already overwrites whatever sits at the archive
path (a planted symlink is replaced, never followed) with a freshly
written, fsync'd archive, so a partial/forged leftover can never gate
source deletion. This is the lowest-regression option.

Refs rustfs/backlog#1211
Co-Authored-By: heihutu <heihutu@gmail.com>

* fix(object-data-cache): cap memory-gate reservation at cache growth headroom

The memory gate subtracts `admitted_since_refresh` from the snapshot's
available bytes so a burst arriving faster than the 5 s refresh cannot
over-allocate. That counter is GROSS: it only rolls over on the refresh and
never rolls back when a fill is later evicted, cancelled, or loses the
invalidation race. Under sustained high-throughput churn (net footprint flat
and far below `max_capacity`) the raw counter balloons past the memory the
cache actually holds, so `effective_available` collapses and the gate reports
false memory pressure — skipping the hottest fills with SkippedMemoryPressure
until the next 5 s refresh. This only lowers hit rate; it never returns wrong
data and self-heals each refresh.

Fix direction 1 (minimal regression): cap the reservation deduction at the
cache's own growth headroom (`max_capacity - weighted_size()`) instead of
letting the unbounded gross counter shrink the system-available budget. The
cache can never hold more than `max_capacity`, so a burst adds at most that
headroom of real memory before moka evicts to stay bounded (net-zero churn
beyond that point) — capping the deduction there keeps the reservation honest
without treating gross churn as growth. Chosen over net-accounting (direction
2, releasing bytes on every failure/cancel/eviction path) because that only
plugs the leak on failed fills and would not address the core defect: churn of
*successful* insert/evict fills over the 5 s window. It also touches only the
gate plus one call site rather than every failure path in moka_backend.

The cap only ever raises `effective_available`, so real memory pressure (a low
snapshot at refresh) still suppresses fills; when the cache is at capacity the
headroom is 0 and the deduction vanishes, correctly reflecting net-zero churn.
`MokaBackend` now stores `max_capacity` and passes the live headroom into
`allows_fill`. Adds targeted gate tests: gross churn far above headroom no
longer falsely suppresses, yet the reservation still bounds a burst while the
cache can genuinely grow.

Refs rustfs/backlog#1212
Co-Authored-By: heihutu <heihutu@gmail.com>

* test(ecstore): assert native O_DIRECT path runs in uring read test

uring_preserves_o_direct_for_eligible_reads only compared bytes through
LocalDisk::read_file_mmap_copy. On a filesystem that rejects O_DIRECT the
read silently degrades to the buffered StdBackend fallback and the byte
check still passes, so the test could go green without the native
read_at_direct path ever executing -- a vacuous pass.

Add a per-disk native_direct_reads counter on UringBackend, incremented
only when pread_uring_direct completes, and rebuild the test to drive a
real UringBackend's pread_bytes and assert the counter is non-zero (every
eligible read went through the native tier). When io_uring or O_DIRECT is
unavailable on the host filesystem (restricted CI runners, tmpfs), the
test skips loudly via eprintln instead of asserting a tautology, while
still checking byte-correctness on whatever tier served the read.

The counter also gives a gray release a positive signal that the O_DIRECT
tier is serving reads, not just a fallback count.

Refs rustfs/backlog#1213
Co-Authored-By: heihutu <heihutu@gmail.com>

* fix(ecstore): warn + count read-time EINVAL on native O_DIRECT reads

classify_direct_read_error is only reached from the read side: the
O_DIRECT open in pread_uring_direct already succeeded (an open-time
refusal is handled earlier as DirectOpenError::ODirectRefused). So an
EINVAL/EOPNOTSUPP arriving here is a read-time error on an fd the kernel
accepted for O_DIRECT -- far more likely an alignment bug in the aligned
read path than an unsupported filesystem. The old code latched the disk's
native path off with only a once-per-disk debug trace, hiding a potential
correctness regression behind a silent buffered-read downgrade.

Diagnostics only: the fallback behaviour is unchanged (the native path is
still latched off and the caller still reads via StdBackend). This adds a
rustfs_io_uring_direct_read_einval_total counter and promotes the
once-per-disk trace from debug to warn so an operator can see an alignment
regression instead of an unexplained latency/CPU shift.

Refs rustfs/backlog#1214
Co-Authored-By: heihutu <heihutu@gmail.com>

* docs(ecstore): document data-blocks-first default and its tail-latency cost

DEFAULT_RUSTFS_GET_DATA_BLOCKS_FIRST_READER_SETUP is true and must stay
true: deferred-parity is the deliberate, already-rolled-out full-object
GET default from backlog#1159/#923. Flipping it back to false in code
would silently revert that rollout for every deployment that has not set
the env var, so this commit only documents -- no behaviour change.

The added notes explain what data-blocks-first does (schedule data shards
up front, engage parity lazily on a missing/corrupt data shard), the known
trade-off (parity is engaged late, so a slow-but-not-dead data drive
raises GET p99 because the faster parity shards are not raced against it
until a data shard is declared missing), and the operational rollback
switch (RUSTFS_GET_DATA_BLOCKS_FIRST_READER_SETUP=false), which is
intentionally an env override rather than a code default change.

No metric was added: the low-risk observability hook for "slow data drive
engaged deferred parity" would live at the deferred-stripe engage point,
which is out of this file's scope; this change stays documentation-only to
avoid touching the hot GET path.

Refs rustfs/backlog#1215
Co-Authored-By: heihutu <heihutu@gmail.com>

* docs(ecstore): document wide-directory walk stall hazard and tuning

list_dir enumerates a whole directory in one os::read_dir call (count =
-1), and the walk caller bounds that entire enumeration with the per-read
stall budget (default 5s) as if it were a single read. For a wide, flat
prefix -- one directory holding millions of immediate children -- a single
readdir can exceed the budget on a healthy disk, trip DiskError::Timeout,
and surface as a ListObjects 500 quorum failure though the drive is fine
(a #2999 sub-class).

This is documented, not rewritten: turning the one-shot readdir into a
streaming/batched enumeration that refreshes the stall deadline between
chunks is an architecture-level change with high regression surface
(ordering, the count contract, quorum merge) and belongs in a separate
follow-up. The supported mitigation today is operational, so the comments
point wide-directory deployments at RUSTFS_DRIVE_WALKDIR_STALL_TIMEOUT_SECS
and the high-latency drive-timeout profile, which widen the budget with no
code change. Notes were added at list_dir, the scan_dir call site, and
get_drive_walkdir_stall_timeout. No behaviour change.

Refs rustfs/backlog#1216
Co-Authored-By: heihutu <heihutu@gmail.com>

* docs(ecstore): document consumer-peek vs producer-stall coupling

In list_path_raw the consumer's peek_timeout is drawn from the same source
and same value (walkdir_stall_timeout, default 5s) as the producer-side
walk stall budget, but the two measure different things: the producer
stall bounds a single drive read, while the consumer peek bounds the gap
between two ADJACENT entries arriving from a reader. Because they share a
value, the consumer cannot wait meaningfully longer for the next entry
than the producer is allowed to spend producing one. Walking a region
dense with non-listable internal items can make a HEALTHY drive miss the
budget between visible entries; the consumer then declares it stalled and
detaches it, dropping a good drive from the merge and capping the "large
prefix succeeds" guarantee.

Documented, not decoupled: giving the consumer peek an independent,
strictly-larger budget would cut these false detaches but equally delays
detaching a genuinely dead drive and shifts listing tail-latency
semantics, so it wants soak data before changing the default. The comment
records the invariant any such follow-up must keep -- consumer peek >=
producer stall, never stricter -- so it can never fail a drive before the
producer would. No behaviour change.

Refs rustfs/backlog#1217
Co-Authored-By: heihutu <heihutu@gmail.com>

* fix(io-metrics): add time-based trigger for low-IOPS latency percentiles

Percentiles were recomputed only every 128 IOs and seeded to 0, so a
low-traffic deployment exported p95/p99 = 0/stale for a long time after
startup. Add a 10s wall-clock trigger alongside the count throttle so the
first recompute can fire before 128 samples accrue. Hot-path per-op mean
update is unchanged.

Refs rustfs/backlog#1218
Co-Authored-By: heihutu <heihutu@gmail.com>

* test(e2e): cover codec-streaming parity under fault injection and NoSuchKey

The codec-streaming compat A/B previously ran only against a healthy
4-disk EC set with successful full GETs: the DiskFaultHarness was
constructed but never faulted, the error path was untested, and the
range assertion silently compared legacy-vs-legacy (ranges always fall
back to the duplex path), overstating what it proved.

Add two genuinely-failable scenarios reusing the existing harness and
fixtures:

- Parity reconstruction A/B: take one data disk offline and re-run the
  full object matrix on both phases while the EC 2+2 set rebuilds each
  large object from the surviving shards. Assert codec == legacy
  byte-for-byte (sha256) and header-for-header, and assert the codec
  phase served the reconstructed objects with zero duplex-pipe fallback
  (the reader gate is drive-health-independent, so the codec fast path
  is really exercised through reconstruction).
- NoSuchKey negative path: compare the HTTP status + S3 error code of a
  missing-key GET across the legacy and codec phases and require them to
  be identical (404/NoSuchKey), guarding against the codec env
  perturbing the error path.

Also clarify the range-phase comment so it is not misread as
codec-range correctness coverage: both sides are served by the same
legacy range path, so the assertion only proves ranges keep working and
keep falling back to legacy with the gates open.

Verified: cargo check/--no-run pass and the test passes locally
(1 passed; dup_codec=0 confirms the codec path ran).

Refs rustfs/backlog#1219
Co-Authored-By: heihutu <heihutu@gmail.com>

* ci(ecstore): exercise native O_DIRECT read path on an ext4 loopback

The uring-integration leg ran on the runner's default TMPDIR, which may sit
on tmpfs/overlayfs where open(O_DIRECT) fails and the native read_at_direct
path silently latches off to the aligned StdBackend fallback. Mount a
dedicated ext4 loopback and point TMPDIR at it so the real io_uring dep
(bumped git->0.1.0->0.2.0->0.2.1) and the native O_DIRECT read path are
actually covered rather than validated only by signature diffing.

Refs rustfs/backlog#1220
Co-Authored-By: heihutu <heihutu@gmail.com>

---------

Co-authored-by: heihutu <heihutu@gmail.com>
2026-07-12 16:03:28 +00:00

362 lines
15 KiB
Rust

// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Metrics collector for I/O operation tracking and latency analysis.
//!
//! Provides latency percentile calculation (P50, P95, P99) and automatic
//! reporting to the `metrics` crate for OTEL export.
use super::performance::PerformanceMetrics;
use std::collections::VecDeque;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::{Duration, Instant};
use tokio::sync::RwLock;
/// How many recorded operations elapse between P95/P99 recomputations.
///
/// The sliding-window mean (`avg`) is refreshed on every operation — it is O(1)
/// and the autotuner reads it — but the percentiles need an O(n log n) sort of
/// the window, so they are recomputed at most once per this many operations.
/// Both consumers (the autotuner tick and OTEL export) sample on their own
/// periodic cadence, never per-IO, so a bounded lag here is invisible to them
/// while the per-op sort cost is amortised away.
const PERCENTILE_RECOMPUTE_INTERVAL: u32 = 128;
/// Maximum wall-clock staleness of the P95/P99 percentiles before a recompute is
/// forced regardless of the operation count.
///
/// The count throttle alone starves low-IOPS deployments: at a few operations
/// per minute it can take hours to accumulate `PERCENTILE_RECOMPUTE_INTERVAL`
/// samples, during which the exported p95/p99 stay pinned at their initial `0`
/// (or a long-stale value). This time bound guarantees the percentiles refresh
/// within a bounded delay even under trickle traffic, while leaving the hot,
/// high-IOPS path governed by the cheaper count throttle.
const PERCENTILE_RECOMPUTE_MAX_INTERVAL: Duration = Duration::from_secs(10);
/// Sliding window of I/O latency samples plus a running sum, so the window mean
/// is maintained in O(1) as samples enter and leave.
struct LatencyWindow {
samples: VecDeque<Duration>,
/// Sum of `samples` in microseconds, kept in step with every push/pop.
sum_micros: u128,
/// When the P95/P99 percentiles were last recomputed, used to force a
/// refresh under low-traffic conditions where the count throttle rarely
/// fires. Seeded at construction so the first time-based refresh is measured
/// from collector start, not from an absent prior recompute.
last_percentile_at: Instant,
}
/// Metrics collector for tracking I/O operations and computing latency percentiles.
///
/// Maintains a sliding window of I/O latency samples and updates P95/P99 metrics.
/// Automatically reports to the `metrics` crate for OTEL export.
pub struct MetricsCollector {
/// The underlying metrics (shared reference)
metrics: Arc<PerformanceMetrics>,
/// Sliding window of I/O latency samples (+ running sum) for mean/percentile calculation
io_latency: RwLock<LatencyWindow>,
/// Maximum number of latency samples to keep
max_latency_samples: usize,
/// Operations recorded since the last P95/P99 recompute (throttle counter).
ops_since_percentile: AtomicU32,
}
impl MetricsCollector {
/// Create a new metrics collector.
///
/// # Arguments
///
/// * `metrics` - The underlying metrics structure to update
/// * `max_latency_samples` - Maximum number of latency samples to keep for percentile calculation
pub fn new(metrics: Arc<PerformanceMetrics>, max_latency_samples: usize) -> Self {
Self {
metrics,
io_latency: RwLock::new(LatencyWindow {
samples: VecDeque::new(),
sum_micros: 0,
last_percentile_at: Instant::now(),
}),
max_latency_samples,
ops_since_percentile: AtomicU32::new(0),
}
}
/// Create a new metrics collector with default settings (1000 max samples).
pub fn with_default_max_samples(metrics: Arc<PerformanceMetrics>) -> Self {
Self::new(metrics, 1000)
}
/// Record an I/O operation with its duration.
///
/// This method:
/// 1. Updates byte counters in PerformanceMetrics
/// 2. Updates operation counters in PerformanceMetrics
/// 3. Records latency for P95/P99 calculation
/// 4. Reports to the `metrics` crate for OTEL export
///
/// # Arguments
///
/// * `bytes` - Number of bytes transferred
/// * `duration` - Duration of the I/O operation
/// * `is_read` - true for read operations, false for writes
pub async fn record_io_operation(&self, bytes: u64, duration: Duration, is_read: bool) {
// Update byte counters in PerformanceMetrics
if is_read {
self.metrics.record_bytes_read(bytes);
} else {
self.metrics.record_bytes_written(bytes);
}
// Update operation counters in PerformanceMetrics
if is_read {
self.metrics.record_disk_read();
} else {
self.metrics.record_disk_write();
}
// Report to metrics crate for OTEL export
crate::record_data_transfer(bytes, duration.as_millis() as f64);
// Update the sliding window and the O(1) running mean under a short write
// lock, and decide — still under the lock, so the count is exact — whether
// this op crosses the percentile-recompute throttle.
let (mean_us, recompute_percentiles) = {
let mut window = self.io_latency.write().await;
window.samples.push_back(duration);
window.sum_micros += duration.as_micros();
// Keep only the most recent samples (O(1) removal from front).
if window.samples.len() > self.max_latency_samples
&& let Some(old) = window.samples.pop_front()
{
window.sum_micros -= old.as_micros();
}
let len = window.samples.len() as u128;
let mean_us = window.sum_micros.checked_div(len).unwrap_or(0) as u64;
// Two independent recompute triggers, both evaluated under the lock so
// the counter and the timestamp stay consistent:
// * count: cheap amortisation for the hot, high-IOPS path;
// * time: a staleness ceiling so low-IOPS deployments do not export
// an initial/stale 0 for p95/p99 while samples trickle in.
// We just pushed a sample, so the window is guaranteed non-empty and a
// time-forced recompute always has data to sort — including the first
// one, which can fire with far fewer than INTERVAL samples.
let now = Instant::now();
let n = self.ops_since_percentile.fetch_add(1, Ordering::Relaxed) + 1;
let count_due = n >= PERCENTILE_RECOMPUTE_INTERVAL;
let time_due = now.duration_since(window.last_percentile_at) >= PERCENTILE_RECOMPUTE_MAX_INTERVAL;
let recompute = count_due || time_due;
if recompute {
self.ops_since_percentile.store(0, Ordering::Relaxed);
window.last_percentile_at = now;
}
(mean_us, recompute)
};
// The mean is cheap and the autotuner reads it, so refresh it every op.
self.metrics.avg_io_latency_us.store(mean_us, Ordering::Relaxed);
crate::record_io_latency(mean_us as f64 / 1000.0); // Convert to ms
// The P95/P99 sort is the expensive part and only feeds OTEL export, so it
// is throttled to once per PERCENTILE_RECOMPUTE_INTERVAL operations.
if recompute_percentiles {
self.update_latency_percentiles().await;
}
}
/// Recompute the P95/P99 latency percentiles from the current window.
///
/// This sorts a snapshot of the window (O(n log n)), so it is driven on a
/// throttle from the record path rather than per operation. The mean is not
/// computed here — it is maintained in O(1) on every `record_io_operation`.
async fn update_latency_percentiles(&self) {
// Snapshot the window micros under a read lock, then sort outside the lock.
let mut sorted: Vec<u128> = {
let window = self.io_latency.read().await;
if window.samples.is_empty() {
return;
}
window.samples.iter().map(|d| d.as_micros()).collect()
};
sorted.sort_unstable();
let len = sorted.len();
// Calculate P95
let p95_idx = ((len as f64) * 0.95) as usize;
if let Some(&p95) = sorted.get(p95_idx.min(len - 1)) {
self.metrics.p95_io_latency_us.store(p95 as u64, Ordering::Relaxed);
crate::record_io_latency_p95(p95 as f64 / 1000.0);
}
// Calculate P99
let p99_idx = ((len as f64) * 0.99) as usize;
if let Some(&p99) = sorted.get(p99_idx.min(len - 1)) {
self.metrics.p99_io_latency_us.store(p99 as u64, Ordering::Relaxed);
crate::record_io_latency_p99(p99 as f64 / 1000.0);
}
}
/// Get the number of recorded latency samples.
pub async fn sample_count(&self) -> usize {
self.io_latency.read().await.samples.len()
}
/// Get the maximum number of samples this collector will retain.
pub fn max_samples(&self) -> usize {
self.max_latency_samples
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_collector_creation() {
let metrics = Arc::new(PerformanceMetrics::new());
let collector = MetricsCollector::with_default_max_samples(metrics);
assert_eq!(collector.max_samples(), 1000);
}
#[tokio::test]
async fn test_record_io_basic() {
let metrics = Arc::new(PerformanceMetrics::new());
let collector = MetricsCollector::new(metrics.clone(), 10);
collector.record_io_operation(1024, Duration::from_millis(10), true).await;
assert_eq!(metrics.total_bytes_read.load(Ordering::Relaxed), 1024);
assert_eq!(metrics.disk_read_count.load(Ordering::Relaxed), 1);
assert_eq!(collector.sample_count().await, 1);
}
#[tokio::test]
async fn test_latency_percentiles() {
let metrics = Arc::new(PerformanceMetrics::new());
let collector = MetricsCollector::new(metrics.clone(), 10);
// Record some latencies
collector.record_io_operation(0, Duration::from_micros(100), true).await;
collector.record_io_operation(0, Duration::from_micros(200), true).await;
collector.record_io_operation(0, Duration::from_micros(300), true).await;
collector.record_io_operation(0, Duration::from_micros(400), true).await;
collector.record_io_operation(0, Duration::from_micros(500), true).await;
// The mean is refreshed on every op.
let avg = metrics.avg_io_latency_us.load(Ordering::Relaxed);
assert_eq!(avg, 300); // (100+200+300+400+500) / 5
// P95/P99 are throttled off the record path; force a recompute to exercise
// the percentile math directly.
collector.update_latency_percentiles().await;
let p95 = metrics.p95_io_latency_us.load(Ordering::Relaxed);
let p99 = metrics.p99_io_latency_us.load(Ordering::Relaxed);
// P95 should be close to 500 (5th element)
// P99 should be 500 (same as max)
assert!(p95 >= 400); // Allow some tolerance
assert_eq!(p99, 500);
}
#[tokio::test]
async fn test_percentiles_throttled_but_mean_updates_per_op() {
let metrics = Arc::new(PerformanceMetrics::new());
let collector = MetricsCollector::new(metrics.clone(), 1000);
// Fewer ops than the recompute interval: the mean tracks every op, but the
// percentiles must not have been recomputed yet (they stay at their init 0).
for _ in 0..(PERCENTILE_RECOMPUTE_INTERVAL - 1) {
collector.record_io_operation(0, Duration::from_micros(200), true).await;
}
assert_eq!(metrics.avg_io_latency_us.load(Ordering::Relaxed), 200);
assert_eq!(
metrics.p99_io_latency_us.load(Ordering::Relaxed),
0,
"percentiles must not be recomputed before the throttle interval"
);
// The op that crosses the interval triggers exactly one recompute.
collector.record_io_operation(0, Duration::from_micros(200), true).await;
assert_eq!(metrics.p99_io_latency_us.load(Ordering::Relaxed), 200);
}
#[tokio::test]
async fn low_frequency_percentiles_recompute_on_time() {
let metrics = Arc::new(PerformanceMetrics::new());
let collector = MetricsCollector::new(metrics.clone(), 1000);
// Only a handful of ops — far below PERCENTILE_RECOMPUTE_INTERVAL — so the
// count throttle alone would never fire and p99 would stay pinned at its
// initial 0 (the low-IOPS staleness bug).
for _ in 0..5 {
collector.record_io_operation(0, Duration::from_micros(200), true).await;
}
assert_eq!(
metrics.p99_io_latency_us.load(Ordering::Relaxed),
0,
"count throttle alone must not have recomputed yet"
);
// Simulate enough wall-clock time elapsing since the last recompute by
// backdating the timestamp past the staleness ceiling.
{
let mut window = collector.io_latency.write().await;
window.last_percentile_at = Instant::now()
.checked_sub(PERCENTILE_RECOMPUTE_MAX_INTERVAL + Duration::from_secs(1))
.expect("monotonic clock has enough history to backdate");
}
// The next op must force a time-based recompute even though the sample
// count is still far below the interval — so p99 is no longer stuck at 0.
collector.record_io_operation(0, Duration::from_micros(200), true).await;
assert_eq!(
metrics.p99_io_latency_us.load(Ordering::Relaxed),
200,
"time-based trigger must refresh p99 on low-traffic deployments"
);
}
#[tokio::test]
async fn test_sample_limit() {
let metrics = Arc::new(PerformanceMetrics::new());
let collector = MetricsCollector::new(metrics.clone(), 5); // Max 5 samples
// Record more than the limit
for _ in 0..10 {
collector.record_io_operation(0, Duration::from_millis(1), true).await;
}
// Should only keep 5 samples
assert_eq!(collector.sample_count().await, 5);
}
#[tokio::test]
async fn test_read_write_distinction() {
let metrics = Arc::new(PerformanceMetrics::new());
let collector = MetricsCollector::new(metrics.clone(), 10);
collector.record_io_operation(1024, Duration::from_millis(10), true).await;
collector.record_io_operation(2048, Duration::from_millis(5), false).await;
assert_eq!(metrics.total_bytes_read.load(Ordering::Relaxed), 1024);
assert_eq!(metrics.total_bytes_written.load(Ordering::Relaxed), 2048);
assert_eq!(metrics.disk_read_count.load(Ordering::Relaxed), 1);
assert_eq!(metrics.disk_write_count.load(Ordering::Relaxed), 1);
}
}