refactor(rdma): bind the NVIDIA cuObject server SDK in RustFS (#9563)

* refactor(rdma): bind the NVIDIA cuObject server SDK in RustFS

* fix(rdma): preserve channel capacity and reuse contiguous registrations

* perf(rdma): transfer ownership of cuObject upload buffers

* fix(rdma): validate cuObject routing fields before transfer

* refactor(rdma): isolate the cuObject server SDK in a sys crate

* docs(rdma): document the workspace cuObject server bindings

* perf(cuobject): reuse channels and completion registrations

* fix(rdma): release eager PUT staging before requesting more chunks

* fix(rdma): consume CQ readiness and copy only retained PUT frames

* fix(rdma): release consumed streaming PUT frames before the next read

---------

Co-authored-by: Hauser Zhi <housemecn@gmail.com>
Co-authored-by: overtrue <anzhengchao@gmail.com>
This commit is contained in:
GatewayJ
2026-11-23 04:13:17 +08:00
committed by GitHub
parent ec8f72b1cf
commit 8c9fc97ae6
19 changed files with 1420 additions and 363 deletions
+37 -6
View File
@@ -1,10 +1,7 @@
name: S3-over-RDMA feature check
# The `nixl` and `cuobject` features are off in every other build, so the code
# behind them is compiled nowhere else. This job compiles the `nixl` half on
# Linux and runs rustfs-nixl's unit tests; nixl-sys builds through its stub
# fallback, so no NIXL SDK is needed.
# The cuObject half needs the NVIDIA cuObject SDK and is not compiled here.
# Compile the optional RDMA features independently. The cuObject tests link
# the NVIDIA SDK and exercise the host-side behavior on a CPU runner.
# Not a required check and not part of the `Test and Lint` aggregate.
on:
@@ -12,6 +9,7 @@ on:
paths:
- "crates/nixl/**"
- "crates/cuobject/**"
- "crates/cuobject-sys/**"
- "rustfs/src/storage/rpc/nixl*"
- "rustfs/src/app/object/cuobject.rs"
- "rustfs/src/app/object/get.rs"
@@ -70,9 +68,42 @@ jobs:
- name: Run the rustfs-nixl unit tests
run: cargo test --locked -p rustfs-nixl --features sys
cuobject-check:
name: cuObject server SDK and unit tests
runs-on: ubuntu-24.04
timeout-minutes: 60
steps:
- uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- uses: ./.github/actions/setup
with:
rust-version: stable
cache-shared-key: ci-feat-cuobject
cache-save-if: 'false'
install-build-packaging-tools: 'false'
- name: Check the cuObject crates without the NVIDIA SDK
run: cargo check --locked -p rustfs-cuobject -p rustfs-cuobject-sys
- name: Install the NVIDIA server SDK
working-directory: ${{ runner.temp }}
run: |
sudo apt-get update
sudo apt-get install --no-install-recommends -y libibverbs-dev librdmacm-dev
repo=https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2404/x86_64
for pkg in libcuobjserver libcuobjserver-dev; do
curl --fail --location --retry 3 "$repo/${pkg}_2.1.0.101-1_amd64.deb" -o "$pkg.deb"
done
sha256sum --check <<'DIGESTS'
39e6271118717e8e726233ae5ac29ee3b83e335e1fbe96b097bb458a4a52393a libcuobjserver.deb
73d4f187e58b784c7cf64633d7e76c2ac59dea5b475fd981cc6897c34cb9876f libcuobjserver-dev.deb
DIGESTS
sudo dpkg -i libcuobjserver.deb libcuobjserver-dev.deb
- name: Test the server bridge
run: cargo test --locked -p rustfs-cuobject --features server
alert-on-failure:
name: Alert on scheduled failure
needs: [nixl-check]
needs: [nixl-check, cuobject-check]
# Only scheduled runs open or update the tracking issue; pull-request and
# manual runs stay quiet.
if: always() && github.event_name == 'schedule' && contains(needs.*.result, 'failure')
Generated
+99 -23
View File
@@ -2322,6 +2322,17 @@ dependencies = [
"x509-cert",
]
[[package]]
name = "codespan-reporting"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681"
dependencies = [
"serde",
"termcolor",
"unicode-width",
]
[[package]]
name = "colorchoice"
version = "1.0.5"
@@ -2800,27 +2811,6 @@ dependencies = [
"subtle",
]
[[package]]
name = "cuobject"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "486fec9045f8057131bf4bba71fbb87bf9dd3e44f853622cf7fa42713f3a108c"
dependencies = [
"cuobject-sys",
"memmap2",
"thiserror 2.0.21",
]
[[package]]
name = "cuobject-sys"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "edc615b2a037eb0d80180d202f809629155742db9c9e94b9f7696b1100a7d52f"
dependencies = [
"bindgen 0.73.2",
"cc",
]
[[package]]
name = "curve25519-dalek"
version = "4.1.3"
@@ -2864,6 +2854,68 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "cxx"
version = "1.0.205"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8a02bfeba9074b2bbb39492c9b0908ec854f455a3cccdcde7a1de55e2315e40"
dependencies = [
"cc",
"cxx-build",
"cxxbridge-cmd",
"cxxbridge-flags",
"cxxbridge-macro",
"foldhash 0.2.0",
"link-cplusplus",
]
[[package]]
name = "cxx-build"
version = "1.0.205"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbc2ac76997619d2d888b58ad79488f1c835de41ca4dd3dd7082acf4ecb0a50f"
dependencies = [
"cc",
"codespan-reporting",
"indexmap 2.14.2",
"proc-macro2",
"quote",
"scratch",
"syn 3.0.10",
]
[[package]]
name = "cxxbridge-cmd"
version = "1.0.205"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "54a486ed16a3f2a053fe7f5b98db4c1a59846a23e8cb9e49f9d1bd48830d51a2"
dependencies = [
"clap",
"codespan-reporting",
"indexmap 2.14.2",
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "cxxbridge-flags"
version = "1.0.205"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c72569be94e2283764d334cd285980b747dbe221e27e315484eb6bcd93fa808a"
[[package]]
name = "cxxbridge-macro"
version = "1.0.205"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "423e795284a7f7b3f843c956a5322c4bc497b60c2dd1a6339da10313cb18d575"
dependencies = [
"indexmap 2.14.2",
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "darling"
version = "0.20.11"
@@ -6424,6 +6476,15 @@ dependencies = [
"uuid",
]
[[package]]
name = "link-cplusplus"
version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f78c730aaa7d0b9336a299029ea49f9ee53b0ed06e9202e8cb7db9bae7b8c82"
dependencies = [
"cc",
]
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
@@ -9417,7 +9478,7 @@ dependencies = [
"cfg-if",
"libc",
"rustix",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -10129,12 +10190,21 @@ name = "rustfs-cuobject"
version = "1.0.5"
dependencies = [
"bytes",
"cuobject",
"parking_lot 0.13.0",
"rustfs-cuobject-sys",
"thiserror 2.0.21",
"tokio",
]
[[package]]
name = "rustfs-cuobject-sys"
version = "1.0.5"
dependencies = [
"cxx",
"cxx-build",
"libc",
]
[[package]]
name = "rustfs-data-usage"
version = "1.0.5"
@@ -12021,6 +12091,12 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "scratch"
version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d68f2ec51b097e4c1a75b681a8bec621909b5e91f15bb7b840c4f2f7b01148b2"
[[package]]
name = "scrypt"
version = "0.11.0"
+4 -1
View File
@@ -23,6 +23,7 @@ members = [
"crates/connect-symbol-catalog", # Release-only CPU profile symbol catalog generator
"crates/credentials", # Credential management system
"crates/crypto", # Cryptography and security features
"crates/cuobject-sys", # Native NVIDIA cuObject server SDK bindings
"crates/cuobject", # NVIDIA cuObject S3-over-RDMA staging and transfers (optional)
"crates/nixl", # NIXL/UCX S3-over-RDMA server side (optional)
"crates/ecstore", # Erasure coding storage implementation
@@ -108,6 +109,7 @@ rustfs-concurrency = { path = "./crates/concurrency", version = "1.0.5" }
rustfs-credentials = { path = "crates/credentials", version = "1.0.5" }
rustfs-crypto = { path = "crates/crypto", version = "1.0.5" }
rustfs-cuobject = { path = "crates/cuobject", version = "1.0.5" }
rustfs-cuobject-sys = { path = "crates/cuobject-sys", version = "1.0.5" }
rustfs-nixl = { path = "crates/nixl", version = "1.0.5" }
rustfs-ecstore = { path = "crates/ecstore", version = "1.0.5" }
rustfs-filemeta = { path = "crates/filemeta", version = "1.0.5" }
@@ -313,7 +315,8 @@ hostname = "0.4.2"
ipnetwork = { version = "0.21.1" }
lazy_static = "1.5.1"
libc = "0.2.191"
cuobject = { version = "0.1.0", default-features = false }
cxx = "1"
cxx-build = "1"
libsystemd = "0.7.2"
local-ip-address = "0.6.13"
log = "0.4"
+22
View File
@@ -0,0 +1,22 @@
[package]
name = "rustfs-cuobject-sys"
edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true
version.workspace = true
description = "Native bindings to the NVIDIA cuObject server SDK"
links = "cuobjserver"
[lints]
workspace = true
[dependencies]
cxx = { workspace = true, optional = true }
libc = { workspace = true, optional = true }
[build-dependencies]
cxx-build = { workspace = true, optional = true }
[features]
server = ["dep:cxx", "dep:cxx-build", "dep:libc"]
+41
View File
@@ -0,0 +1,41 @@
// 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.
fn main() {
#[cfg(feature = "server")]
build_server();
}
#[cfg(feature = "server")]
fn build_server() {
use std::{env, path::PathBuf};
println!("cargo:rerun-if-env-changed=CUOBJSERVER_ROOT");
for file in ["src/sdk.rs", "native/server.h", "native/server.cc"] {
println!("cargo:rerun-if-changed={file}");
}
let mut build = cxx_build::bridge("src/sdk.rs");
if let Some(root) = env::var_os("CUOBJSERVER_ROOT").map(PathBuf::from) {
build.include(root.join("include"));
for subdir in ["lib", "lib64"] {
println!("cargo:rustc-link-search=native={}", root.join(subdir).display());
}
}
build
.include(".")
.file("native/server.cc")
.std("c++17")
.compile("rustfs_cuobject_server");
println!("cargo:rustc-link-lib=cuobjserver");
}
+143
View File
@@ -0,0 +1,143 @@
// 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.
#include "rustfs-cuobject-sys/src/sdk.rs.h"
#include <cuobjserver.h>
#include <array>
#include <cerrno>
#include <limits>
#include <stdexcept>
#include <system_error>
#include <sys/mman.h>
namespace rustfs::cuobject {
class Server {
public:
Server(std::string address, std::uint16_t port, int channels, std::uint32_t depth)
: address_(std::move(address)) {
cuObjRDMATunable options;
if (channels > 0) options.setNumDcis(channels);
if (depth > 0) options.setCqDepth(depth);
sdk = std::make_unique<cuObjServer>(address_.c_str(), port, CUOBJ_PROTO_RDMA_DC_V1, options);
}
// The SDK may retain the address string through server teardown.
const std::string address_;
std::unique_ptr<cuObjServer> sdk;
};
std::uint32_t header_version() noexcept {
return CUOBJ_SERVER_MAJOR_VERSION * 1000 + CUOBJ_SERVER_MINOR_VERSION;
}
std::shared_ptr<Server> open_server(rust::Str addr, std::uint16_t port, int channels, std::uint32_t depth) {
return std::make_shared<Server>(std::string(addr), port, channels, depth);
}
class Buffer {
public:
std::shared_ptr<Server> owner;
std::shared_ptr<Buffer> base;
rdma_buffer* handle = nullptr;
void* mapping = MAP_FAILED;
std::size_t length = 0;
static void destroy(Buffer* buffer) noexcept {
try {
if (buffer->handle) {
if (buffer->base) buffer->owner->sdk->putRDMABufferFromSgList(buffer->handle);
else buffer->owner->sdk->deRegisterBuffer(buffer->handle);
}
} catch (...) {
// The SDK may still reference the mapping and its owning server.
return;
}
if (buffer->mapping != MAP_FAILED) munmap(buffer->mapping, buffer->length);
delete buffer;
}
};
std::shared_ptr<Buffer> register_buffer(std::shared_ptr<Server> server, std::size_t length) {
if (!server || !length) throw std::invalid_argument("invalid host registration");
auto buffer = std::shared_ptr<Buffer>(new Buffer, Buffer::destroy);
buffer->owner = std::move(server);
buffer->length = length;
buffer->mapping = mmap(nullptr, length, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (buffer->mapping == MAP_FAILED) throw std::system_error(errno, std::generic_category(), "mmap");
buffer->handle = buffer->owner->sdk->registerBuffer(buffer->mapping, length);
if (!buffer->handle) throw std::runtime_error("NVIDIA memory registration failed");
return buffer;
}
std::shared_ptr<Buffer> scatter_list(std::shared_ptr<Buffer> base, rust::Slice<const Range> ranges) {
if (!base || base->base || ranges.empty() || ranges.size() > 10) throw std::invalid_argument("invalid scatter list");
auto list = std::shared_ptr<Buffer>(new Buffer, Buffer::destroy);
list->owner = base->owner;
list->base = std::move(base);
std::vector<cuObjScatterGatherEntryWithOffset_t> entries;
entries.reserve(ranges.size());
for (auto range : ranges) {
if (!range.size || range.offset > list->base->length || range.size > list->base->length - range.offset ||
range.offset > std::numeric_limits<loff_t>::max() || range.size > SIZE_MAX - list->length)
throw std::invalid_argument("invalid scatter range");
entries.push_back({static_cast<loff_t>(range.offset), range.size});
list->length += range.size;
}
list->handle = list->owner->sdk->getRDMABufferFromSgList(list->base->handle, std::move(entries));
if (!list->handle) throw std::runtime_error("NVIDIA scatter list registration failed");
return list;
}
std::uint8_t* data(const Buffer& buffer) noexcept { return static_cast<std::uint8_t*>(buffer.mapping); }
std::size_t size(const Buffer& buffer) noexcept { return buffer.length; }
std::uint16_t lease_channel(const Server& server) { return server.sdk->allocateChannelId(); }
void release_channel(const Server& server, std::uint16_t channel) noexcept {
try { server.sdk->freeChannelId(channel); } catch (...) { /* SDK owns the channel. */ }
}
int completion_fd(const Server& server, std::uint16_t channel) noexcept {
try { return server.sdk->getCompletionFd(channel); } catch (...) { return -EIO; }
}
int drain(const Server& server, int fd, rust::Slice<Completion> out) noexcept {
std::array<cuObjAsyncEvent_t, 8> events{};
if (out.empty() || out.size() > events.size()) return -EINVAL;
try {
const int count = server.sdk->processCompletions(events.data(), static_cast<int>(out.size()), fd);
if (count > static_cast<int>(out.size())) return -EIO;
for (int i = 0; i < count; ++i) {
out[i] = {reinterpret_cast<std::uintptr_t>(events[i].async_handle), events[i].status};
}
return count;
} catch (...) { return -EIO; }
}
Outcome transfer(const Server& server, const Buffer& buffer, const Operation& op) noexcept {
if (buffer.owner.get() != &server || !op.length || op.offset > buffer.length ||
op.length > buffer.length - op.offset || (buffer.base && (op.offset || op.length != buffer.length)))
return {-EINVAL, 0, false};
ibv_wc_status verbs = IBV_WC_SUCCESS;
bool submitted_to_sdk = false;
try {
const std::string key(op.key), token(op.token);
void* handle = reinterpret_cast<void*>(op.handle);
auto& sdk = *server.sdk;
submitted_to_sdk = true;
const ssize_t moved = op.put
? sdk.handlePutObject(key, buffer.handle, op.address, op.length, token, op.channel, op.offset, &verbs, handle)
: sdk.handleGetObject(key, buffer.handle, op.address, op.length, token, op.channel, op.offset, &verbs, handle);
return {moved, static_cast<int>(verbs), false};
} catch (...) { return {-EIO, static_cast<int>(verbs), submitted_to_sdk}; }
}
}
+40
View File
@@ -0,0 +1,40 @@
// 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.
#pragma once
#include "rust/cxx.h"
#include <cstddef>
#include <cstdint>
#include <memory>
namespace rustfs::cuobject {
class Server;
class Buffer;
struct Range;
struct Completion;
struct Operation;
struct Outcome;
std::uint32_t header_version() noexcept;
std::shared_ptr<Server> open_server(rust::Str address, std::uint16_t port, int channels, std::uint32_t depth);
std::shared_ptr<Buffer> register_buffer(std::shared_ptr<Server> server, std::size_t length);
std::shared_ptr<Buffer> scatter_list(std::shared_ptr<Buffer> base, rust::Slice<const Range> ranges);
std::uint8_t* data(const Buffer& buffer) noexcept;
std::size_t size(const Buffer& buffer) noexcept;
std::uint16_t lease_channel(const Server& server);
void release_channel(const Server& server, std::uint16_t channel) noexcept;
int completion_fd(const Server& server, std::uint16_t channel) noexcept;
int drain(const Server& server, int fd, rust::Slice<Completion> events) noexcept;
Outcome transfer(const Server& server, const Buffer& buffer, const Operation& op) noexcept;
}
+22
View File
@@ -0,0 +1,22 @@
// 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.
//! Native bindings and SDK handle ownership for the NVIDIA cuObject server.
#![cfg(feature = "server")]
pub use cxx::Exception;
// SAFETY: this module declares the SDK ABI and the ownership of native handles.
#[allow(unsafe_code)]
mod sdk;
pub use sdk::*;
+149
View File
@@ -0,0 +1,149 @@
// 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.
//! Private ABI for the NVIDIA server SDK.
use cxx::SharedPtr;
use std::io;
use std::os::fd::{AsRawFd, RawFd};
#[cxx::bridge(namespace = "rustfs::cuobject")]
mod ffi {
#[derive(Clone, Copy, Debug)]
struct Range {
offset: usize,
size: usize,
}
#[derive(Clone, Copy, Default)]
struct Completion {
handle: usize,
status: isize,
}
struct Operation<'a> {
key: &'a str,
token: &'a str,
address: u64,
offset: usize,
length: usize,
channel: u16,
handle: usize,
put: bool,
}
struct Outcome {
count: isize,
verbs: i32,
uncertain: bool,
}
// SAFETY: native registrations own their server and mapping. Scatter views
// also own their base. The caller keeps DMA ranges exclusive until completion.
unsafe extern "C++" {
include!("native/server.h");
type Server;
type Buffer;
fn header_version() -> u32;
fn open_server(address: &str, port: u16, channels: i32, depth: u32) -> Result<SharedPtr<Server>>;
fn register_buffer(server: SharedPtr<Server>, length: usize) -> Result<SharedPtr<Buffer>>;
fn scatter_list(base: SharedPtr<Buffer>, ranges: &[Range]) -> Result<SharedPtr<Buffer>>;
fn size(buffer: &Buffer) -> usize;
fn data(buffer: &Buffer) -> *mut u8;
fn lease_channel(server: &Server) -> Result<u16>;
fn release_channel(server: &Server, channel: u16);
fn completion_fd(server: &Server, channel: u16) -> i32;
fn drain(server: &Server, fd: i32, events: &mut [Completion]) -> i32;
unsafe fn transfer(server: &Server, buffer: &Buffer, op: &Operation) -> Outcome;
}
}
// SAFETY: the SDK supports concurrent transfers on separately leased channels.
// Server and registration metadata stay immutable after construction. Sharing a
// handle gives no safe access to the host bytes.
unsafe impl Send for ffi::Server {}
unsafe impl Sync for ffi::Server {}
unsafe impl Send for ffi::Buffer {}
unsafe impl Sync for ffi::Buffer {}
pub use ffi::{Completion, Operation, Outcome, Range, data, header_version, open_server, register_buffer, scatter_list, size};
pub type ServerHandle = SharedPtr<ffi::Server>;
pub type BufferHandle = SharedPtr<ffi::Buffer>;
pub fn errno(status: isize) -> io::Error {
match status.checked_neg().and_then(|code| i32::try_from(code).ok()) {
Some(code) => io::Error::from_raw_os_error(code),
None => io::Error::other("invalid NVIDIA error status"),
}
}
pub struct Channel {
server: SharedPtr<ffi::Server>,
id: u16,
}
impl Channel {
pub fn lease(server: &SharedPtr<ffi::Server>) -> io::Result<Self> {
let id = ffi::lease_channel(server).map_err(io::Error::other)?;
if id == u16::MAX {
return Err(io::Error::from_raw_os_error(libc::EBUSY));
}
Ok(Self {
server: server.clone(),
id,
})
}
pub fn fd(&self) -> Option<CompletionFd> {
let fd = ffi::completion_fd(&self.server, self.id);
(fd >= 0).then(|| CompletionFd {
fd,
server: self.server.clone(),
})
}
/// Submits a transfer to the leased channel.
///
/// # Safety
/// The caller must exclusively own the local range, keep the remote token valid,
/// and retain the channel and registrations until the SDK confirms completion.
/// An unknown submission or undelivered completion must preserve those owners.
pub unsafe fn submit(&mut self, buffer: &ffi::Buffer, mut op: ffi::Operation<'_>) -> ffi::Outcome {
op.channel = self.id;
// SAFETY: the caller holds the range and the exclusive channel lease.
unsafe { ffi::transfer(&self.server, buffer, &op) }
}
}
impl Drop for Channel {
fn drop(&mut self) {
ffi::release_channel(&self.server, self.id);
}
}
pub struct CompletionFd {
fd: RawFd,
server: SharedPtr<ffi::Server>,
}
impl AsRawFd for CompletionFd {
fn as_raw_fd(&self) -> RawFd {
self.fd
}
}
impl CompletionFd {
pub fn drain(&self, events: &mut [ffi::Completion]) -> io::Result<usize> {
let count = ffi::drain(&self.server, self.fd, events);
usize::try_from(count).map_err(|_| errno(count as isize))
}
}
+2 -2
View File
@@ -16,11 +16,11 @@ workspace = true
[dependencies]
bytes = { workspace = true, optional = true }
cuobject = { workspace = true, default-features = false, optional = true }
rustfs-cuobject-sys = { workspace = true, features = ["server"], optional = true }
parking_lot = { workspace = true, optional = true }
thiserror = { workspace = true, optional = true }
tokio = { workspace = true, features = ["net", "rt-multi-thread", "sync", "time"], optional = true }
[features]
# Compiles the cuObject server bindings (needs the NVIDIA cuObject SDK).
server = ["dep:bytes", "dep:cuobject", "cuobject/server", "dep:parking_lot", "dep:thiserror", "dep:tokio"]
server = ["dep:bytes", "dep:rustfs-cuobject-sys", "dep:parking_lot", "dep:thiserror", "dep:tokio"]
+652 -226
View File
File diff suppressed because it is too large Load Diff
@@ -19,7 +19,7 @@ This document describes the design and the invariants of RustFS's S3-over-RDMA d
| Layer | Code | Role |
|---|---|---|
| Client last hop, cuObject | `crates/cuobject/src/lib.rs`, `rustfs/src/app/object/cuobject.rs` | First transport: `x-amz-rdma-token`, NVIDIA cuObject server library through the `cuobject` bindings from crates.io. Kept as a compile-time alternative. |
| Client last hop, cuObject | `rustfs/src/app/object/cuobject.rs`, `crates/cuobject`, `crates/cuobject-sys` | The `cuobject` feature enables `x-amz-rdma-token` transfers. `rustfs-cuobject` manages registered buffers and transfers. `rustfs-cuobject-sys` builds the C++ bridge and links the NVIDIA server SDK. |
| Client last hop, NIXL | `crates/nixl/src/lib.rs` (`RdmaToken::from_headers`), `crates/nixl/src/remotes.rs`, `crates/nixl/src/mem.rs` | NIXL/UCX transport selected by the `nixl` feature. The client names a registered `dram` or `vram` buffer; the server WRITEs (GET) or READs (PUT) it. |
| Shared pipeline | `rustfs/src/app/object/cuobject.rs` | Segment fan-out of large GETs, staging chunks, shard arena, completion handling. The same pipeline serves both transports; only the transfer layer differs. |
| Device health | `crates/nixl/src/devices.rs` | Startup check that leaves out RDMA devices that are down, slow or flapping. |
+15 -11
View File
@@ -13,12 +13,9 @@ either can be enabled on its own.
## Build
The feature links NVIDIA's cuObject *server* library (`libcuobjserver`, part
of the CUDA apt repository as `libcuobjserver` / `libcuobjserver-dev`) through
the [`cuobject`](https://crates.io/crates/cuobject) bindings; their
`cuobject-sys` build script generates the FFI with bindgen (needs libclang)
and compiles a C++ wrapper over the library. It is off by default and
Linux-only:
The optional Linux `cuobject` feature enables `rustfs-cuobject` for buffer and transfer management. Its dependency `rustfs-cuobject-sys` compiles the C++17 bridge against `cuobjserver.h` and links NVIDIA's `libcuobjserver`. Install `libcuobjserver`,
`libcuobjserver-dev` and the RDMA development headers for the target
architecture. A default build does not require the NVIDIA SDK.
```bash
# CUOBJSERVER_ROOT points at a prefix holding include/cuobjserver.h and lib/libcuobjserver.so
@@ -60,11 +57,12 @@ and `Content-Length: 0`, plus:
- `x-amz-rdma-bytes-transferred`: bytes written into the client buffer; absent
when zero.
Writes are pipelined: chunk N is written by its own task while the decoder
fills chunk N+1; completions are collected in issue order. Each chunk is
owned by its blocking write until the DMA returns, so on a failure the GET
waits for the outstanding writes before their chunks return to the pool;
a staging slot is never reused while the NIC may still read it.
A GET can fill a staging chunk while an earlier chunk is being sent. Each
transfer holds its own channel and source until DMA completes. Successful
transfers return the channel to the per-server pool. An asynchronous GET
also reuses the channel's completion descriptor registration on the same
Tokio runtime. If completion becomes uncertain, the channel and the
registered source stay reserved.
A malformed token is ignored (the GET is served over HTTP); the client treats
the missing reply header as "declined". A token buffer smaller than the
@@ -85,6 +83,12 @@ and `x-amz-rdma-bytes-transferred`. A malformed token is ignored and the
empty body is stored as an empty object, exactly as without the feature;
the NIXL client treats a reply without `x-amz-rdma-reply` as declined.
For PUT, read-ahead reserves chunks in object order. A streaming PUT or
UploadPart consumes the registered frames directly and returns each staging
slot after its last byte is consumed. An eager reader retaining multiple
frames copies them out of the pool before reserving more. A cache fill also
keeps its retained bytes independently of the staging pool.
## Validation
1. `RUSTFS_CUOBJECT_ENABLE=true RUSTFS_CUOBJECT_ADDRS=<roce ip>` on each node
-1
View File
@@ -119,7 +119,6 @@ use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::RwLock;
use tokio_util::io::StreamReader;
use tracing::{instrument, warn};
use urlencoding::encode;
use uuid::Uuid;
@@ -16,8 +16,8 @@
use super::*;
use crate::app::RequestEnvelope;
use crate::app::object::BodyChunks;
use crate::app::object::request_body::{DemandReader, UploadChunks, guard_native_upload_progress};
use crate::app::object::{BodyChunks, upload_frame_reader};
use crate::app::storage_api::multipart_usecase::access::AuthorizationRequest;
use crate::app::storage_api::multipart_usecase::contract::multipart::MultipartInfo;
use crate::app::storage_api::multipart_usecase::contract::multipart::MultipartOwner;
@@ -205,8 +205,7 @@ impl DefaultMultipartUsecase {
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
let (body, content_length, rdma_put) = match crate::app::object::cuobject::rdma_token_for_request(req.headers()) {
Some(token) if content_length.unwrap_or(0) == 0 => {
let (body, total) =
crate::app::object::cuobject::rdma_put_body(bucket, key, &token, true).map_err(S3Error::from)?;
let (body, total) = crate::app::object::cuobject::rdma_put_body(bucket, key, &token).map_err(S3Error::from)?;
let total = i64::try_from(total).map_err(|_| S3Error::new(S3ErrorCode::EntityTooLarge))?;
(Some(body), Some(total), Some(total))
}
@@ -290,7 +289,7 @@ impl DefaultMultipartUsecase {
let buffer_size = get_buffer_size_opt_in(size);
let body = tokio::io::BufReader::with_capacity(
buffer_size,
StreamReader::new(body_stream.map(|f| f.map_err(s3s_body_error_to_io))),
upload_frame_reader(body_stream.map(|f| f.map_err(s3s_body_error_to_io))),
);
// An SSE-C passthrough session stores ciphertext parts verbatim: a
+56 -64
View File
@@ -780,41 +780,60 @@ pub(crate) async fn serve_get_over_rdma(
type StagedRead = JoinHandle<Result<StagingChunk, CuObjectError>>;
/// The staged bytes of `chunk`: with `zero_copy`, a `Bytes` that owns the
/// chunk (it returns to the pool when the last clone drops), otherwise a copy.
#[cfg(feature = "nixl")]
fn staged_bytes(chunk: StagingChunk, zero_copy: bool) -> io::Result<Bytes> {
if zero_copy {
return Ok(Bytes::from_owner(chunk));
struct PutReads {
server: Arc<CuObjectServer>,
object: String,
token: RdmaToken,
next_offset: u64,
read_ahead: usize,
pending: VecDeque<StagedRead>,
}
impl PutReads {
fn enqueue(&mut self, chunk: StagingChunk) {
let offset = self.next_offset;
let len = (self.token.buffer_len - offset).min(self.server.chunk_bytes() as u64) as usize;
self.next_offset += len as u64;
let server = Arc::clone(&self.server);
let object = self.object.clone();
let token = self.token.clone();
self.pending.push_back(tokio::spawn(async move {
server.read_from_client_owned(&object, &token, offset, len, chunk).await
}));
}
Ok(Bytes::copy_from_slice(chunk.staged().map_err(io::Error::other)?))
}
/// The staged bytes of `chunk`, copied (the cuObject chunk is not a byte owner).
#[cfg(not(feature = "nixl"))]
fn staged_bytes(chunk: StagingChunk, _zero_copy: bool) -> io::Result<Bytes> {
Ok(Bytes::copy_from_slice(chunk.staged().map_err(io::Error::other)?))
}
// Reserve in offset order. Later reads can use available slots but never
// hold staging memory ahead of an earlier range that still needs a slot.
fn prefetch(&mut self) {
while self.pending.len() < self.read_ahead && self.next_offset < self.token.buffer_len {
let Some(chunk) = self.server.try_reserve() else { break };
self.enqueue(chunk);
}
}
fn spawn_staged_read(server: &Arc<CuObjectServer>, object: &str, token: &RdmaToken, offset: u64, len: usize) -> StagedRead {
let server = Arc::clone(server);
let object = object.to_owned();
let token = token.clone();
tokio::spawn(async move {
let chunk = server.reserve(STAGING_RESERVE_TIMEOUT).await?;
server.read_from_client_owned(&object, &token, offset, len, chunk).await
})
async fn next(&mut self) -> io::Result<Option<StagingChunk>> {
if self.pending.is_empty() && self.next_offset < self.token.buffer_len {
let chunk = self.server.reserve(STAGING_RESERVE_TIMEOUT).await.map_err(io::Error::other)?;
self.enqueue(chunk);
}
self.prefetch();
let Some(read) = self.pending.pop_front() else { return Ok(None) };
let wait_started = rustfs_io_metrics::put_stage_timer();
let chunk = read
.await
.map_err(|error| io::Error::other(format!("rdma put read task: {error}")))?
.map_err(|error| io::Error::other(format!("rdma put read: {error}")))?;
rustfs_io_metrics::record_put_object_stage_duration_from("rdma_put_body_wait", wait_started);
Ok(Some(chunk))
}
}
/// Builds the streaming body for a PUT whose bytes live in the client's RDMA
/// buffer (`x-amz-rdma-token`, empty HTTP body). The object length is the
/// token's buffer length. Returns the body and that length.
///
/// With `zero_copy` the body's chunks are the staging chunks themselves, so a
/// consumer that keeps a chunk keeps it out of the pool: only callers whose
/// body is consumed and dropped with the request (UploadPart) may set it.
/// PutObject may hand its body to the object data cache, so it copies.
pub(crate) fn rdma_put_body(bucket: &str, key: &str, token: &RdmaToken, zero_copy: bool) -> S3Result<(Body, u64)> {
/// Each completed frame owns its staging chunk until the consumer releases it.
pub(crate) fn rdma_put_body(bucket: &str, key: &str, token: &RdmaToken) -> S3Result<(Body, u64)> {
let service = SERVICE
.get()
.ok_or_else(|| S3Error::with_message(S3ErrorCode::NotImplemented, "rdma put is not enabled"))?;
@@ -822,45 +841,18 @@ pub(crate) fn rdma_put_body(bucket: &str, key: &str, token: &RdmaToken, zero_cop
let read_ahead = service.put_read_ahead;
let total = token.buffer_len;
let length = usize::try_from(total).map_err(|_| S3Error::with_message(S3ErrorCode::EntityTooLarge, "rdma put too large"))?;
let chunk_bytes = server.chunk_bytes();
let object = format!("{bucket}/{key}");
let token = token.clone();
// Keep `read_ahead` RDMA reads in flight, so the reads of the following
// chunks overlap the consumer's work on this one. The first ones start
// now, overlapping the request's setup.
let fill = move |server: &Arc<CuObjectServer>,
object: &str,
token: &RdmaToken,
pending: &mut VecDeque<StagedRead>,
next_offset: &mut u64| {
while pending.len() < read_ahead && *next_offset < total {
let len = usize::try_from((total - *next_offset).min(chunk_bytes as u64)).unwrap_or(chunk_bytes);
pending.push_back(spawn_staged_read(server, object, token, *next_offset, len));
*next_offset += len as u64;
}
let mut reads = PutReads {
server,
object: format!("{bucket}/{key}"),
token: token.clone(),
next_offset: 0,
read_ahead,
pending: VecDeque::new(),
};
let mut pending = VecDeque::with_capacity(read_ahead);
let mut next_offset = 0u64;
fill(&server, &object, &token, &mut pending, &mut next_offset);
// State: (reads in flight in offset order, offset of the next read to start).
let stream = futures::stream::try_unfold((pending, next_offset), move |(mut pending, mut next_offset)| {
let server = Arc::clone(&server);
let object = object.clone();
let token = token.clone();
async move {
fill(&server, &object, &token, &mut pending, &mut next_offset);
let Some(read) = pending.pop_front() else {
return Ok(None);
};
let wait_started = rustfs_io_metrics::put_stage_timer();
let chunk = read
.await
.map_err(|error| io::Error::other(format!("rdma put read task: {error}")))?
.map_err(|error| io::Error::other(format!("rdma put read: {error}")))?;
rustfs_io_metrics::record_put_object_stage_duration_from("rdma_put_body_wait", wait_started);
let bytes = staged_bytes(chunk, zero_copy)?;
Ok::<_, io::Error>(Some((bytes, (pending, next_offset))))
}
reads.prefetch();
let stream = futures::stream::try_unfold(reads, move |mut reads| async move {
let Some(chunk) = reads.next().await? else { return Ok(None) };
Ok::<_, io::Error>(Some((Bytes::from_owner(chunk), reads)))
});
Ok((super::native_body::from_io_stream_with_length(stream, Some(length)), total))
}
+1 -1
View File
@@ -239,7 +239,7 @@ mod put;
mod put_input;
#[cfg(test)]
pub(crate) use native_body::from_legacy as legacy_put_body;
pub(crate) use native_body::{BodyChunks, FrameTrailers};
pub(crate) use native_body::{BodyChunks, FrameTrailers, upload_frame_reader};
pub(crate) use put_input::{PutObjectWriteInput, PutObjectWriteOutput};
pub(crate) mod request_body;
mod restore;
+61 -2
View File
@@ -18,10 +18,10 @@
use crate::app::storage_api::request_body::StdError;
#[cfg(test)]
use crate::app::storage_api::request_body::{ByteStream, StreamingBlob};
use bytes::Bytes;
use futures::Stream;
use bytes::{Buf, Bytes};
#[cfg(test)]
use futures::StreamExt;
use futures::{Stream, TryStreamExt};
use http::HeaderMap;
use http_body::Body as _;
use parking_lot::Mutex;
@@ -33,6 +33,35 @@ use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
/// StreamReader keeps its last Buf while polling the producer. Release a consumed
/// frame immediately so a bounded producer can reuse its registration.
struct UploadFrame(Bytes);
impl Buf for UploadFrame {
fn remaining(&self) -> usize {
self.0.len()
}
fn chunk(&self) -> &[u8] {
&self.0
}
fn advance(&mut self, count: usize) {
if count == self.0.len() {
self.0 = Bytes::new();
} else {
self.0.advance(count);
}
}
}
pub(crate) fn upload_frame_reader<S>(stream: S) -> impl tokio::io::AsyncRead
where
S: Stream<Item = std::io::Result<Bytes>> + Unpin,
{
tokio_util::io::StreamReader::new(stream.map_ok(UploadFrame))
}
/// The legacy edge preserves the producer's length hint without enforcing it a second time.
#[cfg(test)]
pub(crate) fn from_legacy(body: StreamingBlob) -> Body {
@@ -248,6 +277,36 @@ impl<S: Stream<Item = std::io::Result<Bytes>>> PayloadStream for IoPayload<S> {
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn streaming_put_releases_a_consumed_frame_before_reserving_the_next() {
use tokio::io::AsyncReadExt;
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
struct Registered {
_lease: OwnedSemaphorePermit,
}
impl AsRef<[u8]> for Registered {
fn as_ref(&self) -> &[u8] {
b"abc"
}
}
let slot = Arc::new(Semaphore::new(1));
let stream = futures::stream::iter((0..3).map(|_| {
let lease = slot.clone().try_acquire_owned().expect("previous frame released");
Ok(Bytes::from_owner(Registered { _lease: lease }))
}));
let mut reader = upload_frame_reader(stream);
let mut prefix = [0; 2];
reader.read_exact(&mut prefix).await.unwrap();
assert_eq!(&prefix, b"ab");
assert_eq!(slot.available_permits(), 0);
let mut tail = Vec::new();
reader.read_to_end(&mut tail).await.unwrap();
assert_eq!(tail, b"cabcabc");
assert_eq!(slot.available_permits(), 1);
}
use crate::app::storage_api::request_body::RemainingLength;
use std::collections::VecDeque;
use std::sync::atomic::{AtomicUsize, Ordering};
+72 -21
View File
@@ -599,7 +599,20 @@ where
Ok(std::io::Cursor::new(buf))
}
async fn read_zero_copy_put_body_exact<S, E>(mut body: S, size: usize) -> rustfs_s3_types::S3Result<ChunkedBytesReader>
// Frames retained by an eager reader or cache may outlive the next RDMA reservation.
fn retained_put_frame(frame: Bytes, release_staging: bool) -> Bytes {
if release_staging {
Bytes::copy_from_slice(&frame)
} else {
frame
}
}
async fn read_zero_copy_put_body_exact<S, E>(
mut body: S,
size: usize,
registered_body: bool,
) -> rustfs_s3_types::S3Result<ChunkedBytesReader>
where
S: futures::Stream<Item = std::result::Result<Bytes, E>> + Unpin,
E: Into<StdError>,
@@ -621,7 +634,8 @@ where
rustfs_io_metrics::record_zero_copy_buffer_operation("put_chunk", chunk.len());
filled += chunk.len();
chunks.push(chunk);
let release_staging = registered_body && chunk.len() < size;
chunks.push(retained_put_frame(chunk, release_staging));
}
while let Some(chunk) = body.next().await {
@@ -1042,6 +1056,7 @@ pub(super) enum PutObjectOrigin<'a> {
S3 {
req: &'a RequestEnvelope,
event_name: EventName,
registered_body: bool,
},
/// A trusted in-process caller writing on the server's behalf. There is no
/// request and no credential: managed-SSE authorization treats the write
@@ -1415,12 +1430,8 @@ impl DefaultObjectUsecase {
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
let (body, content_length, rdma_put) = match super::cuobject::rdma_token_for_request(envelope.headers()) {
Some(token) if content_length.unwrap_or(0) == 0 => {
// Zero-copy only when the body cannot outlive the request in the
// object data cache (fill-on-put keeps it).
let zero_copy =
!i64::try_from(token.buffer_len).is_ok_and(|size| put_body_may_fill_cache(&self.object_data_cache(), size));
let (body, total) = super::cuobject::rdma_put_body(&bucket, &key, &token, zero_copy)?;
let total = i64::try_from(total).map_err(|_| S3Error::new(S3ErrorCode::EntityTooLarge))?;
let total = i64::try_from(token.buffer_len).map_err(|_| S3Error::new(S3ErrorCode::EntityTooLarge))?;
let (body, _) = super::cuobject::rdma_put_body(&bucket, &key, &token)?;
(Some(body), Some(total), Some(total))
}
_ => (body, content_length, None),
@@ -1491,6 +1502,7 @@ impl DefaultObjectUsecase {
origin: PutObjectOrigin::S3 {
req: &envelope,
event_name,
registered_body: rdma_put.is_some(),
},
};
#[cfg_attr(
@@ -1498,8 +1510,6 @@ impl DefaultObjectUsecase {
allow(unused_mut, reason = "mutated only by the cuObject RDMA branch")
)]
let mut committed = self.put_object_core(write, body, input.frame_trailers, start_time).await?;
#[cfg(not(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux")))]
let _ = rdma_put;
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
if let Some(moved) = rdma_put {
committed
@@ -1973,11 +1983,18 @@ impl DefaultObjectUsecase {
let fill_on_put_collector =
put_body_cache_collector(&cache_adapter, size, should_compress, ciphertext_passthrough, headers);
let reader_prepare_stage_start = put_stage_metrics_enabled.then(Instant::now);
let registered_body = matches!(
origin,
PutObjectOrigin::S3 {
registered_body: true,
..
}
);
let mut reader = if should_compress {
let compressed_reader_stage_start = put_stage_metrics_enabled.then(Instant::now);
let body = tokio::io::BufReader::with_capacity(
buffer_size,
StreamReader::new(body.map(|f| f.map_err(s3s_body_error_to_io))),
upload_frame_reader(body.map(|f| f.map_err(s3s_body_error_to_io))),
);
let algorithm = CompressionAlgorithm::default();
insert_str(&mut metadata, SUFFIX_COMPRESSION, compression_metadata_value(algorithm));
@@ -2007,7 +2024,7 @@ impl DefaultObjectUsecase {
if use_zero_copy_eager_put_path {
let zero_copy_start = std::time::Instant::now();
let eager_read_stage_start = put_stage_metrics_enabled.then(Instant::now);
let eager_body = read_zero_copy_put_body_exact(body, body_size as usize).await?;
let eager_body = read_zero_copy_put_body_exact(body, body_size as usize, registered_body).await?;
rustfs_io_metrics::record_put_object_stage_duration_from("app_body_eager_read_zero_copy", eager_read_stage_start);
rustfs_io_metrics::record_zero_copy_write(body_size as usize, zero_copy_start.elapsed().as_secs_f64() * 1000.0);
let hash_reader_stage_start = put_stage_metrics_enabled.then(Instant::now);
@@ -2026,7 +2043,7 @@ impl DefaultObjectUsecase {
// for ≤4KiB is negligible cost.
let eager_read_stage_start = put_stage_metrics_enabled.then(Instant::now);
let eager_body = read_small_put_body_exact_direct(
StreamReader::new(body.map(|f| f.map_err(s3s_body_error_to_io))),
upload_frame_reader(body.map(|f| f.map_err(s3s_body_error_to_io))),
body_size as usize,
)
.await?;
@@ -2054,7 +2071,7 @@ impl DefaultObjectUsecase {
let pool = get_concurrency_manager().bytes_pool();
let eager_read_stage_start = put_stage_metrics_enabled.then(Instant::now);
let eager_body = read_small_put_body_exact_pooled(
StreamReader::new(body.map(|f| f.map_err(s3s_body_error_to_io))),
upload_frame_reader(body.map(|f| f.map_err(s3s_body_error_to_io))),
body_size as usize,
pool.as_ref(),
)
@@ -2086,13 +2103,13 @@ impl DefaultObjectUsecase {
let collector = fill_on_put_collector.clone();
let body = tokio::io::BufReader::with_capacity(
buffer_size,
StreamReader::new(body.map(move |f| {
upload_frame_reader(body.map(move |f| {
let f = f.map_err(s3s_body_error_to_io);
if let (Some(collector), Ok(frame)) = (&collector, &f) {
collector
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.push(frame.clone());
.push(retained_put_frame(frame.clone(), registered_body));
}
f
})),
@@ -2122,7 +2139,7 @@ impl DefaultObjectUsecase {
rustfs_io_metrics::record_put_object_stage_duration_from("ingress_prepare", ingress_stage_start);
let (mut completion, request_context) = match &origin {
PutObjectOrigin::S3 { req, event_name } => (
PutObjectOrigin::S3 { req, event_name, .. } => (
PutObjectCompletion::S3(OperationHelper::from_view(&req.audit_view(), *event_name, S3Operation::PutObject)),
req.request_context().cloned(),
),
@@ -3809,6 +3826,40 @@ mod tests {
assert!(!small_eager);
}
#[tokio::test]
async fn eager_rdma_reader_releases_each_multi_frame_owner_before_polling_again() {
use std::sync::atomic::{AtomicUsize, Ordering};
struct Frame(Arc<AtomicUsize>);
impl AsRef<[u8]> for Frame {
fn as_ref(&self) -> &[u8] {
b"abcd"
}
}
impl Drop for Frame {
fn drop(&mut self) {
self.0.fetch_add(1, Ordering::SeqCst);
}
}
let released = Arc::new(AtomicUsize::new(0));
let body = futures::stream::iter((0..3).map(|i| {
assert_eq!(released.load(Ordering::SeqCst), i);
Ok::<_, std::io::Error>(Bytes::from_owner(Frame(released.clone())))
}));
let _reader = read_zero_copy_put_body_exact(body, 12, true).await.unwrap();
assert_eq!(released.load(Ordering::SeqCst), 3);
let body = futures::stream::once(std::future::ready(Ok::<_, std::io::Error>(Bytes::from_owner(Frame(released.clone())))));
let reader = read_zero_copy_put_body_exact(body, 4, true).await.unwrap();
assert_eq!(released.load(Ordering::SeqCst), 3);
drop(reader);
assert_eq!(released.load(Ordering::SeqCst), 4);
let frame = Bytes::from_owner(Frame(released.clone()));
let cached = retained_put_frame(frame, true);
assert_eq!(released.load(Ordering::SeqCst), 5);
assert_eq!(cached.as_ref(), b"abcd");
}
#[test]
fn should_use_zero_copy_eager_put_path_allows_large_plain_objects_within_cap() {
let headers = HeaderMap::new();
@@ -3879,7 +3930,7 @@ mod tests {
async fn read_zero_copy_put_body_maps_upload_stream_sha256_mismatch_to_content_sha256_mismatch() {
let body = futures::stream::iter(vec![Err::<Bytes, UploadStreamError>(UploadStreamError::Sha256Mismatch)]);
let error = match read_zero_copy_put_body_exact(body, 1).await {
let error = match read_zero_copy_put_body_exact(body, 1, false).await {
Ok(_) => panic!("SHA256 mismatch should reject the zero-copy PUT body"),
Err(error) => error,
};
@@ -3933,7 +3984,7 @@ mod tests {
let pool = BytesPool::with_config(BytesPoolConfig::default());
assert_producer_failure(read_small_put_body_exact_pooled(stream_reader(), 2, &pool).await, "pooled");
let zero_copy = futures::stream::iter([Ok(Bytes::from_static(b"a")), Err(producer_error())]);
assert_producer_failure(read_zero_copy_put_body_exact(zero_copy, 2).await, "zero-copy");
assert_producer_failure(read_zero_copy_put_body_exact(zero_copy, 2, false).await, "zero-copy");
}
struct FragmentedBody {
@@ -4331,7 +4382,7 @@ mod tests {
Ok::<Bytes, std::io::Error>(Bytes::from_static(b"world")),
]);
let mut reader = read_zero_copy_put_body_exact(body, 11)
let mut reader = read_zero_copy_put_body_exact(body, 11, false)
.await
.expect("zero-copy eager body read should succeed");
let mut out = Vec::new();
@@ -4350,7 +4401,7 @@ mod tests {
Ok::<Bytes, std::io::Error>(Bytes::from_static(b"!")),
]);
let err = match read_zero_copy_put_body_exact(body, 5).await {
let err = match read_zero_copy_put_body_exact(body, 5, false).await {
Ok(_) => panic!("extra bytes should fail"),
Err(err) => err,
};