Files
rustfs/crates/ecstore/src/object_api/write_commit_context.rs
T
Rain Jiang eca95f2973 perf(ecstore): erasure read path for large GETs (#9304)
Lands the contributor's pull requests #9302 (opt-in lockless KV cache
buckets), #9303 (per-bucket XXH3 ETags; MD5 off the request task) and
#9304 (erasure read path for large GETs) as one change, because #9304
was stacked on the other two.

Maintainer changes on top of the contributed work:
- Merged main. crates/ecstore/src/erasure/coding/bitrot.rs: kept the
  PR's verify_chunked_frame/append_chunked_data restructuring and routed
  its hash-mismatch log through main's throttled log_hash_mismatch.
- rustfs/src/app/multipart_usecase.rs: took main's per-operation split
  and re-applied the PR's changes in place: multipart_etag_algorithm and
  its test in the parent module, the XXH3 pin in create.rs, the stage
  timer and from_stream_with_etag in upload_part.rs.
- Reworded one doc comment in crates/config/src/constants/object.rs that
  spelled an ecstore import path, which the architecture migration guard
  counts as a direct import.
- fix(config): made the MD5 offload opt-in. Each offloaded upload holds
  one blocking-pool thread until its body ends, and that pool also
  serves disk I/O, so many concurrent large uploads could starve disk
  writes. The default threshold is now 0 (disabled); operators enable
  it with RUSTFS_OBJECT_ETAG_MD5_OFFLOAD_MIN_BYTES (for example 8388608).
2026-11-13 10:05:26 +08:00

