diff --git a/zerofs/Cargo.lock b/zerofs/Cargo.lock index 8b83e5e73..305908495 100644 --- a/zerofs/Cargo.lock +++ b/zerofs/Cargo.lock @@ -496,6 +496,16 @@ dependencies = [ "serde", ] +[[package]] +name = "bytes-utils" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dafe3a8757b027e2be6e4e5601ed563c55989fcf1546e933c66c8eb3a058d35" +dependencies = [ + "bytes", + "either", +] + [[package]] name = "bytestream" version = "0.4.1" @@ -6158,7 +6168,7 @@ dependencies = [ [[package]] name = "zerofs" -version = "2.3.3" +version = "2.3.4" dependencies = [ "anyhow", "arc-swap", @@ -6168,6 +6178,7 @@ dependencies = [ "backon", "bincode", "bytes", + "bytes-utils", "chacha20poly1305", "chrono", "clap", @@ -6268,7 +6279,7 @@ dependencies = [ [[package]] name = "zerofs-csi" -version = "2.3.3" +version = "2.3.4" dependencies = [ "anyhow", "clap", diff --git a/zerofs/Cargo.toml b/zerofs/Cargo.toml index 49b1313e6..1b81da75c 100644 --- a/zerofs/Cargo.toml +++ b/zerofs/Cargo.toml @@ -30,7 +30,7 @@ members = [ # same release, so the version the driver reports (GetPluginInfo) must not # drift from zerofs's. [workspace.package] -version = "2.3.3" +version = "2.3.4" [profile.release] lto = true @@ -100,6 +100,7 @@ rustls = { version = "0.23", default-features = false, features = [ ] } redis = { version = "1.0", default-features = false, features = ["tokio-comp", "script"] } bytes = "1.10" +bytes-utils = "0.1.4" serde = { version = "1.0", features = ["derive"] } bincode = "1.3" rand = "0.8" diff --git a/zerofs/src/frame_codec.rs b/zerofs/src/frame_codec.rs index c9b19d645..10793ed90 100644 --- a/zerofs/src/frame_codec.rs +++ b/zerofs/src/frame_codec.rs @@ -14,9 +14,10 @@ //! Compression is auto-detected on `open` from the (decrypted) payload, so a //! codec configured for one algorithm decodes frames written by the other. +use bytes::{Bytes, BytesMut}; use chacha20poly1305::{ - Key, XChaCha20Poly1305, XNonce, - aead::{Aead, AeadInPlace, KeyInit, Payload}, + Key, Tag, XChaCha20Poly1305, XNonce, + aead::{AeadInPlace, KeyInit}, }; use hkdf::Hkdf; use rand::{RngCore, thread_rng}; @@ -45,19 +46,15 @@ pub enum CodecError { LockedMemory(String), } -/// A frame's compressed (but not encrypted) payload: what sits between -/// [`FrameCodec::compress`] and [`FrameCodec::seal_compressed`], or comes out of -/// [`FrameCodec::open_compressed`]. A distinct type so plaintext can't be sealed -/// as if pre-compressed (double compression on read) nor a compressed payload -/// served as plaintext; the only ways out are `seal_compressed` (re-encrypt -/// as-is, the segment-repack passthrough) and `decompress`. +/// Compressed payload for [`FrameCodec::seal_compressed`], kept distinct from +/// plaintext. Includes nonce space and spare tag capacity for sealing in place. pub struct Compressed(Vec); impl Compressed { /// Compressed payload size. #[allow(clippy::len_without_is_empty)] // a compressed payload is never empty pub fn len(&self) -> usize { - self.0.len() + self.0.len() - NONCE_SIZE } } @@ -122,20 +119,16 @@ impl FrameCodec { /// output without a decompress/recompress round trip. pub fn seal_compressed( &self, - Compressed(compressed): Compressed, + Compressed(mut out): Compressed, aad: &[u8], ) -> Result, CodecError> { - let mut out = Vec::with_capacity(NONCE_SIZE + compressed.len() + TAG_SIZE); - let mut nonce_bytes = [0u8; NONCE_SIZE]; - thread_rng().fill_bytes(&mut nonce_bytes); - out.extend_from_slice(&nonce_bytes); - out.extend_from_slice(&compressed); - let nonce = XNonce::from_slice(&nonce_bytes); + let (nonce, compressed) = out.split_at_mut(NONCE_SIZE); + thread_rng().fill_bytes(nonce); // The long-lived subkey stays in locked memory. The RustCrypto cipher // is an operation-local copy whose destructor zeroizes its key. let cipher = XChaCha20Poly1305::new(Key::from_slice(self.subkey.expose_secret())); let tag = cipher - .encrypt_in_place_detached(nonce, aad, &mut out[NONCE_SIZE..]) + .encrypt_in_place_detached(XNonce::from_slice(nonce), aad, compressed) .map_err(|_| CodecError::Encrypt)?; out.extend_from_slice(tag.as_slice()); Ok(out) @@ -144,49 +137,72 @@ impl FrameCodec { /// Decrypt (verifying `aad`) then decompress a frame produced by [`Self::seal`]. pub fn open(&self, frame: &[u8], aad: &[u8]) -> Result, CodecError> { let Compressed(compressed) = self.open_compressed(frame, aad)?; - self.decompress(&compressed) + self.decompress(&compressed[NONCE_SIZE..]) + } + + /// Decode a frame, reusing its allocation when possible. + pub(crate) fn open_owned(&self, frame: Bytes, aad: &[u8]) -> Result, CodecError> { + let mut frame = BytesMut::from(frame); + self.decompress(self.decrypt_in_place(&mut frame, aad)?) } /// Decrypt (verifying `aad`) a frame, returning its still-compressed payload. - /// `open(frame, aad)` is exactly `decompress(open_compressed(frame, aad))`; - /// the split lets a relocation verify and rebind a frame without ever - /// materializing (or recompressing) the plaintext. + /// Relocation can rebind it to new AAD without decompressing or recompressing. pub fn open_compressed(&self, frame: &[u8], aad: &[u8]) -> Result { + let mut out = frame.to_vec(); + self.decrypt_in_place(&mut out, aad)?; + out.truncate(out.len() - TAG_SIZE); + Ok(Compressed(out)) + } + + fn decrypt_in_place<'a>( + &self, + frame: &'a mut [u8], + aad: &[u8], + ) -> Result<&'a mut [u8], CodecError> { if frame.len() < NONCE_SIZE + TAG_SIZE { return Err(CodecError::TooShort(frame.len())); } - let (nonce_bytes, ciphertext) = frame.split_at(NONCE_SIZE); - let nonce = XNonce::from_slice(nonce_bytes); + let (nonce, body) = frame.split_at_mut(NONCE_SIZE); + let (ciphertext, tag) = body.split_at_mut(body.len() - TAG_SIZE); // See `seal_compressed`: only the persistent key is required to remain // in locked memory; this operation-local cipher zeroizes on drop. let cipher = XChaCha20Poly1305::new(Key::from_slice(self.subkey.expose_secret())); cipher - .decrypt( - nonce, - Payload { - msg: ciphertext, - aad, - }, + .decrypt_in_place_detached( + XNonce::from_slice(nonce), + aad, + ciphertext, + Tag::from_slice(tag), ) - .map(Compressed) - .map_err(|_| CodecError::Decrypt) + .map_err(|_| CodecError::Decrypt)?; + Ok(ciphertext) } /// Compress `data` with the configured codec. Pure: the output depends only /// on the bytes and the configured level, never on shared state, so it can /// run on any thread, outside any lock, and feed [`Self::seal_compressed`]. pub fn compress(&self, data: &[u8]) -> Result { + let bound = self.max_sealed_size(data.len()) as usize; + let mut out = Vec::with_capacity(bound); + out.resize(NONCE_SIZE, 0); + out.extend_from_slice(&(data.len() as u32).to_le_bytes()); match self.compression { - CompressionConfig::Lz4 => Ok(Compressed(lz4_flex::compress_prepend_size(data))), + CompressionConfig::Lz4 => { + out.resize(bound - TAG_SIZE, 0); + let len = lz4_flex::block::compress_into(data, &mut out[NONCE_SIZE + 4..]) + .map_err(|e| CodecError::Compress(e.to_string()))?; + out.truncate(NONCE_SIZE + 4 + len); + } CompressionConfig::Zstd(level) => { - let compressed = zstd_compress(data, level)?; - // Prepend original size (LE u32) for decompression. - let mut result = Vec::with_capacity(4 + compressed.len()); - result.extend_from_slice(&(data.len() as u32).to_le_bytes()); - result.extend_from_slice(&compressed); - Ok(Compressed(result)) + let mut dest = std::io::Cursor::new(&mut out); + dest.set_position((NONCE_SIZE + 4) as u64); + zstd_compress(data, level, &mut dest)?; } } + // Release excess capacity, keeping room for the authentication tag. + out.shrink_to(out.len() + TAG_SIZE); + Ok(Compressed(out)) } fn decompress(&self, data: &[u8]) -> Result, CodecError> { @@ -207,7 +223,11 @@ impl FrameCodec { /// 32 KiB frame costs more than low-level compression itself. Keyed by level so /// codecs at different levels (or a config change) rebuild it; the output is /// byte-identical to one-shot `zstd::bulk::compress` at the same level. -fn zstd_compress(data: &[u8], level: i32) -> Result, CodecError> { +fn zstd_compress( + data: &[u8], + level: i32, + dest: &mut impl zstd::zstd_safe::WriteBuf, +) -> Result { use std::cell::RefCell; thread_local! { static ZSTD: RefCell)>> = @@ -223,7 +243,7 @@ fn zstd_compress(data: &[u8], level: i32) -> Result, CodecError> { slot.as_mut() .expect("compressor installed above") .1 - .compress(data) + .compress_to_buffer(data, dest) .map_err(|e| CodecError::Compress(e.to_string())) }) } @@ -231,12 +251,41 @@ fn zstd_compress(data: &[u8], level: i32) -> Result, CodecError> { #[cfg(test)] mod tests { use super::*; + use rand::SeedableRng; fn codec() -> FrameCodec { FrameCodec::try_new(&[7u8; 32], b"frame-codec-test", CompressionConfig::Lz4) .expect("test key should be lockable") } + #[test] + fn owned_and_shared_frames_preserve_authentication_and_cached_ciphertext() { + for compression in [CompressionConfig::Lz4, CompressionConfig::Zstd(3)] { + let c = FrameCodec::try_new(&[7; 32], b"decode-ownership", compression).unwrap(); + let plain = vec![0x5a; 32768]; + let sealed = c.seal(&plain, b"correct aad").unwrap(); + assert_eq!( + c.open_owned(Bytes::from(sealed.clone()), b"correct aad") + .unwrap(), + plain + ); + let shared = Bytes::from(sealed.clone()); + assert_eq!(c.open_owned(shared.clone(), b"correct aad").unwrap(), plain); + assert_eq!(shared.as_ref(), sealed); + assert!(matches!( + c.open_owned(shared.clone(), b"wrong aad"), + Err(CodecError::Decrypt) + )); + assert_eq!(shared.as_ref(), sealed); + let mut corrupt = sealed; + *corrupt.last_mut().unwrap() ^= 1; + assert!(matches!( + c.open_owned(Bytes::from(corrupt), b"correct aad"), + Err(CodecError::Decrypt) + )); + } + } + // seal() must remain exactly seal_compressed(compress(..)): the write path // splits the phases around a lock and both halves must roundtrip together. #[test] @@ -246,16 +295,40 @@ mod tests { FrameCodec::try_new(&[7u8; 32], b"frame-codec-test", CompressionConfig::Zstd(3)) .expect("test key should be lockable"), ] { - let plain = vec![9u8; 40_000]; - let sealed = c - .seal_compressed(c.compress(&plain).unwrap(), b"aad") - .unwrap(); - assert!(sealed.len() as u64 <= c.max_sealed_size(plain.len())); - assert_eq!(c.open(&sealed, b"aad").unwrap(), plain); - assert!(matches!( - c.open(&sealed, b"other"), - Err(CodecError::Decrypt) - )); + let mut random = vec![0; 40_000]; + rand::rngs::StdRng::seed_from_u64(7).fill_bytes(&mut random); + for plain in [vec![], vec![9u8; 40_000], random] { + let expected = match c.compression { + CompressionConfig::Lz4 => lz4_flex::compress_prepend_size(&plain), + CompressionConfig::Zstd(level) => { + let mut bytes = (plain.len() as u32).to_le_bytes().to_vec(); + bytes.extend(zstd::bulk::compress(&plain, level).unwrap()); + bytes + } + }; + let compressed = c.compress(&plain).unwrap(); + assert_eq!(&compressed.0[NONCE_SIZE..], expected); + assert_eq!(compressed.len(), expected.len()); + assert_eq!( + compressed.0.capacity(), + NONCE_SIZE + expected.len() + TAG_SIZE + ); + let allocation = compressed.0.as_ptr(); + let sealed = c.seal_compressed(compressed, b"aad").unwrap(); + assert_eq!(sealed.as_ptr(), allocation); + assert!(sealed.len() as u64 <= c.max_sealed_size(plain.len())); + assert_eq!(c.open(&sealed, b"aad").unwrap(), plain); + assert!(matches!( + c.open(&sealed, b"other"), + Err(CodecError::Decrypt) + )); + let compressed = c.open_compressed(&sealed, b"aad").unwrap(); + assert_eq!(&compressed.0[NONCE_SIZE..], expected); + let allocation = compressed.0.as_ptr(); + let resealed = c.seal_compressed(compressed, b"relocated").unwrap(); + assert_eq!(resealed.as_ptr(), allocation); + assert_eq!(c.open(&resealed, b"relocated").unwrap(), plain); + } } } diff --git a/zerofs/src/fs/ops/io.rs b/zerofs/src/fs/ops/io.rs index 3b83abcf7..897cd7417 100644 --- a/zerofs/src/fs/ops/io.rs +++ b/zerofs/src/fs/ops/io.rs @@ -15,7 +15,8 @@ use crate::fs::types::{AuthContext, FallocateMode, FileAttributes, InodeWithId}; use crate::fs::write_coordinator::LockedMutation; use crate::fs::{ZeroFS, get_current_time}; use ::tracing::{debug, error}; -use bytes::Bytes; +use bytes::{Buf, Bytes}; +use bytes_utils::SegmentedBuf; use std::sync::atomic::Ordering; impl ZeroFS { @@ -231,7 +232,8 @@ impl ZeroFS { offset: u64, count: u32, ) -> Result<(Bytes, bool), FsError> { - self.read_file_inner(Some(auth), id, offset, count).await + let (mut data, eof) = self.read_file_inner(Some(auth), id, offset, count).await?; + Ok((data.copy_to_bytes(data.remaining()), eof)) } /// Read through a fid whose read access was already authorized at open. @@ -240,7 +242,7 @@ impl ZeroFS { id: InodeId, offset: u64, count: u32, - ) -> Result<(Bytes, bool), FsError> { + ) -> Result<(SegmentedBuf, bool), FsError> { self.read_file_inner(None, id, offset, count).await } @@ -250,7 +252,7 @@ impl ZeroFS { id: InodeId, offset: u64, count: u32, - ) -> Result<(Bytes, bool), FsError> { + ) -> Result<(SegmentedBuf, bool), FsError> { debug!("read_file: id={}, offset={}, count={}", id, offset, count); let inode = self.inode_store.get(id).await?; @@ -268,16 +270,16 @@ impl ZeroFS { id, FileOperation::Read { offset, length: 0 }, ); - return Ok((Bytes::new(), true)); + return Ok((SegmentedBuf::new(), true)); } let read_len = std::cmp::min(count as u64, file.size - offset); - let result_bytes = self.extent_store.read(id, offset, read_len).await?; + let result_bytes = self.extent_store.read_chunks(id, offset, read_len).await?; let eof = offset + read_len >= file.size; self.stats .bytes_read - .fetch_add(result_bytes.len() as u64, Ordering::Relaxed); + .fetch_add(result_bytes.remaining() as u64, Ordering::Relaxed); self.stats.read_operations.fetch_add(1, Ordering::Relaxed); self.stats.total_operations.fetch_add(1, Ordering::Relaxed); diff --git a/zerofs/src/fs/ops/setattr.rs b/zerofs/src/fs/ops/setattr.rs index 278043ff6..44cb7eff4 100644 --- a/zerofs/src/fs/ops/setattr.rs +++ b/zerofs/src/fs/ops/setattr.rs @@ -762,7 +762,7 @@ mod tests { .unwrap(); assert_eq!(attrs.size, 500); let (data, _) = fs.read_file_opened(file_id, 0, 1000).await.unwrap(); - assert_eq!(data.len(), 500); + assert_eq!(bytes::Buf::remaining(&data), 500); } #[tokio::test] diff --git a/zerofs/src/fs/store/extent/mod.rs b/zerofs/src/fs/store/extent/mod.rs index f37daa663..10f23d1df 100644 --- a/zerofs/src/fs/store/extent/mod.rs +++ b/zerofs/src/fs/store/extent/mod.rs @@ -28,7 +28,6 @@ use crate::fs::write_coordinator::{LockedMutation, WeakWriteCoordinator}; use crate::fs::{EXTENT_SIZE, FsError}; use crate::segment::Segid; use crate::segment_store::SegmentStore; -use bytes::Bytes; use chrono::{DateTime, Utc}; use foyer::{Cache, CacheBuilder}; use futures::stream::StreamExt; @@ -39,7 +38,7 @@ use tokio::sync::Semaphore; use tokio::time::Instant; use tracing::error; pub(crate) use write::SEAL_THRESHOLD; -use write::{MAX_INFLIGHT_SEALS, OpenSegment}; +use write::{MAX_INFLIGHT_SEALS, OpenSegment, SealingSegment}; pub(super) const PARALLEL_EXTENT_OPS: usize = 20; @@ -77,10 +76,10 @@ pub struct ExtentStore { /// crosses the threshold keeps this gate while waiting for a seal permit, /// so later writers cannot keep extending an overdue open segment. append_gate: Arc>, - /// Finalized bytes of segments whose PUT is in flight (or failed and pending a + /// Finalized segments whose PUT is in flight (or failed and pending a /// re-PUT). Reads consult these before the object store. Ordered so the /// barrier's re-PUT sequence is deterministic (seal order). - sealing: Arc>>, + sealing: Arc>>, /// Permits = max in-flight seals; acquiring all is the fsync drain barrier. seal_sem: Arc, /// Deadline after which each currently-dead segment may be deleted: @@ -131,7 +130,7 @@ impl ExtentStore { let codec = segments.codec(); let open = Arc::new(Mutex::new(OpenSegment { segid: segments.next_segid(), - buf: Vec::new(), + chunks: Vec::new(), dir: Vec::new(), })); Self { @@ -243,13 +242,13 @@ impl ExtentStore { /// include frames superseded by newer buffered writes, so it is not a live- /// byte subset. Read fresh (it is volatile); cheap in-memory lengths. pub fn unflushed_bytes(&self) -> u64 { - let open = self.open.lock().unwrap().buf.len() as u64; + let open = self.open.lock().unwrap().byte_len() as u64; let sealing: u64 = self .sealing .lock() .unwrap() .values() - .map(|b| b.len() as u64) + .map(|s| s.payload.content_length() as u64) .sum(); open + sealing } @@ -291,6 +290,7 @@ impl ExtentStore { mod tests { use super::test_util::*; use super::*; + use bytes::Bytes; #[tokio::test] async fn concurrent_commits_preserve_counter_deltas() { diff --git a/zerofs/src/fs/store/extent/read.rs b/zerofs/src/fs/store/extent/read.rs index 2fc0a6648..452e93dba 100644 --- a/zerofs/src/fs/store/extent/read.rs +++ b/zerofs/src/fs/store/extent/read.rs @@ -7,8 +7,9 @@ use super::{ExtentStore, ZERO_EXTENT}; use crate::failpoints::{self as fp, fail_point}; use crate::fs::inode::InodeId; use crate::fs::{EXTENT_SIZE, FsError}; -use crate::segment::{FrameLoc, Segid}; -use bytes::{Bytes, BytesMut}; +use crate::segment::{DirEntry, FrameLoc, LEN_PREFIX, Segid}; +use bytes::{Buf, Bytes}; +use bytes_utils::SegmentedBuf; use futures::stream::StreamExt; use std::collections::HashMap; use std::sync::Arc; @@ -186,8 +187,7 @@ impl ExtentStore { /// Read a contiguous run of frames from the open or an in-flight sealing /// buffer (read-your-writes), or `None` if `segid` is already on the object - /// store. Frame offsets are identical in the buffer and the finalized - /// segment, so the same slice works for both. + /// store. Release the buffer lock before decrypting and decompressing. fn read_frames_in_ram( &self, segid: Segid, @@ -196,55 +196,73 @@ impl ExtentStore { first_frame: u32, slots: &[(InodeId, u64)], ) -> Result>, FsError> { + let Some(chunks) = + self.frame_chunks_in_ram(segid, byte_offset, byte_len, first_frame, slots.len())? + else { + return Ok(None); + }; + let frames = + crate::segment::read_frames_from_chunks(&self.codec, chunks, segid, first_frame, slots) + .map_err(|_| FsError::IoError)?; + Ok(Some(frames.into_iter().map(Bytes::from).collect())) + } + + pub(super) fn frame_chunks_in_ram( + &self, + segid: Segid, + byte_offset: u64, + byte_len: u32, + first_frame: u32, + count: usize, + ) -> Result>, FsError> { // The range comes from a db-stored FrameLoc: bounds-checked, never // trusted, so a corrupt value surfaces as EIO instead of an // out-of-range panic that would poison the open-segment lock for // every later writer. - fn region( - buf: &[u8], - segid: Segid, + fn region<'a>( + chunks: &'a [Bytes], + dir: &[DirEntry], byte_offset: u64, byte_len: u32, - ) -> Result<&[u8], FsError> { - let start = byte_offset as usize; - start - .checked_add(byte_len as usize) - .and_then(|end| buf.get(start..end)) + first_frame: u32, + count: usize, + ) -> Option<&'a [Bytes]> { + let start = first_frame as usize; + let end = start.checked_add(count)?; + let entries = dir.get(start..end)?; + let first = entries.first()?; + let last = entries.last()?; + let range_end = last + .byte_offset + .checked_add(LEN_PREFIX as u64 + last.len as u64)?; + if first.byte_offset != byte_offset + || range_end != byte_offset.checked_add(byte_len as u64)? + { + return None; + } + chunks.get(start.checked_mul(2)?..end.checked_mul(2)?) + } + let select = |chunks: &[Bytes], dir: &[DirEntry]| { + region(chunks, dir, byte_offset, byte_len, first_frame, count) + .map(|chunks| Some(chunks.iter().cloned().collect())) .ok_or_else(|| { error!( - "Corrupt FrameLoc for in-RAM {segid:?}: {byte_len} bytes at {byte_offset} \ - exceed the {}-byte buffer", - buf.len() + "Corrupt FrameLoc for in-RAM {segid:?}: {count} frames at \ + {first_frame}, {byte_len} bytes at {byte_offset}" ); FsError::IoError }) - } + }; { let open = self.open.lock().unwrap(); if segid == open.segid { - let frames = crate::segment::read_frames_from_region( - &self.codec, - region(&open.buf, segid, byte_offset, byte_len)?, - segid, - first_frame, - slots, - ) - .map_err(|_| FsError::IoError)?; - return Ok(Some(frames.into_iter().map(Bytes::from).collect())); + return select(&open.chunks, &open.dir); } } { let sealing = self.sealing.lock().unwrap(); - if let Some(bytes) = sealing.get(&segid) { - let frames = crate::segment::read_frames_from_region( - &self.codec, - region(bytes.as_ref(), segid, byte_offset, byte_len)?, - segid, - first_frame, - slots, - ) - .map_err(|_| FsError::IoError)?; - return Ok(Some(frames.into_iter().map(Bytes::from).collect())); + if let Some(segment) = sealing.get(&segid) { + return select(segment.payload.as_ref(), &segment.dir); } } Ok(None) @@ -254,7 +272,17 @@ impl ExtentStore { /// sequential-only logical read-ahead so the next read lands warm in the /// parts cache. pub async fn read(&self, id: InodeId, offset: u64, length: u64) -> Result { - let data = self.read_range(id, offset, length).await?; + let mut data = self.read_chunks(id, offset, length).await?; + Ok(data.copy_to_bytes(data.remaining())) + } + + pub(crate) async fn read_chunks( + &self, + id: InodeId, + offset: u64, + length: u64, + ) -> Result, FsError> { + let data = self.read_range_chunks(id, offset, length, false).await?; self.trigger_read_ahead(id, offset, length); Ok(data) } @@ -301,7 +329,7 @@ impl ExtentStore { if cur_seg.is_some() && cur_seg == this.segment_at(id, tgt_ext).await { return; } - let _ = this.read_range(id, start, end - start).await; + let _ = this.read_range_chunks(id, start, end - start, true).await; })) } @@ -317,23 +345,29 @@ impl ExtentStore { .map(|loc| loc.segid) } - /// A byte-range read with no read-ahead side effect (the raw path; also what - /// the read-ahead task calls, so it never recurses). - async fn read_range(&self, id: InodeId, offset: u64, length: u64) -> Result { + /// Read or prefetch a range without triggering further read-ahead. + async fn read_range_chunks( + &self, + id: InodeId, + offset: u64, + length: u64, + prefetch: bool, + ) -> Result, FsError> { if length == 0 { - return Ok(Bytes::new()); + return Ok(SegmentedBuf::new()); } let end = offset + length; let start_extent = offset / EXTENT_SIZE as u64; let end_extent = (end - 1) / EXTENT_SIZE as u64; let start_offset = (offset % EXTENT_SIZE as u64) as usize; - if start_extent == end_extent { + if !prefetch && start_extent == end_extent { let extent_end = start_offset + length as usize; - return Ok(match self.get(id, start_extent).await? { + let data = match self.get(id, start_extent).await? { Some(data) => data.slice(start_offset..extent_end), - None => Bytes::copy_from_slice(&ZERO_EXTENT[start_offset..extent_end]), - }); + None => Bytes::from_static(&ZERO_EXTENT[start_offset..extent_end]), + }; + return Ok(vec![data].into()); } let start_key = self.key_codec.extent_key(id, start_extent); @@ -362,9 +396,9 @@ impl ExtentStore { // Assemble, coalescing each maximal run of extents that are contiguous in // one segment (consecutive frame index + adjacent byte range) into a - // single ranged GET. This is the read-amplification win: a region written + // single ranged GET. A region written // together reads back in one GET instead of one-per-extent. - let mut result = BytesMut::with_capacity(length as usize); + let mut result = SegmentedBuf::new(); let slice = |c: u64| -> (usize, usize) { let cs = if c == start_extent { start_offset } else { 0 }; let ce = if c == end_extent { @@ -377,10 +411,22 @@ impl ExtentStore { let mut extent = start_extent; while extent <= end_extent { let Some(first) = loc_map.get(&extent).copied() else { - // Hole: this extent contributes zeros. - let (cs, ce) = slice(extent); - result.extend_from_slice(&ZERO_EXTENT[cs..ce]); + // Coalesce holes into shared zero buffers, without materializing them. + let hole_start = (extent * EXTENT_SIZE as u64).max(offset); extent += 1; + while extent <= end_extent && !loc_map.contains_key(&extent) { + extent += 1; + } + if !prefetch { + let hole_end = extent.saturating_mul(EXTENT_SIZE as u64).min(end); + static ZEROES: [u8; 1024 * 1024] = [0; 1024 * 1024]; + let mut left = (hole_end - hole_start) as usize; + while left != 0 { + let n = left.min(ZEROES.len()); + result.push(Bytes::from_static(&ZEROES[..n])); + left -= n; + } + } continue; }; let mut n = 1u64; @@ -402,6 +448,18 @@ impl ExtentStore { _ => break, } } + if prefetch { + let in_ram = self.open.lock().unwrap().segid == first.segid + || self.sealing.lock().unwrap().contains_key(&first.segid); + if !in_ram { + let _ = self + .segments + .prefetch_run(first.segid, first.byte_offset, total_len as u32) + .await; + } + extent += n; + continue; + } // Serve the run from RAM (open or in-flight sealing buffer); else GET. let frames = match self.read_frames_in_ram( first.segid, @@ -438,7 +496,7 @@ impl ExtentStore { let idx = extent + i as u64; Self::validate_extent_frame(id, idx, frame)?; let (cs, ce) = slice(idx); - result.extend_from_slice(&frame[cs..ce]); + result.push(frame.slice(cs..ce)); } } None => { @@ -449,13 +507,13 @@ impl ExtentStore { None => Bytes::from_static(ZERO_EXTENT), }; let (cs, ce) = slice(idx); - result.extend_from_slice(&data[cs..ce]); + result.push(data.slice(cs..ce)); } } } extent += n; } - Ok(result.freeze()) + Ok(result) } } @@ -464,6 +522,59 @@ mod tests { use super::super::test_util::*; use super::*; + #[tokio::test] + async fn sparse_chunks_share_zeroes_and_preserve_unaligned_extent_boundaries() { + let (store, db) = make().await; + let a = store + .read_range_chunks(1, 0, 1024 * 1024, false) + .await + .unwrap(); + let b = store + .read_range_chunks(1, 0, 1024 * 1024, false) + .await + .unwrap(); + assert_eq!(a.segments(), 1); + assert_eq!(a.chunk().as_ptr(), b.chunk().as_ptr()); + assert_eq!(a.remaining(), 1024 * 1024); + let tail = store + .read_range_chunks(1, u64::MAX - 65535, 65535, false) + .await + .unwrap(); + assert_eq!(tail.remaining(), 65535); + let mut model = Vec::new(); + write_and_check(&store, &db, &mut model, 0, &vec![0xab; EXTENT_SIZE]).await; + write_and_check( + &store, + &db, + &mut model, + 2 * EXTENT_SIZE, + &vec![0xcd; EXTENT_SIZE], + ) + .await; + store.seal_open().await.unwrap(); + model.resize(3 * EXTENT_SIZE + 7, 0); + let offset = EXTENT_SIZE - 3; + let len = model.len() - offset; + let mut chunks = store + .read_range_chunks(1, offset as u64, len as u64, false) + .await + .unwrap(); + assert_eq!(chunks.segments(), 4); + assert_eq!( + chunks.copy_to_bytes(chunks.remaining()).as_ref(), + &model[offset..] + ); + let warmed = store + .read_range_chunks(1, 0, model.len() as u64, true) + .await + .unwrap(); + assert_eq!( + warmed.remaining(), + 0, + "prefetch must not materialize read data" + ); + } + #[tokio::test] async fn contiguous_multiextent_read_is_one_ranged_get() { let (store, db) = make().await; @@ -524,7 +635,9 @@ mod tests { txn.put_bytes(&key, Bytes::from_static(&[0u8; FrameLoc::ENCODED_LEN - 1])); commit(&store, txn).await; - let r = store.read_range(1, 0, 3 * EXTENT_SIZE as u64).await; + let r = store + .read_range_chunks(1, 0, 3 * EXTENT_SIZE as u64, false) + .await; assert!(matches!(r, Err(FsError::IoError))); } diff --git a/zerofs/src/fs/store/extent/test_util.rs b/zerofs/src/fs/store/extent/test_util.rs index bdcd7665c..90005d6ee 100644 --- a/zerofs/src/fs/store/extent/test_util.rs +++ b/zerofs/src/fs/store/extent/test_util.rs @@ -31,7 +31,7 @@ use slatedb::{BlockTransformer, DbBuilder}; use std::fmt::{self, Display, Formatter}; use std::ops::Deref; use std::sync::Arc; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::time::Duration; use tokio::time::Instant; use tokio_util::sync::CancellationToken; @@ -99,6 +99,7 @@ pub(super) struct InFlightObjectStore { deletes: Arc, listed: Arc, listed_at_first_delete: Arc, + fail_puts: AtomicBool, } impl InFlightObjectStore { @@ -111,6 +112,7 @@ impl InFlightObjectStore { deletes: Arc::default(), listed: Arc::default(), listed_at_first_delete: Arc::new(AtomicUsize::new(usize::MAX)), + fail_puts: AtomicBool::new(false), }) } @@ -120,6 +122,10 @@ impl InFlightObjectStore { self.deletes.reset_peak(); } + pub(super) fn set_fail_puts(&self, fail: bool) { + self.fail_puts.store(fail, Ordering::Relaxed); + } + pub(super) fn peak_gets(&self) -> usize { self.gets.peak.load(Ordering::SeqCst) } @@ -154,6 +160,12 @@ impl ObjectStore for InFlightObjectStore { ) -> slatedb::object_store::Result { let _guard = self.puts.begin(); tokio::time::sleep(self.delay).await; + if self.fail_puts.load(Ordering::Relaxed) { + return Err(slatedb::object_store::Error::Generic { + store: "test", + source: "injected PUT failure".into(), + }); + } self.inner.put_opts(location, payload, options).await } diff --git a/zerofs/src/fs/store/extent/write.rs b/zerofs/src/fs/store/extent/write.rs index a2333051e..285eaf273 100644 --- a/zerofs/src/fs/store/extent/write.rs +++ b/zerofs/src/fs/store/extent/write.rs @@ -14,9 +14,10 @@ use crate::fs::inode::InodeId; use crate::fs::write_coordinator::LockedMutation; use crate::fs::{EXTENT_SIZE, FsError}; use crate::replication::ReplOp; -use crate::segment::{DirEntry, FrameLoc, Segid}; -use bytes::{Bytes, BytesMut}; +use crate::segment::{DirEntry, FrameLoc, LEN_PREFIX, Segid}; +use bytes::{Buf, Bytes, BytesMut}; use futures::stream::{self, StreamExt, TryStreamExt}; +use slatedb::object_store::PutPayload; use std::collections::{HashMap, HashSet}; use std::sync::Arc; use tracing::error; @@ -39,7 +40,21 @@ pub(super) const MAX_INFLIGHT_SEALS: usize = 4; /// the segment object is PUT only on flush or when it crosses [`SEAL_THRESHOLD`]. pub(super) struct OpenSegment { pub(super) segid: Segid, - pub(super) buf: Vec, + // Two chunks per frame: its length prefix followed by the sealed body. + pub(super) chunks: Vec, + pub(super) dir: Vec, +} + +impl OpenSegment { + pub(super) fn byte_len(&self) -> usize { + self.dir.last().map_or(0, |entry| { + entry.byte_offset as usize + LEN_PREFIX + entry.len as usize + }) + } +} + +pub(super) struct SealingSegment { + pub(super) payload: PutPayload, pub(super) dir: Vec, } @@ -47,18 +62,11 @@ impl ExtentStore { /// Raw `[len][sealed]` bytes of a frame still resident in RAM (the open buffer /// or an in-flight seal), or `None` once its segment is PUT (the standby reads /// the shared store directly). Used to ship un-PUT segments' bytes for HA. - fn read_frame_for_ship(&self, segid: Segid, byte_offset: u64, byte_len: u32) -> Option { - let start = byte_offset as usize; - let end = start.checked_add(byte_len as usize)?; - { - let open = self.open.lock().unwrap(); - if open.segid == segid { - return open.buf.get(start..end).map(Bytes::copy_from_slice); - } - } - let sealing = self.sealing.lock().unwrap(); - let bytes = sealing.get(&segid)?; - (end <= bytes.len()).then(|| bytes.slice(start..end)) + fn read_frame_for_ship(&self, loc: FrameLoc) -> Option { + let mut chunks = self + .frame_chunks_in_ram(loc.segid, loc.byte_offset, loc.byte_len, loc.frame_index, 1) + .ok()??; + Some(chunks.copy_to_bytes(chunks.remaining())) } /// Enrich a batch's replication ops: an extent-write `Put` whose segment is @@ -71,8 +79,7 @@ impl ExtentStore { ReplOp::Put(k, v) => { if self.key_codec.parse_extent_key(&k).is_some() && let Some(loc) = FrameLoc::decode(&v) - && let Some(frame) = - self.read_frame_for_ship(loc.segid, loc.byte_offset, loc.byte_len) + && let Some(frame) = self.read_frame_for_ship(loc) { ReplOp::PutFrame(k, v, frame) } else { @@ -231,10 +238,11 @@ impl ExtentStore { compressed.next().expect("one compressed payload per edit"), ) .map_err(|_| FsError::IoError)?; - let byte_offset = open.buf.len() as u64; + let byte_offset = open.byte_len() as u64; let sealed_len = sealed.len() as u32; - open.buf.extend_from_slice(&sealed_len.to_le_bytes()); - open.buf.extend_from_slice(&sealed); + open.chunks + .push(Bytes::copy_from_slice(&sealed_len.to_le_bytes())); + open.chunks.push(Bytes::from(sealed)); open.dir.push(DirEntry { byte_offset, len: sealed_len, @@ -262,7 +270,7 @@ impl ExtentStore { // Overwrite debit of the superseded frame: live only, total untouched. self.seg_delta(txn, segid, -(byte_len as i64), 0); } - let over_threshold = self.open.lock().unwrap().buf.len() >= self.seal_threshold(); + let over_threshold = self.open.lock().unwrap().byte_len() >= self.seal_threshold(); if over_threshold { self.spawn_seal().await; } @@ -283,23 +291,21 @@ impl ExtentStore { .map_err(|_| FsError::IoError)?; // Re-PUT any seal whose background attempt failed (still in `sealing`). - let pending: Vec<(Segid, Bytes)> = { - let s = self.sealing.lock().unwrap(); - s.iter().map(|(seg, b)| (*seg, b.clone())).collect() + let pending: Vec<(Segid, PutPayload)> = { + let sealing = self.sealing.lock().unwrap(); + sealing + .iter() + .map(|(segid, segment)| (*segid, segment.payload.clone())) + .collect() }; - for (segid, bytes) in pending { + for (segid, payload) in pending { self.segments - .put_segment(segid, bytes) + .put_segment(segid, payload) .await .map_err(|_| FsError::IoError)?; self.sealing.lock().unwrap().remove(&segid); } - // Synchronously seal the current open buffer. Register it in `sealing` - // under the open lock and remove it only on success, so the rotated - // segment is never absent from both maps: a concurrent read would 404 - // the not-yet-PUT object, and a failed PUT would strand it. Mirrors - // spawn_seal. let current = { let mut open = self.open.lock().unwrap(); if open.dir.is_empty() { @@ -308,37 +314,18 @@ impl ExtentStore { let segid = open.segid; #[cfg(feature = "failpoints")] fail_point!(fp::SEAL_OPEN_FAIL, |_| Err(FsError::IoError)); - // Seal the directory first: on error the open buffer and its - // committed FrameLocs stay intact for retry, instead of being - // dropped into a dangling pointer. + // Seal the directory before rotating so errors leave the buffer intact. let sealed_dir = crate::segment::seal_directory(&self.codec, segid, &open.dir) .map_err(|_| FsError::IoError)?; - let k = open.dir.len() as u32; - let buf = std::mem::take(&mut open.buf); - let small = (buf.len() as u64) < SMALL_SEGMENT_BYTES; - open.dir.clear(); - open.segid = self.segments.next_segid(); - debug_assert_ne!( - open.segid, segid, - "rotated open segid must differ from the sealed one" - ); - let bytes = Bytes::from(crate::segment::assemble_segment( - segid, - buf, - k, - &sealed_dir, - segid.counter, - )); - self.sealing.lock().unwrap().insert(segid, bytes.clone()); - Some((segid, bytes, small)) + Some(self.rotate_open_segment(&mut open, sealed_dir)) } }; - if let Some((segid, bytes, small)) = current { + if let Some((segid, payload, small)) = current { if small { self.record_reclaim_activity(); } self.segments - .put_segment(segid, bytes) + .put_segment(segid, payload) .await .map_err(|_| FsError::IoError)?; self.sealing.lock().unwrap().remove(&segid); @@ -355,14 +342,12 @@ impl ExtentStore { Ok(p) => p, Err(_) => return, }; - let (segid, bytes, small) = { + let (segid, payload, small) = { let mut open = self.open.lock().unwrap(); if open.dir.is_empty() { return; } let segid = open.segid; - // Directory first, as in seal_open: an error must leave the open - // buffer intact for the next seal/flush to retry. let sealed_dir = match crate::segment::seal_directory(&self.codec, segid, &open.dir) { Ok(s) => s, Err(e) => { @@ -370,26 +355,7 @@ impl ExtentStore { return; } }; - let k = open.dir.len() as u32; - let buf = std::mem::take(&mut open.buf); - let small = (buf.len() as u64) < SMALL_SEGMENT_BYTES; - open.dir.clear(); - open.segid = self.segments.next_segid(); - debug_assert_ne!( - open.segid, segid, - "rotated open segid must differ from the sealed one" - ); - let bytes = Bytes::from(crate::segment::assemble_segment( - segid, - buf, - k, - &sealed_dir, - segid.counter, - )); - // Insert into `sealing` while still holding `open`, so the segid is - // never absent from both maps (a concurrent read would miss it). - self.sealing.lock().unwrap().insert(segid, bytes.clone()); - (segid, bytes, small) + self.rotate_open_segment(&mut open, sealed_dir) }; if small { self.record_reclaim_activity(); @@ -397,7 +363,7 @@ impl ExtentStore { let segments = self.segments.clone(); let sealing = self.sealing.clone(); crate::task::spawn_named("segment-seal", async move { - match segments.put_segment(segid, bytes).await { + match segments.put_segment(segid, payload).await { Ok(()) => { sealing.lock().unwrap().remove(&segid); } @@ -412,6 +378,39 @@ impl ExtentStore { }); } + fn rotate_open_segment( + &self, + open: &mut OpenSegment, + sealed_dir: Vec, + ) -> (Segid, PutPayload, bool) { + let segid = open.segid; + let small = (open.byte_len() as u64) < SMALL_SEGMENT_BYTES; + let chunks = std::mem::take(&mut open.chunks); + let dir = std::mem::take(&mut open.dir); + open.segid = self.segments.next_segid(); + debug_assert_ne!( + open.segid, segid, + "rotated open segid must differ from the sealed one" + ); + let payload = crate::segment::assemble_segment_payload( + segid, + chunks, + dir.len() as u32, + sealed_dir, + segid.counter, + ); + // The caller holds `open` until registration, keeping concurrent reads valid. + // Retain the segment until its PUT succeeds so a failed PUT can be retried. + self.sealing.lock().unwrap().insert( + segid, + SealingSegment { + payload: payload.clone(), + dir, + }, + ); + (segid, payload, small) + } + /// Stage a write at `offset` as read-modify-write over full extents; /// all-zero extents become holes. Commits nothing itself. pub async fn write( @@ -945,6 +944,78 @@ mod tests { ); } + #[tokio::test] + async fn failed_seals_preserve_reads_and_replication_until_retry() { + for background in [false, true] { + let (_original, db, objects) = make_with_compression(CompressionConfig::Lz4).await; + let objects = InFlightObjectStore::new(objects, std::time::Duration::ZERO); + objects.set_fail_puts(true); + let store = make_store(objects.clone(), db.clone(), CompressionConfig::Lz4, 2).await; + let store = store.with_seal_threshold(if background { 1 } else { SEAL_THRESHOLD }); + let mut model = Vec::new(); + let data = incompressible(7, 3 * EXTENT_SIZE); + write_and_check(&store, &db, &mut model, 0, &data).await; + let key = store.key_codec.extent_key(1, 1); + let encoded = db.get_bytes(&key).await.unwrap().unwrap(); + let loc = FrameLoc::decode(&encoded).unwrap(); + let shipped = store.read_frame_for_ship(loc).unwrap(); + assert_eq!(shipped.len(), loc.byte_len as usize); + assert_eq!( + crate::segment::read_frames_from_region( + &store.codec, + &shipped, + loc.segid, + loc.frame_index, + &[(1, 1)], + ) + .unwrap()[0], + data[EXTENT_SIZE..2 * EXTENT_SIZE], + ); + + assert!(store.seal_open().await.is_err()); + assert!(store.open.lock().unwrap().dir.is_empty()); + assert_eq!(store.sealing.lock().unwrap().len(), 1); + assert_read_matches(&store, &model).await; + assert_eq!( + store.get(1, 1).await.unwrap().unwrap(), + &data[EXTENT_SIZE..2 * EXTENT_SIZE] + ); + assert!(store.unflushed_bytes() > 0); + let ops = store.enrich_repl_ops(vec![ReplOp::Put(key.clone(), encoded.clone())]); + assert!(matches!(&ops[..], [ReplOp::PutFrame(k, v, frame)] + if k == &key && v == &encoded && frame == &shipped)); + assert!( + store + .frame_chunks_in_ram( + loc.segid, + loc.byte_offset + 1, + loc.byte_len, + loc.frame_index, + 1, + ) + .is_err() + ); + assert!( + store + .frame_chunks_in_ram(loc.segid, loc.byte_offset, loc.byte_len, u32::MAX, 1) + .is_err() + ); + + objects.set_fail_puts(false); + store.seal_open().await.unwrap(); + assert!(store.seals_quiet()); + assert_eq!(store.unflushed_bytes(), 0); + assert_read_matches(&store, &model).await; + let directory = store.segments.read_directory(loc.segid).await.unwrap(); + assert_eq!(directory.len(), 3); + assert_eq!(directory[1].byte_offset, loc.byte_offset); + assert!(matches!( + &store.enrich_repl_ops(vec![ReplOp::Put(key, encoded)])[..], + [ReplOp::Put(_, _)] + )); + } + } + // Not a correctness test: measures single-stream engine-side write // throughput (codec + open-buffer append + seal + commit, no protocol, no // inode lock) against an in-memory object store. diff --git a/zerofs/src/ninep/handler.rs b/zerofs/src/ninep/handler.rs index 4f655c0c4..363fa747d 100644 --- a/zerofs/src/ninep/handler.rs +++ b/zerofs/src/ninep/handler.rs @@ -1,5 +1,6 @@ use super::errors::{P9Error, P9Result}; use super::lock_manager::{FileLock, FileLockManager, LockGuard}; +use super::response::Response; #[cfg(feature = "failpoints")] use crate::failpoints as fp; use crate::fs::errors::FsError; @@ -11,7 +12,8 @@ use crate::fs::types::{ SetMode, SetSize, SetTime, SetUid, Timestamp, }; use crate::fs::{OpenHandle, ZeroFS}; -use bytes::Bytes; +use bytes::{Buf, Bytes}; +use bytes_utils::SegmentedBuf; #[cfg(feature = "failpoints")] use fp::fail_point; use ninep_proto::*; @@ -617,6 +619,7 @@ impl NinePHandler { None, ) .await + .into_message() } /// Dispatch using a FIRST reservation created by the connection reader. @@ -628,48 +631,28 @@ impl NinePHandler { op_origin_epoch: u64, msg: Message, received_guard: Option, - ) -> P9Message { + ) -> Response { let zerofs_protocol = self.zerofs_protocol_enabled(); let private_request = msg.is_zerofs_private_request(); let has_private_envelope = crate::dedup::has_op_id(&op_id) || op_flags != 0 || op_origin_epoch != 0; if !zerofs_protocol && (private_request || has_private_envelope) { - return P9Message::new( - tag, - Message::Rlerror(Rlerror { - ecode: P9Error::NotSupported.to_errno(), - }), - ); + return Response::error(tag, P9Error::NotSupported.to_errno()); } if op_flags & !ninep_proto::P9_OP_KNOWN_FLAGS != 0 { - return P9Message::new( - tag, - Message::Rlerror(Rlerror { - ecode: ninep_proto::P9_EOPIDSTALE, - }), - ); + return Response::error(tag, ninep_proto::P9_EOPIDSTALE); } if has_private_envelope && !msg.is_mutation() { // Operation envelopes are valid only on mutation messages. - return P9Message::new( - tag, - Message::Rlerror(Rlerror { - ecode: ninep_proto::P9_EOPIDSTALE, - }), - ); + return Response::error(tag, ninep_proto::P9_EOPIDSTALE); } let is_retry = op_flags & ninep_proto::P9_OP_FLAG_RETRY != 0; // Pre-dispatch rejection is CLEAN; loss during dispatch is ambiguous. let lease_gated = !matches!(msg, Message::Tversion(_)); if lease_gated && !self.filesystem.db.permits_successful_response() { - return P9Message::new( - tag, - Message::Rlerror(Rlerror { - ecode: ninep_proto::P9_ENOTLEADER_CLEAN, - }), - ); + return Response::error(tag, ninep_proto::P9_ENOTLEADER_CLEAN); } // Dedup admission precedes mutation dispatch. let _dedup_guard = if let Some(guard) = received_guard { @@ -685,19 +668,14 @@ impl NinePHandler { Err(error) => { // Authority loss while waiting for admission remains pre-dispatch. if lease_gated && !self.filesystem.db.permits_successful_response() { - return P9Message::new( - tag, - Message::Rlerror(Rlerror { - ecode: ninep_proto::P9_ENOTLEADER_CLEAN, - }), - ); + return Response::error(tag, ninep_proto::P9_ENOTLEADER_CLEAN); } let ecode = match error { crate::dedup::DedupAdmissionError::UnseenRetry => { ninep_proto::P9_EOPIDSTALE } }; - return P9Message::new(tag, Message::Rlerror(Rlerror { ecode })); + return Response::error(tag, ecode); } } }; @@ -710,15 +688,16 @@ impl NinePHandler { } else { ninep_proto::P9_ENOTLEADER }; - return P9Message::new(tag, Message::Rlerror(Rlerror { ecode })); + return Response::error(tag, ecode); } + let mut payload = None; let result = match msg { Message::Tversion(tv) => self.version(tv).await, Message::Tattach(ta) => self.attach(ta).await, Message::Twalk(tw) => self.walk(tw).await, Message::Tlopen(tl) => self.lopen(tl).await, Message::Tlcreate(tc) => self.lcreate(tc, op_id).await, - Message::Tread(tr) => self.read(tr).await, + Message::Tread(tr) => self.read(tr, &mut payload).await, Message::Twrite(tw) => self.write(tw, op_id).await, Message::Tclunk(tc) => Ok(self.clunk(tc).await), Message::Treaddir(tr) => self.readdir(tr).await, @@ -745,7 +724,7 @@ impl NinePHandler { Message::Twalkgetattr(tw) => self.walk_getattr(tw).await, Message::Treaddirattr(tr) => self.readdir_attr(tr).await, Message::Tlopenat(tl) => self.lopenat(tl).await, - Message::Tlopenatread(tl) => self.lopenatread(tl).await, + Message::Tlopenatread(tl) => self.lopenatread(tl, &mut payload).await, Message::Tlcreateattr(tc) => self.lcreateattr(tc, op_id).await, Message::Tmkdirattr(tm) => self.mkdir_attr(tm, op_id).await, Message::Tsymlinkattr(ts) => self.symlink_attr(ts, op_id).await, @@ -786,20 +765,15 @@ impl NinePHandler { match result { Ok(body) if !lease_gated || self.filesystem.db.permits_successful_response() => { - P9Message::new(tag, body) + Response::new(P9Message::new(tag, body), payload) } // Authority loss after dispatch suppresses successful responses. - Ok(_) => P9Message::new( - tag, - Message::Rlerror(Rlerror { - ecode: ninep_proto::P9_ENOTLEADER, - }), - ), + Ok(_) => Response::error(tag, ninep_proto::P9_ENOTLEADER), Err(e) => { // CLEAN requires proof that neither replica applied the batch. let ecode = post_dispatch_errno(e, self.filesystem.db.permits_successful_response()); - P9Message::new(tag, Message::Rlerror(Rlerror { ecode })) + Response::error(tag, ecode) } } } @@ -1390,7 +1364,11 @@ impl NinePHandler { // Tlopenatread = Tlopenat + a best-effort read of [0, count). The open is // authoritative: the inline read never fails it, so a read error returns the // open result with empty data (eof=0) and the client falls back to a plain Tread. - async fn lopenatread(&self, tl: Tlopenatread) -> P9Result { + async fn lopenatread( + &self, + tl: Tlopenatread, + payload: &mut Option>, + ) -> P9Result { // Reuse the open path so the fid/handle bookkeeping is identical to Tlopenat. let (qid, iounit) = match self .lopenat(Tlopenat { @@ -1415,24 +1393,22 @@ impl NinePHandler { // The open already authorized this immutable fid capability. // Keep an open descriptor and the inode-wide client page cache // consistent after chmod/chown. - match self - .filesystem + self.filesystem .read_file_opened(new_fid.inode_id, 0, count) .await - { - Ok((d, e)) => (DekuBytes::from(d), e), - Err(_) => (DekuBytes::default(), false), - } + .unwrap_or_default() } else { - (DekuBytes::default(), false) + (SegmentedBuf::new(), false) }; + let count = data.remaining() as u32; + *payload = Some(data); Ok(Message::Rlopenatread(Rlopenatread { qid, iounit, eof: eof as u8, - count: data.len() as u32, - data, + count, + data: DekuBytes::default(), })) } @@ -1704,7 +1680,11 @@ impl NinePHandler { })) } - async fn read(&self, tr: Tread) -> P9Result { + async fn read( + &self, + tr: Tread, + payload: &mut Option>, + ) -> P9Result { let fid_entry = self.get_fid(tr.fid)?; if !fid_allows_read(&fid_entry) { @@ -1721,9 +1701,11 @@ impl NinePHandler { .read_file_opened(fid_entry.inode_id, tr.offset, count) .await?; + let count = data.remaining() as u32; + *payload = Some(data); Ok(Message::Rread(Rread { - count: data.len() as u32, - data: DekuBytes::from(data), + count, + data: DekuBytes::default(), })) } diff --git a/zerofs/src/ninep/mod.rs b/zerofs/src/ninep/mod.rs index 18d82d121..13e333c9a 100644 --- a/zerofs/src/ninep/mod.rs +++ b/zerofs/src/ninep/mod.rs @@ -1,6 +1,7 @@ pub mod errors; pub mod handler; pub mod lock_manager; +pub(crate) mod response; pub mod server; pub use server::NinePServer; diff --git a/zerofs/src/ninep/response.rs b/zerofs/src/ninep/response.rs new file mode 100644 index 000000000..c3916099d --- /dev/null +++ b/zerofs/src/ninep/response.rs @@ -0,0 +1,158 @@ +use bytes::{Buf, Bytes}; +use bytes_utils::SegmentedBuf; +use ninep_proto::{DekuBytes, Message, P9Message, Rlerror}; + +pub(crate) type EncodedResponse = bytes::buf::Chain>; + +/// Keeps read data separate from the message until the socket write. +pub(crate) struct Response { + message: P9Message, + payload: Option>, +} + +fn counted_data(body: &mut Message) -> Option<(&mut u32, &mut DekuBytes)> { + match body { + Message::Rread(r) => Some((&mut r.count, &mut r.data)), + Message::Rlopenatread(r) => Some((&mut r.count, &mut r.data)), + Message::Rreaddir(r) => Some((&mut r.count, &mut r.data)), + Message::Rreaddirattr(r) => Some((&mut r.count, &mut r.data)), + _ => None, + } +} + +impl Response { + pub(crate) fn error(tag: u16, ecode: u32) -> Self { + Self::new( + P9Message::new(tag, Message::Rlerror(Rlerror { ecode })), + None, + ) + } + + pub(crate) fn new(message: P9Message, payload: Option>) -> Self { + // A post-dispatch failure must discard any successfully read payload. + let payload = if matches!(message.body, Message::Rread(_) | Message::Rlopenatread(_)) { + payload + } else { + None + }; + Self { message, payload } + } + + pub(crate) fn encode(mut self) -> Result { + let payload = match counted_data(&mut self.message.body) { + Some((count, data)) => { + let inline = std::mem::take(&mut data.0); + let payload = self.payload.unwrap_or_else(|| vec![inline].into()); + *count = payload.remaining().try_into()?; + payload + } + None => SegmentedBuf::new(), + }; + let mut header = self.message.to_bytes()?; + let size: u32 = (header.len() + payload.remaining()).try_into()?; + header[..4].copy_from_slice(&size.to_le_bytes()); + Ok(Bytes::from(header).chain(payload)) + } + + #[cfg(test)] + pub(crate) fn into_message(mut self) -> P9Message { + if let Some(mut payload) = self.payload { + let (count, data) = counted_data(&mut self.message.body).expect("read payload"); + *count = payload.remaining().try_into().unwrap(); + data.0 = payload.copy_to_bytes(payload.remaining()); + } + self.message + } +} + +#[cfg(test)] +mod tests { + use super::*; + use ninep_proto::Rread; + + fn flatten(mut buf: impl Buf) -> Bytes { + buf.copy_to_bytes(buf.remaining()) + } + + #[test] + fn segmented_read_matches_wire_codec_and_retains_payload() { + let data = Bytes::from(vec![0xab; 32768]); + let message = P9Message::new( + 17, + Message::Rread(Rread { + count: data.len() as u32, + data: data.clone().into(), + }), + ); + let expected = message.to_bytes().unwrap(); + let mut encoded = Response::new(message, None).encode().unwrap(); + encoded.advance(11); + assert_eq!(encoded.chunk().as_ptr(), data.as_ptr()); + let payload = vec![data.slice(..100), data.slice(100..)].into(); + let header = P9Message::new( + 17, + Message::Rread(Rread { + count: 0, + data: DekuBytes::default(), + }), + ); + assert_eq!( + flatten(Response::new(header, Some(payload)).encode().unwrap()).as_ref(), + expected + ); + } + + #[test] + fn failed_response_discards_read_data() { + let message = P9Message::new(17, Message::Rlerror(Rlerror { ecode: 5 })); + let expected = message.to_bytes().unwrap(); + assert_eq!( + flatten( + Response::new(message, Some(vec![Bytes::from_static(b"secret")].into())) + .encode() + .unwrap() + ) + .as_ref(), + expected + ); + } + + #[test] + fn all_counted_responses_match_contiguous_encoding_including_empty_payloads() { + use ninep_proto::{Qid, Rlopenatread, Rreaddir, Rreaddirattr}; + for len in [0, 1, 32768] { + let bytes = Bytes::from(vec![0xa5; len]); + let messages = [ + Message::Rread(Rread { + count: len as u32, + data: bytes.clone().into(), + }), + Message::Rlopenatread(Rlopenatread { + qid: Qid { + path: 93, + ..Default::default() + }, + iounit: 4096, + eof: 1, + count: len as u32, + data: bytes.clone().into(), + }), + Message::Rreaddir(Rreaddir { + count: len as u32, + data: bytes.clone().into(), + }), + Message::Rreaddirattr(Rreaddirattr { + count: len as u32, + data: bytes.clone().into(), + }), + ]; + for body in messages { + let message = P9Message::new(91, body); + let expected = message.to_bytes().unwrap(); + let encoded = flatten(Response::new(message, None).encode().unwrap()); + assert_eq!(encoded.as_ref(), expected); + assert!(P9Message::from_bytes_ctx(&encoded, false).is_ok()); + } + } + } +} diff --git a/zerofs/src/ninep/server.rs b/zerofs/src/ninep/server.rs index 3a245c905..281e874ca 100644 --- a/zerofs/src/ninep/server.rs +++ b/zerofs/src/ninep/server.rs @@ -2,17 +2,17 @@ use super::errors::P9Error; pub(crate) use super::handler::NinePHandler; use super::handler::SessionReleaseGuard; pub(crate) use super::lock_manager::FileLockManager; +use super::response::{EncodedResponse, Response}; use crate::fs::ZeroFS; use crate::task::spawn_named; -use bytes::Bytes; +use bytes::{Buf, Bytes}; use dashmap::DashMap; use dashmap::mapref::entry::Entry; use futures::StreamExt; use futures::stream::FuturesUnordered; use ninep_proto::{ - Message, P9_CHANNEL_SIZE, P9_DEBUG_BUFFER_SIZE, P9_HEADER_SIZE, P9_MAX_MSIZE, - P9_MIN_MESSAGE_SIZE, P9_OP_ENVELOPE_LEN, P9_OP_ID_LEN, P9_SIZE_FIELD_LEN, P9Message, Rlerror, - T_WRITE, + P9_CHANNEL_SIZE, P9_DEBUG_BUFFER_SIZE, P9_HEADER_SIZE, P9_MAX_MSIZE, P9_MIN_MESSAGE_SIZE, + P9_OP_ENVELOPE_LEN, P9_OP_ID_LEN, P9_SIZE_FIELD_LEN, P9Message, T_WRITE, }; use std::net::SocketAddr; use std::path::PathBuf; @@ -299,7 +299,7 @@ impl ResponseAuthority { fn spawn_response_writer( write_stream: W, - mut rx: mpsc::Receiver<(u16, Vec)>, + mut rx: mpsc::Receiver<(u16, EncodedResponse)>, authority: ResponseAuthority, connection_shutdown: CancellationToken, ) -> AbortOnDropHandle<()> @@ -323,9 +323,10 @@ where let second = match rx.try_recv() { Ok(more) => more, Err(_) => { - let (tag, response_bytes) = first; - let requires_authority = response_requires_serving_authority(&response_bytes); - if requires_authority && !authority.may_emit(&response_bytes) { + let (tag, mut response_bytes) = first; + let requires_authority = + response_requires_serving_authority(response_bytes.chunk()); + if requires_authority && !authority.may_emit(response_bytes.chunk()) { warn!( "Dropping successful 9P response for tag {tag} after serving authority \ was lost; closing the connection" @@ -345,7 +346,7 @@ where // its copy for this latency-critical case, but still flush // the underlying AsyncWrite: write_all only guarantees // acceptance, and the transport itself may be buffered. - if let Err(e) = writer.get_mut().write_all(&response_bytes).await { + if let Err(e) = writer.get_mut().write_all_buf(&mut response_bytes).await { error!("Failed to write response for tag {}: {}", tag, e); return; } @@ -378,9 +379,10 @@ where let mut buffered_authority_gated_success = false; let mut dropped_authority_gated_success = false; - for (tag, response_bytes) in batch { - let requires_authority = response_requires_serving_authority(&response_bytes); - if requires_authority && !authority.may_emit(&response_bytes) { + for (tag, mut response_bytes) in batch { + let requires_authority = + response_requires_serving_authority(response_bytes.chunk()); + if requires_authority && !authority.may_emit(response_bytes.chunk()) { warn!( "Dropping successful 9P response for tag {tag} after serving authority \ was lost; closing the connection" @@ -397,7 +399,7 @@ where return; } buffered_authority_gated_success |= requires_authority; - if let Err(e) = writer.write_all(&response_bytes).await { + if let Err(e) = writer.write_all_buf(&mut response_bytes).await { error!("Failed to write response for tag {}: {}", tag, e); return; } @@ -435,7 +437,7 @@ where { let handler = Arc::new(NinePHandler::new(Arc::clone(&filesystem), lock_manager)); - let (tx, rx) = mpsc::channel::<(u16, Vec)>(P9_CHANNEL_SIZE); + let (tx, rx) = mpsc::channel::<(u16, EncodedResponse)>(P9_CHANNEL_SIZE); let connection_shutdown = shutdown.child_token(); let writer_task = spawn_response_writer( write_stream, @@ -644,8 +646,8 @@ impl Drop for RequestLease { /// Reserve response capacity, enqueue the terminal response, then retire its tag. async fn enqueue_terminal_response( - tx: &mpsc::Sender<(u16, Vec)>, - response_bytes: Vec, + tx: &mpsc::Sender<(u16, EncodedResponse)>, + response_bytes: EncodedResponse, request_lease: &RequestLease, ) -> Result<(), mpsc::error::SendError<()>> { let permit = tx.reserve().await?; @@ -737,7 +739,7 @@ fn inspect_frame_metadata(frame: &[u8], zerofs_protocol: bool) -> ShallowFrameMe pub(crate) fn dispatch_9p_frame( frame: Bytes, handler: &Arc, - tx: &mpsc::Sender<(u16, Vec)>, + tx: &mpsc::Sender<(u16, EncodedResponse)>, inflight: &InflightRegistry, ) -> anyhow::Result<()> { if frame.len() < P9_MIN_MESSAGE_SIZE as usize { @@ -816,7 +818,7 @@ pub(crate) fn dispatch_9p_frame( received_guard, ) .await; - response.to_bytes().ok() + response.encode().ok() } Err(e) => { debug!( @@ -829,14 +831,9 @@ pub(crate) fn dispatch_9p_frame( P9_DEBUG_BUFFER_SIZE, &frame[..std::cmp::min(P9_DEBUG_BUFFER_SIZE, frame.len())] ); - P9Message::new( - tag, - Message::Rlerror(Rlerror { - ecode: P9Error::NotImplemented.to_errno(), - }), - ) - .to_bytes() - .ok() + Response::error(tag, P9Error::NotImplemented.to_errno()) + .encode() + .ok() } }; @@ -868,7 +865,7 @@ pub(crate) fn dispatch_9p_frame( async fn handle_client_loop( handler: Arc, read_stream: R, - tx: mpsc::Sender<(u16, Vec)>, + tx: mpsc::Sender<(u16, EncodedResponse)>, shutdown: CancellationToken, ) -> anyhow::Result<()> where @@ -918,8 +915,9 @@ mod tests { use crate::fs::permissions::Credentials; use crate::ninep::lock_manager::FileLock; use ninep_proto::{ - DekuBytes, GETATTR_ALL, LockType, P9String, Rclunk, Rflush, Rlopenat, Rread, Tattach, - Tclunk, Tflush, Tgetattr, Tlopenat, Tmkdir, Tversion, Twrite, VERSION_9P2000L_ZEROFS, + DekuBytes, GETATTR_ALL, LockType, Message, P9String, Rclunk, Rflush, Rlerror, Rlopenat, + Rread, Tattach, Tclunk, Tflush, Tgetattr, Tlopenat, Tmkdir, Tversion, Twrite, + VERSION_9P2000L_ZEROFS, }; use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::Duration; @@ -933,6 +931,14 @@ mod tests { Bytes::from(P9Message::new(tag, body).to_bytes().unwrap()) } + fn flatten(mut bytes: impl Buf) -> Bytes { + bytes.copy_to_bytes(bytes.remaining()) + } + + fn encoded(bytes: Vec) -> EncodedResponse { + Bytes::from(bytes).chain(bytes_utils::SegmentedBuf::new()) + } + fn decode(bytes: &[u8]) -> P9Message { P9Message::from_bytes_ctx(bytes, false).unwrap() } @@ -987,8 +993,8 @@ mod tests { struct DispatchFixture { handler: Arc, - tx: mpsc::Sender<(u16, Vec)>, - rx: mpsc::Receiver<(u16, Vec)>, + tx: mpsc::Sender<(u16, EncodedResponse)>, + rx: mpsc::Receiver<(u16, EncodedResponse)>, inflight: InflightRegistry, } @@ -1021,7 +1027,7 @@ mod tests { .await .expect(context) .expect("response channel"); - (tag, decode(&bytes)) + (tag, decode(&flatten(bytes))) } async fn recv_flush(&mut self, context: &str) -> u16 { @@ -1065,10 +1071,10 @@ mod tests { fn response_queue( responses: [(u16, Vec); N], - ) -> mpsc::Receiver<(u16, Vec)> { + ) -> mpsc::Receiver<(u16, EncodedResponse)> { let (tx, rx) = mpsc::channel(N); for response in responses { - tx.try_send(response).unwrap(); + tx.try_send((response.0, encoded(response.1))).unwrap(); } rx } @@ -1307,6 +1313,53 @@ mod tests { ); } + #[tokio::test] + async fn segmented_responses_handle_partial_writes() { + for batch in [false, true] { + // Smaller than the reply header, so the write cannot finish at once. + let (mut client, server) = tokio::io::duplex(5); + let data = Bytes::from_static(b"hello world"); + let mut expected = frame( + 21, + Message::Rread(Rread { + count: data.len() as u32, + data: data.clone().into(), + }), + ) + .to_vec(); + let chunks = vec![data.slice(..5), data.slice(5..)].into(); + let message = P9Message::new( + 21, + Message::Rread(Rread { + count: data.len() as u32, + data: DekuBytes::default(), + }), + ); + let (tx, rx) = mpsc::channel(2); + tx.try_send((21, Response::new(message, Some(chunks)).encode().unwrap())) + .unwrap(); + let tail = frame(22, Message::Rflush(Rflush)); + if batch { + tx.try_send((22, encoded(tail.to_vec()))).unwrap(); + expected.extend_from_slice(&tail); + } + drop(tx); + let writer = spawn_response_writer( + server, + rx, + ResponseAuthority::always(), + CancellationToken::new(), + ); + let mut received = Vec::new(); + tokio::time::timeout(TEST_TIMEOUT, client.read_to_end(&mut received)) + .await + .unwrap() + .unwrap(); + drain_writer(writer, "segmented writer drains").await; + assert_eq!(received, expected); + } + } + #[tokio::test] async fn already_queued_responses_share_one_transport_write() { let (mut client, server) = tokio::io::duplex(4096); @@ -1538,7 +1591,7 @@ mod tests { connection_shutdown.clone(), ); - tx.send((21, vec![1, 2, 3])) + tx.send((21, encoded(vec![1, 2, 3]))) .await .expect("response enqueue"); tokio::time::timeout(TEST_TIMEOUT, connection_shutdown.cancelled()) @@ -1638,9 +1691,13 @@ mod tests { let original_waiter = inflight.waiter(7).expect("original request"); let response = vec![1, 2, 3]; let (tx, mut rx) = mpsc::channel(1); - tx.send((99, vec![0])).await.unwrap(); + tx.send((99, encoded(vec![0]))).await.unwrap(); - let mut enqueue = Box::pin(enqueue_terminal_response(&tx, response.clone(), &original)); + let mut enqueue = Box::pin(enqueue_terminal_response( + &tx, + encoded(response.clone()), + &original, + )); tokio::select! { biased; result = &mut enqueue => panic!("full response queue accepted a send: {result:?}"), @@ -1650,14 +1707,16 @@ mod tests { inflight.register(7, FidFootprint::None).is_err(), "queue backpressure must keep the tag occupied until capacity is reserved" ); - assert_eq!(rx.recv().await.unwrap(), (99, vec![0])); + let (tag, bytes) = rx.recv().await.unwrap(); + assert_eq!((tag, flatten(bytes).to_vec()), (99, vec![0])); tokio::time::timeout(TEST_TIMEOUT, &mut enqueue) .await .expect("response enqueue") .unwrap(); drop(enqueue); - assert_eq!(rx.recv().await.unwrap(), (7, response)); + let (tag, bytes) = rx.recv().await.unwrap(); + assert_eq!((tag, flatten(bytes).to_vec()), (7, response)); let replacement = inflight .register(7, FidFootprint::None) diff --git a/zerofs/src/object_store_prefetch.rs b/zerofs/src/object_store_prefetch.rs index 18d0c98ab..aaa2ce824 100644 --- a/zerofs/src/object_store_prefetch.rs +++ b/zerofs/src/object_store_prefetch.rs @@ -1,5 +1,5 @@ use async_trait::async_trait; -use bytes::{Bytes, BytesMut}; +use bytes::Bytes; use foyer::{Cache, HybridCache}; use futures::FutureExt; use futures::StreamExt; @@ -32,10 +32,10 @@ const PREFETCH_DEPTH_WINDOWS: usize = 4; type PartId = usize; -/// One window GET shared by every reader whose part falls inside it. Resolves -/// to `(base part id, window bytes)`; a joiner slices out its part. The error -/// is Arc-wrapped so the output is `Clone`, which `Shared` requires. -type SharedFetch = Shared>>>; +type FetchedParts = (PartId, Arc<[Bytes]>); + +/// One window GET shared by readers of any part in the window. +type SharedFetch = Shared>>>; /// Single-flight registry for all window fetches, demand and prefetch alike: /// every part covered by an in-flight GET maps to its shared fetch, so anything @@ -788,78 +788,94 @@ impl PrefetchingObjectStore { where S: stream::Stream> + Unpin, { - let mut buffer = BytesMut::new(); let mut part_number = start_part_number; - - // Owned copies: `split_to(..).freeze()` would share the BytesMut - // allocation between neighbouring parts, invisibly to the weigher. + let mut cache_part = |bytes| { + parts.insert(PartKey::new(location, part_number), bytes); + part_number += 1; + }; + // Insert completed parts immediately so unbounded GETs only stage one + // unfinished part outside the cache, in addition to the incoming chunk. + let mut pending = Vec::new(); while let Some(chunk) = stream.next().await { - let mut chunk = chunk?; - if skip > 0 { - let n = skip.min(chunk.len()); - chunk = chunk.slice(n..); - skip -= n; - if chunk.is_empty() { - continue; - } - } - buffer.extend_from_slice(&chunk); - while buffer.len() >= part_size_bytes { - let to_write = buffer.split_to(part_size_bytes); - parts.insert( - PartKey::new(location, part_number), - Bytes::copy_from_slice(&to_write), - ); - part_number += 1; - } + let chunk = chunk?; + let n = skip.min(chunk.len()); + skip -= n; + Self::append_parts(&mut cache_part, &mut pending, part_size_bytes, &chunk[n..]); + } + if !pending.is_empty() { + cache_part(Bytes::from(pending.into_boxed_slice())); } + Ok(()) + } - if !buffer.is_empty() { - parts.insert( - PartKey::new(location, part_number), - Bytes::copy_from_slice(&buffer), + /// Each part owns its allocation so the cache weigher accounts for all + /// retained bytes. Slices could keep an entire fetch window alive. + async fn collect_parts( + mut stream: S, + part_size: usize, + mut skip: usize, + ) -> object_store::Result> + where + S: stream::Stream> + Unpin, + { + let mut parts = Vec::new(); + let mut pending = Vec::new(); + while let Some(chunk) = stream.next().await { + let chunk = chunk?; + let n = skip.min(chunk.len()); + skip -= n; + Self::append_parts( + |bytes| parts.push(bytes), + &mut pending, + part_size, + &chunk[n..], ); } - Ok(()) + if !pending.is_empty() { + // A short final part must not retain a full-part allocation. + parts.push(Bytes::from(pending.into_boxed_slice())); + } + Ok(parts) + } + + fn append_parts( + mut emit: impl FnMut(Bytes), + pending: &mut Vec, + part_size: usize, + mut chunk: &[u8], + ) { + while !chunk.is_empty() { + if pending.capacity() == 0 { + pending.reserve_exact(part_size); + } + let n = (part_size - pending.len()).min(chunk.len()); + pending.extend_from_slice(&chunk[..n]); + chunk = &chunk[n..]; + if pending.len() == part_size { + emit(Bytes::from(std::mem::take(pending))); + } + } } /// Populate the parts cache from a just-uploaded object's bytes. Inserts /// are synchronous (foyer flushes to disk in the background), so this adds /// no I/O wait to the put. fn write_through(&self, location: &Path, payload: PutPayload) { - let chunks: Vec = payload.into_iter().collect(); - let bytes = match chunks.len() { - 0 => return, - 1 => chunks.into_iter().next().expect("one chunk"), - _ => { - let mut buf = BytesMut::with_capacity(chunks.iter().map(Bytes::len).sum()); - for c in &chunks { - buf.extend_from_slice(c); - } - buf.freeze() - } - }; - self.warm_object(location, bytes); - } - - /// Warm the parts cache with an object's full bytes, sliced into - /// part-sized entries keyed as the read path expects. - fn warm_object(&self, location: &Path, bytes: Bytes) { - let ps = self.part_size_bytes; - let mut off = 0usize; - let mut part_id: PartId = 0; - while off < bytes.len() { - let end = (off + ps).min(bytes.len()); - // Owned copy, not `bytes.slice(..)`: a slice keeps the whole - // source allocation (a 256 MiB sealed segment) alive while any - // one part survives in the cache, and the weigher only sees the - // slice length. That was the multi-GB RSS retention bug. - self.parts.insert( - PartKey::new(location, part_id), - Bytes::copy_from_slice(&bytes[off..end]), + let mut parts = Vec::new(); + let mut pending = Vec::new(); + for chunk in payload { + Self::append_parts( + |bytes| parts.push(bytes), + &mut pending, + self.part_size_bytes, + &chunk, ); - off = end; - part_id += 1; + } + if !pending.is_empty() { + parts.push(Bytes::from(pending.into_boxed_slice())); + } + for (i, part) in parts.into_iter().enumerate() { + self.parts.insert(PartKey::new(location, i), part); } } @@ -934,14 +950,10 @@ impl PrefetchingObjectStore { let leading = guard.is_some(); let _guard = guard; match shared.await { - Ok((base, window)) => { - let off = part_id.saturating_sub(base) * part_size_bytes; - if off >= window.len() { - // Window EOF-truncated short of this part. + Ok((base, parts)) => { + let Some(part_bytes) = parts.get(part_id.saturating_sub(base)) else { return Ok(Bytes::new()); - } - let part_end = (off + part_size_bytes).min(window.len()); - let part_bytes = window.slice(off..part_end); + }; let end = range_in_part.end.min(part_bytes.len()); let start = range_in_part.start.min(end); Ok(part_bytes.slice(start..end)) @@ -980,18 +992,17 @@ impl PrefetchingObjectStore { }, ) .await?; - let bytes = get_result.bytes().await?; - ctx.parts.insert( - PartKey::new(location, part_id), - Bytes::copy_from_slice(&bytes), - ); + let parts = Self::collect_parts(get_result.into_stream(), part_size_bytes, 0).await?; + let bytes = parts.into_iter().next().unwrap_or_default(); + ctx.parts + .insert(PartKey::new(location, part_id), bytes.clone()); let end = range_in_part.end.min(bytes.len()); let start = range_in_part.start.min(end); Ok(bytes.slice(start..end)) } /// One GET spanning `window_parts` from `part_id`; caches every part and - /// resolves to `(part_id, window bytes)`. `access_offset` is the + /// resolves to `(part_id, owned parts)`. `access_offset` is the /// triggering request's start: the stream tracker keys on request /// offsets, so crediting the aligned window start instead would miss the /// stream on unaligned reads and the pipeline would never engage. @@ -1001,7 +1012,7 @@ impl PrefetchingObjectStore { part_id: PartId, window_parts: usize, access_offset: u64, - ) -> Result<(PartId, Bytes), Arc> { + ) -> Result> { let part_size_bytes = ctx.part_size_bytes; let fetch_start = part_id; let fetch_range = Range { @@ -1022,7 +1033,9 @@ impl PrefetchingObjectStore { let meta = get_result.meta.clone(); let attrs = get_result.attributes.clone(); let actual_end = get_result.range.end; - let all_bytes = get_result.bytes().await.map_err(Arc::new)?; + let parts = Self::collect_parts(get_result.into_stream(), part_size_bytes, 0) + .await + .map_err(Arc::new)?; ctx.heads.insert( location.clone(), @@ -1039,20 +1052,11 @@ impl PrefetchingObjectStore { .unwrap() .note_fetch(access_offset, actual_end); } - for i in 0..window_parts { - let start = i * part_size_bytes; - if start >= all_bytes.len() { - break; - } - let end = ((i + 1) * part_size_bytes).min(all_bytes.len()); - // Owned copy: a slice would pin the whole window allocation for - // as long as any one part survives in the cache. - ctx.parts.insert( - PartKey::new(&location, fetch_start + i), - Bytes::copy_from_slice(&all_bytes[start..end]), - ); + for (i, bytes) in parts.iter().enumerate() { + ctx.parts + .insert(PartKey::new(&location, fetch_start + i), bytes.clone()); } - Ok((fetch_start, all_bytes)) + Ok((fetch_start, parts.into())) } fn canonicalize_range( @@ -1547,6 +1551,48 @@ mod tests { ); } + #[tokio::test] + async fn streamed_parts_are_cached_before_eof() { + let (store, _inner, _dir) = make_store(1024, MEM, DISK).await; + let path = Path::from("streamed-parts"); + let skip = 300; + let body = Bytes::from( + (0..skip + 2560) + .map(|i| (i % 251) as u8) + .collect::>(), + ); + let (tx, stream) = futures::channel::mpsc::unbounded(); + let mut save = Box::pin(store.save_parts_stream(&path, stream, 7, skip)); + + // Skip across chunks, then cross two part boundaries while the stream + // stays open. Completed parts must already be available to readers. + for range in [0..100, 100..900, 900..2400] { + tx.unbounded_send(Ok(body.slice(range))).unwrap(); + } + assert!(futures::poll!(&mut save).is_pending()); + for (i, range) in [(0, skip..skip + 1024), (1, skip + 1024..skip + 2048)] { + let part = store + .cached_part(&path, 7 + i) + .await + .expect("completed part must be cached before EOF"); + assert_eq!(part.as_ref(), &body[range]); + } + assert!(store.cached_part(&path, 9).await.is_none()); + + tx.unbounded_send(Ok(body.slice(2400..))).unwrap(); + assert!(futures::poll!(&mut save).is_pending()); + assert!( + store.cached_part(&path, 9).await.is_none(), + "the unfinished part must stay buffered until EOF" + ); + drop(tx); + save.await.unwrap(); + assert_eq!( + store.cached_part(&path, 9).await.unwrap().as_ref(), + &body[skip + 2048..] + ); + } + #[tokio::test] async fn put_writes_through_to_parts_cache() { let (store, _inner, _dir) = make_store(1024, MEM, DISK).await; @@ -1574,7 +1620,7 @@ mod tests { // 2.5 parts: parts 0 and 1 full, part 2 partial (512). No object-store // put: exercise the cache-population helper directly. let body: Vec = (0..2560u32).map(|i| i as u8).collect(); - store.warm_object(&path, body.clone().into()); + store.write_through(&path, body.clone().into()); for (part_id, range) in [(0usize, 0..1024usize), (1, 1024..2048), (2, 2048..2560)] { let entry = store @@ -3019,7 +3065,7 @@ mod tests { let src = Bytes::from((0..2560u32).map(|i| i as u8).collect::>()); let src_start = src.as_ptr() as usize; let src_end = src_start + src.len(); - store.warm_object(&path, src.clone()); + store.write_through(&path, src.clone().into()); for part_id in 0..3 { let bytes = store.cached_part(&path, part_id).await.unwrap(); diff --git a/zerofs/src/segment.rs b/zerofs/src/segment.rs index 925e60689..a7cffeefd 100644 --- a/zerofs/src/segment.rs +++ b/zerofs/src/segment.rs @@ -25,6 +25,8 @@ //! key-domain [`segment_extractor`](crate::segment_extractor). use crate::frame_codec::{CodecError, Compressed, FrameCodec}; +use bytes::Bytes; +use slatedb::object_store::{PutPayload, PutPayloadMut}; /// HKDF info label for the data-plane segment subkey. Domain-separated from the /// block-transformer subkey so a block frame and a segment frame never share a key. @@ -357,11 +359,45 @@ pub(crate) fn assemble_segment( sealed_dir: &[u8], sealed_seqno: u64, ) -> Vec { - let dir_offset = buf.len() as u64; - let dir_len = sealed_dir.len() as u32; + let footer = segment_footer(segid, buf.len() as u64, k, sealed_dir, sealed_seqno); buf.extend_from_slice(sealed_dir); + buf.extend_from_slice(&footer); + buf +} - let total_len = (buf.len() + FOOTER_LEN) as u64; +/// Finalize owned frame chunks without concatenating their payloads. +pub(crate) fn assemble_segment_payload( + segid: Segid, + chunks: Vec, + k: u32, + sealed_dir: Vec, + sealed_seqno: u64, +) -> PutPayload { + let mut payload = PutPayloadMut::new(); + for chunk in chunks { + payload.push(chunk); + } + let footer = segment_footer( + segid, + payload.content_length() as u64, + k, + &sealed_dir, + sealed_seqno, + ); + payload.push(sealed_dir.into()); + payload.push(Bytes::copy_from_slice(&footer)); + payload.freeze() +} + +fn segment_footer( + segid: Segid, + dir_offset: u64, + k: u32, + sealed_dir: &[u8], + sealed_seqno: u64, +) -> [u8; FOOTER_LEN] { + let dir_len = sealed_dir.len() as u32; + let total_len = dir_offset + sealed_dir.len() as u64 + FOOTER_LEN as u64; let mut footer = [0u8; FOOTER_LEN]; footer[F_MAGIC..F_MAGIC + 4].copy_from_slice(MAGIC); footer[F_VERSION..F_VERSION + 4].copy_from_slice(&VERSION.to_le_bytes()); @@ -376,17 +412,14 @@ pub(crate) fn assemble_segment( // (bytes[dir_offset .. total_len - 8]): frames carry per-frame AEAD, so a // reader can verify the tail from a ranged read instead of the whole // object. - buf.extend_from_slice(&footer); - let crc_end = buf.len() - (FOOTER_LEN - F_CRC); - let crc = crc32c::crc32c(&buf[dir_offset as usize..crc_end]); - let crc_pos = buf.len() - FOOTER_LEN + F_CRC; - buf[crc_pos..crc_pos + 4].copy_from_slice(&crc.to_le_bytes()); - buf + let crc = crc32c::crc32c_append(crc32c::crc32c(sealed_dir), &footer[..F_CRC]); + footer[F_CRC..F_CRC + 4].copy_from_slice(&crc.to_le_bytes()); + footer } /// Seal the directory and assemble the final segment bytes in one step, for /// callers that own `buf` outright and have nothing to preserve on error. The -/// open-segment buffer instead uses [`seal_directory`] + [`assemble_segment`] +/// open-segment buffer instead uses [`seal_directory`] + [`assemble_segment_payload`] /// so a seal error can't drop it. pub(crate) fn finalize_segment( codec: &FrameCodec, @@ -647,6 +680,7 @@ fn open_spans( /// Walk the length-prefixed frames packed in `region`, opening each under the /// AAD derived from its absolute index and logical block. +#[cfg(test)] pub(crate) fn read_frames_from_region( codec: &FrameCodec, region: &[u8], @@ -664,8 +698,57 @@ pub(crate) fn read_frames_from_region( }) } -/// As [`read_frames_from_region`] but AEAD-verify only, returning each frame's -/// still-compressed payload. The relocation (repack) read: the payloads +/// Decode a frame run, gathering only frames that cross chunk boundaries. +pub(crate) fn read_frames_from_chunks( + codec: &FrameCodec, + mut region: bytes_utils::SegmentedBuf, + segid: Segid, + first_frame: u32, + slots: &[(u64, u64)], +) -> Result>, SegmentError> { + use bytes::Buf; + let parallel = region.remaining() >= PARALLEL_CRYPTO_MIN_BYTES; + let mut frames = Vec::with_capacity(slots.len()); + for (i, &(inode, extent)) in slots.iter().enumerate() { + if region.remaining() < LEN_PREFIX { + return Err(SegmentError::Malformed("frame length prefix out of bounds")); + } + let len = region.get_u32_le() as usize; + if len > region.remaining() { + return Err(SegmentError::Malformed("frame body out of bounds")); + } + let fi = first_frame + .checked_add(i as u32) + .ok_or(SegmentError::Malformed("frame index overflow"))?; + frames.push(( + region.copy_to_bytes(len), + frame_aad(segid, fi, inode, extent), + )); + } + let open = |(frame, aad): (bytes::Bytes, Vec)| { + codec.open_owned(frame, &aad).map_err(SegmentError::from) + }; + let runtime = tokio::runtime::Handle::try_current().ok(); + if !parallel + || runtime + .as_ref() + .is_some_and(|h| h.runtime_flavor() != tokio::runtime::RuntimeFlavor::MultiThread) + { + return frames.into_iter().map(open).collect(); + } + let run = || { + use rayon::prelude::*; + frames.into_par_iter().map(open).collect() + }; + if runtime.is_some() { + tokio::task::block_in_place(run) + } else { + run() + } +} + +/// Verify length-prefixed frames, returning each still-compressed payload. +/// The relocation (repack) read: the payloads /// re-seal under their new slots' AADs without a decompress/recompress round /// trip, so gather memory tracks stored size, not the compression ratio. pub(crate) fn read_compressed_frames_from_region( @@ -734,6 +817,64 @@ mod tests { .expect("test key should be lockable") } + #[test] + fn chunked_segment_preserves_frames_and_wire_format() { + let c = codec(); + let segid = Segid::new(3, 19); + let plains = vec![(7, 0, vec![0xab; 32768]), (7, 1, vec![0xcd; 32768])]; + let raw = Bytes::from(build(&c, segid, &plains)); + let segment = Segment::parse(raw.clone()).unwrap(); + let dir = segment.directory(&c).unwrap(); + let mut chunks = Vec::new(); + for entry in &dir { + let start = entry.byte_offset as usize; + chunks.push(raw.slice(start..start + LEN_PREFIX)); + chunks.push(raw.slice(start + LEN_PREFIX..start + LEN_PREFIX + entry.len as usize)); + } + let payload = assemble_segment_payload( + segid, + chunks.clone(), + dir.len() as u32, + raw[segment.dir_offset as usize..raw.len() - FOOTER_LEN].to_vec(), + segment.sealed_seqno, + ); + for (original, retained) in chunks.iter().zip(payload.iter()) { + assert_eq!(original.as_ptr(), retained.as_ptr()); + assert_eq!(original.len(), retained.len()); + } + assert_eq!(Bytes::from(payload), raw); + } + + #[test] + fn segmented_frames_decode_across_every_boundary_and_reject_truncation() { + let c = codec(); + let segid = Segid::new(3, 19); + let plains = vec![(7, 0, vec![0xab; 32768]), (7, 1, vec![0xcd; 32768])]; + let raw = Bytes::from(build(&c, segid, &plains)); + let end = Segment::parse(raw.clone()).unwrap().dir_offset as usize; + let slots = [(7, 0), (7, 1)]; + for split in 0..=end { + let chunks = vec![raw.slice(..split), raw.slice(split..end)].into(); + let got = read_frames_from_chunks(&c, chunks, segid, 0, &slots).unwrap(); + assert_eq!(got[0], plains[0].2); + assert_eq!(got[1], plains[1].2); + } + assert!( + read_frames_from_chunks(&c, vec![raw.slice(..end - 1)].into(), segid, 0, &slots) + .is_err() + ); + assert!( + read_frames_from_chunks( + &c, + vec![raw.slice(..end)].into(), + segid, + 0, + &[(8, 0), (7, 1)] + ) + .is_err() + ); + } + // A run past PARALLEL_CRYPTO_MIN_BYTES decodes on rayon and must roundtrip with // the per-frame AADs intact and in order. Content is incompressible so the // stored run clears the byte gate (compressible frames would shrink below it @@ -757,6 +898,17 @@ mod tests { for ((_, _, want), got) in frames.iter().zip(&got) { assert_eq!(want, got); } + let chunks = (0..seg.dir_offset as usize) + .step_by(128 * 1024) + .map(|start| { + seg.bytes + .slice(start..(start + 128 * 1024).min(seg.dir_offset as usize)) + }) + .collect(); + let got = read_frames_from_chunks(&c, chunks, segid, 0, &slots).unwrap(); + for ((_, _, want), got) in frames.iter().zip(&got) { + assert_eq!(want, got); + } } // The relocation crypto (verify-only read, rebind-only batch seal) past the diff --git a/zerofs/src/segment_store.rs b/zerofs/src/segment_store.rs index cfd95500b..f6573b605 100644 --- a/zerofs/src/segment_store.rs +++ b/zerofs/src/segment_store.rs @@ -11,9 +11,10 @@ use std::sync::Arc; use std::sync::atomic::{AtomicU64, Ordering}; use bytes::Bytes; +use bytes_utils::SegmentedBuf; use futures::{StreamExt, TryStreamExt}; use slatedb::object_store::{ - GetOptions, GetRange, ObjectStore, ObjectStoreExt, PutMode, PutOptions, path::Path, + GetOptions, GetRange, ObjectStore, ObjectStoreExt, PutMode, PutOptions, PutPayload, path::Path, }; use crate::frame_codec::{Compressed, FrameCodec}; @@ -93,12 +94,12 @@ impl SegmentStore { /// PUT pre-built segment bytes (durable on return). Used by the open-segment /// buffer's seal, which builds the bytes itself via `seal_directory` + - /// `assemble_segment`. - pub async fn put_segment(&self, segid: Segid, bytes: Bytes) -> Result<()> { - validate_segment_size(bytes.len())?; + /// `assemble_segment_payload`. + pub async fn put_segment(&self, segid: Segid, payload: PutPayload) -> Result<()> { + validate_segment_size(payload.content_length())?; let path = Path::from(segid.object_key()); self.object_store - .put(&path, bytes.into()) + .put(&path, payload) .await .map_err(|e| SegmentStoreError::ObjectStore(e.to_string()))?; Ok(()) @@ -150,7 +151,7 @@ impl SegmentStore { )); } let bytes = builder.finish(segid.counter)?; - self.put_segment(segid, Bytes::from(bytes)).await?; + self.put_segment(segid, bytes.into()).await?; Ok(locs) } @@ -179,10 +180,10 @@ impl SegmentStore { first_frame: u32, slots: &[(InodeId, u64)], ) -> Result> { - let region = self.read_run_region(segid, byte_offset, byte_len).await?; - let frames = crate::segment::read_frames_from_region( + let region = self.read_run_chunks(segid, byte_offset, byte_len).await?; + let frames = crate::segment::read_frames_from_chunks( &self.codec, - ®ion, + region, segid, first_frame, slots, @@ -190,6 +191,37 @@ impl SegmentStore { Ok(frames.into_iter().map(Bytes::from).collect()) } + pub(crate) async fn prefetch_run(&self, segid: Segid, offset: u64, len: u32) -> Result<()> { + self.read_run_chunks(segid, offset, len).await?; + Ok(()) + } + + async fn read_run_chunks( + &self, + segid: Segid, + offset: u64, + len: u32, + ) -> Result> { + let result = self + .object_store + .get_opts( + &Path::from(segid.object_key()), + GetOptions { + range: Some(GetRange::Bounded(offset..offset + len as u64)), + ..Default::default() + }, + ) + .await + .map_err(|e| SegmentStoreError::ObjectStore(e.to_string()))?; + let chunks = result + .into_stream() + .try_collect() + .await + .map_err(|e| SegmentStoreError::ObjectStore(e.to_string()))?; + self.read_calls.fetch_add(1, Ordering::Relaxed); + Ok(chunks) + } + /// As [`Self::read_run`] but AEAD-verify only, returning still-compressed /// payloads for relocation (see [`Self::seal_compressed`]). pub async fn read_compressed_run( diff --git a/zerofs/src/webui.rs b/zerofs/src/webui.rs index 80c74bc60..30267b27e 100644 --- a/zerofs/src/webui.rs +++ b/zerofs/src/webui.rs @@ -2,6 +2,7 @@ use crate::config::WebUIConfig; use crate::fs::ZeroFS; use crate::ninep::handler::{NinePHandler, SessionReleaseGuard}; use crate::ninep::lock_manager::FileLockManager; +use crate::ninep::response::EncodedResponse; use crate::ninep::server::{InflightRegistry, dispatch_9p_frame, response_may_be_emitted}; use crate::rpc::proto; use crate::rpc::server::AdminRpcServer; @@ -11,6 +12,7 @@ use axum::extract::State; use axum::extract::ws::{Message as WsMessage, WebSocket, WebSocketUpgrade}; use axum::response::IntoResponse; use axum::routing::get; +use bytes::Buf; use ninep_proto::P9_CHANNEL_SIZE; use rust_embed::Embed; use std::sync::Arc; @@ -57,7 +59,7 @@ async fn handle_9p_ws(socket: WebSocket, state: AppState, _drain_guard: TaskTrac let mut release_guard = SessionReleaseGuard::new(Arc::clone(&handler)); let inflight = InflightRegistry::default(); - let (tx, mut rx) = mpsc::channel::<(u16, Vec)>(P9_CHANNEL_SIZE); + let (tx, mut rx) = mpsc::channel::<(u16, EncodedResponse)>(P9_CHANNEL_SIZE); // Writer task: sends response bytes as WS binary messages let (mut ws_tx, mut ws_rx) = socket.split(); @@ -67,7 +69,8 @@ async fn handle_9p_ws(socket: WebSocket, state: AppState, _drain_guard: TaskTrac // Abort on early exit; normal teardown drains responses for a bounded interval. let mut writer = AbortOnDropHandle::new(spawn_named("9p-ws-writer", async move { use futures::SinkExt; - while let Some((tag, response_bytes)) = rx.recv().await { + while let Some((tag, mut response_bytes)) = rx.recv().await { + let response_bytes = response_bytes.copy_to_bytes(response_bytes.remaining()); if !response_may_be_emitted(&response_db, &response_bytes) { warn!( "Dropping successful WebSocket 9P response for tag {tag} after serving \ @@ -76,11 +79,7 @@ async fn handle_9p_ws(socket: WebSocket, state: AppState, _drain_guard: TaskTrac writer_authority_lost.cancel(); break; } - if ws_tx - .send(WsMessage::Binary(response_bytes.into())) - .await - .is_err() - { + if ws_tx.send(WsMessage::Binary(response_bytes)).await.is_err() { break; } }