diff --git a/crates/automation/README.md b/crates/automation/README.md index 7c821d58f..23c613d96 100644 --- a/crates/automation/README.md +++ b/crates/automation/README.md @@ -11,7 +11,7 @@ Drive a running Craft app from tests, agents and the CLI, and record and play ac | `protocol` | The JSON-lines wire format: one `{"id", "method", "params"}` request per line, one `{"id", "ok", "result" | "error"}` reply per line; `Params` validators that name the bad parameter. | | `control` | `ControlRequest`, `Reply`, `Dispatch` and `ControlChannel`: the UI-thread side that drains requests between frames, replies after injected input or a background job settles, and admits screenshots. The app supplies the method table. | | `synthetic` | `Click`, `KeyPress` and `move_from_params`: the validated parameters of `ui.click`, `ui.move` and `ui.key`, and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. | -| `server` | `start`: the loopback TCP listener that authenticates each connection and forwards requests to the channel. | +| `server` | `listen` (bind a port) and `serve` (a listener bound earlier): the loopback TCP server that authenticates each connection and forwards requests to the channel, until its `Listening` is dropped. | | `client` | `ControlClient`: connect, authenticate, call (a screenshot is `call("ui.screenshot", ..)`); for integration tests and CLIs. | | `screenshot` | `Captures`: the bounded, cancellable screenshot queue over `WindowHost::screenshot`, with settling, geometry epochs, retries and the PNG reply. | | `profiler` | `FrameStages` and `SlowFrames`: where a frame's time went, the slow ones kept for the control channel's `perf` output and one log line a second. | diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index 6281a49b0..a1a598643 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -3,7 +3,9 @@ use std::io::{BufReader, Write}; use std::net::{SocketAddr, TcpListener, TcpStream}; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{Receiver, Sender, channel}; +use std::thread::JoinHandle; use std::time::Duration; use craft_ui::runtime::motion; @@ -18,30 +20,67 @@ use crate::security::{ read_bounded_line, repeat_auth_reply, }; -/// Bind `127.0.0.1:port` (0 lets the OS pick; the returned address is the one a client needs), -/// authenticate each connection with `token`, forward requests and wake the root window through -/// `host`. The app prints -/// `control server listening on `. -pub fn start(port: u16, token: String, host: WindowHost) -> std::io::Result<(Receiver, SocketAddr)> { - start_with_deadline(port, token, host, AUTH_DEADLINE) +/// A running control server. Dropping it stops accepting connections and returns once the port is +/// free, so a restart on the same port binds it again at once; connections already open end at their +/// next request, once the app has dropped the request channel. +pub struct Listening { + /// The bound address (with port 0, the port the system picked); the one a client needs. + pub addr: SocketAddr, + stop: Arc, + accept: Option>, } -/// [`start`] with `auth_deadline` in place of [`AUTH_DEADLINE`], so a test sees a connection closed at the deadline +impl Drop for Listening { + fn drop(&mut self) { + self.stop.store(true, Ordering::Release); + // The accept loop blocks in `accept`: a connection wakes it to see the flag and close the + // listener. Without that wake-up, joining would block, so it is skipped. + let woke = TcpStream::connect_timeout(&self.addr, Duration::from_millis(500)).is_ok(); + if woke && let Some(accept) = self.accept.take() { + let _ = accept.join(); + } + } +} + +impl std::fmt::Debug for Listening { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Listening").field("addr", &self.addr).finish_non_exhaustive() + } +} + +/// Binds `127.0.0.1:port` (0 lets the OS pick) and [`serve`]s it. +pub fn listen(port: u16, token: String, host: WindowHost) -> std::io::Result<(Receiver, Listening)> { + serve(TcpListener::bind(("127.0.0.1", port))?, token, host) +} + +/// Serves a listener bound earlier (an app's `--control`, bound before its window opens) until the +/// returned [`Listening`] is dropped: authenticates each connection with `token`, forwards its +/// requests to the receiver and wakes the root window through `host`. The app prints +/// `control server listening on `. +pub fn serve(listener: TcpListener, token: String, host: WindowHost) -> std::io::Result<(Receiver, Listening)> { + serve_with_deadline(listener, token, host, AUTH_DEADLINE) +} + +/// [`serve`] with `auth_deadline` in place of [`AUTH_DEADLINE`], so a test sees a connection closed at the deadline /// without waiting the real one. #[doc(hidden)] -pub fn start_with_deadline( - port: u16, +pub fn serve_with_deadline( + listener: TcpListener, token: String, host: WindowHost, auth_deadline: Duration, -) -> std::io::Result<(Receiver, SocketAddr)> { +) -> std::io::Result<(Receiver, Listening)> { let (tx, rx) = channel::(); - let listener = TcpListener::bind(("127.0.0.1", port))?; let addr = listener.local_addr()?; - std::thread::spawn(move || { + let stop = Arc::new(AtomicBool::new(false)); + let stopped = Arc::clone(&stop); + let accept = std::thread::Builder::new().name("control server".into()).spawn(move || { let limiter = ConnectionLimiter::new(MAX_CONNECTIONS); let token = Arc::new(token); for mut stream in listener.incoming().flatten() { + if stopped.load(Ordering::Acquire) { + break; + } let Some(permit) = limiter.try_acquire() else { let _ = configure_stream(&stream); let _ = writeln!(stream, "{}", json!({"id": null, "ok": false, "error": "connection limit reached"})); @@ -51,7 +90,7 @@ pub fn start_with_deadline( let host = host.clone(); let token = Arc::clone(&token); std::thread::spawn(move || { - serve(stream, &token, &tx, &host, auth_deadline); + serve_connection(stream, &token, &tx, &host, auth_deadline); // What the last client held down would otherwise stay held with no one left to // release it; while another connection is live, its input is left alone. if permit.release() { @@ -59,13 +98,13 @@ pub fn start_with_deadline( } }); } - }); - Ok((rx, addr)) + })?; + Ok((rx, Listening { addr, stop, accept: Some(accept) })) } /// Serve one connection: it must authenticate ([`ServerHandshake`]) within `auth_deadline` of /// connecting, however much it sends meanwhile; after that only the idle timeout applies. -fn serve(stream: TcpStream, token: &str, tx: &Sender, host: &WindowHost, auth_deadline: Duration) { +fn serve_connection(stream: TcpStream, token: &str, tx: &Sender, host: &WindowHost, auth_deadline: Duration) { if configure_stream(&stream).is_err() { return; } diff --git a/crates/automation/tests/it/control.rs b/crates/automation/tests/it/control.rs index ef4a59540..7c06dbcd2 100644 --- a/crates/automation/tests/it/control.rs +++ b/crates/automation/tests/it/control.rs @@ -1,12 +1,12 @@ //! `ControlChannel` deadlines and the loopback server's limits. use std::io::{BufRead, BufReader, Write}; -use std::net::TcpStream; -use std::sync::mpsc::channel; +use std::net::{SocketAddr, TcpListener, TcpStream}; +use std::sync::mpsc::{Receiver, channel}; use std::time::Duration; use craft_automation::client::ControlClient; -use craft_automation::control::{ControlChannel, ControlRequest, Reply, expired_error, result_reply, timeout_error}; +use craft_automation::control::{ControlChannel, ControlRequest, ControlResponse, Reply, expired_error, result_reply, timeout_error}; use craft_automation::security::{CHALLENGE_METHOD, MAX_REQUEST_BYTES, ProofRole, generate_nonce, handshake_proof, proof_matches}; use craft_automation::server; use craft_ui::runtime::motion; @@ -102,9 +102,10 @@ fn host() -> WindowHost { fn an_unauthenticated_connection_is_closed_at_the_deadline_whatever_it_sends() { // A short deadline, so the test does not wait out the real one. let deadline = Duration::from_millis(400); - let (rx, addr) = server::start_with_deadline(0, TOKEN.into(), host(), deadline).expect("started"); + let listener = TcpListener::bind("127.0.0.1:0").expect("bound"); + let (rx, server) = server::serve_with_deadline(listener, TOKEN.into(), host(), deadline).expect("started"); // Blank lines and partial frames, one byte every 20 ms: each read succeeds long before the idle timeout. - let mut stream = TcpStream::connect(addr).expect("connected"); + let mut stream = TcpStream::connect(server.addr).expect("connected"); let started = motion::now(); let mut closed = false; for i in 0..1000 { @@ -124,8 +125,8 @@ fn an_unauthenticated_connection_is_closed_at_the_deadline_whatever_it_sends() { /// A request line over `MAX_REQUEST_BYTES` without a newline gets an error reply and the connection is closed. #[trial] fn an_over_long_request_is_refused_and_closes_the_connection() { - let (rx, addr) = server::start(0, TOKEN.into(), host()).expect("started"); - let mut stream = TcpStream::connect(addr).expect("connected"); + let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started"); + let mut stream = TcpStream::connect(server.addr).expect("connected"); stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); let mut reader = BufReader::new(stream.try_clone().expect("cloned")); writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).expect("written"); @@ -139,17 +140,54 @@ fn an_over_long_request_is_refused_and_closes_the_connection() { assert!(rx.try_recv().is_err()); } +/// Answers the next request, which must be `test.ping`, with `pong`. +fn answer_one_ping(rx: Receiver) -> std::thread::JoinHandle<()> { + std::thread::spawn(move || { + let req = rx.recv_timeout(Duration::from_secs(5)).expect("a request"); + assert_eq!(req.method, "test.ping"); + let pong: ControlResponse = json!({"ok": true, "result": "pong"}); + req.reply.send(pong).expect("replied"); + }) +} + +/// Authenticates with the one-frame token, sends `test.ping` and returns its reply. +fn ping(addr: SocketAddr) -> Value { + let mut stream = TcpStream::connect(addr).expect("connected"); + stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + let mut reader = BufReader::new(stream.try_clone().expect("cloned")); + writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).expect("written"); + assert_eq!(read_json(&mut reader).expect("a reply")["ok"], true); + writeln!(stream, "{}", json!({"id": 2, "method": "test.ping"})).expect("written"); + read_json(&mut reader).expect("a reply") +} + +/// A server on port 0 reports the port it bound, serves, and after it is dropped the port binds again at once; dropping +/// one server leaves another one serving. +#[trial] +fn a_listening_server_stops_when_dropped_and_frees_its_port() { + let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started"); + let (other_rx, other) = server::listen(0, TOKEN.into(), host()).expect("started"); + let addr = server.addr; + assert_ne!(addr.port(), 0); + let handler = answer_one_ping(rx); + assert_eq!(ping(addr), json!({"id": 2, "ok": true, "result": "pong"})); + handler.join().expect("handler ran"); + + drop(server); + TcpListener::bind(addr).expect("the port is free once the server is dropped"); + + let handler = answer_one_ping(other_rx); + assert_eq!(ping(other.addr), json!({"id": 2, "ok": true, "result": "pong"})); + handler.join().expect("handler ran"); +} + /// A connection that authenticates with the challenge handshake learns the server holds the token, never sends it, /// and then has its requests dispatched. #[trial] fn a_challenge_authenticated_connection_is_served() { - let (rx, addr) = server::start(0, TOKEN.into(), host()).expect("started"); - let handler = std::thread::spawn(move || { - let req = rx.recv_timeout(Duration::from_secs(5)).expect("a request"); - assert_eq!(req.method, "test.ping"); - req.reply.send(json!({"ok": true, "result": "pong"})).expect("replied"); - }); - let mut stream = TcpStream::connect(addr).expect("connected"); + let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started"); + let handler = answer_one_ping(rx); + let mut stream = TcpStream::connect(server.addr).expect("connected"); stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); let mut reader = BufReader::new(stream.try_clone().expect("cloned")); let client_nonce = generate_nonce().expect("a nonce"); @@ -183,7 +221,8 @@ fn capture_state(client: &mut ControlClient, doc: &Value, state: &Value, label: /// against a server and a method table built as the guide shows. #[trial] fn the_documented_capture_client_sends_setup_steps_and_capture() { - let (requests, addr) = server::start(0, TOKEN.into(), host()).expect("started"); + let (requests, server) = server::listen(0, TOKEN.into(), host()).expect("started"); + let addr = server.addr; let doc = json!({ "size": {"width": 1280, "height": 800}, "theme": "pro", diff --git a/docs/porting.md b/docs/porting.md index bf3843108..d3fabe2cb 100644 --- a/docs/porting.md +++ b/docs/porting.md @@ -128,7 +128,7 @@ The old app is the visual reference, but not automatically right: judge each dif | Part | Library (`craft_automation`) | App | |---|---|---| | Command-line values | `args::ControlOptions`, `EnvNames` | Parses its own flags and calls `ControlOptions::resolve` | -| Transport | `server::start`, `ControlClient` | Calls `start`, owns the `ControlChannel` | +| Transport | `server::listen`, `server::serve`, `ControlClient` | Calls `listen` (or `serve` on a listener it bound earlier), keeps the `Listening` and owns the `ControlChannel` | | Request queue, replies | `ControlChannel`, `Reply`, `result_reply` | Runs each request and returns a `Reply` | | Input methods | `synthetic::Click`, `KeyPress`, `move_from_params`: the checked parameters of `ui.click`, `ui.key`, `ui.move` | Dispatches the method names to them | | Dialog methods | `dialogs`: `ui.dialog.set`, `ui.dialog.confirm`, `ui.dialog.cancel` and the dialog list | Dispatches them; may add `ui.dialog.open` for its own dialog kinds | @@ -144,7 +144,7 @@ Not provided yet, so the porter supplies each today: #### Expose the control channel in the app -The app starts the server once and keeps the channel on its UI thread. +The app starts the server and keeps the channel on its UI thread. The server runs until its `Listening` is dropped. ```rust use craft_automation::args::{ControlOptions, EnvNames}; @@ -160,9 +160,10 @@ if let Some(port) = options.port { let token = options.server_token()?; eprintln!("myapp: {}", options.token_notice(&token)); // Port 0 lets the OS pick; the address is the one a client needs. - let (requests, addr) = server::start(port, token, WindowHost::of(&egui_ctx))?; - eprintln!("myapp: control server listening on {addr}"); + let (requests, listening) = server::listen(port, token, WindowHost::of(&egui_ctx))?; + eprintln!("myapp: control server listening on {}", listening.addr); app.control = Some(ControlChannel::new(requests)); + app.control_server = Some(listening); } ```