251 lines
8.9 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 super::{ObjectOptions, WriteCompletion};
use crate::error::{Error, Result};
use rustfs_utils::path::object_name_disk_identity;
use std::sync::Arc;
use std::time::Duration;
/// A real write guard shared with an inner commit, never a lock-loss signal alone.
///
/// Callers cannot fabricate a guard without acquiring its namespace lock.
///
/// ```compile_fail
/// use rustfs_ecstore::api::object::WriteCommitGuard;
/// use std::sync::Arc;
///
/// let guard = WriteCommitGuard {
/// bucket: "bucket".into(),
/// object: "object".into(),
/// guards: Arc::new(Vec::new()),
/// };
/// ```
#[doc(hidden)]
#[derive(Clone, Debug)]
pub struct WriteCommitGuard {
bucket: Arc<str>,
object: Arc<str>,
guards: Arc<Vec<Arc<rustfs_lock::NamespaceLockGuard>>>,
}
impl WriteCommitGuard {
/// Acquire the key recorded by the namespace wrapper and retain its owner.
pub async fn acquire(
lock: &rustfs_lock::NamespaceLockWrapper,
timeout: Duration,
) -> std::result::Result<Self, rustfs_lock::LockError> {
let guard = Arc::new(lock.get_write_lock(timeout).await?);
let key = lock.resource();
Ok(Self::from_guard(guard, &key.bucket, &key.object))
}
pub(crate) fn from_guard(guard: Arc<rustfs_lock::NamespaceLockGuard>, bucket: &str, object: &str) -> Self {
Self {
bucket: bucket.into(),
object: object_name_disk_identity(object).as_ref().into(),
guards: Arc::new(vec![guard]),
}
}
/// Return the loss signal of the namespace owner retained by acquisition.
#[doc(hidden)]
pub fn lock_lost_signal(&self) -> Option<Arc<rustfs_lock::distributed_lock::LockLostSignal>> {
self.guards.first().and_then(|guard| guard.lock_lost_signal())
}
pub fn is_lock_lost(&self) -> bool {
self.guards.iter().any(|guard| guard.is_lock_lost() || guard.is_released())
}
/// Namespace locks key the disk identity of the name (see `new_ns_lock`),
/// so a guard proves every spelling that resolves to the same file.
fn matches(&self, bucket: &str, object: &str) -> bool {
self.bucket.as_ref() == bucket && self.object.as_ref() == object_name_disk_identity(object).as_ref()
}
}
/// Opaque boundary capability; only real acquisitions or offline startup construct it.
///
/// ```compile_fail
/// use rustfs_ecstore::object_api::WriteLockContext;
///
/// let context = WriteLockContext {};
/// ```
#[doc(hidden)]
#[derive(Clone, Debug)]
pub struct WriteLockContext {
mode: WriteLockMode,
}
#[derive(Clone, Debug)]
enum WriteLockMode {
Borrowed(Vec<WriteCommitGuard>),
OfflineRecovery,
/// A PUT into a lockless cache bucket (`crate::bucket::lockless_cache`).
LocklessCache,
}
pub(crate) enum WriteCommitContext {
Owned,
Borrowed(Vec<WriteCommitGuard>),
Publication,
OfflineRecovery,
LocklessCache,
#[cfg(test)]
UnlockedFixture,
}
impl WriteCommitContext {
pub(crate) fn from_options(opts: &ObjectOptions, bucket: &str, object: &str, publication: bool) -> Result<Self> {
if publication {
if let Some(WriteLockContext {
mode: WriteLockMode::Borrowed(guards),
}) = opts.write_lock_context.as_ref()
&& !guards.iter().any(|guard| guard.matches(bucket, object))
{
return Err(Error::InvalidArgument(
bucket.to_owned(),
object.to_owned(),
"publication carries a different borrowed namespace".to_owned(),
));
}
return Ok(Self::Publication);
}
match (opts.no_lock, opts.write_lock_context.as_ref().map(|context| &context.mode)) {
(false, None | Some(WriteLockMode::Borrowed(_))) => Ok(Self::Owned),
(true, Some(WriteLockMode::Borrowed(guards))) if guards.iter().any(|guard| guard.matches(bucket, object)) => {
Ok(Self::Borrowed(guards.clone()))
}
(true, Some(WriteLockMode::OfflineRecovery)) => Ok(Self::OfflineRecovery),
(true, Some(WriteLockMode::LocklessCache)) if crate::bucket::lockless_cache::is_lockless_cache_bucket(bucket) => {
Ok(Self::LocklessCache)
}
#[cfg(test)]
(true, None) if !opts.metadata_cache_safe => Ok(Self::UnlockedFixture),
_ => Err(Error::InvalidArgument(
bucket.to_owned(),
object.to_owned(),
"write lock context does not prove the target namespace".to_owned(),
)),
}
}
pub(crate) fn acquires_namespace(&self) -> bool {
matches!(self, Self::Owned)
}
pub(crate) fn has_borrowed_owner(&self) -> bool {
matches!(self, Self::Borrowed(_))
}
pub(crate) fn is_lock_lost(&self) -> bool {
matches!(self, Self::Borrowed(guards) if guards.iter().any(WriteCommitGuard::is_lock_lost))
}
pub(crate) fn allows_early_ack(&self, completion: WriteCompletion) -> bool {
completion == WriteCompletion::Quorum && matches!(self, Self::Owned | Self::Borrowed(_) | Self::Publication)
}
}
impl ObjectOptions {
pub fn add_write_commit_guard(&mut self, guard: &WriteCommitGuard) {
for owner in guard.guards.iter() {
self.add_namespace_lock_guard(owner);
}
let mut guards = match self.write_lock_context.as_ref() {
Some(WriteLockContext {
mode: WriteLockMode::Borrowed(existing),
}) => existing.clone(),
_ => Vec::new(),
};
if let Some(existing) = guards.iter_mut().find(|held| held.matches(&guard.bucket, &guard.object)) {
let owners = Arc::make_mut(&mut existing.guards);
for owner in guard.guards.iter() {
if !owners.iter().any(|held| Arc::ptr_eq(held, owner)) {
owners.push(Arc::clone(owner));
}
}
} else {
guards.push(guard.clone());
}
self.no_lock = true;
self.write_lock_context = Some(WriteLockContext {
mode: WriteLockMode::Borrowed(guards),
});
}
pub(crate) fn add_owned_write_lock(&mut self, guard: Arc<rustfs_lock::NamespaceLockGuard>, bucket: &str, object: &str) {
self.add_write_commit_guard(&WriteCommitGuard::from_guard(guard, bucket, object));
}
/// Commit a PUT into `bucket` without a namespace owner when the server lists
/// it as a lockless cache bucket; returns whether the lockless path applies.
pub fn use_lockless_cache_write(&mut self, bucket: &str) -> bool {
if !crate::bucket::lockless_cache::is_lockless_cache_bucket(bucket) || self.write_lock_context.is_some() {
return false;
}
self.no_lock = true;
self.write_lock_context = Some(WriteLockContext {
mode: WriteLockMode::LocklessCache,
});
true
}
/// Return a lockless cache PUT to the locked path (for example once it is
/// known to need replication).
pub fn drop_lockless_cache_write(&mut self) {
if self.is_lockless_cache_write() {
self.no_lock = false;
self.write_lock_context = None;
}
}
pub fn is_lockless_cache_write(&self) -> bool {
matches!(
self.write_lock_context.as_ref().map(|context| &context.mode),
Some(WriteLockMode::LocklessCache)
)
}
/// Only startup migration may publish without a running namespace owner.
pub(crate) fn use_offline_recovery_write(&mut self) {
self.no_lock = true;
self.write_lock_context = Some(WriteLockContext {
mode: WriteLockMode::OfflineRecovery,
});
self.write_completion = WriteCompletion::TailDrained;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unlisted_bucket_never_takes_the_lockless_write_path() {
let mut opts = ObjectOptions::default();
assert!(
!opts.use_lockless_cache_write("ordinary-bucket"),
"only buckets named in the server's lockless list may skip the namespace lock"
);
assert!(!opts.is_lockless_cache_write());
assert!(!opts.no_lock, "a refused lockless request must leave the locked path intact");
assert!(matches!(
WriteCommitContext::from_options(&opts, "ordinary-bucket", "object", false),
Ok(WriteCommitContext::Owned)
));
}
}