repositories / smith
smith
There are many coding harnesses - but this one is fast
owned by admin
smith-harness/src/wasm/kernel.rs
Raw//! Shared synchronous kernel interruption (`SMH-SPEC-PLUG0001`).
use super::{Engine, Result, plugin_fault};
use std::time::{Duration, Instant};
pub(super) struct Watchdog {
stop: Option<std::sync::mpsc::SyncSender<()>>,
worker: Option<std::thread::JoinHandle<()>>,
}
impl Watchdog {
pub(super) fn start(
engine: Engine,
cancel: smith::tool::CancelHandle,
deadline: Instant,
) -> Result<Self> {
Self::start_mode(engine, cancel, deadline, true)
}
pub(super) fn boundary(
engine: Engine,
cancel: smith::tool::CancelHandle,
deadline: Instant,
) -> Result<Self> {
Self::start_mode(engine, cancel, deadline, false)
}
fn start_mode(
engine: Engine,
cancel: smith::tool::CancelHandle,
deadline: Instant,
cancel_on_deadline: bool,
) -> Result<Self> {
let allocation = smith_alloc::AllocationGroup::current();
let (stop, receiver) = std::sync::mpsc::sync_channel(1);
let worker = std::thread::Builder::new()
.name("smith-plugin-deadline".into())
.spawn(move || {
let _allocation = allocation.as_ref().map(smith_alloc::AllocationGroup::enter);
while matches!(
receiver.recv_timeout(Duration::from_millis(5)),
Err(std::sync::mpsc::RecvTimeoutError::Timeout)
) {
if cancel_on_deadline && Instant::now() >= deadline {
cancel.cancel();
}
engine.increment_epoch();
}
})
.map_err(|error| plugin_fault(format!("composition watchdog: {error}")))?;
Ok(Self {
stop: Some(stop),
worker: Some(worker),
})
}
}
impl Drop for Watchdog {
fn drop(&mut self) {
if let Some(stop) = self.stop.take() {
let _closed = stop.send(());
}
if let Some(worker) = self.worker.take() {
let _joined = worker.join();
}
}
}