mirror of
https://github.com/rustfs/rustfs.git
synced 2026-11-26 10:22:44 +00:00
Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a9d9a75edf | |||
| edb2689f80 | |||
| 420e022e1f | |||
| bfa8b431a0 | |||
| 589803525f | |||
| 8f2ae45a1a | |||
| 381a56f2fb |
@@ -110,29 +110,24 @@ pub fn compression_index_storage_bytes(index: &Index) -> Bytes {
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes one complete stored compression index for Range GET planning.
|
||||
pub fn decode_compression_index_bytes(bytes: &Bytes) -> Option<Index> {
|
||||
#[cfg(feature = "rio-v2")]
|
||||
{
|
||||
if let Some(decoded) = decode_minio_index_bytes(bytes) {
|
||||
return Some(decoded);
|
||||
}
|
||||
}
|
||||
|
||||
// Check the legacy frame before attempting to restore a headerless S2
|
||||
// index. Metadata contains exactly one index, so reject partial parses.
|
||||
let mut decoded = Index::new();
|
||||
if decoded.load(bytes.as_ref()).is_ok() {
|
||||
if decoded.load(bytes.as_ref()).is_ok_and(|remaining| remaining.is_empty()) {
|
||||
return Some(decoded);
|
||||
}
|
||||
|
||||
#[cfg(feature = "rio-v2")]
|
||||
{
|
||||
let restored = restore_legacy_index_headers(bytes.as_ref());
|
||||
let mut decoded = Index::new();
|
||||
if decoded.load(&restored).is_ok() {
|
||||
return Some(decoded);
|
||||
}
|
||||
decode_minio_index_bytes(bytes)
|
||||
}
|
||||
|
||||
None
|
||||
#[cfg(not(feature = "rio-v2"))]
|
||||
{
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn compression_reader<R>(reader: R, algorithm: CompressionAlgorithm, encrypted: bool) -> CompressReader<R>
|
||||
@@ -298,30 +293,6 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rio-v2")]
|
||||
fn restore_legacy_index_headers(bytes: &[u8]) -> Vec<u8> {
|
||||
if bytes.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
const S2_INDEX_HEADER: &[u8] = b"s2idx\x00";
|
||||
const S2_INDEX_TRAILER: &[u8] = b"\x00xdi2s";
|
||||
let mut restored = Vec::with_capacity(4 + S2_INDEX_HEADER.len() + bytes.len() + 4 + S2_INDEX_TRAILER.len());
|
||||
restored.extend_from_slice(&[0x99, 0x2A, 0x4D, 0x18]);
|
||||
restored.extend_from_slice(S2_INDEX_HEADER);
|
||||
restored.extend_from_slice(bytes);
|
||||
|
||||
let total_size = (restored.len() + 4 + S2_INDEX_TRAILER.len()) as u32;
|
||||
restored.extend_from_slice(&total_size.to_le_bytes());
|
||||
restored.extend_from_slice(S2_INDEX_TRAILER);
|
||||
|
||||
let chunk_len = restored.len() - 4;
|
||||
restored[1] = chunk_len as u8;
|
||||
restored[2] = (chunk_len >> 8) as u8;
|
||||
restored[3] = (chunk_len >> 16) as u8;
|
||||
restored
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct WriteEncryption {
|
||||
key_bytes: [u8; 32],
|
||||
|
||||
@@ -14,8 +14,9 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
#[cfg(test)]
|
||||
use crate::io_support::rio::Index;
|
||||
use std::mem::MaybeUninit;
|
||||
use std::{mem::MaybeUninit, task::ready};
|
||||
|
||||
#[cfg(feature = "rio-v2")]
|
||||
const DARE_PAYLOAD_SIZE: i64 = 64 * 1024;
|
||||
@@ -41,11 +42,8 @@ pub(crate) fn restore_request_active(opts: &ObjectOptions) -> bool {
|
||||
restore.type_.is_some() || restore.days.is_some() || restore.output_location.is_some() || restore.select_parameters.is_some()
|
||||
}
|
||||
|
||||
fn decode_compression_index(index: Option<&Bytes>) -> Option<Index> {
|
||||
crate::io_support::rio::decode_compression_index_bytes(index?)
|
||||
}
|
||||
|
||||
fn get_compressed_offsets(oi: &ObjectInfo, offset: i64) -> (i64, i64, usize, i64, u64) {
|
||||
#[cfg(feature = "rio-v2")]
|
||||
fn get_encrypted_compressed_offsets(oi: &ObjectInfo, offset: i64) -> (i64, i64, usize, i64, u64) {
|
||||
let mut skip_length = 0_i64;
|
||||
let mut cumulative_actual_size = 0_i64;
|
||||
let mut first_part_idx = 0_usize;
|
||||
@@ -63,30 +61,20 @@ fn get_compressed_offsets(oi: &ObjectInfo, offset: i64) -> (i64, i64, usize, i64
|
||||
}
|
||||
|
||||
let mut part_skip = offset - skip_length;
|
||||
#[cfg(feature = "rio-v2")]
|
||||
let (mut decrypt_skip, mut seq_num) = (0_i64, 0_u64);
|
||||
#[cfg(not(feature = "rio-v2"))]
|
||||
let (decrypt_skip, seq_num) = (0_i64, 0_u64);
|
||||
|
||||
if part_skip > 0
|
||||
&& let Some(part) = oi.parts.get(first_part_idx)
|
||||
&& let Some(index) = decode_compression_index(part.index.as_ref())
|
||||
&& let Some(index) = part
|
||||
.index
|
||||
.as_ref()
|
||||
.and_then(crate::io_support::rio::decode_compression_index_bytes)
|
||||
&& let Ok((comp_off, uncomp_off)) = index.find(part_skip)
|
||||
&& comp_off > 0
|
||||
{
|
||||
#[cfg(feature = "rio-v2")]
|
||||
if oi.is_encrypted() {
|
||||
seq_num = (comp_off / DARE_PAYLOAD_SIZE) as u64;
|
||||
decrypt_skip = comp_off % DARE_PAYLOAD_SIZE;
|
||||
compressed_offset += (comp_off / DARE_PAYLOAD_SIZE) * DARE_PACKAGE_SIZE;
|
||||
} else {
|
||||
compressed_offset += comp_off;
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "rio-v2"))]
|
||||
{
|
||||
compressed_offset += comp_off;
|
||||
}
|
||||
seq_num = (comp_off / DARE_PAYLOAD_SIZE) as u64;
|
||||
decrypt_skip = comp_off % DARE_PAYLOAD_SIZE;
|
||||
compressed_offset += (comp_off / DARE_PAYLOAD_SIZE) * DARE_PACKAGE_SIZE;
|
||||
|
||||
part_skip -= uncomp_off;
|
||||
}
|
||||
@@ -94,6 +82,68 @@ fn get_compressed_offsets(oi: &ObjectInfo, offset: i64) -> (i64, i64, usize, i64
|
||||
(compressed_offset, part_skip, first_part_idx, decrypt_skip, seq_num)
|
||||
}
|
||||
|
||||
// Plan a window of complete compression blocks in stored coordinates. The
|
||||
// index can omit the final block or record a stale total. Part metadata owns
|
||||
// the actual bounds, and missing checkpoints widen only the covering parts.
|
||||
fn compressed_storage_window(oi: &ObjectInfo, offset: usize, length: i64) -> Option<(usize, i64, usize)> {
|
||||
let start = i64::try_from(offset).ok()?;
|
||||
let end = start.checked_add(length)?;
|
||||
if start >= end {
|
||||
return None;
|
||||
}
|
||||
let (mut plaintext_offset, mut stored_offset) = (0_i64, 0_i64);
|
||||
let mut window_start = None;
|
||||
for part in oi.parts.iter() {
|
||||
let stored_size = i64::try_from(part.size).ok()?;
|
||||
let stored_end = stored_offset.checked_add(stored_size)?;
|
||||
if stored_end > oi.size || part.actual_size < 0 || (part.actual_size == 0) != (stored_size == 0) {
|
||||
return None;
|
||||
}
|
||||
let plaintext_end = plaintext_offset.checked_add(part.actual_size)?;
|
||||
let starts_here = window_start.is_none() && start < plaintext_end;
|
||||
let ends_here = end <= plaintext_end;
|
||||
if starts_here || ends_here {
|
||||
let index = part
|
||||
.index
|
||||
.as_ref()
|
||||
.filter(|_| (starts_here && start > plaintext_offset) || (ends_here && end < plaintext_end))
|
||||
.and_then(crate::io_support::rio::decode_compression_index_bytes);
|
||||
if starts_here {
|
||||
let relative_start = start - plaintext_offset;
|
||||
let (stored, plaintext) = index
|
||||
.as_ref()
|
||||
.filter(|_| relative_start > 0)
|
||||
.and_then(|index| index.checkpoint_at_or_before(relative_start))
|
||||
.filter(|&(stored, plaintext)| {
|
||||
(1..stored_size).contains(&stored) && (0..=relative_start).contains(&plaintext)
|
||||
})
|
||||
.unwrap_or((0, 0));
|
||||
window_start = Some((stored_offset + stored, relative_start - plaintext));
|
||||
}
|
||||
if ends_here {
|
||||
let (window_start, skip) = window_start?;
|
||||
let relative_end = end - plaintext_offset;
|
||||
let window_end = index
|
||||
.filter(|_| relative_end < part.actual_size)
|
||||
.as_ref()
|
||||
.and_then(|index| index.checkpoint_at_or_after(relative_end))
|
||||
.filter(|&(stored, plaintext)| {
|
||||
(1..=stored_size).contains(&stored) && (relative_end..=part.actual_size).contains(&plaintext)
|
||||
})
|
||||
.map_or(stored_end, |(stored, _)| stored_offset + stored);
|
||||
return (window_end > window_start).then_some((
|
||||
usize::try_from(window_start).ok()?,
|
||||
window_end - window_start,
|
||||
usize::try_from(skip).ok()?,
|
||||
));
|
||||
}
|
||||
}
|
||||
plaintext_offset = plaintext_end;
|
||||
stored_offset = stored_end;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(feature = "rio-v2")]
|
||||
fn get_encrypted_offsets(oi: &ObjectInfo, offset: i64) -> Result<(i64, usize, usize, u32, i64)> {
|
||||
if oi.parts.is_empty() {
|
||||
@@ -713,10 +763,12 @@ impl ReadPlan {
|
||||
let actual_size = oi.get_actual_size()?;
|
||||
let (storage_offset, storage_length, decompressed_offset, decompressed_length) = if let Some(rs) = rs {
|
||||
let (req_off, req_length) = rs.get_offset_length(actual_size)?;
|
||||
let (physical_off, decompressed_skip, _, _, _) = get_compressed_offsets(oi, req_off as i64);
|
||||
let storage_offset = usize::try_from(physical_off)
|
||||
.map_err(|_| Error::other(format!("invalid compressed offset {physical_off}")))?;
|
||||
(storage_offset, oi.size - physical_off, decompressed_skip as usize, req_length)
|
||||
let (storage_offset, storage_length, skip) = if req_length < actual_size {
|
||||
compressed_storage_window(oi, req_off, req_length).unwrap_or((0, oi.size, req_off))
|
||||
} else {
|
||||
(0, oi.size, req_off)
|
||||
};
|
||||
(storage_offset, storage_length, skip, req_length)
|
||||
} else {
|
||||
(0, oi.size, 0, actual_size)
|
||||
};
|
||||
@@ -794,7 +846,7 @@ impl ReadPlan {
|
||||
)?
|
||||
} else if is_compressed {
|
||||
let (physical_off, decompressed_skip, first_part_idx, decrypt_skip, seq_num) =
|
||||
get_compressed_offsets(oi, requested_offset as i64);
|
||||
get_encrypted_compressed_offsets(oi, requested_offset as i64);
|
||||
(
|
||||
usize::try_from(physical_off)
|
||||
.map_err(|_| Error::other(format!("invalid encrypted compressed offset {physical_off}")))?,
|
||||
@@ -910,40 +962,14 @@ impl ReadPlan {
|
||||
decompressed_length,
|
||||
total_plaintext_size,
|
||||
} => {
|
||||
let dec_reader = crate::io_support::rio::decompression_reader(reader, algorithm, backend);
|
||||
#[cfg(feature = "rio-v2")]
|
||||
let dec_reader = StreamConsumer::new(dec_reader);
|
||||
let final_reader: Box<dyn AsyncRead + Unpin + Send + Sync> = if decompressed_offset > 0
|
||||
|| decompressed_length != total_plaintext_size as i64
|
||||
{
|
||||
#[cfg(feature = "rio-v2")]
|
||||
let ranged_result = RangedDecompressReader::new_draining(
|
||||
dec_reader,
|
||||
decompressed_offset,
|
||||
decompressed_length,
|
||||
total_plaintext_size,
|
||||
);
|
||||
#[cfg(not(feature = "rio-v2"))]
|
||||
let ranged_result =
|
||||
RangedDecompressReader::new(dec_reader, decompressed_offset, decompressed_length, total_plaintext_size);
|
||||
|
||||
match ranged_result {
|
||||
Ok(ranged_reader) => {
|
||||
tracing::debug!(
|
||||
"Successfully created RangedDecompressReader for offset={}, length={}",
|
||||
decompressed_offset,
|
||||
decompressed_length
|
||||
);
|
||||
Box::new(ranged_reader)
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("RangedDecompressReader failed with invalid range parameters: {}", e);
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Box::new(HardLimitReader::new(dec_reader, decompressed_length))
|
||||
};
|
||||
let final_reader = compressed_object_reader(
|
||||
reader,
|
||||
algorithm,
|
||||
backend,
|
||||
decompressed_offset,
|
||||
decompressed_length,
|
||||
total_plaintext_size,
|
||||
)?;
|
||||
|
||||
let mut object_info = oi.clone();
|
||||
object_info.size = self.object_size;
|
||||
@@ -1019,29 +1045,14 @@ impl ReadPlan {
|
||||
|
||||
let final_reader: Box<dyn AsyncRead + Unpin + Send + Sync> =
|
||||
if let Some((algo, compression_backend)) = compression {
|
||||
let decompressed_reader =
|
||||
crate::io_support::rio::decompression_reader(decrypted_reader, algo, compression_backend);
|
||||
#[cfg(feature = "rio-v2")]
|
||||
let decompressed_reader = StreamConsumer::new(decompressed_reader);
|
||||
if plaintext_offset > 0 || plaintext_length != total_plaintext_size_i64 {
|
||||
#[cfg(feature = "rio-v2")]
|
||||
let ranged_reader = RangedDecompressReader::new_draining(
|
||||
decompressed_reader,
|
||||
plaintext_offset,
|
||||
plaintext_length,
|
||||
total_plaintext_size,
|
||||
)?;
|
||||
#[cfg(not(feature = "rio-v2"))]
|
||||
let ranged_reader = RangedDecompressReader::new(
|
||||
decompressed_reader,
|
||||
plaintext_offset,
|
||||
plaintext_length,
|
||||
total_plaintext_size,
|
||||
)?;
|
||||
Box::new(ranged_reader)
|
||||
} else {
|
||||
Box::new(HardLimitReader::new(decompressed_reader, total_plaintext_size_i64))
|
||||
}
|
||||
compressed_object_reader(
|
||||
decrypted_reader,
|
||||
algo,
|
||||
compression_backend,
|
||||
plaintext_offset,
|
||||
plaintext_length,
|
||||
total_plaintext_size,
|
||||
)?
|
||||
} else if plaintext_offset > 0 || plaintext_length != total_plaintext_size_i64 {
|
||||
Box::new(RangedDecompressReader::new(
|
||||
decrypted_reader,
|
||||
@@ -1118,294 +1129,201 @@ impl AsyncRead for GetObjectReader {
|
||||
}
|
||||
}
|
||||
|
||||
fn compressed_object_reader(
|
||||
source: Box<dyn AsyncRead + Unpin + Send + Sync>,
|
||||
algorithm: CompressionAlgorithm,
|
||||
backend: crate::io_support::rio::ReadCompressionBackend,
|
||||
offset: usize,
|
||||
length: i64,
|
||||
total_size: usize,
|
||||
) -> Result<Box<dyn AsyncRead + Unpin + Send + Sync>> {
|
||||
let decoded = crate::io_support::rio::decompression_reader(source, algorithm, backend);
|
||||
if offset != 0 || usize::try_from(length).ok() != Some(total_size) {
|
||||
// A partial response needs the blocks covering its bytes. Dropping the
|
||||
// source closes the producer instead of draining unrelated blocks.
|
||||
return Ok(Box::new(RangedDecompressReader::new(decoded, offset, length, total_size)?));
|
||||
}
|
||||
|
||||
#[cfg(feature = "rio-v2")]
|
||||
let decoded = StreamConsumer::new(decoded);
|
||||
Ok(Box::new(HardLimitReader::new(decoded, length)))
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct SkipReader<R> {
|
||||
inner: R,
|
||||
bytes_to_skip: usize,
|
||||
bytes_skipped: usize,
|
||||
scratch: Box<[MaybeUninit<u8>]>,
|
||||
remaining_skip: usize,
|
||||
scratch: Option<Box<[MaybeUninit<u8>]>>,
|
||||
}
|
||||
|
||||
impl<R: AsyncRead + Unpin + Send + Sync> SkipReader<R> {
|
||||
impl<R: AsyncRead + Unpin> SkipReader<R> {
|
||||
fn new(inner: R, bytes_to_skip: usize) -> Self {
|
||||
Self {
|
||||
inner,
|
||||
bytes_to_skip,
|
||||
bytes_skipped: 0,
|
||||
scratch: Box::<[u8]>::new_uninit_slice(8192),
|
||||
remaining_skip: bytes_to_skip,
|
||||
scratch: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: AsyncRead + Unpin + Send + Sync> AsyncRead for SkipReader<R> {
|
||||
impl<R: AsyncRead + Unpin> AsyncRead for SkipReader<R> {
|
||||
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
|
||||
let this = self.as_mut().get_mut();
|
||||
if buf.remaining() == 0 {
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
|
||||
while this.bytes_skipped < this.bytes_to_skip {
|
||||
let remaining = this.bytes_to_skip - this.bytes_skipped;
|
||||
let scratch_len = remaining.min(this.scratch.len());
|
||||
let mut scratch_buf = ReadBuf::uninit(&mut this.scratch[..scratch_len]);
|
||||
match Pin::new(&mut this.inner).poll_read(cx, &mut scratch_buf) {
|
||||
Poll::Pending => return Poll::Pending,
|
||||
Poll::Ready(Err(err)) => return Poll::Ready(Err(err)),
|
||||
Poll::Ready(Ok(())) => {
|
||||
let n = scratch_buf.filled().len();
|
||||
if n == 0 {
|
||||
return Poll::Ready(Err(std::io::Error::new(
|
||||
std::io::ErrorKind::UnexpectedEof,
|
||||
format!("unexpected EOF while skipping {} bytes from decrypted stream", this.bytes_to_skip),
|
||||
)));
|
||||
}
|
||||
this.bytes_skipped += n;
|
||||
if this.remaining_skip != 0 {
|
||||
let scratch_len = this.remaining_skip.min(8192);
|
||||
let scratch = this.scratch.get_or_insert_with(|| Box::<[u8]>::new_uninit_slice(scratch_len));
|
||||
while this.remaining_skip > 0 {
|
||||
// An unindexed range can skip many decoded blocks without the source yielding.
|
||||
let budget = ready!(tokio::task::coop::poll_proceed(cx));
|
||||
let len = this.remaining_skip.min(scratch.len());
|
||||
let mut discard = ReadBuf::uninit(&mut scratch[..len]);
|
||||
ready!(Pin::new(&mut this.inner).poll_read(cx, &mut discard))?;
|
||||
let n = discard.filled().len();
|
||||
if n == 0 {
|
||||
return Poll::Ready(Err(std::io::Error::new(
|
||||
std::io::ErrorKind::UnexpectedEof,
|
||||
"object stream ended before reaching the range start",
|
||||
)));
|
||||
}
|
||||
this.remaining_skip -= n;
|
||||
budget.made_progress();
|
||||
}
|
||||
this.scratch = None;
|
||||
}
|
||||
|
||||
Pin::new(&mut this.inner).poll_read(cx, buf)
|
||||
}
|
||||
}
|
||||
|
||||
/// A streaming decompression reader that supports range requests by skipping data in the decompressed stream.
|
||||
/// This implementation acknowledges that compressed streams (like LZ4) must be decompressed sequentially
|
||||
/// from the beginning, so it streams and discards data until reaching the target offset.
|
||||
/// Reads a bounded plaintext range from a stream positioned at or before its start.
|
||||
/// The source is released when the range completes. An early source EOF is an error.
|
||||
#[derive(Debug)]
|
||||
pub struct RangedDecompressReader<R: AsyncRead + Unpin + Send + Sync + 'static> {
|
||||
inner: Option<R>,
|
||||
target_offset: usize,
|
||||
target_length: usize,
|
||||
current_offset: usize,
|
||||
bytes_returned: usize,
|
||||
scratch: Box<[MaybeUninit<u8>]>,
|
||||
inner: Option<tokio::io::Take<SkipReader<R>>>,
|
||||
drain_on_done: bool,
|
||||
drain_task: Option<tokio::task::JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl<R: AsyncRead + Unpin + Send + Sync + 'static> RangedDecompressReader<R> {
|
||||
/// Skips `offset` bytes and yields up to `length` bytes, capped by `total_size`.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns an invalid range error if the offset is outside the stream or the length is negative.
|
||||
pub fn new(inner: R, offset: usize, length: i64, total_size: usize) -> Result<Self> {
|
||||
Self::new_with_drain(inner, offset, length, total_size, false)
|
||||
}
|
||||
|
||||
/// Reads like [Self::new] and drains any remainder in the background once the range completes.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns the same range validation errors as [Self::new].
|
||||
pub fn new_draining(inner: R, offset: usize, length: i64, total_size: usize) -> Result<Self> {
|
||||
Self::new_with_drain(inner, offset, length, total_size, true)
|
||||
}
|
||||
|
||||
fn new_with_drain(inner: R, offset: usize, length: i64, total_size: usize, drain_on_done: bool) -> Result<Self> {
|
||||
// Validate the range request
|
||||
if offset >= total_size {
|
||||
tracing::debug!("Range offset {} exceeds total size {}", offset, total_size);
|
||||
return Err(Error::InvalidRangeSpec("Range offset exceeds file size".to_string()));
|
||||
}
|
||||
|
||||
// Adjust length if it extends beyond file end
|
||||
let actual_length = std::cmp::min(length as usize, total_size - offset);
|
||||
|
||||
tracing::debug!(
|
||||
"Creating RangedDecompressReader: offset={}, length={}, total_size={}, actual_length={}",
|
||||
offset,
|
||||
length,
|
||||
total_size,
|
||||
actual_length
|
||||
);
|
||||
let length =
|
||||
u64::try_from(length).map_err(|_| Error::InvalidRangeSpec("Range length must be nonnegative".to_string()))?;
|
||||
let length = length.min((total_size - offset) as u64);
|
||||
|
||||
Ok(Self {
|
||||
inner: Some(inner),
|
||||
target_offset: offset,
|
||||
target_length: actual_length,
|
||||
current_offset: 0,
|
||||
bytes_returned: 0,
|
||||
scratch: Box::<[u8]>::new_uninit_slice(8192),
|
||||
inner: Some(SkipReader::new(inner, offset).take(length)),
|
||||
drain_on_done,
|
||||
drain_task: None,
|
||||
})
|
||||
}
|
||||
|
||||
fn start_drain(&mut self) {
|
||||
if !self.drain_on_done || self.drain_task.is_some() {
|
||||
return;
|
||||
fn finish(&mut self) {
|
||||
if let Some(inner) = self.inner.take()
|
||||
&& self.drain_on_done
|
||||
{
|
||||
drain_stream(inner.into_inner().inner);
|
||||
}
|
||||
|
||||
let Some(mut inner) = self.inner.take() else {
|
||||
return;
|
||||
};
|
||||
|
||||
self.drain_task = Some(tokio::spawn(async move {
|
||||
let mut buf = [0u8; 8192];
|
||||
loop {
|
||||
match inner.read(&mut buf).await {
|
||||
Ok(0) => break,
|
||||
Ok(_) => continue,
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: AsyncRead + Unpin + Send + Sync + 'static> AsyncRead for RangedDecompressReader<R> {
|
||||
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
|
||||
use std::pin::Pin;
|
||||
use std::task::Poll;
|
||||
use tokio::io::ReadBuf;
|
||||
|
||||
let this = self.as_mut().get_mut();
|
||||
|
||||
loop {
|
||||
// If we've returned all the bytes we need, return EOF
|
||||
if this.bytes_returned >= this.target_length {
|
||||
this.start_drain();
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
|
||||
// Read from the inner stream
|
||||
let buf_capacity = buf.remaining();
|
||||
if buf_capacity == 0 {
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
|
||||
let scratch_len = std::cmp::min(this.scratch.len(), std::cmp::max(buf_capacity, 1));
|
||||
let mut temp_read_buf = ReadBuf::uninit(&mut this.scratch[..scratch_len]);
|
||||
|
||||
let Some(inner) = this.inner.as_mut() else {
|
||||
return Poll::Ready(Ok(()));
|
||||
};
|
||||
|
||||
match Pin::new(inner).poll_read(cx, &mut temp_read_buf) {
|
||||
Poll::Pending => return Poll::Pending,
|
||||
Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
|
||||
Poll::Ready(Ok(())) => {
|
||||
let n = temp_read_buf.filled().len();
|
||||
if n == 0 {
|
||||
// EOF from inner stream
|
||||
if this.current_offset < this.target_offset {
|
||||
// We haven't reached the target offset yet - this is an error
|
||||
return Poll::Ready(Err(std::io::Error::new(
|
||||
std::io::ErrorKind::UnexpectedEof,
|
||||
format!(
|
||||
"Unexpected EOF: only read {} bytes, target offset is {}",
|
||||
this.current_offset, this.target_offset
|
||||
),
|
||||
)));
|
||||
}
|
||||
// Normal EOF after reaching target
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
|
||||
// Update current position
|
||||
let old_offset = this.current_offset;
|
||||
this.current_offset += n;
|
||||
|
||||
// Check if we're still in the skip phase
|
||||
if old_offset < this.target_offset {
|
||||
// We're still skipping data
|
||||
let skip_end = std::cmp::min(this.current_offset, this.target_offset);
|
||||
let bytes_to_skip_in_this_read = skip_end - old_offset;
|
||||
|
||||
if this.current_offset <= this.target_offset {
|
||||
// All data in this read should be skipped
|
||||
tracing::trace!("Skipping {} bytes at offset {}", n, old_offset);
|
||||
// Continue reading in the loop instead of recursive call
|
||||
continue;
|
||||
} else {
|
||||
// Partial skip: some data should be returned
|
||||
let data_start_in_buffer = bytes_to_skip_in_this_read;
|
||||
let available_data = n - data_start_in_buffer;
|
||||
let bytes_to_return = std::cmp::min(
|
||||
available_data,
|
||||
std::cmp::min(buf.remaining(), this.target_length - this.bytes_returned),
|
||||
);
|
||||
|
||||
if bytes_to_return > 0 {
|
||||
let data_slice =
|
||||
&temp_read_buf.filled()[data_start_in_buffer..data_start_in_buffer + bytes_to_return];
|
||||
buf.put_slice(data_slice);
|
||||
this.bytes_returned += bytes_to_return;
|
||||
|
||||
tracing::trace!(
|
||||
"Skipped {} bytes, returned {} bytes at offset {}",
|
||||
bytes_to_skip_in_this_read,
|
||||
bytes_to_return,
|
||||
old_offset
|
||||
);
|
||||
}
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
} else {
|
||||
// We're in the data return phase
|
||||
let bytes_to_return =
|
||||
std::cmp::min(n, std::cmp::min(buf.remaining(), this.target_length - this.bytes_returned));
|
||||
|
||||
if bytes_to_return > 0 {
|
||||
buf.put_slice(&temp_read_buf.filled()[..bytes_to_return]);
|
||||
this.bytes_returned += bytes_to_return;
|
||||
|
||||
tracing::trace!("Returned {} bytes at offset {}", bytes_to_return, old_offset);
|
||||
}
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(inner) = this.inner.as_mut() else {
|
||||
return Poll::Ready(Ok(()));
|
||||
};
|
||||
if inner.limit() == 0 {
|
||||
this.finish();
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
if buf.remaining() == 0 {
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
|
||||
let before = buf.filled().len();
|
||||
ready!(Pin::new(&mut *inner).poll_read(cx, buf))?;
|
||||
if before == buf.filled().len() {
|
||||
return Poll::Ready(Err(std::io::Error::new(
|
||||
std::io::ErrorKind::UnexpectedEof,
|
||||
"decompressed stream ended before the requested range was complete",
|
||||
)));
|
||||
}
|
||||
if inner.limit() == 0 {
|
||||
this.finish();
|
||||
}
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: AsyncRead + Unpin + Send + Sync + 'static> Drop for RangedDecompressReader<R> {
|
||||
fn drop(&mut self) {
|
||||
if self.bytes_returned >= self.target_length {
|
||||
self.start_drain();
|
||||
if self.inner.as_ref().is_some_and(|inner| inner.limit() == 0) {
|
||||
self.finish();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A wrapper that ensures the inner stream is fully consumed even if the outer reader stops early.
|
||||
/// This prevents broken pipe errors in erasure coding scenarios where the writer expects
|
||||
/// the full stream to be consumed.
|
||||
fn drain_stream<R: AsyncRead + Unpin + Send + 'static>(mut stream: R) {
|
||||
drop(tokio::spawn(async move {
|
||||
let mut buf = [0u8; 8192];
|
||||
while matches!(stream.read(&mut buf).await, Ok(n) if n > 0) {}
|
||||
}));
|
||||
}
|
||||
|
||||
/// Drains the source in the background if dropped before observing its EOF.
|
||||
pub struct StreamConsumer<R: AsyncRead + Unpin + Send + 'static> {
|
||||
inner: Option<R>,
|
||||
consumer_task: Option<tokio::task::JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl<R: AsyncRead + Unpin + Send + 'static> StreamConsumer<R> {
|
||||
pub fn new(inner: R) -> Self {
|
||||
Self {
|
||||
inner: Some(inner),
|
||||
consumer_task: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_consumer_started(&mut self) {
|
||||
if self.consumer_task.is_none() && self.inner.is_some() {
|
||||
let mut inner = self.inner.take().unwrap();
|
||||
let task = tokio::spawn(async move {
|
||||
let mut buf = [0u8; 8192];
|
||||
loop {
|
||||
match inner.read(&mut buf).await {
|
||||
Ok(0) => break, // EOF
|
||||
Ok(_) => continue, // Keep consuming
|
||||
Err(_) => break, // Error, stop consuming
|
||||
}
|
||||
}
|
||||
});
|
||||
self.consumer_task = Some(task);
|
||||
}
|
||||
Self { inner: Some(inner) }
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: AsyncRead + Unpin + Send + 'static> AsyncRead for StreamConsumer<R> {
|
||||
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
|
||||
use std::pin::Pin;
|
||||
use std::task::Poll;
|
||||
|
||||
if let Some(ref mut inner) = self.inner {
|
||||
Pin::new(inner).poll_read(cx, buf)
|
||||
} else {
|
||||
Poll::Ready(Ok(())) // EOF
|
||||
let Some(inner) = self.inner.as_mut() else {
|
||||
return Poll::Ready(Ok(()));
|
||||
};
|
||||
if buf.remaining() == 0 {
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
let before = buf.filled().len();
|
||||
ready!(Pin::new(inner).poll_read(cx, buf))?;
|
||||
if before == buf.filled().len() {
|
||||
self.inner = None;
|
||||
}
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: AsyncRead + Unpin + Send + 'static> Drop for StreamConsumer<R> {
|
||||
fn drop(&mut self) {
|
||||
self.ensure_consumer_started();
|
||||
if let Some(inner) = self.inner.take() {
|
||||
drain_stream(inner);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1666,6 +1584,129 @@ mod tests {
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::UnexpectedEof);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ranged_reader_fills_large_buffers_without_overreading() {
|
||||
let data = vec![0x32; 128 * 1024];
|
||||
let length = 64 * 1024;
|
||||
let mut reader = RangedDecompressReader::new(Cursor::new(data.clone()), 0, length as i64, data.len()).unwrap();
|
||||
let mut output = vec![0xa5; data.len()];
|
||||
|
||||
assert_eq!(reader.read(&mut output).await.unwrap(), length);
|
||||
assert_eq!(&output[..length], &data[..length]);
|
||||
assert!(output[length..].iter().all(|&byte| byte == 0xa5));
|
||||
assert_eq!(reader.read(&mut output).await.unwrap(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ranged_reader_skips_in_bulk_with_a_small_response_buffer() {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
struct CountReads {
|
||||
cursor: Cursor<Vec<u8>>,
|
||||
calls: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
impl AsyncRead for CountReads {
|
||||
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
|
||||
self.calls.fetch_add(1, Ordering::Relaxed);
|
||||
Pin::new(&mut self.cursor).poll_read(cx, buf)
|
||||
}
|
||||
}
|
||||
|
||||
let skip = 512 * 1024;
|
||||
let mut data = vec![0xa5; skip];
|
||||
data.extend_from_slice(b"wanted bytes here");
|
||||
let total = data.len();
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let inner = CountReads {
|
||||
cursor: Cursor::new(data),
|
||||
calls: Arc::clone(&calls),
|
||||
};
|
||||
let mut reader = RangedDecompressReader::new(inner, skip, 16, total).unwrap();
|
||||
let mut output = [0; 16];
|
||||
|
||||
reader.read_exact(&mut output).await.unwrap();
|
||||
assert_eq!(&output, b"wanted bytes her");
|
||||
assert_eq!(calls.load(Ordering::Relaxed), 65, "64 discards and one response read");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ranged_reader_yields_while_skipping_an_unindexed_prefix() {
|
||||
let skip = 2 * 1024 * 1024;
|
||||
let data = vec![0x36; skip + 1];
|
||||
let total = data.len();
|
||||
let mut reader = RangedDecompressReader::new(Cursor::new(data), skip, 1, total).unwrap();
|
||||
let mut output = [0; 1];
|
||||
let mut buf = ReadBuf::new(&mut output);
|
||||
let mut yielded = false;
|
||||
|
||||
std::future::poll_fn(|cx| {
|
||||
let poll = Pin::new(&mut reader).poll_read(cx, &mut buf);
|
||||
yielded |= poll.is_pending();
|
||||
poll
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(yielded, "a long discard must yield even when the source stays ready");
|
||||
assert_eq!(buf.filled(), &[0x36]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ranged_reader_releases_the_source_when_the_range_completes() {
|
||||
use tokio::io::AsyncWriteExt;
|
||||
|
||||
let (source, mut producer) = tokio::io::duplex(16);
|
||||
producer.write_all(b"abcxyz").await.unwrap();
|
||||
let mut reader = RangedDecompressReader::new(source, 0, 3, 6).unwrap();
|
||||
let mut body = [0; 3];
|
||||
|
||||
reader.read_exact(&mut body).await.unwrap();
|
||||
assert_eq!(&body, b"abc");
|
||||
let error = producer
|
||||
.write_all(b"!")
|
||||
.await
|
||||
.expect_err("completed range must release the pipe");
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::BrokenPipe);
|
||||
assert_eq!(reader.read(&mut body).await.unwrap(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ranged_reader_drains_the_source_when_requested() {
|
||||
use tokio::io::AsyncWriteExt;
|
||||
|
||||
let (source, mut producer) = tokio::io::duplex(8);
|
||||
producer.write_all(b"abc").await.unwrap();
|
||||
let mut reader = RangedDecompressReader::new_draining(source, 0, 3, 19).unwrap();
|
||||
let mut body = [0; 3];
|
||||
|
||||
reader.read_exact(&mut body).await.unwrap();
|
||||
assert_eq!(&body, b"abc");
|
||||
tokio::time::timeout(std::time::Duration::from_secs(2), producer.write_all(b"0123456789abcdef"))
|
||||
.await
|
||||
.expect("completed range must start draining the source")
|
||||
.expect("draining must keep the pipe open");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stream_consumer_observes_eof_only_with_a_nonempty_buffer() {
|
||||
let mut reader = StreamConsumer::new(Cursor::new(b"body"));
|
||||
assert_eq!(reader.read(&mut []).await.unwrap(), 0);
|
||||
|
||||
let mut output = Vec::new();
|
||||
reader.read_to_end(&mut output).await.unwrap();
|
||||
assert_eq!(output, b"body");
|
||||
assert!(reader.inner.is_none(), "observed EOF needs no background drain");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ranged_decompress_reader_rejects_eof_inside_the_requested_range() {
|
||||
let mut reader = RangedDecompressReader::new(Cursor::new(b"abc"), 1, 3, 4).unwrap();
|
||||
let mut output = Vec::new();
|
||||
let error = reader.read_to_end(&mut output).await.expect_err("short range must fail");
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::UnexpectedEof);
|
||||
assert_eq!(output, b"bc");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_ranged_decompress_reader_from_start() {
|
||||
let original_data = b"Hello, World! This is a test.";
|
||||
@@ -2688,10 +2729,6 @@ mod tests {
|
||||
let (compressed_offset, uncompressed_offset) = decoded.find(2_097_152).expect("seek into decoded index");
|
||||
assert!(compressed_offset > 0);
|
||||
assert_eq!(uncompressed_offset, 2_097_152);
|
||||
let (physical_offset, decompressed_skip, _, _, _) = get_compressed_offsets(&object_info, 2_097_152);
|
||||
assert!(physical_offset > 0);
|
||||
assert_eq!(decompressed_skip, 0);
|
||||
|
||||
let range = HTTPRangeSpec {
|
||||
is_suffix_length: false,
|
||||
start: 2_097_152,
|
||||
@@ -2830,7 +2867,8 @@ mod tests {
|
||||
assert!(compressed_offset > 0);
|
||||
assert_eq!(uncompressed_offset, range.start);
|
||||
|
||||
let (physical_offset, decompressed_skip, _, _, _) = get_compressed_offsets(&object_info, range.start);
|
||||
let (physical_offset, _, decompressed_skip) =
|
||||
compressed_storage_window(&object_info, range.start as usize, 10).expect("indexed range");
|
||||
assert!(physical_offset > 0);
|
||||
assert_eq!(decompressed_skip, 0);
|
||||
|
||||
@@ -2838,14 +2876,14 @@ mod tests {
|
||||
.await
|
||||
.expect("MinIO headerless compression index should be decoded");
|
||||
|
||||
assert_eq!(plan.storage_offset as i64, physical_offset);
|
||||
assert_eq!(plan.storage_offset, physical_offset);
|
||||
assert_eq!(plan.storage_length, object_info.size - plan.storage_offset as i64);
|
||||
assert_eq!(plan.object_size, 10);
|
||||
}
|
||||
|
||||
#[cfg(feature = "rio-v2")]
|
||||
#[test]
|
||||
fn test_get_compressed_offsets_aligns_encrypted_ranges_to_dare_packages() {
|
||||
fn test_get_encrypted_compressed_offsets_aligns_encrypted_ranges_to_dare_packages() {
|
||||
let mut index = Index::new();
|
||||
index.add(0, 0).unwrap();
|
||||
index.add(200_000, 2_097_152).unwrap();
|
||||
@@ -2879,7 +2917,7 @@ mod tests {
|
||||
};
|
||||
|
||||
let (physical_offset, decompressed_skip, first_part_idx, decrypt_skip, seq_num) =
|
||||
get_compressed_offsets(&object_info, 2_097_152);
|
||||
get_encrypted_compressed_offsets(&object_info, 2_097_152);
|
||||
|
||||
assert_eq!(first_part_idx, 0);
|
||||
assert_eq!(physical_offset, (expected_comp_off / DARE_PAYLOAD_SIZE) * DARE_PACKAGE_SIZE);
|
||||
|
||||
@@ -12,7 +12,6 @@ const HISTORICAL_INDEX: &[u8] = include_bytes!(concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/tests/fixtures/compression-index/pre-zigzag-index.bin"
|
||||
));
|
||||
#[cfg(not(feature = "rio-v2"))]
|
||||
const CURRENT_INDEX: &[u8] =
|
||||
include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/compression-index/zigzag-index.bin"));
|
||||
const PLAINTEXT_LEN: usize = 3 * 1024 * 1024 + 123;
|
||||
@@ -161,6 +160,16 @@ async fn truncated_index_falls_back_without_truncating_the_range() {
|
||||
assert_eq!(actual, fixture_plaintext()[start..start + 97]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compression_metadata_requires_one_complete_index() {
|
||||
use crate::io_support::rio::decode_compression_index_bytes;
|
||||
|
||||
let index = Bytes::from_static(CURRENT_INDEX);
|
||||
assert!(decode_compression_index_bytes(&index).is_some());
|
||||
let trailing = Bytes::from([CURRENT_INDEX, b"trailing bytes"].concat());
|
||||
assert!(decode_compression_index_bytes(&trailing).is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn historical_index_fallback_does_not_hide_a_body_checksum_failure() {
|
||||
let info = fixture_info(HISTORICAL_INDEX);
|
||||
@@ -183,3 +192,105 @@ async fn historical_index_fallback_does_not_hide_a_body_checksum_failure() {
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
|
||||
assert!(actual.len() < PLAINTEXT_LEN);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn compressed_ranges_bound_storage_for_large_index_and_unsampled_tail() {
|
||||
use crate::io_support::rio::compression_index_storage_bytes;
|
||||
use rustfs_rio::{CompressReader, TryGetIndex};
|
||||
|
||||
const BLOCK: usize = 1024 * 1024;
|
||||
const BLOCKS: usize = 203;
|
||||
const TAIL: usize = 32 * 1024;
|
||||
const LENGTH: usize = 16 * 1024;
|
||||
let len = BLOCK * BLOCKS + TAIL;
|
||||
let mut compressor = CompressReader::new(
|
||||
tokio::io::repeat(b'a')
|
||||
.take((len - TAIL) as u64)
|
||||
.chain(tokio::io::repeat(b'z').take(TAIL as u64)),
|
||||
CompressionAlgorithm::Lz4,
|
||||
);
|
||||
let mut stored = Vec::new();
|
||||
compressor.read_to_end(&mut stored).await.expect("compress fixture");
|
||||
let index = compressor.try_get_index().expect("legacy writer has an index");
|
||||
assert!(index.len() > 200);
|
||||
assert_eq!(index.total_uncompressed, (len - TAIL) as i64, "short final block is not indexed");
|
||||
let index = compression_index_storage_bytes(index);
|
||||
let mut info = fixture_info(&index);
|
||||
info.size = stored.len() as i64;
|
||||
info.actual_size = len as i64;
|
||||
let part = &mut Arc::make_mut(&mut info.parts)[0];
|
||||
part.size = stored.len();
|
||||
part.actual_size = len as i64;
|
||||
|
||||
for start in [1000, 9999, BLOCK - 7, len - LENGTH] {
|
||||
let range = if start == len - LENGTH {
|
||||
HTTPRangeSpec {
|
||||
is_suffix_length: true,
|
||||
start: -(LENGTH as i64),
|
||||
end: -1,
|
||||
}
|
||||
} else {
|
||||
HTTPRangeSpec {
|
||||
is_suffix_length: false,
|
||||
start: start as i64,
|
||||
end: (start + LENGTH - 1) as i64,
|
||||
}
|
||||
};
|
||||
let plan = ReadPlan::build(Some(range), &info, &ObjectOptions::default(), &HeaderMap::new())
|
||||
.await
|
||||
.expect("plan valid range");
|
||||
let physical_start = plan.storage_offset;
|
||||
let physical_end = physical_start + usize::try_from(plan.storage_length).expect("positive storage window");
|
||||
let mut output = Vec::new();
|
||||
let (mut reader, _, _) = plan
|
||||
.into_reader(Box::new(Cursor::new(stored[physical_start..physical_end].to_vec())), &info)
|
||||
.expect("valid plaintext range has a reader");
|
||||
reader.read_to_end(&mut output).await.expect("decode from planned window");
|
||||
let expected_byte = if start == len - LENGTH { b'z' } else { b'a' };
|
||||
assert_eq!(output, vec![expected_byte; LENGTH], "range starting at {start}");
|
||||
assert!(
|
||||
physical_end - physical_start < stored.len() / 20,
|
||||
"range at {start} reads too much compressed data"
|
||||
);
|
||||
if start == len - LENGTH {
|
||||
assert!(physical_start > stored.len() * 9 / 10, "suffix must seek within the final part");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn compressed_multipart_window_stops_at_the_last_covering_part() {
|
||||
let mut info = fixture_info(CURRENT_INDEX);
|
||||
let parts = Arc::make_mut(&mut info.parts);
|
||||
parts.push(ObjectPartInfo {
|
||||
number: 2,
|
||||
..parts[0].clone()
|
||||
});
|
||||
parts.push(ObjectPartInfo {
|
||||
number: 3,
|
||||
..parts[0].clone()
|
||||
});
|
||||
info.size *= 3;
|
||||
info.actual_size = (PLAINTEXT_LEN * 3) as i64;
|
||||
|
||||
let range = HTTPRangeSpec {
|
||||
is_suffix_length: false,
|
||||
start: PLAINTEXT_LEN as i64 - 16,
|
||||
end: PLAINTEXT_LEN as i64 + 15,
|
||||
};
|
||||
let plan = ReadPlan::build(Some(range), &info, &ObjectOptions::default(), &HeaderMap::new())
|
||||
.await
|
||||
.expect("valid range across parts");
|
||||
let physical_start = plan.storage_offset;
|
||||
let physical_end = physical_start + plan.storage_length as usize;
|
||||
assert!(physical_end > STREAM.len(), "range crosses the stored part boundary");
|
||||
assert!(physical_end < STREAM.len() * 2, "range should stop at the first checkpoint in part two");
|
||||
let stored = STREAM.repeat(3);
|
||||
let (mut reader, _, _) = plan
|
||||
.into_reader(Box::new(Cursor::new(stored[physical_start..physical_end].to_vec())), &info)
|
||||
.expect("create multipart range reader");
|
||||
let mut output = Vec::new();
|
||||
reader.read_to_end(&mut output).await.expect("decode part boundary");
|
||||
let plaintext = fixture_plaintext();
|
||||
assert_eq!(output, [&plaintext[PLAINTEXT_LEN - 16..], &plaintext[..16]].concat());
|
||||
}
|
||||
|
||||
@@ -65,10 +65,17 @@ pub fn minio_index_storage_bytes(index: &Index) -> Bytes {
|
||||
.unwrap_or(encoded)
|
||||
}
|
||||
|
||||
/// Decodes a complete framed S2 index or its headerless metadata payload.
|
||||
pub fn decode_minio_index_bytes(bytes: &Bytes) -> Option<Index> {
|
||||
let decoded = S2Index::load(bytes.as_ref())
|
||||
.or_else(|_| S2Index::load(&restore_index_headers(bytes.as_ref())))
|
||||
.ok()?;
|
||||
let bytes = bytes.as_ref();
|
||||
// An unframed index starts with a nonnegative signed varint. Its
|
||||
// low bit is clear, so it cannot start with the odd frame marker.
|
||||
let body = if bytes.first() == Some(&CHUNK_TYPE_INDEX) {
|
||||
remove_index_headers(bytes)?
|
||||
} else {
|
||||
bytes
|
||||
};
|
||||
let decoded = S2Index::load_body(body).ok()?;
|
||||
|
||||
let mut index = Index::new();
|
||||
for info in decoded.info {
|
||||
@@ -165,26 +172,7 @@ impl S2Index {
|
||||
false
|
||||
}
|
||||
|
||||
fn load(mut bytes: &[u8]) -> io::Result<Self> {
|
||||
if bytes.len() <= SKIPPABLE_FRAME_HEADER + S2_INDEX_HEADER.len() + S2_INDEX_TRAILER.len() {
|
||||
return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "buffer too small"));
|
||||
}
|
||||
if bytes[0] != CHUNK_TYPE_INDEX {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid index chunk type"));
|
||||
}
|
||||
|
||||
let chunk_len = (bytes[1] as usize) | ((bytes[2] as usize) << 8) | ((bytes[3] as usize) << 16);
|
||||
bytes = &bytes[SKIPPABLE_FRAME_HEADER..];
|
||||
if bytes.len() < chunk_len {
|
||||
return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "buffer too small"));
|
||||
}
|
||||
bytes = &bytes[..chunk_len];
|
||||
|
||||
if !bytes.starts_with(S2_INDEX_HEADER) {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid index header"));
|
||||
}
|
||||
bytes = &bytes[S2_INDEX_HEADER.len()..];
|
||||
|
||||
fn load_body(mut bytes: &[u8]) -> io::Result<Self> {
|
||||
let (total_uncompressed, used) = read_varint(bytes)?;
|
||||
if total_uncompressed < 0 {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid uncompressed size"));
|
||||
@@ -234,7 +222,10 @@ impl S2Index {
|
||||
|
||||
if idx > 0 {
|
||||
let prev = info[idx - 1].uncompressed_offset;
|
||||
uncompressed_offset += prev + est_block_uncompressed;
|
||||
uncompressed_offset = prev
|
||||
.checked_add(est_block_uncompressed)
|
||||
.and_then(|base| base.checked_add(uncompressed_offset))
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "uncompressed index offset overflow"))?;
|
||||
if uncompressed_offset <= prev {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid uncompressed offset"));
|
||||
}
|
||||
@@ -251,9 +242,14 @@ impl S2Index {
|
||||
bytes = &bytes[used..];
|
||||
|
||||
if idx > 0 {
|
||||
let next_compressed_predict = compressed_predict + compressed_offset / 2;
|
||||
let next_compressed_predict = compressed_predict
|
||||
.checked_add(compressed_offset / 2)
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "compressed index prediction overflow"))?;
|
||||
let prev = info[idx - 1].compressed_offset;
|
||||
compressed_offset += prev + compressed_predict;
|
||||
compressed_offset = prev
|
||||
.checked_add(compressed_predict)
|
||||
.and_then(|base| base.checked_add(compressed_offset))
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "compressed index offset overflow"))?;
|
||||
if compressed_offset <= prev {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid compressed offset"));
|
||||
}
|
||||
@@ -265,12 +261,8 @@ impl S2Index {
|
||||
info[idx].compressed_offset = compressed_offset;
|
||||
}
|
||||
|
||||
if bytes.len() < 4 + S2_INDEX_TRAILER.len() {
|
||||
return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "buffer too small"));
|
||||
}
|
||||
bytes = &bytes[4..];
|
||||
if !bytes.starts_with(S2_INDEX_TRAILER) {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid index trailer"));
|
||||
if !bytes.is_empty() {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "trailing bytes in index body"));
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
@@ -290,10 +282,9 @@ fn remove_index_headers(bytes: &[u8]) -> Option<&[u8]> {
|
||||
|
||||
let chunk_len = (bytes[1] as usize) | ((bytes[2] as usize) << 8) | ((bytes[3] as usize) << 16);
|
||||
let bytes = &bytes[SKIPPABLE_FRAME_HEADER..];
|
||||
if bytes.len() < chunk_len {
|
||||
if bytes.len() != chunk_len {
|
||||
return None;
|
||||
}
|
||||
let bytes = &bytes[..chunk_len];
|
||||
|
||||
let bytes = bytes.strip_prefix(S2_INDEX_HEADER)?;
|
||||
let bytes = bytes.strip_suffix(S2_INDEX_TRAILER)?;
|
||||
@@ -303,25 +294,6 @@ fn remove_index_headers(bytes: &[u8]) -> Option<&[u8]> {
|
||||
Some(&bytes[..bytes.len() - 4])
|
||||
}
|
||||
|
||||
fn restore_index_headers(input: &[u8]) -> Vec<u8> {
|
||||
if input.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let mut bytes = Vec::with_capacity(SKIPPABLE_FRAME_HEADER + S2_INDEX_HEADER.len() + input.len() + 4 + S2_INDEX_TRAILER.len());
|
||||
bytes.extend_from_slice(&[CHUNK_TYPE_INDEX, 0, 0, 0]);
|
||||
bytes.extend_from_slice(S2_INDEX_HEADER);
|
||||
bytes.extend_from_slice(input);
|
||||
bytes.extend_from_slice(&((bytes.len() + 4 + S2_INDEX_TRAILER.len()) as u32).to_le_bytes());
|
||||
bytes.extend_from_slice(S2_INDEX_TRAILER);
|
||||
|
||||
let chunk_len = bytes.len() - SKIPPABLE_FRAME_HEADER;
|
||||
bytes[1] = chunk_len as u8;
|
||||
bytes[2] = (chunk_len >> 8) as u8;
|
||||
bytes[3] = (chunk_len >> 16) as u8;
|
||||
bytes
|
||||
}
|
||||
|
||||
fn write_varint(out: &mut Vec<u8>, value: i64) {
|
||||
let mut unsigned = ((value as u64) << 1) ^ ((value >> 63) as u64);
|
||||
while unsigned >= 0x80 {
|
||||
@@ -342,10 +314,10 @@ fn read_uvarint(bytes: &[u8]) -> io::Result<(u64, usize)> {
|
||||
let mut shift = 0_u32;
|
||||
|
||||
for (idx, byte) in bytes.iter().copied().enumerate() {
|
||||
if idx == 9 && byte > 1 {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "varint overflow"));
|
||||
}
|
||||
if byte < 0x80 {
|
||||
if idx > 9 || (idx == 9 && byte > 1) {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "varint overflow"));
|
||||
}
|
||||
return Ok((value | ((byte as u64) << shift), idx + 1));
|
||||
}
|
||||
|
||||
@@ -388,15 +360,7 @@ mod tests {
|
||||
source.total_compressed = 3_000_000;
|
||||
|
||||
let stored = minio_index_storage_bytes(&source);
|
||||
assert!(!stored.starts_with(&[CHUNK_TYPE_INDEX, 0x2a, 0x4d, 0x18]));
|
||||
assert_eq!(
|
||||
S2Index::load(&restore_index_headers(&stored))
|
||||
.expect("restore full index")
|
||||
.info
|
||||
.len(),
|
||||
2
|
||||
);
|
||||
|
||||
assert_ne!(stored.first(), Some(&CHUNK_TYPE_INDEX));
|
||||
let decoded = decode_minio_index_bytes(&stored).expect("decode headerless MinIO index");
|
||||
assert_eq!(decoded.total_uncompressed, source.total_uncompressed);
|
||||
assert_eq!(decoded.total_compressed, source.total_compressed);
|
||||
@@ -423,12 +387,17 @@ mod tests {
|
||||
let full = index.into_full_bytes();
|
||||
assert_eq!(full[0], CHUNK_TYPE_INDEX);
|
||||
let headerless = Bytes::copy_from_slice(remove_index_headers(full.as_ref()).expect("strip index headers"));
|
||||
let restored = restore_index_headers(&headerless);
|
||||
assert_eq!(restored[0], CHUNK_TYPE_INDEX);
|
||||
for bytes in [&full, &headerless] {
|
||||
let decoded = decode_minio_index_bytes(bytes).expect("decode index with unknown compressed total");
|
||||
assert_eq!(decoded.total_uncompressed, 4_194_304);
|
||||
assert_eq!(decoded.total_compressed, -1);
|
||||
assert_eq!(decoded.find(2_097_152).unwrap(), (1_048_576, 2_097_152));
|
||||
|
||||
let decoded = decode_minio_index_bytes(&headerless).expect("decode index with unknown compressed total");
|
||||
assert_eq!(decoded.total_uncompressed, 4_194_304);
|
||||
assert_eq!(decoded.total_compressed, -1);
|
||||
assert_eq!(decoded.find(2_097_152).unwrap(), (1_048_576, 2_097_152));
|
||||
let truncated = bytes.slice(..bytes.len() - 1);
|
||||
assert!(decode_minio_index_bytes(&truncated).is_none());
|
||||
let mut trailing = bytes.to_vec();
|
||||
trailing.push(0);
|
||||
assert!(decode_minio_index_bytes(&Bytes::from(trailing)).is_none());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,7 +115,7 @@ impl Index {
|
||||
));
|
||||
}
|
||||
|
||||
if latest.uncompressed_offset + MIN_INDEX_DIST > uncompressed_offset {
|
||||
if uncompressed_offset.saturating_sub(latest.uncompressed_offset) < MIN_INDEX_DIST {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -150,34 +150,23 @@ impl Index {
|
||||
return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "empty index"));
|
||||
}
|
||||
|
||||
if self.info.len() > 200 {
|
||||
let n = self
|
||||
.info
|
||||
.binary_search_by(|info| {
|
||||
if info.uncompressed_offset > offset {
|
||||
std::cmp::Ordering::Greater
|
||||
} else {
|
||||
std::cmp::Ordering::Less
|
||||
}
|
||||
})
|
||||
.unwrap_or_else(|i| i);
|
||||
Ok(self.checkpoint_at_or_before(offset).unwrap_or((0, 0)))
|
||||
}
|
||||
|
||||
if n == 0 {
|
||||
return Ok((self.info[0].compressed_offset, self.info[0].uncompressed_offset));
|
||||
}
|
||||
return Ok((self.info[n - 1].compressed_offset, self.info[n - 1].uncompressed_offset));
|
||||
}
|
||||
/// Returns the last recorded (stored, plaintext) offset at or before `offset`.
|
||||
/// Index totals can be stale, so the caller must check the actual part bounds.
|
||||
pub fn checkpoint_at_or_before(&self, offset: i64) -> Option<(i64, i64)> {
|
||||
let next = self.info.partition_point(|entry| entry.uncompressed_offset <= offset);
|
||||
let entry = self.info.get(next.checked_sub(1)?)?;
|
||||
Some((entry.compressed_offset, entry.uncompressed_offset))
|
||||
}
|
||||
|
||||
let mut compressed_off = 0;
|
||||
let mut uncompressed_off = 0;
|
||||
for info in &self.info {
|
||||
if info.uncompressed_offset > offset {
|
||||
break;
|
||||
}
|
||||
compressed_off = info.compressed_offset;
|
||||
uncompressed_off = info.uncompressed_offset;
|
||||
}
|
||||
Ok((compressed_off, uncompressed_off))
|
||||
/// Returns the first recorded (stored, plaintext) offset at or after `offset`.
|
||||
/// Index totals can be stale, so the caller must check the actual part bounds.
|
||||
pub fn checkpoint_at_or_after(&self, offset: i64) -> Option<(i64, i64)> {
|
||||
let next = self.info.partition_point(|entry| entry.uncompressed_offset < offset);
|
||||
let entry = self.info.get(next)?;
|
||||
Some((entry.compressed_offset, entry.uncompressed_offset))
|
||||
}
|
||||
|
||||
fn reduce(&mut self) {
|
||||
@@ -366,7 +355,10 @@ impl Index {
|
||||
|
||||
if idx > 0 {
|
||||
let prev = self.info[idx - 1].uncompressed_offset;
|
||||
u_off += prev + self.est_block_uncomp;
|
||||
u_off = prev
|
||||
.checked_add(self.est_block_uncomp)
|
||||
.and_then(|base| base.checked_add(u_off))
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "uncompressed index offset overflow"))?;
|
||||
if u_off <= prev {
|
||||
return Err(io::Error::other("invalid offset"));
|
||||
}
|
||||
@@ -385,9 +377,14 @@ impl Index {
|
||||
b = &b[n..];
|
||||
|
||||
if idx > 0 {
|
||||
let next_c_predict = c_predict + c_off / 2;
|
||||
let next_c_predict = c_predict
|
||||
.checked_add(c_off / 2)
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "compressed index prediction overflow"))?;
|
||||
let prev = self.info[idx - 1].compressed_offset;
|
||||
c_off += prev + c_predict;
|
||||
c_off = prev
|
||||
.checked_add(c_predict)
|
||||
.and_then(|base| base.checked_add(c_off))
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "compressed index offset overflow"))?;
|
||||
if c_off <= prev {
|
||||
return Err(io::Error::other("invalid offset"));
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
|
||||
use crate::compress_index::{Index, TryGetIndex};
|
||||
use pin_project_lite::pin_project;
|
||||
use rustfs_utils::compress::{CompressionAlgorithm, compress_block, decompress_block_with_limit};
|
||||
use rustfs_utils::compress::{CompressionAlgorithm, compress_block, decompress_block_into};
|
||||
use rustfs_utils::{put_uvarint, uvarint};
|
||||
use std::cmp::min;
|
||||
use std::io::{self};
|
||||
@@ -177,7 +177,7 @@ where
|
||||
delegate_reader_capabilities_generic_no_index!(CompressReader<R>, inner);
|
||||
|
||||
pin_project! {
|
||||
/// A reader wrapper that decompresses data on the fly using DEFLATE algorithm.
|
||||
/// Streams legacy compressed blocks after verifying their decoded length and checksum.
|
||||
/// Header format:
|
||||
/// - First byte: compression type (00 = compressed, 01 = uncompressed, FF = end)
|
||||
/// - Bytes 1-3: length of compressed data (little-endian)
|
||||
@@ -347,97 +347,19 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
let typ = this.header_buf[0];
|
||||
let crc = (this.header_buf[4] as u32)
|
||||
| ((this.header_buf[5] as u32) << 8)
|
||||
| ((this.header_buf[6] as u32) << 16)
|
||||
| ((this.header_buf[7] as u32) << 24);
|
||||
let compressed_buf = &this.compressed_buf[..*this.compressed_len];
|
||||
// `compressed_buf`'s length comes from the untrusted 24-bit header length field, so it
|
||||
// can be shorter than 16 bytes. `uvarint` is safe on any slice length (reads at most 10
|
||||
// bytes and stops at the terminator), so pass the whole slice instead of a fixed
|
||||
// `[0..16]` index that panics on corrupted/truncated blocks shorter than 16 bytes.
|
||||
let (uncompress_len, uvarint) = uvarint(compressed_buf);
|
||||
// Reject a length prefix that could not be decoded: `uvarint <= 0` means the varint was
|
||||
// empty/unterminated (0) or overflowed (negative — as usize it would index far past the
|
||||
// buffer and panic the slice below). The `> len` bound is belt-and-suspenders (uvarint's
|
||||
// positive return is always <= buf.len()) but keeps the slice panic-free regardless.
|
||||
if uvarint <= 0 || uvarint as usize > compressed_buf.len() {
|
||||
*this.compressed_read = 0;
|
||||
*this.compressed_len = 0;
|
||||
*this.poisoned = true;
|
||||
return Poll::Ready(Err(io::Error::new(io::ErrorKind::InvalidData, "Invalid compressed block length prefix")));
|
||||
}
|
||||
// Bound the untrusted declared plaintext length up front and enforce it
|
||||
// inside the decoder so a small block cannot expand into GiB before the
|
||||
// post-decode length check runs.
|
||||
if uncompress_len > MAX_BLOCK_PLAINTEXT_LEN {
|
||||
*this.compressed_read = 0;
|
||||
*this.compressed_len = 0;
|
||||
*this.poisoned = true;
|
||||
return Poll::Ready(Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Compressed block declares an oversized length",
|
||||
)));
|
||||
}
|
||||
let Ok(uncompress_len_usize) = usize::try_from(uncompress_len) else {
|
||||
*this.compressed_read = 0;
|
||||
*this.compressed_len = 0;
|
||||
*this.poisoned = true;
|
||||
return Poll::Ready(Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Compressed block declares an oversized length",
|
||||
)));
|
||||
};
|
||||
let compressed_data = &compressed_buf[uvarint as usize..];
|
||||
let decompressed = if typ == COMPRESS_TYPE_COMPRESSED {
|
||||
match decompress_block_with_limit(compressed_data, *this.compression_algorithm, uncompress_len_usize) {
|
||||
Ok(out) => out,
|
||||
Err(e) => {
|
||||
// error!("DecompressReader decompress_block error: {e}");
|
||||
*this.compressed_read = 0;
|
||||
*this.compressed_len = 0;
|
||||
*this.poisoned = true;
|
||||
return Poll::Ready(Err(e));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// The header phase already rejected every type other than
|
||||
// COMPRESS_TYPE_COMPRESSED / COMPRESS_TYPE_UNCOMPRESSED.
|
||||
compressed_data.to_vec()
|
||||
};
|
||||
if decompressed.is_empty() {
|
||||
// The writer never emits zero-length plaintext blocks; an empty
|
||||
// decode surfacing as Ready(Ok) with no bytes would read as EOF and
|
||||
// silently truncate the stream.
|
||||
*this.poisoned = true;
|
||||
*this.compressed_read = 0;
|
||||
*this.compressed_len = 0;
|
||||
return Poll::Ready(Err(io::Error::new(io::ErrorKind::InvalidData, "Empty compressed block")));
|
||||
}
|
||||
if decompressed.len() != uncompress_len_usize {
|
||||
// error!("DecompressReader decompressed length mismatch: {} != {}", decompressed.len(), uncompress_len);
|
||||
*this.compressed_read = 0;
|
||||
*this.compressed_len = 0;
|
||||
*this.poisoned = true;
|
||||
return Poll::Ready(Err(io::Error::new(io::ErrorKind::InvalidData, "Decompressed length mismatch")));
|
||||
}
|
||||
let actual_crc = {
|
||||
let mut hasher = crc_fast::Digest::new(crc_fast::CrcAlgorithm::Crc32IsoHdlc);
|
||||
hasher.update(&decompressed);
|
||||
hasher.finalize() as u32
|
||||
};
|
||||
if actual_crc != crc {
|
||||
// error!("DecompressReader CRC32 mismatch: actual {actual_crc} != expected {crc}");
|
||||
*this.compressed_read = 0;
|
||||
*this.compressed_len = 0;
|
||||
*this.poisoned = true;
|
||||
return Poll::Ready(Err(io::Error::new(io::ErrorKind::InvalidData, "CRC32 mismatch")));
|
||||
}
|
||||
*this.buffer = decompressed;
|
||||
*this.buffer_pos = 0;
|
||||
let result = decode_block(
|
||||
this.header_buf,
|
||||
&this.compressed_buf[..*this.compressed_len],
|
||||
*this.compression_algorithm,
|
||||
this.buffer,
|
||||
);
|
||||
*this.compressed_read = 0;
|
||||
*this.compressed_len = 0;
|
||||
if let Err(error) = result {
|
||||
this.buffer.clear();
|
||||
*this.poisoned = true;
|
||||
return Poll::Ready(Err(error));
|
||||
}
|
||||
let to_copy = min(buf.remaining(), this.buffer.len());
|
||||
buf.put_slice(&this.buffer[..to_copy]);
|
||||
*this.buffer_pos += to_copy;
|
||||
@@ -451,6 +373,50 @@ where
|
||||
|
||||
delegate_reader_capabilities_generic_no_index!(DecompressReader<R>, inner);
|
||||
|
||||
fn decode_block(
|
||||
header: &[u8; HEADER_LEN],
|
||||
payload: &[u8],
|
||||
algorithm: CompressionAlgorithm,
|
||||
output: &mut Vec<u8>,
|
||||
) -> io::Result<()> {
|
||||
let (declared_len, prefix_len) = uvarint(payload);
|
||||
let data = usize::try_from(prefix_len)
|
||||
.ok()
|
||||
.filter(|len| *len != 0)
|
||||
.and_then(|len| payload.get(len..))
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Invalid compressed block length prefix"))?;
|
||||
let declared_len = usize::try_from(declared_len)
|
||||
.ok()
|
||||
.filter(|_| declared_len <= MAX_BLOCK_PLAINTEXT_LEN)
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Compressed block declares an oversized length"))?;
|
||||
|
||||
let compressed = header[0] == COMPRESS_TYPE_COMPRESSED;
|
||||
let plaintext = if compressed {
|
||||
decompress_block_into(data, algorithm, declared_len, output)?;
|
||||
output.as_slice()
|
||||
} else {
|
||||
data
|
||||
};
|
||||
if plaintext.is_empty() {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "Empty compressed block"));
|
||||
}
|
||||
if plaintext.len() != declared_len {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "Decompressed length mismatch"));
|
||||
}
|
||||
let expected_crc = u32::from_le_bytes([header[4], header[5], header[6], header[7]]);
|
||||
let mut hasher = crc_fast::Digest::new(crc_fast::CrcAlgorithm::Crc32IsoHdlc);
|
||||
hasher.update(plaintext);
|
||||
if hasher.finalize() as u32 != expected_crc {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "CRC32 mismatch"));
|
||||
}
|
||||
|
||||
if !compressed {
|
||||
output.clear();
|
||||
output.extend_from_slice(data);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Build compressed block with header + uvarint + compressed data
|
||||
fn build_compressed_block(uncompressed_data: &[u8], compression_algorithm: CompressionAlgorithm) -> Vec<u8> {
|
||||
let crc = {
|
||||
@@ -503,6 +469,43 @@ mod tests {
|
||||
assert_eq!(&decompressed, data);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn decompress_reader_reuses_the_verified_plaintext_buffer() {
|
||||
let algorithm = CompressionAlgorithm::Lz4;
|
||||
let len = 128 * 1024;
|
||||
let first = vec![0x23; len];
|
||||
let second = vec![0x45; len];
|
||||
let mut stored = build_compressed_block(&first, algorithm);
|
||||
stored.extend_from_slice(&build_compressed_block(&second, algorithm));
|
||||
let mut bad_crc = build_compressed_block(&first, algorithm);
|
||||
bad_crc[4] ^= 1;
|
||||
stored.extend_from_slice(&bad_crc);
|
||||
|
||||
let mut reader = DecompressReader::new(Cursor::new(stored), algorithm);
|
||||
let mut output = vec![0; len];
|
||||
reader.read_exact(&mut output).await.unwrap();
|
||||
assert_eq!(output, first);
|
||||
let allocation = reader.buffer.as_ptr();
|
||||
|
||||
reader.read_exact(&mut output).await.unwrap();
|
||||
assert_eq!(output, second);
|
||||
assert_eq!(
|
||||
reader.buffer.as_ptr(),
|
||||
allocation,
|
||||
"equal-sized blocks should reuse the output allocation"
|
||||
);
|
||||
|
||||
let mut probe = [0xa5; 16];
|
||||
for _ in 0..2 {
|
||||
let error = reader
|
||||
.read(&mut probe)
|
||||
.await
|
||||
.expect_err("a rejected block must never be readable");
|
||||
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
|
||||
assert_eq!(probe, [0xa5; 16]);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_compress_reader_basic_deflate() {
|
||||
let data = b"hello world, hello world, hello world!";
|
||||
|
||||
@@ -141,37 +141,57 @@ pub fn decompress_block(compressed: &[u8], algorithm: CompressionAlgorithm) -> i
|
||||
/// Returns [`io::ErrorKind::InvalidData`] if the decompressed output exceeds `max_len`,
|
||||
/// or propagates any underlying codec initialization or decoding error.
|
||||
pub fn decompress_block_with_limit(compressed: &[u8], algorithm: CompressionAlgorithm, max_len: usize) -> io::Result<Vec<u8>> {
|
||||
let mut out = Vec::new();
|
||||
decompress_block_into(compressed, algorithm, max_len, &mut out)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Decodes a block into a reusable buffer. Replaces its contents and caps the output at `max_len`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`io::ErrorKind::InvalidData`] if the output exceeds the limit, or propagates
|
||||
/// a codec error. The output is empty on error and retains its capacity for reuse.
|
||||
pub fn decompress_block_into(
|
||||
compressed: &[u8],
|
||||
algorithm: CompressionAlgorithm,
|
||||
max_len: usize,
|
||||
out: &mut Vec<u8>,
|
||||
) -> io::Result<()> {
|
||||
out.clear();
|
||||
let input = std::io::Cursor::new(compressed);
|
||||
match algorithm {
|
||||
CompressionAlgorithm::Gzip => read_to_end_with_limit(flate2::read::GzDecoder::new(input), max_len),
|
||||
CompressionAlgorithm::Deflate => read_to_end_with_limit(flate2::read::DeflateDecoder::new(input), max_len),
|
||||
let result = match algorithm {
|
||||
CompressionAlgorithm::Gzip => read_to_end_with_limit(flate2::read::GzDecoder::new(input), max_len, out),
|
||||
CompressionAlgorithm::Deflate => read_to_end_with_limit(flate2::read::DeflateDecoder::new(input), max_len, out),
|
||||
CompressionAlgorithm::Zstd => {
|
||||
let mut decoder = zstd::Decoder::new(input)?;
|
||||
if max_len <= ZSTD_BOUNDED_BLOCK_LIMIT {
|
||||
decoder.window_log_max(ZSTD_BLOCK_MAX_WINDOW_LOG)?;
|
||||
}
|
||||
read_to_end_with_limit(decoder, max_len)
|
||||
read_to_end_with_limit(decoder, max_len, out)
|
||||
}
|
||||
CompressionAlgorithm::Lz4 => read_to_end_with_limit(lz4::Decoder::new(input)?, max_len),
|
||||
CompressionAlgorithm::Brotli => read_to_end_with_limit(brotli::Decompressor::new(input, 4096), max_len),
|
||||
CompressionAlgorithm::Snappy => read_to_end_with_limit(snap::read::FrameDecoder::new(input), max_len),
|
||||
CompressionAlgorithm::None => Ok(Vec::new()),
|
||||
CompressionAlgorithm::Lz4 => read_to_end_with_limit(lz4::Decoder::new(input)?, max_len, out),
|
||||
CompressionAlgorithm::Brotli => read_to_end_with_limit(brotli::Decompressor::new(input, 4096), max_len, out),
|
||||
CompressionAlgorithm::Snappy => read_to_end_with_limit(snap::read::FrameDecoder::new(input), max_len, out),
|
||||
CompressionAlgorithm::None => Ok(()),
|
||||
};
|
||||
if result.is_err() {
|
||||
out.clear();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn read_to_end_with_limit(decoder: impl Read, max_len: usize) -> io::Result<Vec<u8>> {
|
||||
let mut out = Vec::new();
|
||||
// Read at most one byte past `max_len`: enough to distinguish an exact-length
|
||||
// frame (and verify its trailer) from an over-limit expansion without unbounded allocation.
|
||||
fn read_to_end_with_limit(decoder: impl Read, max_len: usize, out: &mut Vec<u8>) -> io::Result<()> {
|
||||
// Probe past the limit to verify an exact-length frame's trailer and reject expansion.
|
||||
let probe_len = u64::try_from(max_len).unwrap_or(u64::MAX).saturating_add(1);
|
||||
decoder.take(probe_len).read_to_end(&mut out)?;
|
||||
decoder.take(probe_len).read_to_end(out)?;
|
||||
if out.len() > max_len {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"decompressed block exceeds its declared length",
|
||||
));
|
||||
}
|
||||
Ok(out)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -254,10 +274,11 @@ mod tests {
|
||||
CompressionAlgorithm::Snappy,
|
||||
] {
|
||||
let compressed = compress_block(&data, algo);
|
||||
let exact = decompress_block_with_limit(&compressed, algo, data.len()).expect("exact limit should succeed");
|
||||
let mut exact = decompress_block_with_limit(&compressed, algo, data.len()).expect("exact limit should succeed");
|
||||
assert_eq!(exact, data, "{algo}");
|
||||
|
||||
let err = decompress_block_with_limit(&compressed, algo, data.len() - 1).expect_err("limit must be enforced");
|
||||
let err = decompress_block_into(&compressed, algo, data.len() - 1, &mut exact).expect_err("limit must be enforced");
|
||||
assert!(exact.is_empty(), "an error must clear reused output");
|
||||
assert_eq!(err.kind(), io::ErrorKind::InvalidData, "{algo}");
|
||||
assert_eq!(err.to_string(), "decompressed block exceeds its declared length", "{algo}");
|
||||
|
||||
|
||||
@@ -389,11 +389,8 @@ mod tests {
|
||||
"every plaintext POST Object SSE-C form upload must increment the counter"
|
||||
);
|
||||
let logs = String::from_utf8(buffer.0.lock().expect("log buffer").clone()).expect("UTF-8 logs");
|
||||
let warning_lines: Vec<_> = logs
|
||||
.lines()
|
||||
.filter(|line| line.contains("ssec_request_without_tls"))
|
||||
.collect();
|
||||
assert_eq!(warning_lines.len(), 1, "the plaintext SSE-C warning must fire once per process");
|
||||
let warning_count = logs.lines().filter(|line| line.contains("ssec_request_without_tls")).count();
|
||||
assert_eq!(warning_count, 1, "the plaintext SSE-C warning must fire once per process");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
1|crates/ecstore/src/layout/format.rs
|
||||
1|crates/ecstore/src/layout/pool_space.rs
|
||||
1|crates/ecstore/src/layout/set_layout.rs
|
||||
19|crates/ecstore/src/object_api/readers.rs
|
||||
18|crates/ecstore/src/object_api/readers.rs
|
||||
1|crates/ecstore/src/object_api/types.rs
|
||||
3|crates/ecstore/src/runtime/sources.rs
|
||||
4|crates/ecstore/src/services/batch_processor.rs
|
||||
|
||||
Reference in New Issue
Block a user