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

@ -2,3 +2,8 @@
# without the Visual C++ Redistributable (VCRUNTIME140.dll). # without the Visual C++ Redistributable (VCRUNTIME140.dll).
[target.x86_64-pc-windows-msvc] [target.x86_64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static"] rustflags = ["-C", "target-feature=+crt-static"]
# WebAssembly in a browser: random numbers from crypto.getRandomValues (getrandom 0.3
# needs this as well as its `wasm_js` feature, enabled by apps/web).
[target.wasm32-unknown-unknown]
rustflags = ["--cfg", "getrandom_backend=\"wasm_js\""]

75
Cargo.lock generated
View file

@ -716,6 +716,12 @@ dependencies = [
"thiserror 2.0.21", "thiserror 2.0.21",
] ]
[[package]]
name = "cast"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
[[package]] [[package]]
name = "cc" name = "cc"
version = "1.8.0" version = "1.8.0"
@ -2445,6 +2451,16 @@ dependencies = [
"unicase", "unicase",
] ]
[[package]]
name = "minicov"
version = "0.3.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4869b6a491569605d66d3952bcdf03df789e5b536e5f0cf7758a7f08a55ae24d"
dependencies = [
"cc",
"walkdir",
]
[[package]] [[package]]
name = "minimal-lexical" name = "minimal-lexical"
version = "0.2.1" version = "0.2.1"
@ -2619,6 +2635,15 @@ dependencies = [
"winapi", "winapi",
] ]
[[package]]
name = "nu-ansi-term"
version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [
"windows-sys 0.61.2",
]
[[package]] [[package]]
name = "num-bigint" name = "num-bigint"
version = "0.4.8" version = "0.4.8"
@ -3080,6 +3105,12 @@ dependencies = [
"ureq", "ureq",
] ]
[[package]]
name = "oorandom"
version = "11.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
[[package]] [[package]]
name = "option-ext" name = "option-ext"
version = "0.2.0" version = "0.2.0"
@ -4678,8 +4709,13 @@ checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
name = "uci" name = "uci"
version = "2.1.1" version = "2.1.1"
dependencies = [ dependencies = [
"js-sys",
"libc", "libc",
"thiserror 2.0.21", "thiserror 2.0.21",
"wasm-bindgen",
"wasm-bindgen-futures",
"wasm-bindgen-test",
"web-sys",
"web-time", "web-time",
] ]
@ -5051,6 +5087,45 @@ dependencies = [
"unicode-ident", "unicode-ident",
] ]
[[package]]
name = "wasm-bindgen-test"
version = "0.3.79"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae7499dfd45780a0a91d7ee6bb9ac51970a4479a41a89da443fdda5a39547d42"
dependencies = [
"async-trait",
"cast",
"js-sys",
"libm",
"minicov",
"nu-ansi-term",
"num-traits",
"oorandom",
"serde",
"serde_json",
"wasm-bindgen",
"wasm-bindgen-futures",
"wasm-bindgen-test-macro",
"wasm-bindgen-test-shared",
]
[[package]]
name = "wasm-bindgen-test-macro"
version = "0.3.79"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b84b5ac638bfb168196a1a461fcc8f46a294a18b1b6be52133b4e0db122cc9f"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "wasm-bindgen-test-shared"
version = "0.2.129"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f692aa943ccd88363733b77063f32cfed5bc6cbea8e6e8b251b302f881606fe"
[[package]] [[package]]
name = "wayland-backend" name = "wayland-backend"
version = "0.3.17" version = "0.3.17"

78
apps/web/check/bidi.mjs Normal file
View file

@ -0,0 +1,78 @@
// A minimal WebDriver BiDi client for headless Firefox (Node 22+: global WebSocket).
// Used by the web checks (docs/dev/web.md, «Проверки»); no windows are opened.
export async function connect(port) {
const ws = new WebSocket(`ws://127.0.0.1:${port}/session`);
let id = 0;
const pending = new Map();
const listeners = [];
ws.onmessage = (m) => {
const d = JSON.parse(m.data);
if (d.id && pending.has(d.id)) {
const p = pending.get(d.id);
pending.delete(d.id);
if (d.type === 'error') p.rej(new Error(`${d.error}: ${d.message}`));
else p.res(d.result);
} else if (d.method) {
for (const l of listeners) l(d.method, d.params);
}
};
await new Promise((res, rej) => {
ws.onopen = res;
ws.onerror = () => rej(new Error('cannot connect to Firefox'));
});
const send = (method, params) =>
new Promise((res, rej) => {
const i = ++id;
pending.set(i, { res, rej });
ws.send(JSON.stringify({ id: i, method, params }));
});
await send('session.new', { capabilities: {} });
return {
send,
on: (f) => listeners.push(f),
close: async () => {
await send('session.end', {}).catch(() => {});
ws.close();
},
};
}
export const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// A tab of `width`×`height` CSS pixels with the console forwarded to `log`.
export async function tab(b, width, height, log = console.log) {
await b.send('session.subscribe', { events: ['log.entryAdded'] });
b.on((method, p) => {
if (method === 'log.entryAdded') log(`[${p.level}] ${p.text}`);
});
const { context } = await b.send('browsingContext.create', { type: 'tab' });
await b.send('browsingContext.setViewport', { context, viewport: { width, height } });
const evaluate = async (expression) => {
const r = await b.send('script.evaluate', {
expression,
target: { context },
awaitPromise: true,
});
if (r.type === 'exception') throw new Error(r.exceptionDetails?.text || 'script failed');
return r.result?.value;
};
return {
context,
evaluate,
navigate: (url) => b.send('browsingContext.navigate', { context, url, wait: 'complete' }),
screenshot: async () =>
Buffer.from((await b.send('browsingContext.captureScreenshot', { context })).data, 'base64'),
actions: (actions) => b.send('input.performActions', { context, actions }),
// Waits until `expression` is truthy (polled), or throws after `ms`.
waitFor: async (expression, ms = 10000) => {
const end = Date.now() + ms;
for (;;) {
const v = await evaluate(expression).catch(() => undefined);
if (v) return v;
if (Date.now() > end) throw new Error(`timed out waiting for ${expression}`);
await sleep(100);
}
},
};
}

View file

@ -0,0 +1,51 @@
// Starts a headless Firefox with a temporary profile and WebDriver BiDi; stops it by
// its PID. No window is ever shown (MOZ_HEADLESS).
import { spawn } from 'node:child_process';
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { connect, sleep } from './bidi.mjs';
export async function launch(port = 19222) {
const profile = mkdtempSync(join(process.env.TMPDIR || tmpdir(), 'cp-firefox-'));
writeFileSync(
join(profile, 'user.js'),
[
'user_pref("remote.active-protocols", 1);',
'user_pref("browser.shell.checkDefaultBrowser", false);',
'user_pref("datareporting.policy.dataSubmissionEnabled", false);',
'user_pref("toolkit.telemetry.reportingpolicy.firstRun", false);',
// Downloads go to the profile without asking.
'user_pref("browser.download.folderList", 2);',
`user_pref("browser.download.dir", "${join(profile, 'downloads')}");`,
'user_pref("browser.download.useDownloadDir", true);',
'user_pref("browser.download.always_ask_before_handling_new_types", false);',
'',
].join('\n'),
);
const log = join(profile, 'firefox.log');
const out = (await import('node:fs')).openSync(log, 'a');
const ff = spawn(
'firefox',
['--headless', '--no-remote', '--profile', profile, '--remote-debugging-port', String(port), 'about:blank'],
{ env: { ...process.env, MOZ_HEADLESS: '1' }, stdio: ['ignore', out, out] },
);
for (let i = 0; i < 100; i++) {
if (readFileSync(log, 'utf8').includes('WebDriver BiDi listening')) break;
await sleep(100);
}
const browser = await connect(port);
return {
browser,
profile,
downloads: join(profile, 'downloads'),
stop: async () => {
await browser.close().catch(() => {});
try {
process.kill(ff.pid);
} catch {}
await sleep(300);
rmSync(profile, { recursive: true, force: true });
},
};
}

View file

@ -0,0 +1,60 @@
// The tests of uci's worker transport (crates/uci/tests/worker.rs) in headless
// Firefox. wasm-bindgen-test-runner serves them (NO_HEADLESS: it does not look for a
// WebDriver) and this script opens its page and reads the outcome.
//
// node apps/web/check/uci-worker.mjs
//
// Needs wasm-bindgen-test-runner of the wasm-bindgen version in Cargo.lock in PATH
// or in WASM_BINDGEN_TEST_RUNNER.
import { spawn } from 'node:child_process';
import { launch } from './firefox.mjs';
import { sleep, tab } from './bidi.mjs';
const runner = process.env.WASM_BINDGEN_TEST_RUNNER || 'wasm-bindgen-test-runner';
const address = '127.0.0.1:18731';
const cargo = spawn(
'cargo',
['test', '-p', 'uci', '--target', 'wasm32-unknown-unknown', '--test', 'worker'],
{
env: {
...process.env,
CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUNNER: runner,
NO_HEADLESS: '1',
WASM_BINDGEN_TEST_ADDRESS: address,
},
stdio: ['ignore', 'pipe', 'inherit'],
// Its own process group: the runner it starts is stopped with it.
detached: true,
},
);
const stopCargo = () => {
try {
process.kill(-cargo.pid);
} catch {}
};
let served = false;
cargo.stdout.on('data', (d) => {
if (String(d).includes(address)) served = true;
});
for (let i = 0; i < 1200 && !served; i++) await sleep(100);
if (!served) {
console.error('the test runner did not start');
stopCargo();
process.exit(1);
}
const ff = await launch();
let failed = true;
try {
const t = await tab(ff.browser, 1000, 800, () => {});
await t.navigate(`http://${address}/`);
const text = await t.waitFor(
`(() => { const t = document.body.innerText; return /test result: /.test(t) && t; })()`,
60000,
);
console.log(text.trim());
failed = !/test result: ok\./.test(text);
} finally {
await ff.stop();
stopCargo();
}
process.exit(failed ? 1 : 0);

View file

@ -10,14 +10,16 @@
//! gets the same evaluations, and the same marks. Speed comes from several engine //! gets the same evaluations, and the same marks. Speed comes from several engine
//! processes, each taking the next position; their number changes nothing but the time. //! processes, each taking the next position; their number changes nothing but the time.
use std::collections::HashSet; use uci::{EnginePosition, Side};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::mpsc::channel;
use std::time::{Duration, Instant};
use uci::{EngineEvent, EnginePosition, ScoreBound, SearchId, SearchLimits, Side}; use crate::PosEval;
use crate::{Eval, PosEval, Second, Shallow}; // The job in engine processes, each on a thread of its own: a computer's and a
// phone's.
#[cfg(not(target_family = "wasm"))]
mod engines;
#[cfg(not(target_family = "wasm"))]
pub use engines::run;
/// Nodes of every search of a game analysis (0.85 s on one thread of an i7-13700KF, /// Nodes of every search of a game analysis (0.85 s on one thread of an i7-13700KF,
/// depth about 24). /// depth about 24).
@ -54,9 +56,6 @@ const SHARED_MB: u64 = 200;
/// in MB. /// in MB.
const PROCESS_MB: u64 = 70; const PROCESS_MB: u64 = 70;
/// A node-limited search should never take this long; stop it if it does.
const SEARCH_GUARD: Duration = Duration::from_secs(300);
/// Engine processes for a job on this machine: one per logical CPU, at most `limit` /// Engine processes for a job on this machine: one per logical CPU, at most `limit`
/// (and [`MAX_PROCESSES`]), and no more than the free memory holds. /// (and [`MAX_PROCESSES`]), and no more than the free memory holds.
pub fn processes(limit: usize) -> usize { pub fn processes(limit: usize) -> usize {
@ -151,277 +150,12 @@ pub enum JobFailure {
Terminated(uci::TerminationReason), Terminated(uci::TerminationReason),
} }
enum WorkerMsg {
Event(JobEvent),
Failed(JobFailure),
}
/// Evaluates `targets` in `settings.processes` engine processes; `on_event` gets every
/// result, on the caller's thread, in the order they come. Returns when all are done,
/// or soon after `cancel` is set (then with `Ok`). When an engine fails, the others
/// stop too and the first failure is returned; what came before it was reported.
pub fn run(
config: uci::EngineConfig,
settings: &JobSettings,
targets: Vec<Target>,
cancel: &AtomicBool,
on_event: &mut dyn FnMut(JobEvent),
) -> Result<(), JobFailure> {
if targets.is_empty() {
return Ok(());
}
let workers = settings
.processes
.clamp(1, MAX_PROCESSES)
.min(targets.len());
let next = AtomicUsize::new(0);
let failed = AtomicBool::new(false);
let halted = || cancel.load(Ordering::Relaxed) || failed.load(Ordering::Relaxed);
let (tx, rx) = channel();
let mut failure = None;
std::thread::scope(|s| {
for _ in 0..workers {
let tx = tx.clone();
let (config, targets, next, halted) = (config.clone(), &targets, &next, &halted);
s.spawn(move || {
let mut send = |e| {
let _ = tx.send(WorkerMsg::Event(e));
};
if let Err(e) = worker(config, settings, targets, next, halted, &mut send) {
let _ = tx.send(WorkerMsg::Failed(e));
}
});
}
drop(tx);
let mut names = HashSet::new();
for msg in rx {
match msg {
WorkerMsg::Event(JobEvent::Engine(name)) => {
if names.insert(name.clone()) {
on_event(JobEvent::Engine(name));
}
}
WorkerMsg::Event(e) => on_event(e),
WorkerMsg::Failed(e) => {
failed.store(true, Ordering::Relaxed);
failure.get_or_insert(e);
}
}
}
});
match failure {
Some(e) if !cancel.load(Ordering::Relaxed) => Err(e),
_ => Ok(()),
}
}
/// One engine process: takes the next target until there is none or `halted`.
fn worker(
config: uci::EngineConfig,
settings: &JobSettings,
targets: &[Target],
next: &AtomicUsize,
halted: &dyn Fn() -> bool,
on_event: &mut dyn FnMut(JobEvent),
) -> Result<(), JobFailure> {
let handle = uci::Engine::spawn_with(config, Box::new(|| {}))
.map_err(|e| JobFailure::Start(e.to_string()))?;
if let Some(name) = &handle.info().name {
on_event(JobEvent::Engine(name.clone()));
}
if let Some(file) = &settings.eval_file {
handle
.set_option("EvalFile", Some(file))
.map_err(|e| JobFailure::Start(e.to_string()))?;
}
// Unknown options are not fatal: some engines lack Threads/Hash/MultiPV.
let _ = handle.set_threads(1);
let _ = handle.set_hash_mb(SEARCH_HASH_MB);
let _ = handle.set_multipv(1);
let mut next_id = 0;
// Every search starts from a clear hash, so that it depends on its position alone.
let mut search = |pos: &EnginePosition, among: Vec<String>, nodes: u64| {
next_id += 1;
let _ = handle.new_game();
search_once(&handle, pos, SearchId(next_id), among, nodes, halted)
};
while let Some(t) = targets.get(next.fetch_add(1, Ordering::Relaxed)) {
if halted() {
break;
}
let (mut eval, nps) = match &t.known {
Some(e) => (e.clone(), 0),
None => {
let Some((info, best)) = search(&t.pos, Vec::new(), settings.nodes)? else {
continue;
};
let Some(score) = info.score else { continue };
let mut pv: Vec<String> = info.pv.iter().take(12).cloned().collect();
if let Some(b) = best
&& pv.first() != Some(&b)
{
pv = vec![b];
}
let eval = PosEval {
eval: Eval::from_white_eval(score.to_white(t.turn).eval),
pv,
depth: info.depth.unwrap_or(0),
second: None,
shallow: None,
};
(eval, info.nps.unwrap_or(0))
}
};
// The move played is the engine's best: what the best of the others gives says
// whether it was the only good move, or a sacrifice when nothing else won.
let mover = match t.turn {
Side::White => chess_core::shakmaty::Color::White,
Side::Black => chess_core::shakmaty::Color::Black,
};
let played = t.played.as_ref().filter(|p| {
eval.pv.first() == Some(*p)
&& !t.others.is_empty()
&& crate::report::worth_second(eval.eval, mover)
});
if let Some(played) = played
&& eval.second.as_ref().map(|s| &s.without) != Some(played)
{
match search(&t.pos, t.others.clone(), settings.nodes)? {
// An engine that ignores `searchmoves` answers with the move played:
// no second move then.
Some((info, best))
if best.as_ref() != Some(played) && info.pv.first() != Some(played) =>
{
if let Some(score) = info.score {
eval.second = Some(Second {
without: played.clone(),
eval: Eval::from_white_eval(score.to_white(t.turn).eval),
});
}
}
None if halted() => break,
_ => {}
}
}
// How hard it was to find: what a shallow search makes of it.
if let (Some(played), Some(nodes)) = (played, t.shallow)
&& !eval
.shallow
.as_ref()
.is_some_and(|s| &s.played == played && s.nodes == nodes)
{
match shallow(&mut search, t, played, nodes)? {
Some(s) => eval.shallow = Some(s),
None if halted() => break,
None => {}
}
}
on_event(JobEvent::Eval {
key: t.key.clone(),
eval,
nps,
});
}
handle.quit();
Ok(())
}
/// What a search gave: its last full line and the best move, `None` when there is none
/// (see [`search_once`]).
type SearchResult = Result<Option<(uci::SearchInfo, Option<String>)>, JobFailure>;
/// The shallow search of `played` at `t`: the best move at `nodes` and, when it is
/// another, the move played alone. `None` when the engine gave no answer (or ignored
/// `searchmoves`) or the job was halted.
fn shallow(
search: &mut dyn FnMut(&EnginePosition, Vec<String>, u64) -> SearchResult,
t: &Target,
played: &str,
nodes: u64,
) -> Result<Option<Shallow>, JobFailure> {
let eval_of = |info: &uci::SearchInfo| {
info.score
.map(|s| Eval::from_white_eval(s.to_white(t.turn).eval))
};
let Some((info, best)) = search(&t.pos, Vec::new(), nodes)? else {
return Ok(None);
};
let (Some(best), Some(best_eval)) = (best.or_else(|| info.pv.first().cloned()), eval_of(&info))
else {
return Ok(None);
};
let played_eval = if best == played {
best_eval
} else {
match search(&t.pos, vec![played.to_owned()], nodes)? {
Some((info, b)) if b.as_deref().is_none_or(|b| b == played) => {
let Some(e) = eval_of(&info) else {
return Ok(None);
};
e
}
_ => return Ok(None),
}
};
Ok(Some(Shallow {
nodes,
played: played.to_owned(),
best,
best_eval,
played_eval,
}))
}
/// One node-limited search: its last full line and the best move. `None` when it gave
/// no line or the job was halted.
fn search_once(
handle: &uci::EngineHandle,
pos: &EnginePosition,
id: SearchId,
among: Vec<String>,
nodes: u64,
halted: &dyn Fn() -> bool,
) -> SearchResult {
handle
.search_among(pos.clone(), id, SearchLimits::Nodes(nodes), among)
.map_err(|e| JobFailure::Engine(e.to_string()))?;
let started = Instant::now();
let mut stopping = false;
let mut last: Option<uci::SearchInfo> = None;
loop {
if halted() {
return Ok(None);
}
if !stopping && started.elapsed() > SEARCH_GUARD {
let _ = handle.stop();
stopping = true;
}
match handle.recv_timeout(Duration::from_millis(100)) {
Some(EngineEvent::Info { search_id, info }) if search_id == id => {
if info.multipv_index() == 1 && info.score.is_some() {
let exact = info.score.is_some_and(|s| s.bound == ScoreBound::Exact);
if exact || last.is_none() {
last = Some(info);
}
}
}
Some(EngineEvent::BestMove {
search_id, best, ..
}) if search_id == id => {
return Ok(last.map(|info| (info, best.map(|b| b.to_string()))));
}
Some(EngineEvent::Terminated(reason)) => {
return Err(JobFailure::Terminated(reason));
}
_ => {}
}
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::GameAnalysis; use crate::GameAnalysis;
use crate::Eval;
use std::sync::atomic::{AtomicBool, Ordering};
/// The fake engine of the `uci` crate (`cargo build -p uci --bin fake_uci`). /// The fake engine of the `uci` crate (`cargo build -p uci --bin fake_uci`).
fn fake() -> &'static str { fn fake() -> &'static str {

View file

@ -0,0 +1,281 @@
//! The engine job in engine processes, each driven from a thread of its own.
use std::collections::HashSet;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::mpsc::channel;
use std::time::{Duration, Instant};
use uci::{EngineEvent, EnginePosition, ScoreBound, SearchId, SearchLimits, Side};
use super::{JobEvent, JobFailure, JobSettings, MAX_PROCESSES, SEARCH_HASH_MB, Target};
use crate::{Eval, PosEval, Second, Shallow};
/// A node-limited search should never take this long; stop it if it does.
const SEARCH_GUARD: Duration = Duration::from_secs(300);
enum WorkerMsg {
Event(JobEvent),
Failed(JobFailure),
}
/// Evaluates `targets` in `settings.processes` engine processes; `on_event` gets every
/// result, on the caller's thread, in the order they come. Returns when all are done,
/// or soon after `cancel` is set (then with `Ok`). When an engine fails, the others
/// stop too and the first failure is returned; what came before it was reported.
pub fn run(
config: uci::EngineConfig,
settings: &JobSettings,
targets: Vec<Target>,
cancel: &AtomicBool,
on_event: &mut dyn FnMut(JobEvent),
) -> Result<(), JobFailure> {
if targets.is_empty() {
return Ok(());
}
let workers = settings
.processes
.clamp(1, MAX_PROCESSES)
.min(targets.len());
let next = AtomicUsize::new(0);
let failed = AtomicBool::new(false);
let halted = || cancel.load(Ordering::Relaxed) || failed.load(Ordering::Relaxed);
let (tx, rx) = channel();
let mut failure = None;
std::thread::scope(|s| {
for _ in 0..workers {
let tx = tx.clone();
let (config, targets, next, halted) = (config.clone(), &targets, &next, &halted);
s.spawn(move || {
let mut send = |e| {
let _ = tx.send(WorkerMsg::Event(e));
};
if let Err(e) = worker(config, settings, targets, next, halted, &mut send) {
let _ = tx.send(WorkerMsg::Failed(e));
}
});
}
drop(tx);
let mut names = HashSet::new();
for msg in rx {
match msg {
WorkerMsg::Event(JobEvent::Engine(name)) => {
if names.insert(name.clone()) {
on_event(JobEvent::Engine(name));
}
}
WorkerMsg::Event(e) => on_event(e),
WorkerMsg::Failed(e) => {
failed.store(true, Ordering::Relaxed);
failure.get_or_insert(e);
}
}
}
});
match failure {
Some(e) if !cancel.load(Ordering::Relaxed) => Err(e),
_ => Ok(()),
}
}
/// One engine process: takes the next target until there is none or `halted`.
fn worker(
config: uci::EngineConfig,
settings: &JobSettings,
targets: &[Target],
next: &AtomicUsize,
halted: &dyn Fn() -> bool,
on_event: &mut dyn FnMut(JobEvent),
) -> Result<(), JobFailure> {
let handle = uci::Engine::spawn_with(config, Box::new(|| {}))
.map_err(|e| JobFailure::Start(e.to_string()))?;
if let Some(name) = &handle.info().name {
on_event(JobEvent::Engine(name.clone()));
}
if let Some(file) = &settings.eval_file {
handle
.set_option("EvalFile", Some(file))
.map_err(|e| JobFailure::Start(e.to_string()))?;
}
// Unknown options are not fatal: some engines lack Threads/Hash/MultiPV.
let _ = handle.set_threads(1);
let _ = handle.set_hash_mb(SEARCH_HASH_MB);
let _ = handle.set_multipv(1);
let mut next_id = 0;
// Every search starts from a clear hash, so that it depends on its position alone.
let mut search = |pos: &EnginePosition, among: Vec<String>, nodes: u64| {
next_id += 1;
let _ = handle.new_game();
search_once(&handle, pos, SearchId(next_id), among, nodes, halted)
};
while let Some(t) = targets.get(next.fetch_add(1, Ordering::Relaxed)) {
if halted() {
break;
}
let (mut eval, nps) = match &t.known {
Some(e) => (e.clone(), 0),
None => {
let Some((info, best)) = search(&t.pos, Vec::new(), settings.nodes)? else {
continue;
};
let Some(score) = info.score else { continue };
let mut pv: Vec<String> = info.pv.iter().take(12).cloned().collect();
if let Some(b) = best
&& pv.first() != Some(&b)
{
pv = vec![b];
}
let eval = PosEval {
eval: Eval::from_white_eval(score.to_white(t.turn).eval),
pv,
depth: info.depth.unwrap_or(0),
second: None,
shallow: None,
};
(eval, info.nps.unwrap_or(0))
}
};
// The move played is the engine's best: what the best of the others gives says
// whether it was the only good move, or a sacrifice when nothing else won.
let mover = match t.turn {
Side::White => chess_core::shakmaty::Color::White,
Side::Black => chess_core::shakmaty::Color::Black,
};
let played = t.played.as_ref().filter(|p| {
eval.pv.first() == Some(*p)
&& !t.others.is_empty()
&& crate::report::worth_second(eval.eval, mover)
});
if let Some(played) = played
&& eval.second.as_ref().map(|s| &s.without) != Some(played)
{
match search(&t.pos, t.others.clone(), settings.nodes)? {
// An engine that ignores `searchmoves` answers with the move played:
// no second move then.
Some((info, best))
if best.as_ref() != Some(played) && info.pv.first() != Some(played) =>
{
if let Some(score) = info.score {
eval.second = Some(Second {
without: played.clone(),
eval: Eval::from_white_eval(score.to_white(t.turn).eval),
});
}
}
None if halted() => break,
_ => {}
}
}
// How hard it was to find: what a shallow search makes of it.
if let (Some(played), Some(nodes)) = (played, t.shallow)
&& !eval
.shallow
.as_ref()
.is_some_and(|s| &s.played == played && s.nodes == nodes)
{
match shallow(&mut search, t, played, nodes)? {
Some(s) => eval.shallow = Some(s),
None if halted() => break,
None => {}
}
}
on_event(JobEvent::Eval {
key: t.key.clone(),
eval,
nps,
});
}
handle.quit();
Ok(())
}
/// What a search gave: its last full line and the best move, `None` when there is none
/// (see [`search_once`]).
type SearchResult = Result<Option<(uci::SearchInfo, Option<String>)>, JobFailure>;
/// The shallow search of `played` at `t`: the best move at `nodes` and, when it is
/// another, the move played alone. `None` when the engine gave no answer (or ignored
/// `searchmoves`) or the job was halted.
fn shallow(
search: &mut dyn FnMut(&EnginePosition, Vec<String>, u64) -> SearchResult,
t: &Target,
played: &str,
nodes: u64,
) -> Result<Option<Shallow>, JobFailure> {
let eval_of = |info: &uci::SearchInfo| {
info.score
.map(|s| Eval::from_white_eval(s.to_white(t.turn).eval))
};
let Some((info, best)) = search(&t.pos, Vec::new(), nodes)? else {
return Ok(None);
};
let (Some(best), Some(best_eval)) = (best.or_else(|| info.pv.first().cloned()), eval_of(&info))
else {
return Ok(None);
};
let played_eval = if best == played {
best_eval
} else {
match search(&t.pos, vec![played.to_owned()], nodes)? {
Some((info, b)) if b.as_deref().is_none_or(|b| b == played) => {
let Some(e) = eval_of(&info) else {
return Ok(None);
};
e
}
_ => return Ok(None),
}
};
Ok(Some(Shallow {
nodes,
played: played.to_owned(),
best,
best_eval,
played_eval,
}))
}
/// One node-limited search: its last full line and the best move. `None` when it gave
/// no line or the job was halted.
fn search_once(
handle: &uci::EngineHandle,
pos: &EnginePosition,
id: SearchId,
among: Vec<String>,
nodes: u64,
halted: &dyn Fn() -> bool,
) -> SearchResult {
handle
.search_among(pos.clone(), id, SearchLimits::Nodes(nodes), among)
.map_err(|e| JobFailure::Engine(e.to_string()))?;
let started = Instant::now();
let mut stopping = false;
let mut last: Option<uci::SearchInfo> = None;
loop {
if halted() {
return Ok(None);
}
if !stopping && started.elapsed() > SEARCH_GUARD {
let _ = handle.stop();
stopping = true;
}
match handle.recv_timeout(Duration::from_millis(100)) {
Some(EngineEvent::Info { search_id, info }) if search_id == id => {
if info.multipv_index() == 1 && info.score.is_some() {
let exact = info.score.is_some_and(|s| s.bound == ScoreBound::Exact);
if exact || last.is_none() {
last = Some(info);
}
}
}
Some(EngineEvent::BestMove {
search_id, best, ..
}) if search_id == id => {
return Ok(last.map(|info| (info, best.map(|b| b.to_string()))));
}
Some(EngineEvent::Terminated(reason)) => {
return Err(JobFailure::Terminated(reason));
}
_ => {}
}
}
}

View file

@ -22,9 +22,11 @@ mod job;
pub mod report; pub mod report;
pub use features::{MoveFeatures, Rules}; pub use features::{MoveFeatures, Rules};
#[cfg(not(target_family = "wasm"))]
pub use job::run;
pub use job::{ pub use job::{
JobEvent, JobFailure, JobSettings, MAX_PROCESSES, PHONE_PROCESSES, SEARCH_HASH_MB, JobEvent, JobFailure, JobSettings, MAX_PROCESSES, PHONE_PROCESSES, SEARCH_HASH_MB,
SEARCH_NODES, SEARCH_VERSION, SHALLOW_NODES, Target, estimate_secs, processes, run, SEARCH_NODES, SEARCH_VERSION, SHALLOW_NODES, Target, estimate_secs, processes,
}; };
pub use report::{ pub use report::{
Eval, Hardness, Judgement, Measure, Phase, Phases, Ply, Report, SideStats, judge, Eval, Hardness, Judgement, Measure, Phase, Phases, Ply, Report, SideStats, judge,

View file

@ -4,12 +4,18 @@ version.workspace = true
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
license.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] [dependencies]
thiserror.workspace = true thiserror.workspace = true
web-time.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] [target.'cfg(unix)'.dependencies]
# nice(2) for EngineConfig::nice (std has no way to lower a child's priority). # nice(2) for EngineConfig::nice (std has no way to lower a child's priority).
libc = "0.2" libc = "0.2"
@ -20,3 +26,9 @@ name = "fake_uci"
path = "src/bin/fake_uci.rs" path = "src/bin/fake_uci.rs"
test = false test = false
doc = 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 //! feeds the machine. The UI talks to it through the non-blocking
//! [`EngineHandle`] and polls [`EngineEvent`]s every frame; the [`Waker`] //! [`EngineHandle`] and polls [`EngineEvent`]s every frame; the [`Waker`]
//! callback is invoked after each new event. WebAssembly in a browser has no //! 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 //! Search boundary: UCI has no request ids. A new `position`/`go` is written
//! only after the previous search ended with `bestmove` and a subsequent //! only after the previous search ended with `bestmove` and a subsequent
@ -21,15 +22,17 @@ mod events;
pub mod parse; pub mod parse;
#[cfg(not(target_family = "wasm"))] #[cfg(not(target_family = "wasm"))]
mod process; mod process;
// The machine is built where a transport drives it.
#[cfg(not(target_family = "wasm"))]
mod protocol; mod protocol;
mod types; mod types;
#[cfg(target_family = "wasm")]
mod worker;
pub use error::EngineError; pub use error::EngineError;
pub use events::{EngineEvent, TerminationReason, Waker}; pub use events::{EngineEvent, TerminationReason, Waker};
#[cfg(not(target_family = "wasm"))] #[cfg(not(target_family = "wasm"))]
pub use process::{Engine, EngineConfig, EngineHandle}; pub use process::{Engine, EngineConfig, EngineHandle};
#[cfg(target_family = "wasm")]
pub use worker::{Engine, EngineHandle, Starting, WorkerConfig};
pub use types::{ pub use types::{
EngineInfo, EngineOption, EnginePosition, EngineScore, OptionKind, PositionBase, Score, EngineInfo, EngineOption, EnginePosition, EngineScore, OptionKind, PositionBase, Score,
ScoreBound, SearchId, SearchInfo, SearchLimits, Side, Timeouts, WhiteEval, WhiteScore, 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::error::EngineError;
use crate::events::{EngineEvent, TerminationReason, Waker}; use crate::events::{EngineEvent, TerminationReason, Waker};
use crate::protocol::{Cmd, Exit, Gone, Handshake, HandshakeStep, Link, Session}; use crate::protocol::{Cmd, Exit, Gone, Handshake, HandshakeStep, Link, Session, option_line};
use crate::types::{EngineInfo, EnginePosition, OptionKind, SearchId, SearchLimits, Timeouts}; use crate::types::{EngineInfo, EnginePosition, SearchId, SearchLimits, Timeouts};
/// Maximum stored length of one output line; longer lines are truncated. /// Maximum stored length of one output line; longer lines are truncated.
const MAX_LINE_BYTES: usize = 64 * 1024; const MAX_LINE_BYTES: usize = 64 * 1024;
@ -175,16 +175,7 @@ impl EngineHandle {
limits: SearchLimits, limits: SearchLimits,
among: Vec<String>, among: Vec<String>,
) -> Result<(), EngineError> { ) -> Result<(), EngineError> {
position.validate()?; self.send(Cmd::search(position, search_id, limits, among)?)
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,
})
} }
/// Stops the running search (its `BestMove` still arrives) and cancels a /// 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 /// search boundary (UCI forbids `setoption` during a search) — to see the
/// effect on the current analysis, call [`Self::analyze`] again. /// effect on the current analysis, call [`Self::analyze`] again.
pub fn set_option(&self, name: &str, value: Option<&str>) -> Result<(), EngineError> { pub fn set_option(&self, name: &str, value: Option<&str>) -> Result<(), EngineError> {
let opt = self self.send(Cmd::Setup(option_line(&self.info, name, value)?))
.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))
} }
pub fn set_multipv(&self, lines: u32) -> Result<(), EngineError> { 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::error::EngineError;
use crate::events::EngineEvent; use crate::events::EngineEvent;
use crate::parse::{EngineLine, parse_line}; 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). /// Maximum number of `Warning` events emitted per engine (flood protection).
const MAX_WARNINGS: usize = 100; const MAX_WARNINGS: usize = 100;
@ -27,6 +27,80 @@ pub(crate) enum Cmd {
Setup(String), 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. /// The engine could not be written to: it is gone.
#[derive(Debug)] #[derive(Debug)]
pub(crate) struct Gone; 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). //! 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::collections::{HashMap, HashSet};
use std::path::Path; use std::path::Path;

View file

@ -1,6 +1,8 @@
//! Integration test with a real Stockfish binary. Ignored by default. //! Integration test with a real Stockfish binary. Ignored by default.
//! //!
//! Run: UCI_STOCKFISH=/path/to/stockfish cargo test -p uci --test stockfish -- --ignored //! 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::collections::BTreeMap;
use std::time::{Duration, Instant}; 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:?}"
);
}