use std::future::Future;
use crate::error::ProverError;
#[cfg(target_arch = "wasm32")]
pub async fn prove_offthread<T, F, Fut>(build: F) -> Result<T, ProverError>
where
F: FnOnce() -> Fut + Send + 'static,
Fut: Future<Output = T>,
T: Send + 'static,
{
Ok(build().await)
}
#[cfg(not(target_arch = "wasm32"))]
mod pool {
use std::collections::VecDeque;
use std::sync::{Arc, Condvar, Mutex, OnceLock};
type Job = Box<dyn FnOnce(&tokio::runtime::Runtime) + Send + 'static>;
struct Queue {
jobs: Mutex<VecDeque<Job>>,
ready: Condvar,
}
pub struct ProvingPool {
queue: Arc<Queue>,
}
impl ProvingPool {
fn global() -> Result<&'static Self, String> {
static POOL: OnceLock<Result<ProvingPool, String>> = OnceLock::new();
POOL.get_or_init(Self::start).as_ref().map_err(Clone::clone)
}
fn start() -> Result<Self, String> {
let workers = num_cpus::get().clamp(2, 8);
let queue = Arc::new(Queue {
jobs: Mutex::new(VecDeque::new()),
ready: Condvar::new(),
});
for idx in 0..workers {
let q = Arc::clone(&queue);
std::thread::Builder::new()
.name(format!("moonproof-prove-{idx}"))
.spawn(move || {
let rt = match tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
{
Ok(rt) => rt,
Err(e) => {
tracing::error!(
worker = idx,
error = %e,
"proving worker could not build tokio runtime"
);
return;
}
};
loop {
let job = {
let mut guard = q.jobs.lock().expect("proving pool mutex poisoned");
loop {
if let Some(job) = guard.pop_front() {
break job;
}
guard =
q.ready.wait(guard).expect("proving pool condvar poisoned");
}
};
job(&rt);
}
})
.map_err(|e| format!("spawn proving worker {idx}: {e}"))?;
}
Ok(Self { queue })
}
pub fn submit(job: Job) -> Result<(), String> {
let pool = Self::global()?;
let mut guard = pool
.queue
.jobs
.lock()
.map_err(|_| "proving pool mutex poisoned".to_owned())?;
guard.push_back(job);
drop(guard);
pool.queue.ready.notify_one();
Ok(())
}
}
}
#[cfg(not(target_arch = "wasm32"))]
pub async fn prove_offthread<T, F, Fut>(build: F) -> Result<T, ProverError>
where
F: FnOnce() -> Fut + Send + 'static,
Fut: Future<Output = T>,
T: Send + 'static,
{
let (tx, rx) = tokio::sync::oneshot::channel();
pool::ProvingPool::submit(Box::new(move |rt| {
let out = rt.block_on(build());
let _ = tx.send(out);
}))
.map_err(|e| ProverError::Proving(format!("dispatch proving job: {e}")))?;
rx.await
.map_err(|_| ProverError::Proving("proving thread ended without a result".to_owned()))
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn runs_a_non_send_future_and_returns_its_output() {
let out = prove_offthread(|| async {
let local = std::rc::Rc::new(41);
tokio::task::yield_now().await;
*local + 1
})
.await
.unwrap();
assert_eq!(out, 42);
}
#[tokio::test]
async fn propagates_the_inner_result() {
let out: Result<u8, String> =
prove_offthread(|| async { Err("circuit too large".to_owned()) })
.await
.unwrap();
assert_eq!(out, Err("circuit too large".to_owned()));
}
}