use std::cell::Cell;
use std::rc::{Rc, Weak};
use std::sync::Arc;
use std::time::Duration;
use mln_engine::exec::pool::Pool;
use mln_style::time::Instant;
use wasm_bindgen::prelude::*;
const SLICE: Duration = Duration::from_millis(4);
type StepFn = Box<dyn FnMut() -> bool>;
struct Entry {
#[expect(clippy::disallowed_types, reason = "single-threaded wasm32 pump step closure")]
run: std::cell::RefCell<StepFn>,
live: Cell<bool>,
}
struct Pump {
channel: Option<web_sys::MessageChannel>,
scheduled: Cell<bool>,
running: Cell<bool>,
stopped: Cell<bool>,
pool_time: Cell<Duration>,
#[expect(clippy::disallowed_types, reason = "single-threaded wasm32 pump step list")]
steps: std::cell::RefCell<Vec<Rc<Entry>>>,
#[expect(clippy::disallowed_types, reason = "single-threaded wasm32 pump pool list")]
pools: std::cell::RefCell<Vec<Rc<Pool>>>,
timeout: Cell<Option<(Instant, JsValue)>>,
_on_message: Closure<dyn FnMut()>,
on_timeout: Closure<dyn FnMut()>,
}
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_name = setTimeout)]
fn set_timeout(handler: &js_sys::Function, delay: i32) -> JsValue;
#[wasm_bindgen(js_name = clearTimeout)]
fn clear_timeout(id: &JsValue);
}
thread_local! {
static PUMP: Rc<Pump> = Pump::new();
}
impl Pump {
fn new() -> Rc<Pump> {
Rc::new_cyclic(|pump: &Weak<Pump>| {
let channel = web_sys::MessageChannel::new()
.inspect_err(|error| {
web_sys::console::error_2(&JsValue::from_str("the pump has no MessageChannel:"), error);
})
.ok();
let weak = Weak::clone(pump);
let on_message = Closure::<dyn FnMut()>::new(move || {
if let Some(pump) = weak.upgrade() {
pump.run_slice();
}
});
let weak = Weak::clone(pump);
let on_timeout = Closure::<dyn FnMut()>::new(move || {
if let Some(pump) = weak.upgrade() {
pump.timeout.take();
pump.wake();
}
});
if let Some(channel) = &channel {
channel.port1().set_onmessage(Some(on_message.as_ref().unchecked_ref()));
}
Pump {
channel,
scheduled: Cell::new(false),
running: Cell::new(false),
stopped: Cell::new(false),
pool_time: Cell::new(Duration::ZERO),
#[expect(clippy::disallowed_types, reason = "single-threaded wasm32 pump step list")]
steps: std::cell::RefCell::new(Vec::new()),
#[expect(clippy::disallowed_types, reason = "single-threaded wasm32 pump pool list")]
pools: std::cell::RefCell::new(Vec::new()),
timeout: Cell::new(None),
_on_message: on_message,
on_timeout,
}
})
}
fn wake(&self) {
if let Some(channel) = &self.channel
&& !self.stopped.get()
&& !self.scheduled.replace(true)
{
let _ = channel.port2().post_message(&JsValue::NULL);
}
}
fn wake_at(&self, deadline: Instant) {
if self.stopped.get() {
return;
}
match self.timeout.take() {
Some(armed) if armed.0 <= deadline => {
self.timeout.set(Some(armed));
return;
}
Some((_, id)) => clear_timeout(&id),
None => {}
}
let delay = deadline.saturating_duration_since(Instant::now()).as_micros().div_ceil(1000);
let delay = i32::try_from(delay).unwrap_or(i32::MAX);
self.timeout.set(Some((deadline, set_timeout(self.on_timeout.as_ref().unchecked_ref(), delay))));
}
fn run_slice(&self) {
self.scheduled.set(false);
if self.stopped.get() || self.running.replace(true) {
return;
}
let deadline = Instant::now() + SLICE;
self.run_steps();
let tasks = Instant::now();
let more = self.run_tasks(deadline);
self.pool_time.set(self.pool_time.get() + tasks.elapsed());
self.run_steps();
self.running.set(false);
if more {
self.wake();
}
}
fn run_tasks(&self, deadline: Instant) -> bool {
let pools: Vec<Rc<Pool>> = self.pools.try_borrow().map(|pools| pools.clone()).unwrap_or_default();
let mut more = false;
for pool in pools {
more |= pool.run_until(|| Instant::now() >= deadline);
}
more
}
fn run_steps(&self) {
let steps: Vec<Rc<Entry>> = self.steps.borrow().clone();
for entry in steps {
let Ok(mut run) = entry.run.try_borrow_mut() else { continue };
if entry.live.get() && !run() {
entry.live.set(false);
}
}
self.steps.borrow_mut().retain(|entry| entry.live.get());
}
}
#[must_use = "the step stops when its guard drops"]
pub struct Step {
entry: Option<Rc<Entry>>,
}
impl Step {
pub fn detach(mut self) {
self.entry = None;
}
}
impl Drop for Step {
fn drop(&mut self) {
if let Some(entry) = self.entry.take() {
entry.live.set(false);
let _ = PUMP.try_with(|pump| {
if let Ok(mut steps) = pump.steps.try_borrow_mut() {
steps.retain(|other| !Rc::ptr_eq(other, &entry));
}
});
}
}
}
pub fn add(step: impl FnMut() -> bool + 'static) -> Step {
#[expect(clippy::disallowed_types, reason = "single-threaded wasm32 pump step closure")]
let entry = Rc::new(Entry { run: std::cell::RefCell::new(Box::new(step)), live: Cell::new(true) });
PUMP.with(|pump| {
pump.steps.borrow_mut().push(Rc::clone(&entry));
pump.wake();
});
Step { entry: Some(entry) }
}
#[must_use = "the pool stops running when its guard drops"]
pub fn add_pool(pool: Pool) -> PoolGuard {
let pool = Rc::new(pool);
PUMP.with(|pump| {
if let Ok(mut pools) = pump.pools.try_borrow_mut() {
pools.push(Rc::clone(&pool));
}
pump.wake();
});
PoolGuard { pool }
}
pub struct PoolGuard {
pool: Rc<Pool>,
}
impl Drop for PoolGuard {
fn drop(&mut self) {
let _ = PUMP.try_with(|pump| {
if let Ok(mut pools) = pump.pools.try_borrow_mut() {
pools.retain(|other| !Rc::ptr_eq(other, &self.pool));
}
});
}
}
pub fn wake() {
PUMP.with(|pump| pump.wake());
}
pub fn wake_at(deadline: Instant) {
PUMP.with(|pump| pump.wake_at(deadline));
}
#[must_use]
pub fn waker() -> Arc<dyn Fn() + Send + Sync> {
Arc::new(wake)
}
#[must_use]
pub fn take_pool_time() -> Duration {
PUMP.with(|pump| pump.pool_time.take())
}
#[wasm_bindgen(js_name = mlnWebStopPump)]
pub fn stop() {
PUMP.with(|pump| {
pump.stopped.set(true);
if let Some((_, id)) = pump.timeout.take() {
clear_timeout(&id);
}
});
}