use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, mpsc};
use std::thread::JoinHandle;
use crate::Store as AsyncStore;
use crate::error::{Error, Result};
use crate::store::{Config, Needs, Record, decode_record, encode_record};
type Job = Pin<Box<dyn Future<Output = ()> + Send>>;
struct Worker {
jobs: Option<tokio::sync::mpsc::UnboundedSender<Job>>,
thread: Option<JoinHandle<()>>,
}
impl Worker {
fn start() -> Result<Worker> {
let (jobs, mut rx) = tokio::sync::mpsc::unbounded_channel::<Job>();
let (ready_tx, ready_rx) = mpsc::channel::<std::result::Result<(), String>>();
let thread = std::thread::Builder::new()
.name("persistant-worker".into())
.spawn(move || {
let rt = match tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
{
Ok(rt) => rt,
Err(e) => {
let _ = ready_tx.send(Err(e.to_string()));
return;
}
};
let _ = ready_tx.send(Ok(()));
rt.block_on(async move {
while let Some(job) = rx.recv().await {
tokio::spawn(job);
}
});
})
.map_err(|e| Error::Backend(format!("cannot start worker thread: {e}")))?;
let worker = Worker {
jobs: Some(jobs),
thread: Some(thread),
};
match ready_rx.recv() {
Ok(Ok(())) => Ok(worker),
Ok(Err(e)) => Err(Error::Backend(format!("cannot start runtime: {e}"))),
Err(_) => Err(Error::Backend("worker thread died at start".into())),
}
}
fn run<Fut, T>(&self, fut: Fut) -> Result<T>
where
Fut: Future<Output = Result<T>> + Send + 'static,
T: Send + 'static,
{
let (tx, rx) = mpsc::channel();
let job: Job = Box::pin(async move {
let _ = tx.send(fut.await);
});
self.jobs
.as_ref()
.ok_or_else(|| Error::Backend("worker is gone".into()))?
.send(job)
.map_err(|_| Error::Backend("worker is gone".into()))?;
rx.recv()
.map_err(|_| Error::Backend("worker failed before replying".into()))?
}
}
impl Drop for Worker {
fn drop(&mut self) {
self.jobs.take();
if let Some(t) = self.thread.take() {
let _ = t.join();
}
}
}
pub struct Store {
inner: Arc<AsyncStore>,
worker: Worker,
}
impl std::fmt::Debug for Store {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("blocking::Store").finish_non_exhaustive()
}
}
impl Store {
pub fn open(config: Config, needs: Needs) -> Result<Store> {
let worker = Worker::start()?;
let inner = Arc::new(worker.run(AsyncStore::open(config, needs))?);
Ok(Store { inner, worker })
}
pub fn read(&self, key: &str) -> Result<Vec<u8>> {
let (s, key) = (self.inner.clone(), key.to_string());
self.worker.run(async move { s.read(&key).await })
}
pub fn replace(&self, key: &str, bytes: Vec<u8>) -> Result<()> {
let (s, key) = (self.inner.clone(), key.to_string());
self.worker.run(async move { s.replace(&key, bytes).await })
}
pub fn delete(&self, key: &str) -> Result<()> {
let (s, key) = (self.inner.clone(), key.to_string());
self.worker.run(async move { s.delete(&key).await })
}
pub fn put_record<R: Record>(&self, key: &str, record: &R) -> Result<()> {
self.replace(key, encode_record(record)?)
}
pub fn get_record<R: Record>(&self, key: &str) -> Result<Option<R>> {
let (s, key) = (self.inner.clone(), key.to_string());
match self
.worker
.run(async move { s.read_optional(&key).await })?
{
Some(bytes) => decode_record(&bytes).map(Some),
None => Ok(None),
}
}
}