use std::{
cell::RefCell,
collections::HashMap,
io, ptr,
sync::atomic::{fence, AtomicBool, AtomicPtr, Ordering},
};
use bytemuck::Pod;
mod blob_tape;
mod fixed_size;
mod memory;
mod metadata;
mod unsafe_tape;
pub use blob_tape::{Blob, BlobTapeAppender, BlobTapePopper, BlobTapeSlice};
pub use fixed_size::{FixedSizedTapeSlice, FixedSizedTapeAppender, FixedSizedTapePopper};
pub use memory::{BackingMemory, InMemory, MmapFile};
use metadata::{Metadata, APPEND_OP, POP_OP};
use unsafe_tape::UnsafeTape;
const METADATA_RING_LEN: usize = 8;
#[derive(Copy, Clone, Debug)]
pub enum Advice {
Normal,
Random,
Sequential,
}
impl Advice {
const fn to_memmap2_advice(self) -> memmap2::Advice {
match self {
Self::Normal => memmap2::Advice::Normal,
Self::Random => memmap2::Advice::Random,
Self::Sequential => memmap2::Advice::Sequential,
}
}
}
#[derive(Copy, Clone)]
pub enum Flush {
Sync,
Async,
NoSync,
}
#[derive(Copy, Clone, Debug)]
pub struct ResizeNeeded;
#[derive(Debug)]
pub struct Tape<M: BackingMemory> {
pub name: &'static str,
pub backing_memory_options: M::OpenOption,
pub advice: Advice,
pub initial_memory_size: u64,
}
impl<M: BackingMemory> Clone for Tape<M> {
fn clone(&self) -> Self {
Self {
name: self.name,
backing_memory_options: self.backing_memory_options.clone(),
advice: self.advice,
initial_memory_size: self.initial_memory_size,
}
}
}
pub struct Tapes<M: BackingMemory> {
metadata: Metadata<M>,
tapes_to_index: HashMap<&'static str, usize>,
old_tapes: Box<[AtomicPtr<UnsafeTape<M>>]>,
old_tapes_need_flush: AtomicBool,
tapes: Box<[AtomicPtr<UnsafeTape<M>>]>,
min_resize: u64,
}
impl<M: BackingMemory> Drop for Tapes<M> {
fn drop(&mut self) {
unsafe { self.flush_old_tapes() };
for tape in &self.tapes {
unsafe {
drop(Box::from_raw(tape.load(Ordering::Acquire)));
}
}
}
}
impl<M: BackingMemory> Tapes<M> {
pub unsafe fn new(
mut tapes: Vec<Tape<M>>,
metadata_open_options: M::OpenOption,
min_resize: u64,
) -> Result<Self, io::Error> {
tapes.sort_unstable_by_key(|tape| tape.name);
let metadata =
unsafe { Metadata::open(metadata_open_options, tapes.len(), METADATA_RING_LEN)? };
let tapes_to_index = tapes.iter().enumerate().map(|(i, t)| (t.name, i)).collect();
let (old_tapes, tapes) = tapes
.iter()
.map(|tape| {
unsafe {
let tape = Box::into_raw(Box::new(UnsafeTape::open(tape.clone())?));
Ok::<_, io::Error>((AtomicPtr::new(ptr::null_mut()), AtomicPtr::new(tape)))
}
})
.collect::<Result<(Vec<_>, Vec<_>), _>>()?;
Ok(Self {
tapes_to_index,
metadata,
old_tapes: old_tapes.into_boxed_slice(),
old_tapes_need_flush: AtomicBool::new(false),
min_resize,
tapes: tapes.into_boxed_slice(),
})
}
unsafe fn flush_old_tapes(&self) {
for old_tape in &self.old_tapes {
let ptr = old_tape.swap(ptr::null_mut(), Ordering::Relaxed);
if ptr.is_null() {
continue;
}
fence(Ordering::Acquire);
unsafe {
drop(Box::from_raw(ptr));
}
}
}
pub fn appender(&self) -> Appender<'_, M> {
let meta_guard = self.metadata.start_write(APPEND_OP);
if self
.old_tapes_need_flush
.compare_exchange(true, false, Ordering::Relaxed, Ordering::Relaxed)
.is_ok()
{
self.metadata
.wait_for_all_readers(meta_guard.current_data_slot_idx());
unsafe { self.flush_old_tapes() };
}
Appender {
meta_guard,
tapes: self,
min_resize: self.min_resize,
added_bytes: vec![RefCell::new(0); self.tapes.len()],
resized_tapes: (0..self.tapes.len()).map(|_| RefCell::new(None)).collect(),
}
}
pub fn popper(&self) -> Popper<'_, M> {
let meta_guard = self.metadata.start_write(POP_OP);
if self
.old_tapes_need_flush
.compare_exchange(true, false, Ordering::Relaxed, Ordering::Relaxed)
.is_ok()
{
self.metadata
.wait_for_all_readers(meta_guard.current_data_slot_idx());
unsafe { self.flush_old_tapes() };
}
Popper {
meta_guard,
tapes: self,
}
}
pub fn reader(&self) -> Result<Reader<'_, M>, ResizeNeeded> {
let meta_guard = self.metadata.start_read();
let loaded_tapes = self
.tapes
.iter()
.map(|tape_ptr| tape_ptr.load(Ordering::Relaxed).cast_const())
.collect::<Vec<_>>();
fence(Ordering::Acquire);
let loaded_tapes = loaded_tapes
.into_iter()
.enumerate()
.map(|(i, tape)| {
let tape = unsafe { &*tape };
let bytes_used = meta_guard[i];
if tape.map_size() < bytes_used {
return Err(ResizeNeeded);
}
Ok(tape)
})
.collect::<Result<Vec<_>, _>>()?;
Ok(Reader {
meta_guard,
loaded_tapes,
tapes: self,
})
}
pub fn flush_all_tapes(&self, mode: Flush) -> io::Result<()> {
let _meta_guard = self.metadata.start_read();
let loaded_tapes = self
.tapes
.iter()
.map(|tape_ptr| tape_ptr.load(Ordering::Relaxed).cast_const())
.collect::<Vec<_>>();
fence(Ordering::Acquire);
for tape in loaded_tapes.into_iter() {
let tape = unsafe { &*tape };
tape.flush(mode)?
}
Ok(())
}
}
pub struct Appender<'a, M: BackingMemory> {
meta_guard: metadata::MetadataWriteGuard<'a, M>,
tapes: &'a Tapes<M>,
min_resize: u64,
added_bytes: Vec<RefCell<usize>>,
resized_tapes: Vec<RefCell<Option<UnsafeTape<M>>>>,
}
impl<M: BackingMemory> Appender<'_, M> {
pub fn fixed_sized_tape_appender<'a, P: Pod>(
&'a self,
table_name: &'static str,
) -> FixedSizedTapeAppender<'a, P, M> {
let i = *self
.tapes
.tapes_to_index
.get(table_name)
.expect("Tape was not specified when opening tapes");
let tape = &self.tapes.tapes[i];
FixedSizedTapeAppender {
backing_file: unsafe { &*tape.load(Ordering::Acquire) },
resized_backing_file: self.resized_tapes[i].borrow_mut(),
min_resize: self.min_resize,
phantom: Default::default(),
current_used_bytes: self.meta_guard.tables_len()[i],
bytes_added: self.added_bytes[i].borrow_mut(),
}
}
pub fn blob_tape_appender<'a>(&'a self, table_name: &'static str) -> BlobTapeAppender<'a, M> {
let i = *self
.tapes
.tapes_to_index
.get(table_name)
.expect("Tape was not specified when opening tapes");
let tape = &self.tapes.tapes[i];
BlobTapeAppender {
backing_file: unsafe { &*tape.load(Ordering::Acquire) },
resized_backing_file: self.resized_tapes[i].borrow_mut(),
min_resize: self.min_resize,
current_used_bytes: self.meta_guard.tables_len()[i],
bytes_added: self.added_bytes[i].borrow_mut(),
}
}
pub fn flush(mut self, mode: Flush) -> io::Result<()> {
let mut resize_happened = false;
for (i, resized_tape) in self.resized_tapes.iter_mut().enumerate() {
if let Some(resized_tape) = resized_tape.take() {
let resized_tape = Box::into_raw(Box::new(resized_tape));
let old_tape = self.tapes.tapes[i].swap(resized_tape, Ordering::Release);
let null = self.tapes.old_tapes[i].swap(old_tape, Ordering::Relaxed);
assert!(null.is_null());
resize_happened = true;
}
}
if resize_happened {
self.tapes
.old_tapes_need_flush
.store(true, Ordering::Relaxed);
}
for (i, tape) in self.tapes.tapes.iter().enumerate() {
if *self.added_bytes[i].borrow() != 0 {
unsafe { &*tape.load(Ordering::Acquire) }.flush_range(
self.meta_guard.tables_len_mut()[i],
*self.added_bytes[i].borrow(),
mode,
)?;
}
}
for (len, added_bytes) in self
.meta_guard
.tables_len_mut()
.iter_mut()
.zip(&self.added_bytes)
{
*len += *added_bytes.borrow();
}
self.meta_guard.push_update(mode)
}
}
pub struct Popper<'a, M: BackingMemory> {
meta_guard: metadata::MetadataWriteGuard<'a, M>,
tapes: &'a Tapes<M>,
}
impl<M: BackingMemory> Popper<'_, M> {
pub fn fixed_sized_tape_popper<'a, P: Pod>(
&'a mut self,
table_name: &'static str,
) -> FixedSizedTapePopper<'a, P, M> {
let i = *self
.tapes
.tapes_to_index
.get(table_name)
.expect("Tape was not specified when opening tapes");
let tape = &self.tapes.tapes[i];
FixedSizedTapePopper {
backing_file: unsafe { &*tape.load(Ordering::Acquire) },
phantom: Default::default(),
current_used_bytes: &mut self.meta_guard.tables_len_mut()[i],
}
}
pub fn blob_tape_popper<'a>(&'a mut self, table_name: &'static str) -> BlobTapePopper<'a, M> {
let i = *self
.tapes
.tapes_to_index
.get(table_name)
.expect("Tape was not specified when opening tapes");
let tape = &self.tapes.tapes[i];
BlobTapePopper {
backing_file: unsafe { &*tape.load(Ordering::Acquire) },
current_used_bytes: &mut self.meta_guard.tables_len_mut()[i],
}
}
pub fn fixed_sized_tape_slice<'a, P: Pod>(
&'a self,
table_name: &'static str,
) -> FixedSizedTapeSlice<'a, P> {
let i = *self
.tapes
.tapes_to_index
.get(table_name)
.expect("Tape was not specified when opening tapes");
let backing_file = unsafe { &*self.tapes.tapes[i].load(Ordering::Acquire) };
let bytes = unsafe { backing_file.slice(0, self.meta_guard.tables_len()[i]) };
FixedSizedTapeSlice {
slice: bytemuck::cast_slice(bytes),
}
}
pub fn blob_tape_tape_reader<'a>(&'a self, table_name: &'static str) -> BlobTapeSlice<'a, M> {
let i = *self
.tapes
.tapes_to_index
.get(table_name)
.expect("Tape was not specified when opening tapes");
let backing_file = unsafe { &*self.tapes.tapes[i].load(Ordering::Acquire) };
let bytes = unsafe { backing_file.slice(0, self.meta_guard.tables_len()[i]) };
BlobTapeSlice {
backing_file,
slice: bytes,
}
}
pub fn flush(mut self, mode: Flush) -> io::Result<()> {
self.meta_guard.push_update(mode)
}
}
pub struct Reader<'a, M: BackingMemory> {
meta_guard: metadata::MetadataHandle<'a>,
loaded_tapes: Vec<&'a UnsafeTape<M>>,
tapes: &'a Tapes<M>,
}
unsafe impl<M: BackingMemory> Sync for Reader<'_, M> {}
unsafe impl<M: BackingMemory> Send for Reader<'_, M> {}
impl<M: BackingMemory> Reader<'_, M> {
pub fn fixed_sized_tape_slice<P: Pod>(
&self,
table_name: &'static str,
) -> FixedSizedTapeSlice<'_, P> {
let i = *self
.tapes
.tapes_to_index
.get(table_name)
.expect("Tape was not specified when opening tapes");
let backing_file = self.loaded_tapes[i];
let bytes = unsafe { backing_file.slice(0, self.meta_guard[i]) };
FixedSizedTapeSlice {
slice: bytemuck::cast_slice(bytes),
}
}
pub fn blob_tape_tape_slice<'a>(&'a self, table_name: &'static str) -> BlobTapeSlice<'a, M> {
let i = *self
.tapes
.tapes_to_index
.get(table_name)
.expect("Tape was not specified when opening tapes");
let backing_file = self.loaded_tapes[i];
let bytes = unsafe { backing_file.slice(0, self.meta_guard[i]) };
BlobTapeSlice {
slice: bytes,
backing_file,
}
}
}