use send_wrapper::SendWrapper;
use tokio::sync::OnceCell;
use wasm_bindgen::{prelude::wasm_bindgen, JsValue, UnwrapThrowExt};
use crate::pool::{WebWorkerPool, WorkerPoolOptions};
static WORKER_POOL: OnceCell<SendWrapper<WebWorkerPool>> = OnceCell::const_new();
#[derive(Debug, Clone, Copy)]
pub struct AlreadyInitialized;
impl std::fmt::Display for AlreadyInitialized {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Worker pool has already been initialized")
}
}
impl std::error::Error for AlreadyInitialized {}
impl From<AlreadyInitialized> for JsValue {
fn from(err: AlreadyInitialized) -> Self {
JsValue::from_str(&err.to_string())
}
}
#[wasm_bindgen(js_name = initWorkerPool)]
pub async fn init_worker_pool(options: WorkerPoolOptions) -> Result<(), AlreadyInitialized> {
let pool = SendWrapper::new(
WebWorkerPool::with_options(options)
.await
.expect_throw("Couldn't instantiate worker pool"),
);
WORKER_POOL.set(pool).map_err(|_| AlreadyInitialized)
}
#[wasm_bindgen(js_name = initOptimizedWorkerPool)]
pub async fn init_optimized_worker_pool() -> Result<(), AlreadyInitialized> {
let mut options = WorkerPoolOptions::new();
options.precompile_wasm = Some(true);
init_worker_pool(options).await
}
pub async fn worker_pool() -> &'static WebWorkerPool {
WORKER_POOL
.get_or_init(|| async {
SendWrapper::new(
WebWorkerPool::with_options(WorkerPoolOptions::default())
.await
.expect_throw("Couldn't instantiate worker pool"),
)
})
.await
}
pub fn has_worker_pool() -> bool {
WORKER_POOL.initialized()
}