use super::*;
use std::collections::VecDeque;
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::{Arc, Condvar, Mutex};
pub enum SpillBytes {
Pinned { ptr: *const u8, len: usize },
Owned(Vec<u8>),
}
unsafe impl Send for SpillBytes {}
pub enum SpillIo {
Block {
key: SpillKey,
generation: u64,
kv: SpillBytes,
state: Option<Vec<u8>>,
refuse_existing: bool,
},
Unlink { key: SpillKey },
Index { build: Box<dyn FnOnce() -> Vec<u8> + Send> },
}
pub enum SpillIoDone {
Block { key: SpillKey, raw: RawDiskWrite },
Unlink { key: SpillKey, result: io::Result<bool> },
Index { result: io::Result<()> },
}
#[cfg(test)]
type BlockHook = Arc<dyn Fn(SpillKey) + Send + Sync>;
struct Queue {
jobs: HashMap<u64, SpillIo>,
urgent: VecDeque<u64>,
bulk: VecDeque<u64>,
closed: bool,
}
impl Queue {
fn take_next(&mut self) -> Option<SpillIo> {
while let Some(id) = self.urgent.pop_front() {
if let Some(job) = self.jobs.remove(&id) {
return Some(job);
}
}
while let Some(id) = self.bulk.pop_front() {
if let Some(job) = self.jobs.remove(&id) {
return Some(job);
}
}
None
}
}
struct Shared {
queue: Mutex<Queue>,
ready: Condvar,
}
impl Shared {
fn lock(&self) -> std::sync::MutexGuard<'_, Queue> {
self.queue.lock().unwrap_or_else(|e| e.into_inner())
}
}
fn run_spill_io(dir: &Path, kvb: u32, job: SpillIo) -> SpillIoDone {
match job {
SpillIo::Block { key, generation, kv, state, refuse_existing } => {
let kv_bytes: &[u8] = match &kv {
SpillBytes::Pinned { ptr, len } => unsafe { std::slice::from_raw_parts(*ptr, *len) },
SpillBytes::Owned(bytes) => bytes,
};
let raw = write_block_to_dir(dir, kvb, key, generation, kv_bytes, state.as_deref(), refuse_existing);
SpillIoDone::Block { key, raw }
}
SpillIo::Unlink { key } => SpillIoDone::Unlink { key, result: unlink_block_in_dir(dir, key) },
SpillIo::Index { build } => SpillIoDone::Index { result: write_index_to_dir(dir, &build()) },
}
}
pub struct SpillWriter {
shared: Arc<Shared>,
dir: PathBuf,
kvb: u32,
done_tx: Sender<SpillIoDone>,
done_rx: Receiver<SpillIoDone>,
next_id: u64,
join: Option<std::thread::JoinHandle<()>>,
#[cfg(test)]
block_hook: Option<BlockHook>,
}
impl SpillWriter {
pub fn new(dir: &Path, kvb: u32) -> Self {
let (done_tx, done_rx) = channel();
Self {
shared: Arc::new(Shared {
queue: Mutex::new(Queue {
jobs: HashMap::new(),
urgent: VecDeque::new(),
bulk: VecDeque::new(),
closed: false,
}),
ready: Condvar::new(),
}),
dir: dir.to_path_buf(),
kvb,
done_tx,
done_rx,
next_id: 1,
join: None,
#[cfg(test)]
block_hook: None,
}
}
pub fn start_thread(&mut self, wake: Arc<dyn Fn() + Send + Sync>) {
if self.join.is_some() {
return;
}
let shared = self.shared.clone();
let dir = self.dir.clone();
let kvb = self.kvb;
let done = self.done_tx.clone();
let join = std::thread::Builder::new()
.name("inky-spill-write".into())
.spawn(move || loop {
let job = {
let mut q = shared.lock();
loop {
if let Some(job) = q.take_next() {
break job;
}
if q.closed {
return;
}
q = shared.ready.wait(q).unwrap_or_else(|e| e.into_inner());
}
};
if done.send(run_spill_io(&dir, kvb, job)).is_err() {
return;
}
wake();
})
.expect("spawn inky-spill-write worker");
self.join = Some(join);
}
pub fn has_thread(&self) -> bool {
self.join.is_some()
}
pub fn push(&mut self, job: SpillIo, urgent: bool) -> u64 {
let id = self.next_id;
self.next_id += 1;
{
let mut q = self.shared.lock();
q.jobs.insert(id, job);
if urgent {
q.urgent.push_back(id);
} else {
q.bulk.push_back(id);
}
}
self.shared.ready.notify_one();
id
}
pub fn cancel(&self, id: u64) -> bool {
self.shared.lock().jobs.remove(&id).is_some()
}
pub fn try_recv(&self) -> Option<SpillIoDone> {
self.done_rx.try_recv().ok()
}
pub fn queued(&self) -> usize {
self.shared.lock().jobs.len()
}
pub fn run_queued(&self, max: usize) -> usize {
let mut ran = 0;
while ran < max {
let Some(job) = self.shared.lock().take_next() else { break };
#[cfg(test)]
if let (Some(hook), SpillIo::Block { key, .. }) = (&self.block_hook, &job) {
hook(*key);
}
let _ = self.done_tx.send(run_spill_io(&self.dir, self.kvb, job));
ran += 1;
}
ran
}
#[cfg(test)]
pub fn set_block_hook(&mut self, hook: Option<BlockHook>) {
self.block_hook = hook;
}
pub fn stop(&mut self) -> Vec<SpillIo> {
let mut dropped = Vec::new();
{
let mut q = self.shared.lock();
while let Some(job) = q.take_next() {
dropped.push(job);
}
q.jobs.clear();
q.closed = true;
}
self.shared.ready.notify_all();
if let Some(join) = self.join.take() {
let _ = join.join();
}
dropped
}
}
impl Drop for SpillWriter {
fn drop(&mut self) {
let _ = self.stop();
}
}