use std::io::{self, Cursor};
use chrono_tz::Tz;
use crate::{
binary::ReadEx,
errors::{Error, Result},
types::{
block::{
compression::{decompress_frame, frame_len, FRAME_HEAD_SIZE},
Block,
},
column::measure::{BlockWalk, Measure},
},
};
const RETAINED: usize = 4 << 20;
const RETAINED_BLOCK: usize = 64 << 20;
const SMALL_BLOCKS: u8 = 16;
#[derive(Default)]
pub(crate) struct PendingBlock {
active: bool,
body: usize,
raw_end: usize,
decoded: Vec<u8>,
small: u8,
frame: Vec<u8>,
scratch: Vec<u8>,
walk: BlockWalk,
tried: Option<usize>,
short: Option<usize>,
}
fn would_block() -> Error {
io::Error::new(io::ErrorKind::WouldBlock, "would block").into()
}
impl PendingBlock {
pub(crate) fn parse(
&mut self,
input: &[u8],
tz: Tz,
compress: bool,
revision: u64,
) -> Result<(Block, usize)> {
if !self.active {
let mut cursor = Cursor::new(input);
cursor.read_uvarint()?;
cursor.skip_string()?;
let body = cursor.position() as usize;
*self = PendingBlock {
active: true,
body,
raw_end: body,
decoded: std::mem::take(&mut self.decoded),
small: self.small,
frame: std::mem::take(&mut self.frame),
scratch: std::mem::take(&mut self.scratch),
walk: BlockWalk::default(),
tried: None,
short: None,
};
}
let result = if compress {
self.parse_compressed(input, tz, revision)
} else {
self.parse_plain(input, tz, revision)
};
match result {
Err(e) if e.is_would_block() => Err(e),
done => {
self.active = false;
self.finish_block(done.is_ok());
if self.frame.capacity() > RETAINED {
self.frame = Vec::new();
}
if self.scratch.capacity() > RETAINED {
self.scratch = Vec::new();
}
done
}
}
}
fn finish_block(&mut self, kept: bool) {
let used = self.decoded.len();
self.decoded.clear();
let capacity = self.decoded.capacity();
if !kept || capacity > RETAINED_BLOCK {
self.decoded = Vec::new();
self.small = 0;
} else if used < capacity / 4 {
self.small += 1;
if self.small >= SMALL_BLOCKS {
self.decoded = Vec::new();
self.small = 0;
}
} else {
self.small = 0;
}
}
pub(crate) fn release(&mut self) {
if !self.active && self.decoded.capacity() > RETAINED {
self.decoded = Vec::new();
self.small = 0;
}
}
fn parse_plain(&mut self, input: &[u8], tz: Tz, revision: u64) -> Result<(Block, usize)> {
let body = &input[self.body..];
let measure = self.walk.walk(body, revision);
if measure == Measure::Incomplete {
return Err(would_block());
}
let (block, len) = load(body, tz, revision)?;
check(&measure, len);
Ok((block, self.body + len))
}
fn parse_compressed(&mut self, input: &[u8], tz: Tz, revision: u64) -> Result<(Block, usize)> {
loop {
let measure = if self.short == Some(self.decoded.len()) {
Measure::Incomplete
} else {
self.walk.walk(&self.decoded, revision)
};
if measure == Measure::Incomplete {
self.short = Some(self.decoded.len());
}
let attempt = match measure {
Measure::Complete(_) => true,
Measure::Unknown => self.tried != Some(self.decoded.len()),
Measure::Incomplete => false,
};
if attempt {
match load(&self.decoded, tz, revision) {
Ok((block, len)) => {
check(&measure, len);
return Ok((block, self.raw_end));
}
Err(e) if e.is_would_block() && measure == Measure::Unknown => {
self.tried = Some(self.decoded.len());
}
Err(e) => return Err(e),
}
}
if !self.decompress_next(input)? {
return Err(would_block());
}
}
}
fn decompress_next(&mut self, input: &[u8]) -> Result<bool> {
let raw = &input[self.raw_end..];
let Some(head) = raw.first_chunk::<FRAME_HEAD_SIZE>() else {
return Ok(false);
};
if raw.len() < frame_len(head)? {
return Ok(false);
}
let mut cursor = Cursor::new(raw);
decompress_frame(&mut cursor, &mut self.scratch, &mut self.frame)?;
self.raw_end += cursor.position() as usize;
self.decoded.extend_from_slice(&self.frame);
Ok(true)
}
}
fn load(bytes: &[u8], tz: Tz, revision: u64) -> Result<(Block, usize)> {
let mut cursor = Cursor::new(bytes);
let block = Block::raw_load(&mut cursor, tz, revision)?;
Ok((block, cursor.position() as usize))
}
fn check(measure: &Measure, len: usize) {
if let Measure::Complete(walked) = measure {
debug_assert_eq!(*walked, len, "the walk and the parser disagree");
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::{
binary::Encoder,
types::{Compression, Simple},
};
fn packet(block: &Block<Simple>, compression: Compression, revision: u64) -> Vec<u8> {
let mut encoder = Encoder::new();
encoder.uvarint(1);
encoder.string("");
block.write_at(&mut encoder, compression, revision).unwrap();
encoder.write(4_u8);
encoder.get_buffer()
}
#[test]
fn test_a_packet_read_byte_by_byte() {
let strings: Vec<String> = (0..70_000).map(|i| format!("value {i}")).collect();
let numbers: Vec<u64> = (0..70_000).collect();
let block = Block::<Simple>::new()
.column("s", strings)
.column("n", numbers)
.column("o", vec![Some(1_u8); 70_000]);
for compression in [Compression::None, Compression::Lz4, Compression::Zstd] {
for revision in [54491, 54492] {
let bytes = packet(&block, compression, revision);
let end = bytes.len() - 1;
let mut pending = PendingBlock::default();
let mut len = 0;
while len < end {
let err = pending
.parse(&bytes[..len], Tz::UTC, compression.is_enabled(), revision)
.expect_err("a packet not all there");
assert!(
err.is_would_block(),
"{compression} {revision} {len}: {err}"
);
len += 4099;
}
let (read, packet_len) = pending
.parse(&bytes, Tz::UTC, compression.is_enabled(), revision)
.unwrap();
assert_eq!(read, block, "{compression} {revision}");
assert_eq!(packet_len, end, "{compression} {revision}");
assert!(!pending.active);
let (read, _) = PendingBlock::default()
.parse(&bytes, Tz::UTC, compression.is_enabled(), revision)
.unwrap();
assert_eq!(read, block);
}
}
}
#[test]
fn test_a_bad_frame_header_is_an_error_at_once() {
let mut bytes = vec![1, 0];
bytes.extend_from_slice(&[0; 16]);
bytes.push(0x77);
bytes.extend_from_slice(&1000_u32.to_le_bytes());
bytes.extend_from_slice(&991_u32.to_le_bytes());
let err = PendingBlock::default()
.parse(&bytes, Tz::UTC, true, 54492)
.expect_err("an unknown method");
assert!(
err.to_string().contains("unsupported compression method"),
"{err}"
);
}
#[test]
fn test_a_replicated_index_past_its_rows_is_an_error_at_once() {
let mut body = Encoder::new();
body.write_bytes(&[1, 0, 2, 0xff, 0xff, 0xff, 0xff, 0]);
body.uvarint(1);
body.uvarint(2);
body.string("c");
body.string("String");
body.write_bytes(&[1, 4]);
body.uvarint(2);
body.write_bytes(&[1, 0, 3]);
body.uvarint(2);
let body = body.get_buffer();
for compression in [Compression::None, Compression::Lz4] {
let mut bytes = vec![1, 0];
if compression.is_enabled() {
crate::types::block::compression::compress(compression, 3, &body, &mut bytes)
.unwrap();
} else {
bytes.extend_from_slice(&body);
}
let err = PendingBlock::default()
.parse(&bytes, Tz::UTC, compression.is_enabled(), 54492)
.expect_err("an index past the distinct rows");
assert!(
err.to_string().contains("points to row 3"),
"{compression}: {err}"
);
}
}
#[test]
fn test_the_block_buffer_serves_the_next_block() {
let first = Block::<Simple>::new().column("n", (0..600_000_u64).collect::<Vec<_>>());
let second = Block::<Simple>::new().column(
"s",
(0..50_000).map(|i| format!("s{i}")).collect::<Vec<_>>(),
);
let mut pending = PendingBlock::default();
let bytes = packet(&first, Compression::Lz4, 54492);
let (read, _) = pending.parse(&bytes, Tz::UTC, true, 54492).unwrap();
assert_eq!(read, first);
let capacity = pending.decoded.capacity();
let buffer = pending.decoded.as_ptr();
assert!(capacity >= 4_800_000, "{capacity}");
let bytes = packet(&second, Compression::Lz4, 54492);
let end = bytes.len() - 1;
let half = bytes.len() / 2;
assert!(pending.parse(&bytes[..half], Tz::UTC, true, 54492).is_err());
let (read, len) = pending.parse(&bytes, Tz::UTC, true, 54492).unwrap();
assert_eq!((read, len), (second, end));
assert_eq!(pending.decoded.capacity(), capacity);
assert_eq!(pending.decoded.as_ptr(), buffer);
pending.release();
assert_eq!(pending.decoded.capacity(), 0);
}
#[test]
fn test_the_block_buffer_is_kept_within_bounds() {
let mut pending = PendingBlock::default();
pending.decoded.resize(1 << 20, 0);
pending.finish_block(true);
assert!(pending.decoded.is_empty() && pending.decoded.capacity() >= 1 << 20);
for block in 1..=SMALL_BLOCKS {
pending.decoded.resize(16, 0);
pending.finish_block(true);
assert_eq!(pending.decoded.capacity() == 0, block == SMALL_BLOCKS);
}
pending.decoded = Vec::with_capacity(RETAINED_BLOCK + 1);
pending.finish_block(true);
assert_eq!(pending.decoded.capacity(), 0);
pending.decoded.resize(16, 0);
pending.finish_block(false);
assert_eq!(pending.decoded.capacity(), 0);
}
#[test]
fn test_corrupt_frame_is_an_error() {
let block = Block::<Simple>::new().column("n", vec![1_u32, 2, 3]);
let mut bytes = packet(&block, Compression::Lz4, 54492);
bytes[2] ^= 0xff;
let err = PendingBlock::default()
.parse(&bytes, Tz::UTC, true, 54492)
.expect_err("a corrupt frame");
assert!(!err.is_would_block(), "{err}");
}
}