uci: the engine as a Web Worker in a browser, on the same protocol machine; game-review: the process job is native

On WebAssembly the engine is a Web Worker: a line of UCI is one message each
way, the protocol machine is driven by the worker's messages and by timers set
for its deadlines; the handshake does not block (Engine::start_worker gives a
Starting, polled until readyok). EngineHandle has the same methods as the
process one, minus those that block or name a process. Option and search
checks are shared by both transports.

tests/worker.rs runs the worker transport against a fake engine in JavaScript
in headless Firefox (apps/web/check/uci-worker.mjs: wasm-bindgen-test-runner
serves, a WebDriver BiDi client reads the outcome): handshake, analysis and
stop, coalescing of rapid requests without mixing output, an engine hung on
stop, a crash, and every handshake failure. 5 of 5 pass.

game-review: the job in engine processes (run and its workers) moves to
job/engines.rs, built where there are processes. .cargo/config.toml: the
getrandom backend of WebAssembly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-30 14:29:12 +03:00
parent a66d1016d9
commit 2703e5de38
16 changed files with 1369 additions and 339 deletions

View file

@ -4,12 +4,18 @@ version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
description = "UCI chess engine process supervisor (no UI dependencies)"
description = "UCI chess engine supervisor: a process, or a Web Worker in a browser (no UI dependencies)"
[dependencies]
thiserror.workspace = true
web-time.workspace = true
# The engine as a Web Worker in a browser.
[target.'cfg(target_family = "wasm")'.dependencies]
wasm-bindgen = "0.2.129"
js-sys = "0.3"
web-sys = { version = "0.3", features = ["Worker", "MessageEvent", "ErrorEvent"] }
[target.'cfg(unix)'.dependencies]
# nice(2) for EngineConfig::nice (std has no way to lower a child's priority).
libc = "0.2"
@ -20,3 +26,9 @@ name = "fake_uci"
path = "src/bin/fake_uci.rs"
test = false
doc = false
# tests/worker.rs: the worker transport in a browser (docs/dev/web.md).
[target.'cfg(target_family = "wasm")'.dev-dependencies]
wasm-bindgen-test = "0.3"
wasm-bindgen-futures = "0.4"
web-sys = { version = "0.3", features = ["Window", "Blob", "BlobPropertyBag", "Url"] }

View file

@ -6,7 +6,8 @@
//! feeds the machine. The UI talks to it through the non-blocking
//! [`EngineHandle`] and polls [`EngineEvent`]s every frame; the [`Waker`]
//! callback is invoked after each new event. WebAssembly in a browser has no
//! processes, so there is no process transport there.
//! processes: there the engine is a Web Worker, its handle the same, its start
//! not blocking ([`Engine::start_worker`]).
//!
//! Search boundary: UCI has no request ids. A new `position`/`go` is written
//! only after the previous search ended with `bestmove` and a subsequent
@ -21,15 +22,17 @@ mod events;
pub mod parse;
#[cfg(not(target_family = "wasm"))]
mod process;
// The machine is built where a transport drives it.
#[cfg(not(target_family = "wasm"))]
mod protocol;
mod types;
#[cfg(target_family = "wasm")]
mod worker;
pub use error::EngineError;
pub use events::{EngineEvent, TerminationReason, Waker};
#[cfg(not(target_family = "wasm"))]
pub use process::{Engine, EngineConfig, EngineHandle};
#[cfg(target_family = "wasm")]
pub use worker::{Engine, EngineHandle, Starting, WorkerConfig};
pub use types::{
EngineInfo, EngineOption, EnginePosition, EngineScore, OptionKind, PositionBase, Score,
ScoreBound, SearchId, SearchInfo, SearchLimits, Side, Timeouts, WhiteEval, WhiteScore,

View file

@ -15,8 +15,8 @@ use std::time::{Duration, Instant};
use crate::error::EngineError;
use crate::events::{EngineEvent, TerminationReason, Waker};
use crate::protocol::{Cmd, Exit, Gone, Handshake, HandshakeStep, Link, Session};
use crate::types::{EngineInfo, EnginePosition, OptionKind, SearchId, SearchLimits, Timeouts};
use crate::protocol::{Cmd, Exit, Gone, Handshake, HandshakeStep, Link, Session, option_line};
use crate::types::{EngineInfo, EnginePosition, SearchId, SearchLimits, Timeouts};
/// Maximum stored length of one output line; longer lines are truncated.
const MAX_LINE_BYTES: usize = 64 * 1024;
@ -175,16 +175,7 @@ impl EngineHandle {
limits: SearchLimits,
among: Vec<String>,
) -> Result<(), EngineError> {
position.validate()?;
if let Some(bad) = among.iter().find(|m| !crate::types::is_uci_move(m)) {
return Err(EngineError::InvalidInput(format!("not a move: {bad:?}")));
}
self.send(Cmd::Search {
position,
id: search_id,
limits,
among,
})
self.send(Cmd::search(position, search_id, limits, among)?)
}
/// Stops the running search (its `BestMove` still arrives) and cancels a
@ -198,51 +189,7 @@ impl EngineHandle {
/// search boundary (UCI forbids `setoption` during a search) — to see the
/// effect on the current analysis, call [`Self::analyze`] again.
pub fn set_option(&self, name: &str, value: Option<&str>) -> Result<(), EngineError> {
let opt = self
.info
.option(name)
.ok_or_else(|| EngineError::UnknownOption(name.to_string()))?;
let bad = |reason: String| EngineError::InvalidOptionValue {
name: opt.name.clone(),
reason,
};
if let Some(v) = value
&& v.chars().any(char::is_control)
{
return Err(bad("control characters in value".into()));
}
let value = match (&opt.kind, value) {
(OptionKind::Button, None) => None,
(OptionKind::Button, Some(_)) => return Err(bad("button takes no value".into())),
(_, None) => return Err(bad("value required".into())),
(OptionKind::Check { .. }, Some(v)) => match v {
"true" | "false" => Some(v.to_string()),
_ => return Err(bad(format!("expected true/false, got {v:?}"))),
},
(OptionKind::Spin { min, max, .. }, Some(v)) => {
let n: i64 = v
.trim()
.parse()
.map_err(|_| bad(format!("not an integer: {v:?}")))?;
if min.is_some_and(|m| n < m) || max.is_some_and(|m| n > m) {
return Err(bad(format!("{n} outside {min:?}..={max:?}")));
}
Some(n.to_string())
}
(OptionKind::Combo { vars, .. }, Some(v)) => {
let var = vars
.iter()
.find(|x| x.eq_ignore_ascii_case(v))
.ok_or_else(|| bad(format!("{v:?} is not one of {vars:?}")))?;
Some(var.clone())
}
(OptionKind::String { .. }, Some(v)) => Some(v.to_string()),
};
let line = match value {
Some(v) => format!("setoption name {} value {}", opt.name, v),
None => format!("setoption name {}", opt.name),
};
self.send(Cmd::Setup(line))
self.send(Cmd::Setup(option_line(&self.info, name, value)?))
}
pub fn set_multipv(&self, lines: u32) -> Result<(), EngineError> {

View file

@ -9,7 +9,7 @@ use web_time::Instant;
use crate::error::EngineError;
use crate::events::EngineEvent;
use crate::parse::{EngineLine, parse_line};
use crate::types::{EngineInfo, EnginePosition, SearchId, SearchLimits, Timeouts};
use crate::types::{EngineInfo, EnginePosition, OptionKind, SearchId, SearchLimits, Timeouts};
/// Maximum number of `Warning` events emitted per engine (flood protection).
const MAX_WARNINGS: usize = 100;
@ -27,6 +27,80 @@ pub(crate) enum Cmd {
Setup(String),
}
impl Cmd {
/// A search request, checked: a valid position, UCI moves to search among.
pub(crate) fn search(
position: EnginePosition,
id: SearchId,
limits: SearchLimits,
among: Vec<String>,
) -> Result<Cmd, EngineError> {
position.validate()?;
if let Some(bad) = among.iter().find(|m| !crate::types::is_uci_move(m)) {
return Err(EngineError::InvalidInput(format!("not a move: {bad:?}")));
}
Ok(Cmd::Search {
position,
id,
limits,
among,
})
}
}
/// The `setoption` line for `name` = `value` (`None` for buttons), checked against
/// the options the engine declared.
pub(crate) fn option_line(
info: &EngineInfo,
name: &str,
value: Option<&str>,
) -> Result<String, EngineError> {
let opt = info
.option(name)
.ok_or_else(|| EngineError::UnknownOption(name.to_string()))?;
let bad = |reason: String| EngineError::InvalidOptionValue {
name: opt.name.clone(),
reason,
};
if let Some(v) = value
&& v.chars().any(char::is_control)
{
return Err(bad("control characters in value".into()));
}
let value = match (&opt.kind, value) {
(OptionKind::Button, None) => None,
(OptionKind::Button, Some(_)) => return Err(bad("button takes no value".into())),
(_, None) => return Err(bad("value required".into())),
(OptionKind::Check { .. }, Some(v)) => match v {
"true" | "false" => Some(v.to_string()),
_ => return Err(bad(format!("expected true/false, got {v:?}"))),
},
(OptionKind::Spin { min, max, .. }, Some(v)) => {
let n: i64 = v
.trim()
.parse()
.map_err(|_| bad(format!("not an integer: {v:?}")))?;
if min.is_some_and(|m| n < m) || max.is_some_and(|m| n > m) {
return Err(bad(format!("{n} outside {min:?}..={max:?}")));
}
Some(n.to_string())
}
(OptionKind::Combo { vars, .. }, Some(v)) => {
let var = vars
.iter()
.find(|x| x.eq_ignore_ascii_case(v))
.ok_or_else(|| bad(format!("{v:?} is not one of {vars:?}")))?;
Some(var.clone())
}
(OptionKind::String { .. }, Some(v)) => Some(v.to_string()),
};
let line = match value {
Some(v) => format!("setoption name {} value {}", opt.name, v),
None => format!("setoption name {}", opt.name),
};
Ok(line)
}
/// The engine could not be written to: it is gone.
#[derive(Debug)]
pub(crate) struct Gone;

432
crates/uci/src/worker.rs Normal file
View file

@ -0,0 +1,432 @@
//! The engine as a Web Worker (WebAssembly in a browser, which has no processes):
//! the engine's script runs in the worker, a line of UCI is one message each way,
//! and the protocol ([`crate::protocol`]) is driven by the worker's messages and by
//! timers set for its deadlines. Everything happens on the page's thread, so nothing
//! here blocks: the handshake is finished by the worker's messages and its outcome
//! taken by [`Starting::poll`].
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::{Rc, Weak};
use wasm_bindgen::JsCast;
use wasm_bindgen::prelude::*;
use web_time::Instant;
use crate::error::EngineError;
use crate::events::{EngineEvent, TerminationReason, Waker};
use crate::protocol::{Cmd, Exit, Gone, Handshake, HandshakeStep, Link, Session, option_line};
use crate::types::{EngineInfo, EnginePosition, SearchId, SearchLimits, Timeouts};
#[wasm_bindgen]
extern "C" {
// The global timer functions: a page's and a worker's alike.
#[wasm_bindgen(js_name = setTimeout)]
fn set_timeout(f: &js_sys::Function, ms: f64) -> JsValue;
#[wasm_bindgen(js_name = clearTimeout)]
fn clear_timeout(id: &JsValue);
}
/// How to start an engine in a worker.
#[derive(Debug, Clone)]
pub struct WorkerConfig {
/// The URL of the engine's worker script.
pub script: String,
pub timeouts: Timeouts,
}
impl WorkerConfig {
pub fn new(script: impl Into<String>) -> Self {
WorkerConfig {
script: script.into(),
timeouts: Timeouts::default(),
}
}
}
/// The worker side of the session: the worker itself and the events' queue.
struct Port {
worker: web_sys::Worker,
events: VecDeque<EngineEvent>,
waker: Waker,
}
impl Link for Port {
fn write(&mut self, line: &str) -> Result<(), Gone> {
self.worker
.post_message(&JsValue::from_str(line))
.map_err(|_| Gone)
}
fn emit(&mut self, ev: EngineEvent) {
self.events.push_back(ev);
(self.waker)();
}
}
enum Phase {
Handshake(Handshake),
Running(Session),
Ended,
}
struct Inner {
port: Port,
phase: Phase,
timeouts: Timeouts,
/// The outcome of the handshake until [`Starting::poll`] takes it.
started: Option<Result<EngineInfo, EngineError>>,
/// The timer of the protocol's next deadline.
timer: Option<JsValue>,
/// The worker's handlers and the timer's callback, alive as long as the engine.
callbacks: Vec<Closure<dyn FnMut(JsValue)>>,
on_timer: Option<Closure<dyn FnMut()>>,
}
impl Inner {
fn deadline(&self) -> Option<Instant> {
match &self.phase {
Phase::Handshake(h) => Some(h.deadline()),
Phase::Running(s) => s.deadline(),
Phase::Ended => None,
}
}
/// Sets the timer for the protocol's next deadline (clearing the old one).
fn arm(&mut self) {
if let Some(id) = self.timer.take() {
clear_timeout(&id);
}
let (Some(at), Some(f)) = (self.deadline(), &self.on_timer) else {
return;
};
let ms = at.saturating_duration_since(Instant::now()).as_secs_f64() * 1000.0;
// A millisecond late rather than early: the deadline must have passed.
self.timer = Some(set_timeout(f.as_ref().unchecked_ref(), ms.ceil() + 1.0));
}
fn on_line(&mut self, line: String) {
let now = Instant::now();
match &mut self.phase {
Phase::Handshake(h) => match h.on_line(line, now) {
HandshakeStep::Continue => {}
HandshakeStep::Write(l) => {
if self.port.write(l).is_err() {
self.fail_start(gone(Vec::new()));
}
}
HandshakeStep::Done(info, warnings) => {
let mut session = Session::new(self.timeouts);
for w in warnings {
session.warn(w, &mut self.port);
}
self.phase = Phase::Running(session);
self.started = Some(Ok(info));
(self.port.waker)();
}
},
Phase::Running(s) => {
if let Err(e) = s.on_line(&line, now, &mut self.port) {
self.end(e);
}
}
Phase::Ended => {}
}
self.arm();
}
fn on_cmd(&mut self, cmd: Cmd) -> Result<(), EngineError> {
let Phase::Running(s) = &mut self.phase else {
return Err(EngineError::NotRunning);
};
if let Err(e) = s.on_cmd(cmd, Instant::now(), &mut self.port) {
self.end(e);
}
self.arm();
Ok(())
}
fn on_timer(&mut self) {
self.timer = None;
let now = Instant::now();
match &mut self.phase {
Phase::Handshake(h) if now >= h.deadline() => {
let Phase::Handshake(h) = std::mem::replace(&mut self.phase, Phase::Ended) else {
unreachable!("matched above");
};
self.port.worker.terminate();
self.started = Some(Err(h.timed_out()));
(self.port.waker)();
}
Phase::Running(s) => {
if let Err(e) = s.on_time(now) {
self.end(e);
}
}
Phase::Handshake(_) | Phase::Ended => {}
}
self.arm();
}
/// The worker reported an error: its script did not load or the engine failed.
fn on_error(&mut self, message: String) {
match self.phase {
Phase::Handshake(_) => self.fail_start(gone(vec![message])),
Phase::Running(_) => self.end(Exit::Gone),
Phase::Ended => {}
}
self.arm();
}
fn fail_start(&mut self, e: EngineError) {
self.port.worker.terminate();
self.phase = Phase::Ended;
self.started = Some(Err(e));
(self.port.waker)();
}
/// The session ended on its own; the worker is stopped.
fn end(&mut self, exit: Exit) {
self.port.worker.terminate();
self.phase = Phase::Ended;
let reason = match exit {
Exit::Hung(waiting_for) => TerminationReason::Hung { waiting_for },
Exit::Gone => TerminationReason::Exited { status: None },
};
self.port.emit(EngineEvent::Terminated(reason));
}
fn quit(&mut self) {
if let Phase::Running(s) = &mut self.phase {
s.quit(&mut self.port);
self.port.worker.terminate();
self.phase = Phase::Ended;
self.port
.emit(EngineEvent::Terminated(TerminationReason::Quit { status: None }));
} else {
self.port.worker.terminate();
self.phase = Phase::Ended;
}
self.arm();
self.port.worker.set_onmessage(None);
self.port.worker.set_onerror(None);
}
}
fn gone(stderr: Vec<String>) -> EngineError {
EngineError::ProcessExited {
status: None,
stderr,
}
}
/// An engine whose handshake is under way.
pub struct Starting {
inner: Option<Rc<RefCell<Inner>>>,
}
impl Starting {
/// The engine once its handshake is over (`None`: not yet). After a result it
/// keeps returning `None`.
pub fn poll(&mut self) -> Option<Result<EngineHandle, EngineError>> {
let started = self.inner.as_ref()?.borrow_mut().started.take()?;
let inner = self.inner.take()?;
Some(started.map(|info| EngineHandle { info, inner }))
}
}
impl Drop for Starting {
fn drop(&mut self) {
if let Some(inner) = self.inner.take() {
inner.borrow_mut().quit();
}
}
}
/// Namespace for starting engines.
pub struct Engine;
impl Engine {
/// Starts the engine of `cfg.script` in a new worker, and its handshake. The
/// worker's events wake the UI through `waker`; [`Starting::poll`] gives the
/// engine once it answered `readyok`.
pub fn start_worker(cfg: WorkerConfig, waker: Waker) -> Result<Starting, EngineError> {
start(cfg, waker)
}
}
fn start(cfg: WorkerConfig, waker: Waker) -> Result<Starting, EngineError> {
let script_error = |e: JsValue| {
EngineError::Spawn(std::io::Error::other(
e.as_string()
.unwrap_or_else(|| format!("cannot start the worker {}", cfg.script)),
))
};
let worker = web_sys::Worker::new(&cfg.script).map_err(script_error)?;
let inner = Rc::new(RefCell::new(Inner {
port: Port {
worker: worker.clone(),
events: VecDeque::new(),
waker,
},
phase: Phase::Handshake(Handshake::new(&cfg.timeouts, Instant::now())),
timeouts: cfg.timeouts,
started: None,
timer: None,
callbacks: Vec::new(),
on_timer: None,
}));
let weak = Rc::downgrade(&inner);
let with = move |f: &dyn Fn(&mut Inner)| {
if let Some(inner) = Weak::upgrade(&weak) {
f(&mut inner.borrow_mut());
}
};
let on_message = {
let with = with.clone();
Closure::<dyn FnMut(JsValue)>::new(move |ev: JsValue| {
let data = ev.unchecked_into::<web_sys::MessageEvent>().data();
// A message is a line; some builds join several with `\n`.
let text = data.as_string().unwrap_or_default();
with(&|inner| {
for line in text.lines() {
inner.on_line(line.to_owned());
}
});
})
};
let on_error = {
let with = with.clone();
Closure::<dyn FnMut(JsValue)>::new(move |ev: JsValue| {
let message = ev
.dyn_ref::<web_sys::ErrorEvent>()
.map(web_sys::ErrorEvent::message)
.unwrap_or_else(|| "the engine's worker failed".into());
with(&|inner| inner.on_error(message.clone()));
})
};
let on_timer = Closure::<dyn FnMut()>::new(move || with(&|inner| inner.on_timer()));
worker.set_onmessage(Some(on_message.as_ref().unchecked_ref()));
worker.set_onerror(Some(on_error.as_ref().unchecked_ref()));
{
let mut i = inner.borrow_mut();
i.callbacks = vec![on_message, on_error];
i.on_timer = Some(on_timer);
if i.port.write(Handshake::FIRST_LINE).is_err() {
i.fail_start(gone(Vec::new()));
}
i.arm();
}
Ok(Starting { inner: Some(inner) })
}
/// Handle owned by the UI. Dropping it quits the engine (its worker is stopped).
pub struct EngineHandle {
info: EngineInfo,
inner: Rc<RefCell<Inner>>,
}
impl std::fmt::Debug for EngineHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("EngineHandle")
.field("name", &self.info.name)
.field("alive", &self.is_running())
.finish()
}
}
impl EngineHandle {
/// `id name/author` and declared options from the handshake.
pub fn info(&self) -> &EngineInfo {
&self.info
}
/// `false` after the engine terminated (quit, crash, hung).
pub fn is_running(&self) -> bool {
matches!(self.inner.borrow().phase, Phase::Running(_))
}
/// Non-blocking poll for the next event (call every frame).
pub fn try_recv(&self) -> Option<EngineEvent> {
self.inner.borrow_mut().port.events.pop_front()
}
/// Drains all currently queued events.
pub fn drain_events(&self) -> impl Iterator<Item = EngineEvent> + '_ {
std::iter::from_fn(|| self.try_recv())
}
/// Infinite analysis (`go infinite`) of `position` under `search_id`.
pub fn analyze(
&self,
position: EnginePosition,
search_id: SearchId,
) -> Result<(), EngineError> {
self.search(position, search_id, SearchLimits::Infinite)
}
/// Requests a search: a running search is stopped first and only the latest
/// request is started.
pub fn search(
&self,
position: EnginePosition,
search_id: SearchId,
limits: SearchLimits,
) -> Result<(), EngineError> {
self.search_among(position, search_id, limits, Vec::new())
}
/// A search among these moves only (UCI moves of `position`); empty: all.
pub fn search_among(
&self,
position: EnginePosition,
search_id: SearchId,
limits: SearchLimits,
among: Vec<String>,
) -> Result<(), EngineError> {
let cmd = Cmd::search(position, search_id, limits, among)?;
self.inner.borrow_mut().on_cmd(cmd)
}
/// Stops the running search (its `BestMove` still arrives) and cancels a
/// queued one.
pub fn stop(&self) -> Result<(), EngineError> {
self.inner.borrow_mut().on_cmd(Cmd::Stop)
}
/// `setoption`, checked against the declared options; applied at the next
/// search boundary when a search runs.
pub fn set_option(&self, name: &str, value: Option<&str>) -> Result<(), EngineError> {
let line = option_line(&self.info, name, value)?;
self.inner.borrow_mut().on_cmd(Cmd::Setup(line))
}
pub fn set_multipv(&self, lines: u32) -> Result<(), EngineError> {
self.set_option("MultiPV", Some(&lines.to_string()))
}
pub fn set_threads(&self, threads: u32) -> Result<(), EngineError> {
self.set_option("Threads", Some(&threads.to_string()))
}
pub fn set_hash_mb(&self, mb: u32) -> Result<(), EngineError> {
self.set_option("Hash", Some(&mb.to_string()))
}
/// `ucinewgame` (applied at the next idle point, followed by `isready`).
pub fn new_game(&self) -> Result<(), EngineError> {
self.inner
.borrow_mut()
.on_cmd(Cmd::Setup("ucinewgame".into()))
}
/// Sends `stop`/`quit` and stops the worker at once (a worker needs no grace
/// time: nothing of it outlives `terminate`).
pub fn quit(self) {}
}
impl Drop for EngineHandle {
fn drop(&mut self) {
self.inner.borrow_mut().quit();
}
}

