mirror of
https://github.com/rustfs/rustfs.git
synced 2026-08-05 12:57:42 +00:00
b604074217
* fix(object-data-cache): make cache metrics one-increment-per-GET
Rework the object data cache observability so each counter carries one
clear meaning, and drop dead per-entry state.
ODC-17 (backlog#1122): split requests_total, which was incremented by
both plan_get and lookup_body, into plan_total{decision,reason,size_class}
(emitted only by plan_get) and lookup_total{result,size_class} (emitted
only by lookup_body). Each is now incremented exactly once per GET per
layer; help text states this.
ODC-18 (backlog#1123): add a JoinedInflightFill result (label
joined_inflight) so a singleflight waiter is no longer counted as an
insert. record_fill_result now always counts the outcome but records
fill bytes only when non-zero and the duration histogram only when
present, so joined_inflight / skipped_by_mode / skipped_size_mismatch
no longer inflate fill_bytes_total or add non-fill duration samples.
The waiter->JoinedInflightFill mapping lives in MokaBackend (owned by a
concurrent branch); cache.rs handles the variant already.
ODC-29 (backlog#1134): stop refreshing the cache-state gauge on every
lookup, and debounce it on fill/invalidate to at most once per second
via an AtomicU64 millis timestamp, since moka's entry_count is a
settling approximation.
ODC-36 (backlog#1141): give invalidations_total an outcome label
(removed|noop) and skip the gauge refresh on the no-op path. Extend
ObjectDataCacheInvalidationResult with Removed{keys}/NoOp (Success kept
as a transitional variant until MokaBackend reports the removal count);
NoopBackend now reports NoOp.
ODC-30 (backlog#1141): drop the dead content_length/etag/inserted_at
fields (and getters) from ObjectDataCacheEntry, which are redundant with
the moka key identity; the constructor keeps its arity so the
out-of-scope MokaBackend caller still compiles. Gate is_null_version
behind cfg(test).
Tests use a thread-local metrics recorder to avoid the global-singleton
flakiness. Fill-enabled test configs set min_free_memory_percent=0 so
the cgroup gate does not refuse fills in CI pods.
Co-Authored-By: heihutu <heihutu@gmail.com>
* fix(object-data-cache): move fill off GET path, bound & harden the fill
Implements five object-data-cache audit findings.
ODC-15 (backlog#1120): the GET response no longer blocks on cache fill.
The buffered/materialized body is already in hand, so the fill now runs
in a detached task and the response is built immediately. Singleflight is
made non-blocking: `try_acquire` returns Leader or Busy, and a non-leader
skips its own fill (SkippedSingleflightBusy) instead of waiting on another
request's leader. The inner fill spawn is KEPT: once the index key is
registered, the recheck/undo must complete even if the enclosing fill
future is aborted, so removing it would weaken the cancellation-safety
guarantee (ODC-13 test) and the invalidation-race undo.
ODC-11 (backlog#1116): enforce the fill-concurrency knobs. MokaBackend
now holds a Semaphore sized min(per_cpu * parallelism, max), acquired
after winning leadership and before the memory gate. On saturation it
rejects (try_acquire_owned) with SkippedFillConcurrency rather than
queueing, so the fill path never reintroduces GET-latency coupling.
ODC-14 (backlog#1119): the memory gate no longer does a blocking sysinfo
refresh under a mutex on the async fill path. A dedicated periodic
refresher (tokio interval + spawn_blocking) updates an atomic snapshot
every 5s; allows_fill is now lock-free. The min_free_memory_percent == 0
short-circuit still runs before any snapshot read. No runtime at
construction (sync unit tests) simply keeps the seed snapshot.
ODC-32 (backlog#1137): singleflight no longer emits metrics while holding
the map mutex. try_acquire/remove_entry capture the map length under the
guard, drop it, then emit the gauge/counter.
ODC-07 (backlog#1112): the materialize read is bounded via
take(capacity + 1) so an over-long stream cannot grow the buffer past the
in-memory GET threshold, and any length mismatch is now a hard error
matching the direct-memory GET path, instead of warn-and-serve.
cache.rs is owned by a concurrent branch; this commit only appends the
SkippedFillConcurrency and SkippedSingleflightBusy variants + label arms.
Co-Authored-By: heihutu <heihutu@gmail.com>
* fix(object-data-cache): report JoinedInflightFill and invalidation outcome
Reconciles the moka_backend half of two metrics-semantics findings after
merging fix/odc-metrics-semantics (which landed the cache.rs half).
ODC-18 (backlog#1123): the singleflight non-leader path now returns
JoinedInflightFill instead of counting as an insert, so N concurrent GETs
of one cold key record one insert, not N. This composes with the ODC-15
redesign: the non-leader does NOT wait for the leader (it already owns the
body and never re-serves from the fill result), so no blocking wait is
reintroduced. Drops the redundant local SkippedSingleflightBusy variant in
favor of the canonical JoinedInflightFill (mapped to no bytes / no duration
by the facade). SkippedFillConcurrency (ODC-11) is retained.
ODC-36 (backlog#1141): MokaBackend::invalidate_object now returns
Removed { keys } / NoOp instead of the transitional Success, so the facade
labels invalidations_total{outcome=removed|noop} and skips the cache-state
gauge refresh on the no-op path.
Tests: duplicate-fill test asserts JoinedInflightFill (bites when reverted
to Inserted); new no-op invalidation test; matching-identity test asserts
Removed { keys: 1 }.
Co-Authored-By: heihutu <heihutu@gmail.com>
* fix(object-data-cache): drop unused mut on materialize stream binding
The ODC-07 change moves `final_stream` into `AsyncReadExt::take`, so the
`build_get_object_body_with_cache` parameter is no longer mutated in place.
Co-Authored-By: heihutu <heihutu@gmail.com>
* refactor(object-data-cache): close the cross-branch coordination seams
Merging the metrics and hot-path branches left four transitional shims that
only existed because each side could not edit the other's files. With both
sides present they are dead weight, and two of them actively misreport.
- ObjectDataCacheEntry::new took content_length and etag only to keep the
caller in moka_backend.rs compiling, then discarded both. Drop them; the
entry is a Bytes wrapper and the caller now passes only the body.
- SkippedSingleflightClosed lost its only producer when the waiter model was
replaced by Leader/Busy election. Remove the variant.
- The fill-accounting match ended in a wildcard that charged fill_bytes and a
duration to every non-Inserted outcome, so a fill rejected by the memory
gate or the concurrency semaphore — which never touched the backend and
wrote nothing — still inflated fill_bytes_total. Enumerate every variant
explicitly: only outcomes that wrote the body report bytes and duration.
Exhaustiveness also forces a future variant to state its accounting rather
than inherit a wrong default.
- InvalidationResult::Success mapped a no-op to outcome=removed, the exact lie
backlog#1141 set out to fix, and its doc comment claimed MokaBackend still
returned it after that backend had been widened. It has no producer left.
Remove it, and tighten the app-layer test from "any successful variant" to
the real contract: the pre-mutation call reports Removed{keys:1}, the
post-delete call NoOp.
Refs: backlog#1123, backlog#1141, backlog#1135
Co-Authored-By: heihutu <heihutu@gmail.com>
---------
Co-authored-by: heihutu <heihutu@gmail.com>
224 lines
8.6 KiB
Rust
224 lines
8.6 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.
|
|
|
|
use crate::cache::ObjectDataCacheFillResult;
|
|
use crate::key::ObjectDataCacheKey;
|
|
use crate::metrics::{record_singleflight_join, set_inflight_fills};
|
|
use crate::stats::ObjectDataCacheStats;
|
|
use std::collections::HashSet;
|
|
use std::sync::{Arc, Mutex};
|
|
|
|
type FillSet = Mutex<HashSet<ObjectDataCacheKey>>;
|
|
|
|
fn lock_fills(fills: &FillSet) -> std::sync::MutexGuard<'_, HashSet<ObjectDataCacheKey>> {
|
|
fills.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
|
|
}
|
|
|
|
/// Shared singleflight controller that dedups concurrent cache fills per key.
|
|
///
|
|
/// The fill path already holds the fully materialized body, so a non-leader
|
|
/// gains nothing by waiting for the leader's result — a duplicate fill is
|
|
/// simply skipped. The controller therefore only elects a leader per key and
|
|
/// reports [`Busy`](ObjectDataCacheSingleflightAcquire::Busy) to everyone else.
|
|
#[derive(Debug)]
|
|
pub struct ObjectDataCacheSingleflight {
|
|
fills: FillSet,
|
|
stats: Arc<ObjectDataCacheStats>,
|
|
}
|
|
|
|
impl ObjectDataCacheSingleflight {
|
|
/// Creates a new singleflight controller.
|
|
pub fn new(stats: Arc<ObjectDataCacheStats>) -> Self {
|
|
Self {
|
|
fills: Mutex::new(HashSet::new()),
|
|
stats,
|
|
}
|
|
}
|
|
|
|
/// Tries to become the leader for the supplied cache key without blocking.
|
|
///
|
|
/// Returns [`Leader`](ObjectDataCacheSingleflightAcquire::Leader) when no
|
|
/// fill for the key is in flight, otherwise
|
|
/// [`Busy`](ObjectDataCacheSingleflightAcquire::Busy). The caller already
|
|
/// owns the body, so a `Busy` outcome skips the redundant fill rather than
|
|
/// waiting for another request's leader to finish.
|
|
pub fn try_acquire(&self, key: ObjectDataCacheKey) -> ObjectDataCacheSingleflightAcquire<'_> {
|
|
// Keep the critical section to the map mutation only; emit metrics after
|
|
// dropping the guard so the recorder round-trip never serializes fills.
|
|
let inflight_len = {
|
|
let mut fills = lock_fills(&self.fills);
|
|
if fills.contains(&key) {
|
|
None
|
|
} else {
|
|
fills.insert(key.clone());
|
|
Some(fills.len())
|
|
}
|
|
};
|
|
|
|
match inflight_len {
|
|
None => {
|
|
record_singleflight_join(&self.stats);
|
|
ObjectDataCacheSingleflightAcquire::Busy
|
|
}
|
|
Some(len) => {
|
|
set_inflight_fills(&self.stats, "moka", len);
|
|
ObjectDataCacheSingleflightAcquire::Leader(ObjectDataCacheSingleflightLeader {
|
|
key,
|
|
fills: &self.fills,
|
|
stats: Arc::clone(&self.stats),
|
|
finished: false,
|
|
})
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Returns whether a leader fill is currently in flight for the key.
|
|
///
|
|
/// Used by the fill hot path to keep another in-flight fill's index key
|
|
/// (a different key under the same identity that has registered in the index
|
|
/// but not yet published its cache entry) from being pruned as stale.
|
|
pub fn has_inflight(&self, key: &ObjectDataCacheKey) -> bool {
|
|
lock_fills(&self.fills).contains(key)
|
|
}
|
|
}
|
|
|
|
/// Leader-or-busy result from the singleflight controller.
|
|
pub enum ObjectDataCacheSingleflightAcquire<'a> {
|
|
/// Caller is responsible for performing the fill operation.
|
|
Leader(ObjectDataCacheSingleflightLeader<'a>),
|
|
/// A fill for the same key is already in flight; the caller skips its own.
|
|
Busy,
|
|
}
|
|
|
|
/// Leader handle for a singleflight fill operation.
|
|
pub struct ObjectDataCacheSingleflightLeader<'a> {
|
|
key: ObjectDataCacheKey,
|
|
fills: &'a FillSet,
|
|
stats: Arc<ObjectDataCacheStats>,
|
|
finished: bool,
|
|
}
|
|
|
|
impl<'a> ObjectDataCacheSingleflightLeader<'a> {
|
|
/// Completes the leader operation and releases the key.
|
|
pub fn finish(mut self, result: ObjectDataCacheFillResult) -> ObjectDataCacheFillResult {
|
|
self.remove_entry();
|
|
self.finished = true;
|
|
result
|
|
}
|
|
|
|
fn remove_entry(&self) {
|
|
// Capture the length under the guard, then emit the gauge after dropping
|
|
// it so the recorder round-trip stays out of the critical section.
|
|
let len = {
|
|
let mut fills = lock_fills(self.fills);
|
|
fills.remove(&self.key);
|
|
fills.len()
|
|
};
|
|
set_inflight_fills(&self.stats, "moka", len);
|
|
}
|
|
}
|
|
|
|
impl<'a> Drop for ObjectDataCacheSingleflightLeader<'a> {
|
|
fn drop(&mut self) {
|
|
// A leader dropped without finish() was cancelled mid-fill (e.g. the
|
|
// fill task was aborted). Release the key so a later fill can become the
|
|
// new leader instead of seeing a phantom in-flight entry forever.
|
|
if !self.finished {
|
|
self.remove_entry();
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::{ObjectDataCacheSingleflight, ObjectDataCacheSingleflightAcquire};
|
|
use crate::cache::ObjectDataCacheFillResult;
|
|
use crate::key::{ObjectDataCacheBodyVariant, ObjectDataCacheKey};
|
|
use crate::stats::ObjectDataCacheStats;
|
|
use std::sync::Arc;
|
|
|
|
fn key() -> ObjectDataCacheKey {
|
|
ObjectDataCacheKey::new("bucket", "object", None, "etag", 1, ObjectDataCacheBodyVariant::FullObjectPlainV1)
|
|
}
|
|
|
|
#[test]
|
|
fn first_caller_leads_and_second_caller_is_busy() {
|
|
let stats = Arc::new(ObjectDataCacheStats::default());
|
|
let singleflight = ObjectDataCacheSingleflight::new(Arc::clone(&stats));
|
|
|
|
let first = singleflight.try_acquire(key());
|
|
let second = singleflight.try_acquire(key());
|
|
|
|
assert!(
|
|
matches!(first, ObjectDataCacheSingleflightAcquire::Leader(_)),
|
|
"first caller must become leader"
|
|
);
|
|
assert!(
|
|
matches!(second, ObjectDataCacheSingleflightAcquire::Busy),
|
|
"second caller must not wait; it is busy and skips"
|
|
);
|
|
assert_eq!(stats.snapshot().singleflight_joins, 1);
|
|
|
|
// Completing the leader releases the key for a subsequent fill.
|
|
let ObjectDataCacheSingleflightAcquire::Leader(leader) = first else {
|
|
unreachable!("first caller must be the leader");
|
|
};
|
|
let result = leader.finish(ObjectDataCacheFillResult::Inserted);
|
|
assert_eq!(result, ObjectDataCacheFillResult::Inserted);
|
|
|
|
assert!(
|
|
matches!(singleflight.try_acquire(key()), ObjectDataCacheSingleflightAcquire::Leader(_)),
|
|
"key must be released after the leader finishes"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn cancelled_leader_releases_key() {
|
|
let stats = Arc::new(ObjectDataCacheStats::default());
|
|
let singleflight = ObjectDataCacheSingleflight::new(Arc::clone(&stats));
|
|
|
|
let leader = match singleflight.try_acquire(key()) {
|
|
ObjectDataCacheSingleflightAcquire::Leader(leader) => leader,
|
|
ObjectDataCacheSingleflightAcquire::Busy => panic!("first caller must become leader"),
|
|
};
|
|
assert!(singleflight.has_inflight(&key()), "leader must register the key as in-flight");
|
|
|
|
// Dropping without finish() simulates the fill task being cancelled.
|
|
drop(leader);
|
|
|
|
assert!(!singleflight.has_inflight(&key()), "a cancelled leader must release the key");
|
|
assert!(
|
|
matches!(singleflight.try_acquire(key()), ObjectDataCacheSingleflightAcquire::Leader(_)),
|
|
"key must be released after a cancelled leader"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn distinct_keys_lead_independently() {
|
|
let stats = Arc::new(ObjectDataCacheStats::default());
|
|
let singleflight = ObjectDataCacheSingleflight::new(Arc::clone(&stats));
|
|
let other = ObjectDataCacheKey::new("bucket", "other", None, "etag", 1, ObjectDataCacheBodyVariant::FullObjectPlainV1);
|
|
|
|
let first = singleflight.try_acquire(key());
|
|
let second = singleflight.try_acquire(other);
|
|
|
|
assert!(matches!(first, ObjectDataCacheSingleflightAcquire::Leader(_)));
|
|
assert!(
|
|
matches!(second, ObjectDataCacheSingleflightAcquire::Leader(_)),
|
|
"a distinct key must not be deduped against another in-flight fill"
|
|
);
|
|
assert_eq!(stats.snapshot().singleflight_joins, 0);
|
|
}
|
|
}
|