Unverified Commit c86a07db authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Turbopack: Streaming write of SST files (#82048)

### What?

Write SST while processing blocks to avoid keeping all blocks in memory. Reduces temporary memory used by persisting.
parent 4f410927
......@@ -31,8 +31,8 @@ fn main() -> Result<()> {
sequence_number,
min_hash,
max_hash,
aqmf_size,
aqmf_entries,
amqf_size,
amqf_entries,
sst_size,
key_compression_dictionary_size,
value_compression_dictionary_size,
......@@ -43,7 +43,7 @@ fn main() -> Result<()> {
" SST {sequence_number:08}.sst: {min_hash:016x} - {max_hash:016x} (p = 1/{})",
u64::MAX / (max_hash - min_hash + 1)
);
println!(" AQMF {aqmf_entries} entries = {} KiB", aqmf_size / 1024);
println!(" AMQF {amqf_entries} entries = {} KiB", amqf_size / 1024);
println!(
" {} KiB = {} kiB key compression dict + {} KiB value compression dict + \
{block_count} blocks (avg {} bytes/block)",
......
......@@ -21,7 +21,7 @@ There are four different file types:
- Static Sorted Table (SST, `*.sst`): These files contain key value pairs.
- Blob files (`*.blob`): These files contain large values.
- Delete files (`*.del`): These files contain a list of sequence numbers of files that should be considered as deleted.
- Meta files (`*.meta`): These files contain metadata about the SST files. They contains the hash range and a AQMF for quick filtering.
- Meta files (`*.meta`): These files contain metadata about the SST files. They contains the hash range and a AMQF for quick filtering.
Therefore there are there value types:
......@@ -50,9 +50,9 @@ A meta file can contain metadata about multiple SST files. The metadata is store
- 8 bytes min hash
- 8 bytes max hash
- 8 bytes SST file size
- 4 bytes end of AQMF offset relative to start of all AQMF data
- 4 bytes end of AMQF offset relative to start of all AMQF data
- foreach described SST file
- serialized AQMF
- serialized AMQF
### SST file
......@@ -139,7 +139,7 @@ Reading start from the current sequence number and goes downwards.
- We have all SST files memory mapped
- for i = CURRENT sequence number .. 0
- Check AQMF from SST file for key existance -> if not continue
- Check AMQF from SST file for key existance -> if not continue
- let block = 0
- loop
- Index Block: find key range that contains the key by binary search
......
......@@ -21,9 +21,9 @@ pub const DATA_THRESHOLD_PER_COMPACTED_FILE: usize = 256 * 1024 * 1024;
/// MAX_ENTRIES_PER_INITIAL_FILE and DATA_THRESHOLD_PER_INITIAL_FILE.
pub const THREAD_LOCAL_SIZE_SHIFT: usize = 7;
/// Maximum RAM bytes for AQMF cache
pub const AQMF_CACHE_SIZE: u64 = 300 * 1024 * 1024;
pub const AQMF_AVG_SIZE: usize = 37399;
/// Maximum RAM bytes for AMQF cache
pub const AMQF_CACHE_SIZE: u64 = 300 * 1024 * 1024;
pub const AMQF_AVG_SIZE: usize = 37399;
/// Maximum RAM bytes for key block cache
pub const KEY_BLOCK_CACHE_SIZE: u64 = 400 * 1024 * 1024;
......
......@@ -27,18 +27,18 @@ use crate::{
arc_slice::ArcSlice,
compaction::selector::{Compactable, compute_metrics, get_merge_segments},
constants::{
AQMF_AVG_SIZE, AQMF_CACHE_SIZE, DATA_THRESHOLD_PER_COMPACTED_FILE, KEY_BLOCK_AVG_SIZE,
AMQF_AVG_SIZE, AMQF_CACHE_SIZE, DATA_THRESHOLD_PER_COMPACTED_FILE, KEY_BLOCK_AVG_SIZE,
KEY_BLOCK_CACHE_SIZE, MAX_ENTRIES_PER_COMPACTED_FILE, VALUE_BLOCK_AVG_SIZE,
VALUE_BLOCK_CACHE_SIZE,
},
key::{StoreKey, hash_key},
lookup_entry::{LookupEntry, LookupValue},
merge_iter::MergeIter,
meta_file::{AqmfCache, MetaFile, MetaLookupResult, StaticSortedFileRange},
meta_file::{AmqfCache, MetaFile, MetaLookupResult, StaticSortedFileRange},
meta_file_builder::MetaFileBuilder,
sst_filter::SstFilter,
static_sorted_file::{BlockCache, SstLookupResult},
static_sorted_file_builder::{StaticSortedFileBuilder, StaticSortedFileBuilderMeta},
static_sorted_file_builder::{StaticSortedFileBuilderMeta, write_static_stored_file},
write_batch::{FinishResult, WriteBatch},
};
......@@ -84,12 +84,12 @@ pub struct Statistics {
pub sst_files: usize,
pub key_block_cache: CacheStatistics,
pub value_block_cache: CacheStatistics,
pub aqmf_cache: CacheStatistics,
pub amqf_cache: CacheStatistics,
pub hits: u64,
pub misses: u64,
pub miss_family: u64,
pub miss_range: u64,
pub miss_aqmf: u64,
pub miss_amqf: u64,
pub miss_key: u64,
}
......@@ -101,7 +101,7 @@ struct TrackedStats {
hits_blob: std::sync::atomic::AtomicU64,
miss_family: std::sync::atomic::AtomicU64,
miss_range: std::sync::atomic::AtomicU64,
miss_aqmf: std::sync::atomic::AtomicU64,
miss_amqf: std::sync::atomic::AtomicU64,
miss_key: std::sync::atomic::AtomicU64,
miss_global: std::sync::atomic::AtomicU64,
}
......@@ -119,8 +119,8 @@ pub struct TurboPersistence {
/// A flag to indicate if a write operation is currently active. Prevents multiple concurrent
/// write operations.
active_write_operation: AtomicBool,
/// A cache for deserialized AQMF filters.
aqmf_cache: AqmfCache,
/// A cache for deserialized AMQF filters.
amqf_cache: AmqfCache,
/// A cache for decompressed key blocks.
key_block_cache: BlockCache,
/// A cache for decompressed value blocks.
......@@ -158,9 +158,9 @@ impl TurboPersistence {
current_sequence_number: 0,
}),
active_write_operation: AtomicBool::new(false),
aqmf_cache: AqmfCache::with(
AQMF_CACHE_SIZE as usize / AQMF_AVG_SIZE,
AQMF_CACHE_SIZE,
amqf_cache: AmqfCache::with(
AMQF_CACHE_SIZE as usize / AMQF_AVG_SIZE,
AMQF_CACHE_SIZE,
Default::default(),
Default::default(),
Default::default(),
......@@ -876,11 +876,11 @@ impl TurboPersistence {
let index_in_meta = ssts_with_ranges[index].index_in_meta;
let meta_file = &meta_files[meta_index];
let entry = meta_file.entry(index_in_meta);
let aqmf = Cow::Borrowed(entry.raw_aqmf(meta_file.aqmf_data()));
let amqf = Cow::Borrowed(entry.raw_amqf(meta_file.amqf_data()));
let meta = StaticSortedFileBuilderMeta {
min_hash: entry.min_hash(),
max_hash: entry.max_hash(),
aqmf,
amqf,
key_compression_dictionary_length: entry
.key_compression_dictionary_length(),
value_compression_dictionary_length: entry
......@@ -904,13 +904,12 @@ impl TurboPersistence {
) -> Result<(u32, File, StaticSortedFileBuilderMeta<'static>)>
{
let _span = tracing::trace_span!("write merged sst file").entered();
let builder = StaticSortedFileBuilder::new(
let (meta, file) = write_static_stored_file(
entries,
total_key_size,
total_value_size,
&path.join(format!("{seq:08}.sst")),
)?;
let (meta, file) =
builder.write(&path.join(format!("{seq:08}.sst")))?;
Ok((seq, file, meta))
}
......@@ -1148,7 +1147,7 @@ impl TurboPersistence {
family as u32,
hash,
key,
&self.aqmf_cache,
&self.amqf_cache,
&self.key_block_cache,
&self.value_block_cache,
)? {
......@@ -1162,7 +1161,7 @@ impl TurboPersistence {
}
MetaLookupResult::QuickFilterMiss => {
#[cfg(feature = "stats")]
self.stats.miss_aqmf.fetch_add(1, Ordering::Relaxed);
self.stats.miss_amqf.fetch_add(1, Ordering::Relaxed);
}
MetaLookupResult::SstLookup(result) => match result {
SstLookupResult::Found(result) => match result {
......@@ -1204,14 +1203,14 @@ impl TurboPersistence {
sst_files: inner.meta_files.iter().map(|m| m.entries().len()).sum(),
key_block_cache: CacheStatistics::new(&self.key_block_cache),
value_block_cache: CacheStatistics::new(&self.value_block_cache),
aqmf_cache: CacheStatistics::new(&self.aqmf_cache),
amqf_cache: CacheStatistics::new(&self.amqf_cache),
hits: self.stats.hits_deleted.load(Ordering::Relaxed)
+ self.stats.hits_small.load(Ordering::Relaxed)
+ self.stats.hits_blob.load(Ordering::Relaxed),
misses: self.stats.miss_global.load(Ordering::Relaxed),
miss_family: self.stats.miss_family.load(Ordering::Relaxed),
miss_range: self.stats.miss_range.load(Ordering::Relaxed),
miss_aqmf: self.stats.miss_aqmf.load(Ordering::Relaxed),
miss_amqf: self.stats.miss_amqf.load(Ordering::Relaxed),
miss_key: self.stats.miss_key.load(Ordering::Relaxed),
}
}
......@@ -1228,14 +1227,14 @@ impl TurboPersistence {
.entries()
.iter()
.map(|entry| {
let aqmf = entry.raw_aqmf(meta_file.aqmf_data());
let amqf = entry.raw_amqf(meta_file.amqf_data());
MetaFileEntryInfo {
sequence_number: entry.sequence_number(),
min_hash: entry.min_hash(),
max_hash: entry.max_hash(),
sst_size: entry.size(),
aqmf_size: entry.aqmf_size(),
aqmf_entries: aqmf.len(),
amqf_size: entry.amqf_size(),
amqf_entries: amqf.len(),
key_compression_dictionary_size: entry
.key_compression_dictionary_length(),
value_compression_dictionary_size: entry
......@@ -1273,8 +1272,8 @@ pub struct MetaFileEntryInfo {
pub sequence_number: u32,
pub min_hash: u64,
pub max_hash: u64,
pub aqmf_size: u32,
pub aqmf_entries: usize,
pub amqf_size: u32,
pub amqf_entries: usize,
pub sst_size: u64,
pub key_compression_dictionary_size: u16,
pub value_compression_dictionary_size: u16,
......
......@@ -20,16 +20,16 @@ use crate::{
};
#[derive(Clone, Default)]
pub struct AqmfWeighter;
pub struct AmqfWeighter;
impl quick_cache::Weighter<u32, Arc<qfilter::Filter>> for AqmfWeighter {
impl quick_cache::Weighter<u32, Arc<qfilter::Filter>> for AmqfWeighter {
fn weight(&self, _key: &u32, filter: &Arc<qfilter::Filter>) -> u64 {
filter.capacity() + 1
}
}
pub type AqmfCache =
quick_cache::sync::Cache<u32, Arc<qfilter::Filter>, AqmfWeighter, BuildHasherDefault<FxHasher>>;
pub type AmqfCache =
quick_cache::sync::Cache<u32, Arc<qfilter::Filter>, AmqfWeighter, BuildHasherDefault<FxHasher>>;
pub struct MetaEntry {
/// The metadata for the static sorted file.
......@@ -42,15 +42,15 @@ pub struct MetaEntry {
max_hash: u64,
/// The size of the SST file in bytes.
size: u64,
/// The offset of the start of the AQMF data in the meta file relative to the end of the
/// The offset of the start of the AMQF data in the meta file relative to the end of the
/// header.
start_of_aqmf_data_offset: u32,
/// The offset of the end of the AQMF data in the the meta file relative to the end of the
start_of_amqf_data_offset: u32,
/// The offset of the end of the AMQF data in the the meta file relative to the end of the
/// header.
end_of_aqmf_data_offset: u32,
/// The AQMF filter of this file. This is only used if the range is very large. Smaller ranges
/// use the AQMF cache instead.
aqmf: OnceLock<qfilter::Filter>,
end_of_amqf_data_offset: u32,
/// The AMQF filter of this file. This is only used if the range is very large. Smaller ranges
/// use the AMQF cache instead.
amqf: OnceLock<qfilter::Filter>,
/// The static sorted file that is lazily loaded
sst: OnceLock<StaticSortedFile>,
}
......@@ -64,51 +64,51 @@ impl MetaEntry {
self.size
}
pub fn aqmf_size(&self) -> u32 {
self.end_of_aqmf_data_offset - self.start_of_aqmf_data_offset
pub fn amqf_size(&self) -> u32 {
self.end_of_amqf_data_offset - self.start_of_amqf_data_offset
}
pub fn raw_aqmf<'l>(&self, aqmf_data: &'l [u8]) -> &'l [u8] {
aqmf_data
.get(self.start_of_aqmf_data_offset as usize..self.end_of_aqmf_data_offset as usize)
.expect("AQMF data out of bounds")
pub fn raw_amqf<'l>(&self, amqf_data: &'l [u8]) -> &'l [u8] {
amqf_data
.get(self.start_of_amqf_data_offset as usize..self.end_of_amqf_data_offset as usize)
.expect("AMQF data out of bounds")
}
pub fn deserialize_aqmf(&self, meta: &MetaFile) -> Result<qfilter::Filter> {
let aqmf = self.raw_aqmf(meta.aqmf_data());
pot::from_slice(aqmf).with_context(|| {
pub fn deserialize_amqf(&self, meta: &MetaFile) -> Result<qfilter::Filter> {
let amqf = self.raw_amqf(meta.amqf_data());
pot::from_slice(amqf).with_context(|| {
format!(
"Failed to deserialize AQMF from {:08}.meta for {:08}.sst",
"Failed to deserialize AMQF from {:08}.meta for {:08}.sst",
meta.sequence_number,
self.sequence_number()
)
})
}
pub fn aqmf(
pub fn amqf(
&self,
meta: &MetaFile,
aqmf_cache: &AqmfCache,
amqf_cache: &AmqfCache,
) -> Result<impl Deref<Target = qfilter::Filter>> {
let use_aqmf_cache = self.max_hash - self.min_hash < 1 << 60;
Ok(if use_aqmf_cache {
let aqmf = match aqmf_cache.get_value_or_guard(&self.sequence_number(), None) {
GuardResult::Value(aqmf) => aqmf,
let use_amqf_cache = self.max_hash - self.min_hash < 1 << 60;
Ok(if use_amqf_cache {
let amqf = match amqf_cache.get_value_or_guard(&self.sequence_number(), None) {
GuardResult::Value(amqf) => amqf,
GuardResult::Guard(guard) => {
let aqmf = self.deserialize_aqmf(meta)?;
let aqmf: Arc<qfilter::Filter> = Arc::new(aqmf);
let _ = guard.insert(aqmf.clone());
aqmf
let amqf = self.deserialize_amqf(meta)?;
let amqf: Arc<qfilter::Filter> = Arc::new(amqf);
let _ = guard.insert(amqf.clone());
amqf
}
GuardResult::Timeout => unreachable!(),
};
Either::Left(aqmf)
Either::Left(amqf)
} else {
let aqmf = self.aqmf.get_or_try_init(|| {
let aqmf = self.deserialize_aqmf(meta)?;
anyhow::Ok(aqmf)
let amqf = self.amqf.get_or_try_init(|| {
let amqf = self.deserialize_amqf(meta)?;
anyhow::Ok(amqf)
})?;
Either::Right(aqmf)
Either::Right(amqf)
})
}
......@@ -160,9 +160,9 @@ pub enum MetaLookupResult {
/// The key was not found because it is out of the range of this SST file. But it was the
/// correct key family.
RangeMiss,
/// The key was not found because it was not in the AQMF filter. But it was in the range.
/// The key was not found because it was not in the AMQF filter. But it was in the range.
QuickFilterMiss,
/// The key was looked up in the SST file. It was in the AQMF filter.
/// The key was looked up in the SST file. It was in the AMQF filter.
SstLookup(SstLookupResult),
}
......@@ -216,7 +216,7 @@ impl MetaFile {
}
let count = file.read_u32::<BE>()?;
let mut entries = Vec::with_capacity(count as usize);
let mut start_of_aqmf_data_offset = 0;
let mut start_of_amqf_data_offset = 0;
for _ in 0..count {
let entry = MetaEntry {
sst_data: StaticSortedFileMetaData {
......@@ -229,12 +229,12 @@ impl MetaFile {
min_hash: file.read_u64::<BE>()?,
max_hash: file.read_u64::<BE>()?,
size: file.read_u64::<BE>()?,
start_of_aqmf_data_offset,
end_of_aqmf_data_offset: file.read_u32::<BE>()?,
aqmf: OnceLock::new(),
start_of_amqf_data_offset,
end_of_amqf_data_offset: file.read_u32::<BE>()?,
amqf: OnceLock::new(),
sst: OnceLock::new(),
};
start_of_aqmf_data_offset = entry.end_of_aqmf_data_offset;
start_of_amqf_data_offset = entry.end_of_amqf_data_offset;
entries.push(entry);
}
let offset = file.stream_position()?;
......@@ -273,7 +273,7 @@ impl MetaFile {
&self.entries[index]
}
pub fn aqmf_data(&self) -> &[u8] {
pub fn amqf_data(&self) -> &[u8] {
&self.mmap
}
......@@ -307,7 +307,7 @@ impl MetaFile {
key_family: u32,
key_hash: u64,
key: &K,
aqmf_cache: &AqmfCache,
amqf_cache: &AmqfCache,
key_block_cache: &BlockCache,
value_block_cache: &BlockCache,
) -> Result<MetaLookupResult> {
......@@ -320,8 +320,8 @@ impl MetaFile {
continue;
}
{
let aqmf = entry.aqmf(self, aqmf_cache)?;
if !aqmf.contains_fingerprint(key_hash) {
let amqf = entry.amqf(self, amqf_cache)?;
if !amqf.contains_fingerprint(key_hash) {
miss_result = MetaLookupResult::QuickFilterMiss;
continue;
}
......
......@@ -54,7 +54,7 @@ impl<'a> MetaFileBuilder<'a> {
file.write_u32::<BE>(self.entries.len() as u32)?;
let mut aqmf_offset = 0;
let mut amqf_offset = 0;
for (sequence_number, sst) in &self.entries {
file.write_u32::<BE>(*sequence_number)?;
file.write_u16::<BE>(sst.key_compression_dictionary_length)?;
......@@ -63,12 +63,12 @@ impl<'a> MetaFileBuilder<'a> {
file.write_u64::<BE>(sst.min_hash)?;
file.write_u64::<BE>(sst.max_hash)?;
file.write_u64::<BE>(sst.size)?;
aqmf_offset += sst.aqmf.len();
file.write_u32::<BE>(aqmf_offset as u32)?;
amqf_offset += sst.amqf.len();
file.write_u32::<BE>(amqf_offset as u32)?;
}
for (_, sst) in &self.entries {
file.write_all(&sst.aqmf)?;
file.write_all(&sst.amqf)?;
}
Ok(file.into_inner()?)
}
......
use std::{
borrow::Cow,
cmp::{max, min},
cmp::min,
fs::File,
io::{self, BufWriter, Seek, Write},
io::{BufWriter, Seek, Write},
path::Path,
};
......@@ -26,8 +26,8 @@ const KEY_BLOCK_ENTRY_META_OVERHEAD: usize = 8;
const MAX_SMALL_VALUE_BLOCK_ENTRIES: usize = 100 * 1024;
/// The maximum bytes that should go into a single small value block
const MAX_SMALL_VALUE_BLOCK_SIZE: usize = 16 * 1024;
/// The aimed false positive rate for the AQMF
const AQMF_FALSE_POSITIVE_RATE: f64 = 0.01;
/// The aimed false positive rate for the AMQF
const AMQF_FALSE_POSITIVE_RATE: f64 = 0.01;
/// The maximum compression dictionary size for value blocks
const VALUE_COMPRESSION_DICTIONARY_SIZE: usize = 64 * 1024 - 1;
......@@ -80,8 +80,8 @@ pub struct StaticSortedFileBuilderMeta<'a> {
pub min_hash: u64,
/// The maximum hash of the keys in the SST file
pub max_hash: u64,
/// The AQMF data
pub aqmf: Cow<'a, [u8]>,
/// The AMQF data
pub amqf: Cow<'a, [u8]>,
/// The key compression dictionary
pub key_compression_dictionary_length: u16,
/// The value compression dictionary
......@@ -94,387 +94,464 @@ pub struct StaticSortedFileBuilderMeta<'a> {
pub entries: u64,
}
#[derive(Debug, Default)]
pub struct StaticSortedFileBuilder<'a> {
aqmf: Cow<'a, [u8]>,
key_compression_dictionary: Vec<u8>,
value_compression_dictionary: Vec<u8>,
blocks: Vec<(u32, Vec<u8>)>,
min_hash: u64,
max_hash: u64,
entries: u64,
}
impl<'a> StaticSortedFileBuilder<'a> {
pub fn new<E: Entry>(
entries: &[E],
total_key_size: usize,
total_value_size: usize,
) -> Result<Self> {
debug_assert!(entries.iter().map(|e| e.key_hash()).is_sorted());
let mut builder = Self {
min_hash: entries.first().map(|e| e.key_hash()).unwrap_or(u64::MAX),
max_hash: entries.last().map(|e| e.key_hash()).unwrap_or(0),
entries: entries.len() as u64,
..Default::default()
};
builder.compute_aqmf(entries);
builder.compute_compression_dictionary(entries, total_key_size, total_value_size)?;
builder.compute_blocks(entries);
Ok(builder)
pub fn write_static_stored_file<E: Entry>(
entries: &[E],
total_key_size: usize,
total_value_size: usize,
file: &Path,
) -> Result<(StaticSortedFileBuilderMeta<'static>, File)> {
debug_assert!(entries.iter().map(|e| e.key_hash()).is_sorted());
let mut file = BufWriter::new(File::create(file)?);
let capacity = get_compression_buffer_capacity(total_key_size, total_value_size);
// We use a shared buffer for all operations to avoid excessive allocations
let mut buffer = Vec::with_capacity(capacity);
let key_dict = compute_key_compression_dictionary(entries, total_key_size, &mut buffer)?;
let value_dict = compute_value_compression_dictionary(entries, total_value_size, &mut buffer)?;
file.write_all(&key_dict)?;
file.write_all(&value_dict)?;
let mut block_writer = BlockWriter::new(&mut file, &mut buffer);
// Another shared buffer for the uncompressed blocks
// The existing shared buffer will be used for compressed blocks
// So we need both
let mut buffer = Vec::new();
let min_hash = entries.first().map_or(u64::MAX, |e| e.key_hash());
let value_locations = write_value_blocks(entries, &value_dict, &mut block_writer, &mut buffer)
.context("Failed to write value blocks")?;
let amqf = write_key_blocks_and_compute_amqf(
entries,
&value_locations,
&key_dict,
&mut block_writer,
&mut buffer,
)
.context("Failed to write key blocks")?;
let max_hash = entries.last().map_or(0, |e| e.key_hash());
let block_count = block_writer.block_count();
for offset in &block_writer.block_offsets {
file.write_u32::<BE>(*offset)
.context("Failed to write block offset")?;
}
/// Computes a AQMF from the keys of all entries.
#[tracing::instrument(level = "trace", skip_all)]
fn compute_aqmf<E: Entry>(&mut self, entries: &[E]) {
let mut filter = qfilter::Filter::new(entries.len() as u64, AQMF_FALSE_POSITIVE_RATE)
// This won't fail as we limit the number of entries per SST file
.expect("Filter can't be constructed");
for entry in entries {
filter
.insert_fingerprint(false, entry.key_hash())
// This can't fail as we allocated enough capacity
.expect("AQMF insert failed");
}
for entry in entries {
debug_assert!(filter.contains_fingerprint(entry.key_hash()));
}
self.aqmf = Cow::Owned(pot::to_vec(&filter).expect("AQMF serialization failed"));
}
let meta = StaticSortedFileBuilderMeta {
min_hash,
max_hash,
amqf: Cow::Owned(amqf),
key_compression_dictionary_length: key_dict.len().try_into().unwrap(),
value_compression_dictionary_length: value_dict.len().try_into().unwrap(),
block_count,
size: file.stream_position()?,
entries: entries.len() as u64,
};
Ok((meta, file.into_inner()?))
}
/// Computes compression dictionaries from keys and values of all entries
#[tracing::instrument(level = "trace", skip_all)]
fn compute_compression_dictionary<E: Entry>(
&mut self,
entries: &[E],
total_key_size: usize,
total_value_size: usize,
) -> Result<()> {
if total_key_size < MIN_KEY_COMPRESSION_SAMPLES_SIZE
&& total_value_size < MIN_VALUE_COMPRESSION_SAMPLES_SIZE
{
return Ok(());
}
fn get_compression_buffer_capacity(total_key_size: usize, total_value_size: usize) -> usize {
let mut size = 0;
if total_key_size >= MIN_KEY_COMPRESSION_SAMPLES_SIZE {
let key_compression_samples_size = min(KEY_COMPRESSION_SAMPLES_SIZE, total_key_size / 16);
size = key_compression_samples_size;
}
if total_value_size >= MIN_VALUE_COMPRESSION_SAMPLES_SIZE {
let value_compression_samples_size =
min(VALUE_COMPRESSION_SAMPLES_SIZE, total_value_size / 16);
let mut value_samples = Vec::with_capacity(value_compression_samples_size);
let mut value_sample_sizes = Vec::new();
let mut key_samples = Vec::with_capacity(key_compression_samples_size);
let mut key_sample_sizes = Vec::new();
// Limit the number of iterations to avoid infinite loops
let max_iterations =
max(total_key_size, total_value_size) / COMPRESSION_DICTIONARY_SAMPLE_PER_ENTRY * 2;
for i in 0..max_iterations {
let entry = &entries[i % entries.len()];
let value_remaining = value_compression_samples_size - value_samples.len();
if value_remaining < MIN_COMPRESSION_DICTIONARY_SAMPLE_PER_ENTRY {
break;
}
if let EntryValue::Small { value } | EntryValue::Medium { value } = entry.value() {
let len = value.len();
if len >= MIN_COMPRESSION_DICTIONARY_SAMPLE_PER_ENTRY {
let used_len = min(value_remaining, COMPRESSION_DICTIONARY_SAMPLE_PER_ENTRY);
if len <= used_len {
value_sample_sizes.push(len);
value_samples.extend_from_slice(value);
} else {
value_sample_sizes.push(used_len);
let p = value_samples.len() % (len - used_len);
value_samples.extend_from_slice(&value[p..p + used_len]);
};
}
}
size = size.max(value_compression_samples_size);
}
size
}
/// Computes compression dictionaries from keys of all entries
#[tracing::instrument(level = "trace", skip(entries))]
fn compute_key_compression_dictionary<E: Entry>(
entries: &[E],
total_key_size: usize,
buffer: &mut Vec<u8>,
) -> Result<Vec<u8>> {
if total_key_size < MIN_KEY_COMPRESSION_SAMPLES_SIZE {
return Ok(Vec::new());
}
let key_compression_samples_size = min(KEY_COMPRESSION_SAMPLES_SIZE, total_key_size / 16);
let mut sample_sizes = Vec::new();
// Limit the number of iterations to avoid infinite loops
let max_iterations = total_key_size / COMPRESSION_DICTIONARY_SAMPLE_PER_ENTRY * 2;
for i in 0..max_iterations {
let entry = &entries[i % entries.len()];
let key_remaining = key_compression_samples_size - buffer.len();
if key_remaining < MIN_COMPRESSION_DICTIONARY_SAMPLE_PER_ENTRY {
break;
}
assert!(value_samples.len() == value_sample_sizes.iter().sum::<usize>());
if value_samples.len() > MIN_VALUE_COMPRESSION_SAMPLES_SIZE && value_sample_sizes.len() > 5
{
self.value_compression_dictionary = zstd::dict::from_continuous(
&value_samples,
&value_sample_sizes,
VALUE_COMPRESSION_DICTIONARY_SIZE,
)
.context("Value dictionary creation failed")?;
} else {
self.value_compression_dictionary = Vec::new();
let len = entry.key_len();
if len >= MIN_COMPRESSION_DICTIONARY_SAMPLE_PER_ENTRY {
let used_len = min(key_remaining, COMPRESSION_DICTIONARY_SAMPLE_PER_ENTRY);
if len <= used_len {
sample_sizes.push(len);
entry.write_key_to(buffer);
} else {
let mut temp = Vec::with_capacity(len);
entry.write_key_to(&mut temp);
debug_assert!(temp.len() == len);
let p = buffer.len() % (len - used_len);
sample_sizes.push(used_len);
buffer.extend_from_slice(&temp[p..p + used_len]);
}
}
}
debug_assert!(buffer.len() == sample_sizes.iter().sum::<usize>());
let result = if buffer.len() > MIN_KEY_COMPRESSION_SAMPLES_SIZE && sample_sizes.len() > 5 {
zstd::dict::from_continuous(buffer, &sample_sizes, KEY_COMPRESSION_DICTIONARY_SIZE)
.context("Key dictionary creation failed")?
} else {
Vec::new()
};
buffer.clear();
Ok(result)
}
for i in 0..max_iterations {
let entry = &entries[i % entries.len()];
let key_remaining = key_compression_samples_size - key_samples.len();
if key_remaining < MIN_COMPRESSION_DICTIONARY_SAMPLE_PER_ENTRY {
break;
}
let len = entry.key_len();
/// Computes compression dictionaries from values of all entries
#[tracing::instrument(level = "trace", skip(entries))]
fn compute_value_compression_dictionary<E: Entry>(
entries: &[E],
total_value_size: usize,
buffer: &mut Vec<u8>,
) -> Result<Vec<u8>> {
if total_value_size < MIN_VALUE_COMPRESSION_SAMPLES_SIZE {
return Ok(Vec::new());
}
let value_compression_samples_size = min(VALUE_COMPRESSION_SAMPLES_SIZE, total_value_size / 16);
let mut sample_sizes = Vec::new();
// Limit the number of iterations to avoid infinite loops
let max_iterations = total_value_size / COMPRESSION_DICTIONARY_SAMPLE_PER_ENTRY * 2;
for i in 0..max_iterations {
let entry = &entries[i % entries.len()];
let remaining = value_compression_samples_size - buffer.len();
if remaining < MIN_COMPRESSION_DICTIONARY_SAMPLE_PER_ENTRY {
break;
}
if let EntryValue::Small { value } | EntryValue::Medium { value } = entry.value() {
let len = value.len();
if len >= MIN_COMPRESSION_DICTIONARY_SAMPLE_PER_ENTRY {
let used_len = min(key_remaining, COMPRESSION_DICTIONARY_SAMPLE_PER_ENTRY);
let used_len = min(remaining, COMPRESSION_DICTIONARY_SAMPLE_PER_ENTRY);
if len <= used_len {
key_sample_sizes.push(len);
entry.write_key_to(&mut key_samples);
sample_sizes.push(len);
buffer.extend_from_slice(value);
} else {
let mut temp = Vec::with_capacity(len);
entry.write_key_to(&mut temp);
debug_assert!(temp.len() == len);
let p = key_samples.len() % (len - used_len);
key_sample_sizes.push(used_len);
key_samples.extend_from_slice(&temp[p..p + used_len]);
}
sample_sizes.push(used_len);
let p = buffer.len() % (len - used_len);
buffer.extend_from_slice(&value[p..p + used_len]);
};
}
}
assert!(key_samples.len() == key_sample_sizes.iter().sum::<usize>());
if key_samples.len() > MIN_KEY_COMPRESSION_SAMPLES_SIZE && key_sample_sizes.len() > 5 {
self.key_compression_dictionary = zstd::dict::from_continuous(
&key_samples,
&key_sample_sizes,
KEY_COMPRESSION_DICTIONARY_SIZE,
)
.context("Key dictionary creation failed")?;
}
debug_assert!(buffer.len() == sample_sizes.iter().sum::<usize>());
let result = if buffer.len() > MIN_VALUE_COMPRESSION_SAMPLES_SIZE && sample_sizes.len() > 5 {
zstd::dict::from_continuous(buffer, &sample_sizes, VALUE_COMPRESSION_DICTIONARY_SIZE)
.context("Value dictionary creation failed")?
} else {
Vec::new()
};
buffer.clear();
Ok(result)
}
struct BlockWriter<'l> {
buffer: &'l mut Vec<u8>,
block_offsets: Vec<u32>,
writer: &'l mut BufWriter<File>,
}
impl<'l> BlockWriter<'l> {
fn new(writer: &'l mut BufWriter<File>, buffer: &'l mut Vec<u8>) -> Self {
Self {
buffer,
block_offsets: Vec::new(),
writer,
}
}
fn next_block_index(&mut self) -> u16 {
self.block_offsets
.len()
.try_into()
.expect("Block index overflow")
}
fn block_count(&self) -> u16 {
self.block_offsets
.len()
.try_into()
.expect("Block count overflow")
}
#[tracing::instrument(level = "trace", skip_all)]
fn write_key_block(&mut self, block: &[u8], dict: &[u8]) -> Result<()> {
self.write_block(block, dict)
.context("Failed to write key block")
}
#[tracing::instrument(level = "trace", skip_all)]
fn write_index_block(&mut self, block: &[u8], dict: &[u8]) -> Result<()> {
self.write_block(block, dict)
.context("Failed to write index block")
}
#[tracing::instrument(level = "trace", skip_all)]
fn write_value_block(&mut self, block: &[u8], dict: &[u8]) -> Result<()> {
self.write_block(block, dict)
.context("Failed to write value block")
}
fn write_block(&mut self, block: &[u8], dict: &[u8]) -> Result<()> {
let uncompressed_size = block.len().try_into().unwrap();
self.compress_block_into_buffer(block, dict);
let len = (self.buffer.len() + 4).try_into().unwrap();
let offset = self
.block_offsets
.last()
.copied()
.unwrap_or_default()
.checked_add(len)
.expect("Block offset overflow");
self.block_offsets.push(offset);
self.writer
.write_u32::<BE>(uncompressed_size)
.context("Failed to write uncompressed size")?;
self.writer
.write_all(self.buffer)
.context("Failed to write compressed block")?;
self.buffer.clear();
Ok(())
}
/// Compute index, key and value blocks.
/// Compresses a block with a compression dictionary.
#[tracing::instrument(level = "trace", skip_all)]
fn compute_blocks<E: Entry>(&mut self, entries: &[E]) {
// TODO implement multi level index
// TODO place key and value block near to each other
// For now we use something simple to implement:
// Start with Value blocks
// And then Key blocks
// Last block is Index block
// Store the locations of the values
let mut value_locations: Vec<(u16, u32)> = Vec::with_capacity(entries.len());
// Split the values into blocks
let mut current_block_start = 0;
let mut current_block_count = 0;
let mut current_block_size = 0;
for (i, entry) in entries.iter().enumerate() {
match entry.value() {
EntryValue::Small { value } => {
if current_block_size + value.len() > MAX_SMALL_VALUE_BLOCK_SIZE
|| current_block_count + 1 >= MAX_SMALL_VALUE_BLOCK_ENTRIES
{
let block_index = self.blocks.len().try_into().unwrap();
let mut block = Vec::with_capacity(current_block_size);
for j in current_block_start..i {
if let EntryValue::Small { value } = &entries[j].value() {
block.extend_from_slice(value);
value_locations[j].0 = block_index;
}
fn compress_block_into_buffer(&mut self, block: &[u8], dict: &[u8]) {
let mut compressor =
lzzzz::lz4::Compressor::with_dict(dict).expect("LZ4 compressor creation failed");
self.buffer.reserve(max_compressed_size(block.len()));
compressor
.next_to_vec(block, self.buffer, ACC_LEVEL_DEFAULT)
.expect("Compression failed");
}
}
/// Splits the values of the entries into blocks and writes them to the writer.
#[tracing::instrument(level = "trace", skip_all)]
fn write_value_blocks(
entries: &[impl Entry],
value_compression_dictionary: &[u8],
writer: &mut BlockWriter<'_>,
buffer: &mut Vec<u8>,
) -> Result<Vec<(u16, u32)>> {
let mut value_locations: Vec<(u16, u32)> = Vec::with_capacity(entries.len());
let mut current_block_start = 0;
let mut current_block_count = 0;
let mut current_block_size = 0;
for (i, entry) in entries.iter().enumerate() {
match entry.value() {
EntryValue::Small { value } => {
if current_block_size + value.len() > MAX_SMALL_VALUE_BLOCK_SIZE
|| current_block_count + 1 >= MAX_SMALL_VALUE_BLOCK_ENTRIES
{
let block_index = writer.next_block_index();
buffer.reserve(current_block_size);
for j in current_block_start..i {
if let EntryValue::Small { value } = &entries[j].value() {
buffer.extend_from_slice(value);
value_locations[j].0 = block_index;
}
self.blocks.push(self.compress_value_block(&block));
current_block_start = i;
current_block_size = 0;
current_block_count = 0;
}
value_locations.push((0, current_block_size.try_into().unwrap()));
current_block_size += value.len();
current_block_count += 1;
}
EntryValue::Medium { value } => {
let block_index = self.blocks.len().try_into().unwrap();
value_locations.push((block_index, 0));
self.blocks.push(self.compress_value_block(value));
}
_ => {
value_locations.push((0, 0));
writer.write_value_block(buffer, value_compression_dictionary)?;
buffer.clear();
current_block_start = i;
current_block_size = 0;
current_block_count = 0;
}
value_locations.push((0, current_block_size.try_into().unwrap()));
current_block_size += value.len();
current_block_count += 1;
}
EntryValue::Medium { value } => {
let block_index = writer.next_block_index();
value_locations.push((block_index, 0));
writer.write_value_block(value, value_compression_dictionary)?;
}
_ => {
value_locations.push((0, 0));
}
}
if current_block_count > 0 {
let block_index = self.blocks.len().try_into().unwrap();
let mut block = Vec::with_capacity(current_block_size);
for j in current_block_start..entries.len() {
if let EntryValue::Small { value } = &entries[j].value() {
block.extend_from_slice(value);
value_locations[j].0 = block_index;
}
}
if current_block_count > 0 {
let block_index = writer.next_block_index();
buffer.reserve(current_block_size);
for j in current_block_start..entries.len() {
if let EntryValue::Small { value } = &entries[j].value() {
buffer.extend_from_slice(value);
value_locations[j].0 = block_index;
}
self.blocks.push(self.compress_value_block(&block));
}
writer.write_value_block(buffer, value_compression_dictionary)?;
buffer.clear();
}
let mut key_block_boundaries = Vec::new();
// Split the keys into blocks
fn add_entry_to_block<E: Entry>(
entry: &E,
value_location: &(u16, u32),
block: &mut KeyBlockBuilder,
) {
match entry.value() {
EntryValue::Small { value } => {
block.put_small(
entry,
value_location.0,
value_location.1,
value.len().try_into().unwrap(),
);
}
EntryValue::Medium { .. } => {
block.put_medium(entry, value_location.0);
}
EntryValue::Large { blob } => {
block.put_blob(entry, blob);
}
EntryValue::Deleted => {
block.delete(entry);
}
Ok(value_locations)
}
/// Splits the keys of the entries into blocks and writes them to the writer. Also writes an index
/// block.
#[tracing::instrument(level = "trace", skip_all)]
fn write_key_blocks_and_compute_amqf(
entries: &[impl Entry],
value_locations: &[(u16, u32)],
key_compression_dictionary: &[u8],
writer: &mut BlockWriter<'_>,
buffer: &mut Vec<u8>,
) -> Result<Vec<u8>> {
let mut filter = qfilter::Filter::new(entries.len() as u64, AMQF_FALSE_POSITIVE_RATE)
// This won't fail as we limit the number of entries per SST file
.expect("Filter can't be constructed");
let mut key_block_boundaries = Vec::new();
// Split the keys into blocks
fn add_entry_to_block<E: Entry>(
entry: &E,
value_location: &(u16, u32),
block: &mut KeyBlockBuilder,
) {
match entry.value() {
EntryValue::Small { value } => {
block.put_small(
entry,
value_location.0,
value_location.1,
value.len().try_into().unwrap(),
);
}
EntryValue::Medium { .. } => {
block.put_medium(entry, value_location.0);
}
EntryValue::Large { blob } => {
block.put_blob(entry, blob);
}
EntryValue::Deleted => {
block.delete(entry);
}
}
let mut current_block_start = 0;
let mut current_block_size = 0;
for (i, entry) in entries.iter().enumerate() {
if current_block_size > 0
}
let mut current_block_start = 0;
let mut current_block_size = 0;
let mut last_hash = 0;
for (i, entry) in entries.iter().enumerate() {
let key_hash = entry.key_hash();
// Add to AMQF
filter
.insert_fingerprint(false, key_hash)
// This can't fail as we allocated enough capacity
.expect("AMQF insert failed");
// Accumulate until the block is full
if current_block_size > 0
&& (current_block_size + entry.key_len() + KEY_BLOCK_ENTRY_META_OVERHEAD
> MAX_KEY_BLOCK_SIZE
|| i - current_block_start >= MAX_KEY_BLOCK_ENTRIES) &&
// avoid breaking the block in the middle of a hash conflict
entries[i - 1].key_hash() != entry.key_hash()
{
let mut block = KeyBlockBuilder::new((i - current_block_start) as u32);
for j in current_block_start..i {
let entry = &entries[j];
let value_location = &value_locations[j];
add_entry_to_block(entry, value_location, &mut block);
}
key_block_boundaries
.push((entries[current_block_start].key_hash(), self.blocks.len()));
self.blocks.push(self.compress_key_block(&block.finish()));
current_block_size = 0;
current_block_start = i;
}
current_block_size += entry.key_len() + KEY_BLOCK_ENTRY_META_OVERHEAD;
}
if current_block_size > 0 {
let mut block = KeyBlockBuilder::new((entries.len() - current_block_start) as u32);
for j in current_block_start..entries.len() {
last_hash != key_hash
{
let mut block = KeyBlockBuilder::new(buffer, (i - current_block_start) as u32);
for j in current_block_start..i {
let entry = &entries[j];
let value_location = &value_locations[j];
add_entry_to_block(entry, value_location, &mut block);
}
key_block_boundaries.push((entries[current_block_start].key_hash(), self.blocks.len()));
self.blocks.push(self.compress_key_block(&block.finish()));
key_block_boundaries.push((
entries[current_block_start].key_hash(),
writer.next_block_index(),
));
block.finish();
writer.write_key_block(buffer, key_compression_dictionary)?;
buffer.clear();
current_block_size = 0;
current_block_start = i;
}
// Compute the index
let mut index_block = IndexBlockBuilder::new(
key_block_boundaries.len() as u16,
key_block_boundaries[0].1 as u16,
);
for (hash, block) in &key_block_boundaries[1..] {
index_block.put(*hash, *block as u16);
}
self.blocks
.push(self.compress_key_block(&index_block.finish()));
current_block_size += entry.key_len() + KEY_BLOCK_ENTRY_META_OVERHEAD;
last_hash = key_hash;
}
/// Compresses a block with a compression dictionary.
fn compress_block(&self, block: &[u8], dict: &[u8]) -> (u32, Vec<u8>) {
let mut compressor =
lzzzz::lz4::Compressor::with_dict(dict).expect("LZ4 compressor creation failed");
let mut compressed = Vec::with_capacity(max_compressed_size(block.len()));
compressor
.next_to_vec(block, &mut compressed, ACC_LEVEL_DEFAULT)
.expect("Compression failed");
if compressed.capacity() > compressed.len() * 2 {
compressed.shrink_to_fit();
// Finish the last block
if current_block_size > 0 {
let mut block = KeyBlockBuilder::new(buffer, (entries.len() - current_block_start) as u32);
for j in current_block_start..entries.len() {
let entry = &entries[j];
let value_location = &value_locations[j];
add_entry_to_block(entry, value_location, &mut block);
}
(block.len().try_into().unwrap(), compressed)
}
/// Compresses an index or key block.
#[tracing::instrument(level = "trace", skip_all)]
fn compress_key_block(&self, block: &[u8]) -> (u32, Vec<u8>) {
self.compress_block(block, &self.key_compression_dictionary)
key_block_boundaries.push((
entries[current_block_start].key_hash(),
writer.next_block_index(),
));
block.finish();
writer.write_key_block(buffer, key_compression_dictionary)?;
buffer.clear();
}
/// Compresses a value block.
#[tracing::instrument(level = "trace", skip_all)]
fn compress_value_block(&self, block: &[u8]) -> (u32, Vec<u8>) {
self.compress_block(block, &self.value_compression_dictionary)
// Compute the index
let mut index_block = IndexBlockBuilder::new(
buffer,
key_block_boundaries
.len()
.try_into()
.expect("Index entries count overflow"),
key_block_boundaries[0].1,
);
for (hash, block) in &key_block_boundaries[1..] {
index_block.put(*hash, *block);
}
let _ = writer.next_block_index();
index_block.finish();
writer.write_index_block(buffer, key_compression_dictionary)?;
buffer.clear();
/// Writes the SST file.
#[tracing::instrument(level = "trace", skip_all)]
pub fn write(self, file: &Path) -> io::Result<(StaticSortedFileBuilderMeta<'a>, File)> {
let mut file = BufWriter::new(File::create(file)?);
// Write the key compression dictionary
file.write_all(&self.key_compression_dictionary)?;
// Write the value compression dictionary
file.write_all(&self.value_compression_dictionary)?;
// Write the blocks
let block_count = self.blocks.len().try_into().unwrap();
let mut block_offsets = Vec::with_capacity(self.blocks.len());
let mut offset = 0;
for (uncompressed_size, block) in self.blocks {
// Block length (including the uncompressed length field)
let len = block.len() + 4;
offset += len;
block_offsets.push(offset.try_into().unwrap());
// Uncompressed size
file.write_u32::<BE>(uncompressed_size)?;
// Compressed block
file.write_all(&block)?;
}
// Write the block offsets
for offset in block_offsets {
file.write_u32::<BE>(offset)?;
}
let meta = StaticSortedFileBuilderMeta {
min_hash: self.min_hash,
max_hash: self.max_hash,
aqmf: self.aqmf,
key_compression_dictionary_length: self
.key_compression_dictionary
.len()
.try_into()
.unwrap(),
value_compression_dictionary_length: self
.value_compression_dictionary
.len()
.try_into()
.unwrap(),
block_count,
size: file.stream_position()?,
entries: self.entries,
};
Ok((meta, file.into_inner()?))
}
Ok(pot::to_vec(&filter).expect("AMQF serialization failed"))
}
/// Builder for a single key block
pub struct KeyBlockBuilder {
pub struct KeyBlockBuilder<'l> {
current_entry: usize,
header_size: usize,
data: Vec<u8>,
buffer: &'l mut Vec<u8>,
}
/// The size of the key block header.
const KEY_BLOCK_HEADER_SIZE: usize = 4;
impl KeyBlockBuilder {
impl<'l> KeyBlockBuilder<'l> {
/// Creates a new key block builder for the number of entries.
pub fn new(entry_count: u32) -> Self {
pub fn new(buffer: &'l mut Vec<u8>, entry_count: u32) -> Self {
debug_assert!(entry_count < (1 << 24));
const ESTIMATED_KEY_SIZE: usize = 16;
let mut data = Vec::with_capacity(entry_count as usize * ESTIMATED_KEY_SIZE);
data.write_u8(BLOCK_TYPE_KEY).unwrap();
data.write_u24::<BE>(entry_count).unwrap();
buffer.reserve(entry_count as usize * ESTIMATED_KEY_SIZE);
buffer.write_u8(BLOCK_TYPE_KEY).unwrap();
buffer.write_u24::<BE>(entry_count).unwrap();
for _ in 0..entry_count {
data.write_u32::<BE>(0).unwrap();
buffer.write_u32::<BE>(0).unwrap();
}
Self {
current_entry: 0,
header_size: data.len(),
data,
header_size: buffer.len(),
buffer,
}
}
......@@ -486,90 +563,94 @@ impl KeyBlockBuilder {
value_offset: u32,
value_size: u16,
) {
let pos = self.data.len() - self.header_size;
let pos = self.buffer.len() - self.header_size;
let header_offset = KEY_BLOCK_HEADER_SIZE + self.current_entry * 4;
let header = (pos as u32) | ((KEY_BLOCK_ENTRY_TYPE_SMALL as u32) << 24);
BE::write_u32(&mut self.data[header_offset..header_offset + 4], header);
BE::write_u32(&mut self.buffer[header_offset..header_offset + 4], header);
self.data.write_u64::<BE>(entry.key_hash()).unwrap();
entry.write_key_to(&mut self.data);
self.data.write_u16::<BE>(value_block).unwrap();
self.data.write_u16::<BE>(value_size).unwrap();
self.data.write_u32::<BE>(value_offset).unwrap();
self.buffer.write_u64::<BE>(entry.key_hash()).unwrap();
entry.write_key_to(self.buffer);
self.buffer.write_u16::<BE>(value_block).unwrap();
self.buffer.write_u16::<BE>(value_size).unwrap();
self.buffer.write_u32::<BE>(value_offset).unwrap();
self.current_entry += 1;
}
/// Writes a medium-sized value to the buffer.
pub fn put_medium<E: Entry>(&mut self, entry: &E, value_block: u16) {
let pos = self.data.len() - self.header_size;
let pos = self.buffer.len() - self.header_size;
let header_offset = KEY_BLOCK_HEADER_SIZE + self.current_entry * 4;
let header = (pos as u32) | ((KEY_BLOCK_ENTRY_TYPE_MEDIUM as u32) << 24);
BE::write_u32(&mut self.data[header_offset..header_offset + 4], header);
BE::write_u32(&mut self.buffer[header_offset..header_offset + 4], header);
self.data.write_u64::<BE>(entry.key_hash()).unwrap();
entry.write_key_to(&mut self.data);
self.data.write_u16::<BE>(value_block).unwrap();
self.buffer.write_u64::<BE>(entry.key_hash()).unwrap();
entry.write_key_to(self.buffer);
self.buffer.write_u16::<BE>(value_block).unwrap();
self.current_entry += 1;
}
/// Writes a tombstone to the buffer.
pub fn delete<E: Entry>(&mut self, entry: &E) {
let pos = self.data.len() - self.header_size;
let pos = self.buffer.len() - self.header_size;
let header_offset = KEY_BLOCK_HEADER_SIZE + self.current_entry * 4;
let header = (pos as u32) | ((KEY_BLOCK_ENTRY_TYPE_DELETED as u32) << 24);
BE::write_u32(&mut self.data[header_offset..header_offset + 4], header);
BE::write_u32(&mut self.buffer[header_offset..header_offset + 4], header);
self.data.write_u64::<BE>(entry.key_hash()).unwrap();
entry.write_key_to(&mut self.data);
self.buffer.write_u64::<BE>(entry.key_hash()).unwrap();
entry.write_key_to(self.buffer);
self.current_entry += 1;
}
/// Writes a blob value to the buffer.
pub fn put_blob<E: Entry>(&mut self, entry: &E, blob: u32) {
let pos = self.data.len() - self.header_size;
let pos = self.buffer.len() - self.header_size;
let header_offset = KEY_BLOCK_HEADER_SIZE + self.current_entry * 4;
let header = (pos as u32) | ((KEY_BLOCK_ENTRY_TYPE_BLOB as u32) << 24);
BE::write_u32(&mut self.data[header_offset..header_offset + 4], header);
BE::write_u32(&mut self.buffer[header_offset..header_offset + 4], header);
self.data.write_u64::<BE>(entry.key_hash()).unwrap();
entry.write_key_to(&mut self.data);
self.data.write_u32::<BE>(blob).unwrap();
self.buffer.write_u64::<BE>(entry.key_hash()).unwrap();
entry.write_key_to(self.buffer);
self.buffer.write_u32::<BE>(blob).unwrap();
self.current_entry += 1;
}
/// Returns the key block buffer
pub fn finish(self) -> Vec<u8> {
self.data
pub fn finish(self) -> &'l mut Vec<u8> {
self.buffer
}
}
/// Builder for a single index block.
pub struct IndexBlockBuilder {
data: Vec<u8>,
pub struct IndexBlockBuilder<'l> {
buffer: &'l mut Vec<u8>,
}
impl IndexBlockBuilder {
impl<'l> IndexBlockBuilder<'l> {
/// Creates a new builder for an index block with the specified number of entries and a pointer
/// to the first block.
pub fn new(entry_count: u16, first_block: u16) -> Self {
let mut data = Vec::with_capacity(entry_count as usize * 10 + 3);
data.write_u8(BLOCK_TYPE_INDEX).unwrap();
data.write_u16::<BE>(first_block).unwrap();
Self { data }
pub fn new(buffer: &'l mut Vec<u8>, entry_count: u16, first_block: u16) -> Self {
buffer.reserve(
entry_count as usize * (size_of::<u64>() + size_of::<u16>())
+ size_of::<u8>()
+ size_of::<u16>(),
);
buffer.write_u8(BLOCK_TYPE_INDEX).unwrap();
buffer.write_u16::<BE>(first_block).unwrap();
Self { buffer }
}
/// Adds a hash boundary to the index block.
pub fn put(&mut self, hash: u64, block: u16) {
self.data.write_u64::<BE>(hash).unwrap();
self.data.write_u16::<BE>(block).unwrap();
self.buffer.write_u64::<BE>(hash).unwrap();
self.buffer.write_u16::<BE>(block).unwrap();
}
/// Returns the index block buffer
fn finish(self) -> Vec<u8> {
self.data
fn finish(self) -> &'l mut Vec<u8> {
self.buffer
}
}
......@@ -26,7 +26,7 @@ use crate::{
constants::{MAX_MEDIUM_VALUE_SIZE, THREAD_LOCAL_SIZE_SHIFT},
key::StoreKey,
meta_file_builder::MetaFileBuilder,
static_sorted_file_builder::{StaticSortedFileBuilder, StaticSortedFileBuilderMeta},
static_sorted_file_builder::{StaticSortedFileBuilderMeta, write_static_stored_file},
};
/// The thread local state of a `WriteBatch`. `FAMILIES` should fit within a `u32`.
......@@ -408,12 +408,10 @@ impl<K: StoreKey + Send + Sync, const FAMILIES: usize> WriteBatch<K, FAMILIES> {
let (entries, total_key_size, total_value_size) = collector_data;
let seq = self.current_sequence_number.fetch_add(1, Ordering::SeqCst) + 1;
let builder = StaticSortedFileBuilder::new(entries, total_key_size, total_value_size)?;
let path = self.db_path.join(format!("{seq:08}.sst"));
let (meta, file) = builder
.write(&path)
.with_context(|| format!("Unable to write SST file {seq:08}.sst"))?;
let (meta, file) =
write_static_stored_file(entries, total_key_size, total_value_size, &path)
.with_context(|| format!("Unable to write SST file {seq:08}.sst"))?;
#[cfg(feature = "verify_sst_content")]
{
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment