From a4445d2c1571e9c2cdf0e0f8a0df62128994f497 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 30 Oct 2026 15:09:17 +0300 Subject: [PATCH] Crates for the browser: trainer and play on web-time, Judge everywhere, files closed by scope trainer keeps its deadline in web_time::Instant (std's panics in a browser; on a computer it is std's). play: the Judge type is on every target, only starting it (an engine process) is native. chess-import: files are closed by the end of their block before a rename instead of drop(), which a browser's File (no destructor) makes a lint there. rustfmt of the earlier changes. Co-Authored-By: Claude Opus 5.5 --- crates/chess-import/src/chessbase/booster.rs | 9 ++++---- crates/chess-import/src/chessbase/openings.rs | 12 ++++------ crates/game-review/src/job.rs | 2 +- crates/play/src/lib.rs | 13 +++++------ crates/trainer/Cargo.toml | 1 + crates/trainer/src/lib.rs | 3 ++- crates/uci/src/lib.rs | 4 ++-- crates/uci/src/worker.rs | 4 +++- crates/uci/tests/worker.rs | 23 +++++++++++++++---- 9 files changed, 44 insertions(+), 27 deletions(-) diff --git a/crates/chess-import/src/chessbase/booster.rs b/crates/chess-import/src/chessbase/booster.rs index eef1db7..a08b3ea 100644 --- a/crates/chess-import/src/chessbase/booster.rs +++ b/crates/chess-import/src/chessbase/booster.rs @@ -269,10 +269,11 @@ pub(super) fn build( // The header last: a file without the count is never taken for a booster. let mut header = [0u8; CBB_RECORD]; header[..4].copy_from_slice(&(count as u32).to_be_bytes()); - let file = File::options().write(true).open(part)?; - write_all_at(&file, &header, 0)?; - file.sync_all()?; - drop(file); + { + let file = File::options().write(true).open(part)?; + write_all_at(&file, &header, 0)?; + file.sync_all()?; + } // Closed before the rename. std::fs::rename(part, out)?; } if let (Some(out), Some(sink)) = (openings, sink) { diff --git a/crates/chess-import/src/chessbase/openings.rs b/crates/chess-import/src/chessbase/openings.rs index 16a3d43..d4911a3 100644 --- a/crates/chess-import/src/chessbase/openings.rs +++ b/crates/chess-import/src/chessbase/openings.rs @@ -314,13 +314,12 @@ impl Sink { let keys_len = keys.len() as u64; file.write_all(&keys)?; drop(keys); - let mut games = games.into_inner().map_err(|e| e.into_error())?; { use std::io::Seek; + let mut games = games.into_inner().map_err(|e| e.into_error())?; games.seek(io::SeekFrom::Start(0))?; io::copy(&mut games, &mut file)?; - } - drop(games); + } // Closed before it is removed. let _ = std::fs::remove_file(&games_path); // The games from a set-up position, ascending. let mut set_up = @@ -330,17 +329,16 @@ impl Sink { file.write_all(&g.to_le_bytes())?; } let set_up_len = set_up.len() as u64 * 4; - let mut file = file.into_inner().map_err(|e| e.into_error())?; { use std::io::Seek; + let mut file = file.into_inner().map_err(|e| e.into_error())?; file.seek(io::SeekFrom::Start(16))?; file.write_all(&prefix_len.to_le_bytes())?; file.write_all(&keys_len.to_le_bytes())?; file.write_all(&games_len.to_le_bytes())?; file.write_all(&set_up_len.to_le_bytes())?; - } - file.sync_all()?; - drop(file); + file.sync_all()?; + } // Closed before the rename. std::fs::rename(&part, out)?; Ok(true) } diff --git a/crates/game-review/src/job.rs b/crates/game-review/src/job.rs index a3bffb5..ba76f78 100644 --- a/crates/game-review/src/job.rs +++ b/crates/game-review/src/job.rs @@ -153,8 +153,8 @@ pub enum JobFailure { #[cfg(test)] mod tests { use super::*; - use crate::GameAnalysis; use crate::Eval; + use crate::GameAnalysis; use std::sync::atomic::{AtomicBool, Ordering}; /// The fake engine of the `uci` crate (`cargo build -p uci --bin fake_uci`). diff --git a/crates/play/src/lib.rs b/crates/play/src/lib.rs index 15dbf08..dd344bb 100644 --- a/crates/play/src/lib.rs +++ b/crates/play/src/lib.rs @@ -1,17 +1,16 @@ //! A game against the computer (docs/design/play-mode.md, android-play.md ยง31): how it //! ends, how long the opponent "thinks", its resignation judged by an engine, and Rodent //! (`rodent`). Shared by the desktop and the Android apps; nothing here draws. The -//! engines that play or judge run as processes, each driven from a thread: not built -//! for a browser. +//! engines that play or judge run as processes, each driven from a thread: a browser +//! cannot start them. pub mod rodent; mod rodent4_files; -#[cfg(not(target_family = "wasm"))] -use std::sync::mpsc::{Receiver, Sender, channel}; +use std::sync::mpsc::{Receiver, Sender}; use std::time::Duration; #[cfg(not(target_family = "wasm"))] -use std::time::Instant; +use std::{sync::mpsc::channel, time::Instant}; use shakmaty::zobrist::Zobrist64; use shakmaty::{Chess, Color, EnPassantMode, Position}; @@ -247,7 +246,6 @@ pub fn hopeless(score: uci::Score) -> bool { } } -#[cfg(not(target_family = "wasm"))] /// The engine (Stockfish, unseen by the user) judging the positions where Maia is to /// move, in its own thread for the whole game: the newest request is searched, older /// ones are dropped; an engine that does not start or dies leaves the game without @@ -262,10 +260,11 @@ pub struct Judge { refused_at: Option, } -#[cfg(not(target_family = "wasm"))] impl Judge { /// The engine of `config` with `options` set (an Android Stockfish: its `EvalFile`); /// `wake` is called when an answer comes (the app draws again). + /// (A process driven from a thread: not in a browser.) + #[cfg(not(target_family = "wasm"))] pub fn start( config: uci::EngineConfig, options: Vec<(String, String)>, diff --git a/crates/trainer/Cargo.toml b/crates/trainer/Cargo.toml index 132ca15..419cdce 100644 --- a/crates/trainer/Cargo.toml +++ b/crates/trainer/Cargo.toml @@ -12,4 +12,5 @@ publish = false chess-core.workspace = true serde.workspace = true serde_json.workspace = true +web-time.workspace = true chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } diff --git a/crates/trainer/src/lib.rs b/crates/trainer/src/lib.rs index 0b4f12d..2ba57e7 100644 --- a/crates/trainer/src/lib.rs +++ b/crates/trainer/src/lib.rs @@ -11,7 +11,8 @@ use std::path::PathBuf; use std::sync::Mutex; -use std::time::{Duration, Instant}; +use std::time::Duration; +use web_time::Instant; use chess_core::shakmaty::fen::Fen; use chess_core::shakmaty::{CastlingMode, Chess, EnPassantMode, Move, Square}; diff --git a/crates/uci/src/lib.rs b/crates/uci/src/lib.rs index b19f0ca..db125eb 100644 --- a/crates/uci/src/lib.rs +++ b/crates/uci/src/lib.rs @@ -31,9 +31,9 @@ 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, }; +#[cfg(target_family = "wasm")] +pub use worker::{Engine, EngineHandle, Starting, WorkerConfig}; diff --git a/crates/uci/src/worker.rs b/crates/uci/src/worker.rs index d85b367..3ce9cc7 100644 --- a/crates/uci/src/worker.rs +++ b/crates/uci/src/worker.rs @@ -202,7 +202,9 @@ impl Inner { self.port.worker.terminate(); self.phase = Phase::Ended; self.port - .emit(EngineEvent::Terminated(TerminationReason::Quit { status: None })); + .emit(EngineEvent::Terminated(TerminationReason::Quit { + status: None, + })); } else { self.port.worker.terminate(); self.phase = Phase::Ended; diff --git a/crates/uci/tests/worker.rs b/crates/uci/tests/worker.rs index b81fdb1..078acff 100644 --- a/crates/uci/tests/worker.rs +++ b/crates/uci/tests/worker.rs @@ -135,7 +135,7 @@ async fn handshake_then_analysis_and_stop() { 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"); + assert!(woke > 0, "the waker was not called"); h.set_multipv(2).unwrap(); assert!(matches!( h.set_multipv(11), @@ -170,7 +170,13 @@ async fn rapid_requests_start_only_the_latest_and_never_mix_output() { h.analyze(fen(m), SearchId(id)).unwrap(); } let evs = until(&h, 3000, |e| { - matches!(e, EngineEvent::Info { search_id: SearchId(4), .. }) + matches!( + e, + EngineEvent::Info { + search_id: SearchId(4), + .. + } + ) }) .await; for id in [2, 3] { @@ -191,7 +197,13 @@ async fn rapid_requests_start_only_the_latest_and_never_mix_output() { h.search(fen("n"), SearchId(5), SearchLimits::Nodes(1000)) .unwrap(); let evs = until(&h, 2000, |e| { - matches!(e, EngineEvent::BestMove { search_id: SearchId(5), .. }) + matches!( + e, + EngineEvent::BestMove { + search_id: SearchId(5), + .. + } + ) }) .await; assert!(matches!(evs.last(), Some(EngineEvent::BestMove { best: Some(b), .. }) if b == "n")); @@ -232,7 +244,10 @@ async fn a_crash_ends_the_session() { #[wasm_bindgen_test] async fn handshake_failures_are_named() { let (silent, _) = start("silent: true").await; - assert!(matches!(silent, Err(EngineError::NotUci { .. })), "{silent:?}"); + assert!( + matches!(silent, Err(EngineError::NotUci { .. })), + "{silent:?}" + ); let (no_uciok, _) = start("noUciok: true").await; assert!( matches!(