View file

@ -1,4 +1,6 @@
//! Supervisor tests against the deterministic fake engine (src/bin/fake_uci.rs).
// The process transport.
#![cfg(not(target_family = "wasm"))]
use std::collections::{HashMap, HashSet};
use std::path::Path;

View file

@ -1,6 +1,8 @@
//! Integration test with a real Stockfish binary. Ignored by default.
//!
//! Run: UCI_STOCKFISH=/path/to/stockfish cargo test -p uci --test stockfish -- --ignored
// The process transport.
#![cfg(not(target_family = "wasm"))]
use std::collections::BTreeMap;
use std::time::{Duration, Instant};

272
crates/uci/tests/worker.rs Normal file
View file

@ -0,0 +1,272 @@
//! The worker transport against a fake engine written in JavaScript, in a browser
//! (`docs/dev/web.md`, «Проверки»: wasm-bindgen-test-runner with headless Firefox).
//!
//! The fake engine answers like `src/bin/fake_uci.rs` in the points that matter
//! here: the first PV move of a search is the marker of its position (the first
//! FEN field), info lines come every few milliseconds until `stop`, and flags make
//! it hang, crash or stay silent.
#![cfg(target_family = "wasm")]
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::Duration;
use uci::{
Engine, EngineError, EngineEvent, EngineHandle, EnginePosition, SearchId, SearchLimits,
Starting, TerminationReason, Timeouts, WorkerConfig,
};
use wasm_bindgen::prelude::*;
use wasm_bindgen_test::*;
wasm_bindgen_test_configure!(run_in_browser);
const FAKE: &str = r#"
let searching = null, timer = null, marker = 'startpos', n = 0;
const send = (l) => postMessage(l);
function stopSearch() {
if (searching === null) return;
clearInterval(timer); timer = null;
const m = searching; searching = null;
if (FLAGS.hangOnStop) return;
send('info depth 9 score cp 1 pv ' + m);
send('bestmove ' + m);
}
onmessage = (e) => {
const line = String(e.data), w = line.split(' ');
switch (w[0]) {
case 'uci':
if (FLAGS.silent) return;
send('id name Fake Worker'); send('id author Test Suite');
send('option name MultiPV type spin default 1 min 1 max 10');
send('option name Hash type spin default 16 min 1 max 1024');
if (!FLAGS.noUciok) send('uciok');
break;
case 'isready': if (!FLAGS.noReadyok) send('readyok'); break;
case 'position':
if (w[1] === 'fen') marker = w[2];
else { const i = w.indexOf('moves'); marker = i > 0 && w.length > i + 1 ? w[w.length - 1] : 'startpos'; }
break;
case 'go':
if (FLAGS.crashOnGo) throw new Error('fake engine crashed');
searching = marker; n = 0;
if (w[1] === 'nodes') { send('info depth 1 score cp 3 nodes ' + w[2] + ' pv ' + marker); stopSearch(); break; }
timer = setInterval(() => { n++; send('info depth ' + n + ' score cp ' + n + ' pv ' + searching); }, 5);
break;
case 'stop': stopSearch(); break;
case 'quit': close(); break;
}
};
"#;
/// A worker script of the fake engine with these flags (a `blob:` URL).
fn fake(flags: &str) -> String {
let source = format!("const FLAGS = {{{flags}}};\n{FAKE}");
let parts = js_sys::Array::of1(&JsValue::from_str(&source));
let opts = web_sys::BlobPropertyBag::new();
opts.set_type("text/javascript");
let blob = web_sys::Blob::new_with_str_sequence_and_options(&parts, &opts).unwrap();
web_sys::Url::create_object_url_with_blob(&blob).unwrap()
}
fn timeouts() -> Timeouts {
Timeouts {
uciok: Duration::from_millis(1500),
readyok: Duration::from_millis(1500),
stop: Duration::from_millis(500),
quit: Duration::from_millis(500),
}
}
async fn sleep(ms: i32) {
let promise = js_sys::Promise::new(&mut |resolve, _| {
web_sys::window()
.unwrap()
.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms)
.unwrap();
});
wasm_bindgen_futures::JsFuture::from(promise).await.unwrap();
}
/// Starts the fake engine and waits for its handshake; also counts the waker's calls.
async fn start(flags: &str) -> (Result<EngineHandle, EngineError>, u32) {
let woke = Arc::new(AtomicU32::new(0));
let w = Arc::clone(&woke);
let mut config = WorkerConfig::new(fake(flags));
config.timeouts = timeouts();
let mut starting: Starting = Engine::start_worker(
config,
Box::new(move || {
w.fetch_add(1, Ordering::Relaxed);
}),
)
.expect("worker created");
for _ in 0..400 {
if let Some(r) = starting.poll() {
return (r, woke.load(Ordering::Relaxed));
}
sleep(10).await;
}
panic!("the handshake neither ended nor timed out");
}
/// Events until `pred` holds for one (inclusive), or `ms` pass.
async fn until(h: &EngineHandle, ms: u32, pred: impl Fn(&EngineEvent) -> bool) -> Vec<EngineEvent> {
let mut out = Vec::new();
for _ in 0..ms / 5 {
while let Some(ev) = h.try_recv() {
let hit = pred(&ev);
out.push(ev);
if hit {
return out;
}
}
sleep(5).await;
}
panic!("no expected event in {ms} ms: {out:?}");
}
fn fen(marker: &str) -> EnginePosition {
EnginePosition::fen(format!("{marker} w - - 0 1"), Vec::<String>::new())
}
#[wasm_bindgen_test]
async fn handshake_then_analysis_and_stop() {
let (h, woke) = start("").await;
let h = h.expect("started");
assert_eq!(h.info().name.as_deref(), Some("Fake Worker"));
assert_eq!(h.info().options.len(), 2);
assert!(woke > 0,"the waker was not called");
h.set_multipv(2).unwrap();
assert!(matches!(
h.set_multipv(11),
Err(EngineError::InvalidOptionValue { .. })
));
h.analyze(fen("m1"), SearchId(1)).unwrap();
let evs = until(&h, 2000, |e| matches!(e, EngineEvent::Info { .. })).await;
assert!(evs.contains(&EngineEvent::SearchStarted {
search_id: SearchId(1)
}));
h.stop().unwrap();
let evs = until(&h, 2000, |e| matches!(e, EngineEvent::BestMove { .. })).await;
match evs.last() {
Some(EngineEvent::BestMove {
search_id, best, ..
}) => {
assert_eq!(*search_id, SearchId(1));
assert_eq!(best.as_deref(), Some("m1"));
}
other => panic!("{other:?}"),
}
assert!(h.is_running());
}
#[wasm_bindgen_test]
async fn rapid_requests_start_only_the_latest_and_never_mix_output() {
let (h, _) = start("").await;
let h = h.expect("started");
h.analyze(fen("a"), SearchId(1)).unwrap();
until(&h, 2000, |e| matches!(e, EngineEvent::Info { .. })).await;
for (id, m) in [(2, "b"), (3, "c"), (4, "d")] {
h.analyze(fen(m), SearchId(id)).unwrap();
}
let evs = until(&h, 3000, |e| {
matches!(e, EngineEvent::Info { search_id: SearchId(4), .. })
})
.await;
for id in [2, 3] {
assert!(evs.contains(&EngineEvent::Superseded {
search_id: SearchId(id)
}));
assert!(!evs.contains(&EngineEvent::SearchStarted {
search_id: SearchId(id)
}));
}
for e in &evs {
if let EngineEvent::Info { search_id, info } = e {
let want = if *search_id == SearchId(1) { "a" } else { "d" };
assert_eq!(info.pv.first().map(String::as_str), Some(want), "{e:?}");
}
}
// A node-limited search ends by itself.
h.search(fen("n"), SearchId(5), SearchLimits::Nodes(1000))
.unwrap();
let evs = until(&h, 2000, |e| {
matches!(e, EngineEvent::BestMove { search_id: SearchId(5), .. })
})
.await;
assert!(matches!(evs.last(), Some(EngineEvent::BestMove { best: Some(b), .. }) if b == "n"));
}
#[wasm_bindgen_test]
async fn an_engine_hung_on_stop_is_terminated() {
let (h, _) = start("hangOnStop: true").await;
let h = h.expect("started");
h.analyze(fen("h"), SearchId(1)).unwrap();
until(&h, 2000, |e| matches!(e, EngineEvent::Info { .. })).await;
h.stop().unwrap();
let evs = until(&h, 3000, |e| matches!(e, EngineEvent::Terminated(_))).await;
assert_eq!(
evs.last(),
Some(&EngineEvent::Terminated(TerminationReason::Hung {
waiting_for: "bestmove"
}))
);
assert!(!h.is_running());
assert!(matches!(h.stop(), Err(EngineError::NotRunning)));
}
#[wasm_bindgen_test]
async fn a_crash_ends_the_session() {
let (h, _) = start("crashOnGo: true").await;
let h = h.expect("started");
h.analyze(fen("x"), SearchId(1)).unwrap();
let evs = until(&h, 3000, |e| matches!(e, EngineEvent::Terminated(_))).await;
assert_eq!(
evs.last(),
Some(&EngineEvent::Terminated(TerminationReason::Exited {
status: None
}))
);
}
#[wasm_bindgen_test]
async fn handshake_failures_are_named() {
let (silent, _) = start("silent: true").await;
assert!(matches!(silent, Err(EngineError::NotUci { .. })), "{silent:?}");
let (no_uciok, _) = start("noUciok: true").await;
assert!(
matches!(
no_uciok,
Err(EngineError::HandshakeTimeout {
waiting_for: "uciok"
})
),
"{no_uciok:?}"
);
let (no_readyok, _) = start("noReadyok: true").await;
assert!(
matches!(
no_readyok,
Err(EngineError::HandshakeTimeout {
waiting_for: "readyok"
})
),
"{no_readyok:?}"
);
// A script that does not load.
let mut config = WorkerConfig::new("/no-such-engine.js");
config.timeouts = timeouts();
let mut starting = Engine::start_worker(config, Box::new(|| {})).expect("worker created");
let mut result = None;
for _ in 0..400 {
result = starting.poll();
if result.is_some() {
break;
}
sleep(10).await;
}
assert!(
matches!(result, Some(Err(EngineError::ProcessExited { .. }))),
"{result:?}"
);
}