From a3f83102f10d34266e3be6191f101da455d0b88d Mon Sep 17 00:00:00 2001 From: danny Date: Wed, 14 Oct 2026 06:47:30 +0200 Subject: [PATCH] M0.7: control channel over JSON lines lutra_control::start binds 127.0.0.1:PORT and serves app.ping, engine.execute, engine.listCommands and ui.screenshot through the Backend trait the host implements. Lines are capped at 16 MiB, every input gets a well-formed response with a stable error code, and backend panics become internal errors. Proptests cover arbitrary lines; a TCP integration test uses the new testkit EngineBackend. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 327 ++++++++++++++++++++++++++++++++ crates/control/Cargo.toml | 7 + crates/control/src/backend.rs | 29 +++ crates/control/src/lib.rs | 14 +- crates/control/src/protocol.rs | 328 +++++++++++++++++++++++++++++++++ crates/control/src/server.rs | 99 ++++++++++ crates/control/tests/tcp.rs | 111 +++++++++++ crates/testkit/Cargo.toml | 3 + crates/testkit/src/lib.rs | 64 ++++++- 9 files changed, 979 insertions(+), 3 deletions(-) create mode 100644 crates/control/src/backend.rs create mode 100644 crates/control/src/protocol.rs create mode 100644 crates/control/src/server.rs create mode 100644 crates/control/tests/tcp.rs diff --git a/Cargo.lock b/Cargo.lock index 27ecb6c..ad407c1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,12 +2,145 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "bit-set" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5727b15fa97d4f4fee0a3b7c3d550ed0269f54329207b86388de918604e31269" +dependencies = [ + "borsh", + "serde", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "borsh" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" +dependencies = [ + "borsh-derive", + "bytes", + "cfg_aliases", +] + +[[package]] +name = "borsh-derive" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core", +] + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + [[package]] name = "equivalent" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "rand_core", +] + [[package]] name = "hashbrown" version = "0.17.1" @@ -30,6 +163,18 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "libc" +version = "0.2.190" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + [[package]] name = "lutra-cli" version = "0.0.0" @@ -37,6 +182,13 @@ version = "0.0.0" [[package]] name = "lutra-control" version = "0.0.0" +dependencies = [ + "lutra-engine", + "lutra-testkit", + "proptest", + "serde", + "serde_json", +] [[package]] name = "lutra-engine" @@ -74,6 +226,11 @@ version = "0.0.0" [[package]] name = "lutra-testkit" version = "0.0.0" +dependencies = [ + "lutra-control", + "lutra-engine", + "serde_json", +] [[package]] name = "lutra-text" @@ -89,6 +246,30 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -98,6 +279,32 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "proptest" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" +dependencies = [ + "bit-set", + "bit-vec", + "bitflags", + "chacha20", + "core_detect", + "num-traits", + "rand", + "rand_xorshift", + "regex-syntax", + "rusty-fork", + "tempfile", + "unarray", +] + +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + [[package]] name = "quote" version = "1.0.47" @@ -107,6 +314,68 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "getrandom", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_xorshift" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf" +dependencies = [ + "rand_core", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "rusty-fork" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" +dependencies = [ + "fnv", + "quick-error", + "tempfile", + "wait-timeout", +] + [[package]] name = "serde" version = "1.0.229" @@ -170,6 +439,19 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + [[package]] name = "thiserror" version = "2.0.21" @@ -214,6 +496,18 @@ dependencies = [ "serde_core", ] +[[package]] +name = "toml_edit" +version = "0.25.17+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + [[package]] name = "toml_parser" version = "1.1.5+spec-1.1.0" @@ -229,17 +523,50 @@ version = "1.1.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + [[package]] name = "unicode-ident" version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + [[package]] name = "winnow" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] [[package]] name = "xtask" diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml index 99d7bc2..3e59835 100644 --- a/crates/control/Cargo.toml +++ b/crates/control/Cargo.toml @@ -12,6 +12,13 @@ publish.workspace = true layer = 5 [dependencies] +lutra-engine.workspace = true +serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.154" [lints] workspace = true + +[dev-dependencies] +lutra-testkit.workspace = true +proptest = "1.12.0" diff --git a/crates/control/src/backend.rs b/crates/control/src/backend.rs new file mode 100644 index 0000000..ec0e0f8 --- /dev/null +++ b/crates/control/src/backend.rs @@ -0,0 +1,29 @@ +//! The interface the control channel needs from its host. + +use std::path::Path; + +use lutra_engine::{CommandInfo, EngineError}; +use serde_json::Value; + +/// What the control channel can ask the host to do. +/// +/// The desktop app implements it on top of its engine and window; tests +/// implement it with a bare engine. Methods are called from connection +/// threads, so implementations synchronise internally. +pub trait Backend: Send + Sync + 'static { + /// Runs an engine command and applies its effects. + /// + /// # Errors + /// The engine's error for the command. + fn execute(&self, command: &str, params: Value) -> Result; + + /// Lists every command with its current enabled state. + fn list_commands(&self) -> Vec; + + /// Writes a PNG screenshot of the main window to `path`. + /// + /// # Errors + /// A message if there is no window to capture or the file cannot be + /// written. + fn screenshot(&self, path: &Path) -> Result<(), String>; +} diff --git a/crates/control/src/lib.rs b/crates/control/src/lib.rs index 6b7449c..979f100 100644 --- a/crates/control/src/lib.rs +++ b/crates/control/src/lib.rs @@ -1,4 +1,14 @@ //! Control channel of Lutra (layer L5). //! -//! Serves JSON lines on a local TCP port so that scripts and agents can run -//! engine commands and inspect the user interface. +//! Serves JSON lines on `127.0.0.1:PORT` so that scripts and agents can run +//! engine commands and inspect the user interface. The protocol is described +//! in docs/architecture.md › Control channel; [`protocol`] parses and answers +//! single lines, [`server`] owns the sockets. Hosts plug in through +//! [`Backend`]. + +mod backend; +pub mod protocol; +pub mod server; + +pub use backend::Backend; +pub use server::{ServerHandle, start}; diff --git a/crates/control/src/protocol.rs b/crates/control/src/protocol.rs new file mode 100644 index 0000000..03f8d21 --- /dev/null +++ b/crates/control/src/protocol.rs @@ -0,0 +1,328 @@ +//! The line protocol: one JSON request in, one JSON response out. +//! +//! Requests are `{"id": , "method": "...", "params": {...}}`. +//! Responses are `{"id": ..., "result": ...}` or +//! `{"id": ..., "error": {"code": "...", "message": "..."}}`. Every input +//! line is untrusted; [`handle_line`] answers anything, including garbage, +//! with a well-formed response and never panics. + +use std::path::PathBuf; + +use lutra_engine::{EngineError, guard}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use crate::Backend; + +/// Largest accepted request line in bytes, newline excluded. +pub const MAX_LINE_BYTES: usize = 16 * 1024 * 1024; + +/// Error codes of the protocol itself; engine errors use +/// [`EngineError::code`]. +pub mod codes { + /// The line is not valid JSON or not UTF-8. + pub const PARSE_ERROR: &str = "parse_error"; + /// The JSON is not a request object. + pub const INVALID_REQUEST: &str = "invalid_request"; + /// No such method. + pub const METHOD_NOT_FOUND: &str = "method_not_found"; + /// The method's params are wrong. + pub const INVALID_PARAMS: &str = "invalid_params"; + /// The line exceeds [`super::MAX_LINE_BYTES`]. + pub const LINE_TOO_LONG: &str = "line_too_long"; + /// The screenshot could not be taken. + pub const SCREENSHOT_FAILED: &str = "screenshot_failed"; +} + +/// A parsed request. +#[derive(Debug, Clone, PartialEq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Request { + /// Caller-chosen id, echoed in the response: a number or a string. + pub id: Value, + /// Method name, e.g. `engine.execute`. + pub method: String, + /// Method params; defaults to null. + #[serde(default)] + pub params: Value, +} + +/// Error object of a response. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ErrorObject { + /// Stable code. + pub code: String, + /// Human-readable message. + pub message: String, +} + +/// A response line. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Response { + /// The request id, or null if it could not be read. + pub id: Value, + /// The result on success. + #[serde(skip_serializing_if = "Option::is_none")] + pub result: Option, + /// The error on failure. + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +impl Response { + /// A success response. + pub fn ok(id: Value, result: Value) -> Self { + Self { + id, + result: Some(result), + error: None, + } + } + + /// An error response. + pub fn err(id: Value, code: &str, message: impl Into) -> Self { + Self { + id, + result: None, + error: Some(ErrorObject { + code: code.to_string(), + message: message.into(), + }), + } + } + + /// The response as one JSON line without the trailing newline. + pub fn to_line(&self) -> String { + serde_json::to_string(self).unwrap_or_else(|e| { + format!(r#"{{"id":null,"error":{{"code":"internal","message":"cannot encode response: {e}"}}}}"#) + }) + } +} + +/// Params of `engine.execute`. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct ExecuteParams { + /// Command id. + command: String, + /// Command params. + #[serde(default)] + params: Value, +} + +/// Params of `ui.screenshot`. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct ScreenshotParams { + /// Where to write the PNG. + path: PathBuf, +} + +/// Parses a request line. +/// +/// # Errors +/// An error response for invalid JSON, a non-object, a missing or +/// non-scalar id, or unknown fields. +pub fn parse_request(line: &str) -> Result { + let value: Value = serde_json::from_str(line) + .map_err(|e| Response::err(Value::Null, codes::PARSE_ERROR, e.to_string()))?; + let id = value.get("id").cloned().unwrap_or(Value::Null); + let id_ok = matches!(id, Value::Number(_) | Value::String(_)); + let echo = if id_ok { id } else { Value::Null }; + if !id_ok { + return Err(Response::err( + echo, + codes::INVALID_REQUEST, + "request needs an id (number or string)", + )); + } + serde_json::from_value(value) + .map_err(|e| Response::err(echo, codes::INVALID_REQUEST, e.to_string())) +} + +/// Answers one request line. Never panics: a panic in the backend becomes an +/// `internal` error response. +pub fn handle_line(line: &str, backend: &dyn Backend) -> Response { + let request = match parse_request(line) { + Ok(request) => request, + Err(response) => return response, + }; + let id = request.id.clone(); + match guard::run(|| Ok(dispatch(request, backend))) { + Ok(response) => response, + Err(e) => engine_error(id, &e), + } +} + +/// Runs a parsed request. +fn dispatch(request: Request, backend: &dyn Backend) -> Response { + let Request { id, method, params } = request; + match method.as_str() { + "app.ping" => Response::ok( + id, + json!({ "pong": true, "version": env!("CARGO_PKG_VERSION") }), + ), + "engine.execute" => match serde_json::from_value::(params) { + Ok(p) => match backend.execute(&p.command, p.params) { + Ok(value) => Response::ok(id, value), + Err(e) => engine_error(id, &e), + }, + Err(e) => Response::err(id, codes::INVALID_PARAMS, e.to_string()), + }, + "engine.listCommands" => match serde_json::to_value(backend.list_commands()) { + Ok(list) => Response::ok(id, list), + Err(e) => Response::err(id, "internal", e.to_string()), + }, + "ui.screenshot" => match serde_json::from_value::(params) { + Ok(p) => match backend.screenshot(&p.path) { + Ok(()) => Response::ok(id, json!({ "path": p.path })), + Err(message) => Response::err(id, codes::SCREENSHOT_FAILED, message), + }, + Err(e) => Response::err(id, codes::INVALID_PARAMS, e.to_string()), + }, + other => Response::err( + id, + codes::METHOD_NOT_FOUND, + format!("unknown method: {other}"), + ), + } +} + +/// An error response for an engine error. +fn engine_error(id: Value, error: &EngineError) -> Response { + Response::err(id, error.code(), error.to_string()) +} + +#[cfg(test)] +mod tests { + use std::path::Path; + use std::sync::Mutex; + + use lutra_engine::{CommandInfo, Effect, Engine}; + use proptest::prelude::*; + + use super::*; + + struct TestBackend { + engine: Mutex, + effects: Mutex>, + } + + impl TestBackend { + fn new() -> Self { + Self { + engine: Mutex::new(Engine::new().unwrap()), + effects: Mutex::new(Vec::new()), + } + } + } + + impl Backend for TestBackend { + fn execute(&self, command: &str, params: Value) -> Result { + let out = self.engine.lock().unwrap().execute(command, params)?; + self.effects.lock().unwrap().extend(out.effects); + Ok(out.value) + } + + fn list_commands(&self) -> Vec { + self.engine.lock().unwrap().list_commands() + } + + fn screenshot(&self, path: &Path) -> Result<(), String> { + if path.as_os_str() == "panic" { + panic!("screenshot exploded"); + } + Err("no window".into()) + } + } + + fn call(line: &str) -> Response { + handle_line(line, &TestBackend::new()) + } + + #[test] + fn ping() { + let r = call(r#"{"id":1,"method":"app.ping"}"#); + assert_eq!(r.id, json!(1)); + assert_eq!(r.result.unwrap()["pong"], true); + } + + #[test] + fn execute_runs_commands_and_collects_effects() { + let backend = TestBackend::new(); + let r = handle_line( + r#"{"id":"a","method":"engine.execute","params":{"command":"app.about"}}"#, + &backend, + ); + assert_eq!(r.result.unwrap()["name"], "Lutra"); + let r = handle_line( + r#"{"id":2,"method":"engine.execute","params":{"command":"app.quit","params":{}}}"#, + &backend, + ); + assert_eq!(r.result, Some(Value::Null)); + assert_eq!(*backend.effects.lock().unwrap(), vec![Effect::Quit]); + } + + #[test] + fn errors_carry_stable_codes() { + let code = |line: &str| call(line).error.unwrap().code; + assert_eq!(code("not json"), "parse_error"); + assert_eq!(code("[1,2]"), "invalid_request"); + assert_eq!(code(r#"{"method":"app.ping"}"#), "invalid_request"); + assert_eq!(code(r#"{"id":{},"method":"app.ping"}"#), "invalid_request"); + assert_eq!( + code(r#"{"id":1,"method":"app.ping","x":1}"#), + "invalid_request" + ); + assert_eq!(code(r#"{"id":1,"method":"nope"}"#), "method_not_found"); + assert_eq!( + code(r#"{"id":1,"method":"engine.execute"}"#), + "invalid_params" + ); + assert_eq!( + code(r#"{"id":1,"method":"engine.execute","params":{"command":"x.y"}}"#), + "unknown_command" + ); + assert_eq!( + code(r#"{"id":1,"method":"ui.screenshot","params":{"path":"a.png"}}"#), + "screenshot_failed" + ); + } + + #[test] + fn backend_panics_become_internal_errors() { + let r = call(r#"{"id":9,"method":"ui.screenshot","params":{"path":"panic"}}"#); + assert_eq!(r.id, json!(9)); + let e = r.error.unwrap(); + assert_eq!(e.code, "internal"); + assert!(e.message.contains("screenshot exploded")); + } + + #[test] + fn lists_commands() { + let r = call(r#"{"id":1,"method":"engine.listCommands"}"#); + let list = r.result.unwrap(); + assert_eq!(list[0]["id"], "app.about"); + } + + proptest! { + #[test] + fn any_line_gets_a_well_formed_response(line in ".{0,200}") { + let r = call(&line); + prop_assert!(r.result.is_some() != r.error.is_some()); + let back: Response = serde_json::from_str(&r.to_line()).unwrap(); + prop_assert_eq!(back, r); + } + + #[test] + fn json_shaped_lines_get_a_well_formed_response( + id in prop_oneof![Just(json!(1)), Just(json!("x")), Just(Value::Null), Just(json!([1]))], + method in prop_oneof![Just("app.ping".to_string()), Just("engine.execute".to_string()), Just("ui.screenshot".to_string()), "[a-z.]{0,20}"], + params in prop_oneof![Just(Value::Null), Just(json!({"command": "app.about"})), Just(json!({"path": 3})), Just(json!("s"))], + ) { + let line = json!({"id": id, "method": method, "params": params}).to_string(); + let r = call(&line); + prop_assert!(r.result.is_some() != r.error.is_some()); + } + } +} diff --git a/crates/control/src/server.rs b/crates/control/src/server.rs new file mode 100644 index 0000000..64fc747 --- /dev/null +++ b/crates/control/src/server.rs @@ -0,0 +1,99 @@ +//! The TCP side: a listener on the loopback interface, one thread per +//! connection, JSON lines in and out. + +use std::io::{self, BufRead, BufReader, Read, Write}; +use std::net::{Ipv4Addr, SocketAddr, TcpListener, TcpStream}; +use std::sync::Arc; +use std::thread; + +use serde_json::Value; + +use crate::Backend; +use crate::protocol::{MAX_LINE_BYTES, Response, codes, handle_line}; + +/// A running control server. +#[derive(Debug)] +pub struct ServerHandle { + /// The address the server listens on. + addr: SocketAddr, +} + +impl ServerHandle { + /// The bound address; useful when started on port 0. + pub fn local_addr(&self) -> SocketAddr { + self.addr + } +} + +/// Binds `127.0.0.1:port` and serves requests on a background thread for +/// the rest of the process's life. +/// +/// # Errors +/// The bind error, e.g. when the port is taken. +pub fn start(port: u16, backend: Arc) -> io::Result { + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, port))?; + let addr = listener.local_addr()?; + thread::Builder::new() + .name("lutra-control".into()) + .spawn(move || accept_loop(&listener, &backend))?; + Ok(ServerHandle { addr }) +} + +/// Accepts connections until the listener fails. Failed accepts and threads +/// that cannot be spawned drop that one connection and keep serving. +fn accept_loop(listener: &TcpListener, backend: &Arc) { + for stream in listener.incoming() { + let Ok(stream) = stream else { continue }; + let backend = Arc::clone(backend); + let spawned = thread::Builder::new() + .name("lutra-control-conn".into()) + .spawn(move || { + let _ = serve_connection(stream, backend.as_ref()); + }); + drop(spawned); + } +} + +/// Serves one connection until the peer closes it or sends an oversized +/// line. I/O errors end the connection; the caller ignores them because the +/// peer is gone either way. +/// +/// # Errors +/// The first read or write error. +fn serve_connection(stream: TcpStream, backend: &dyn Backend) -> io::Result<()> { + let mut writer = stream.try_clone()?; + let mut reader = BufReader::new(stream); + let mut buf = Vec::new(); + loop { + buf.clear(); + let limit = u64::try_from(MAX_LINE_BYTES) + .unwrap_or(u64::MAX) + .saturating_add(2); + let read = (&mut reader).take(limit).read_until(b'\n', &mut buf)?; + if read == 0 { + return Ok(()); + } + let complete = buf.last() == Some(&b'\n'); + while matches!(buf.last(), Some(b'\n' | b'\r')) { + buf.pop(); + } + if buf.len() > MAX_LINE_BYTES || (!complete && read as u64 >= limit) { + let response = Response::err( + Value::Null, + codes::LINE_TOO_LONG, + format!("request lines are limited to {MAX_LINE_BYTES} bytes"), + ); + writeln!(writer, "{}", response.to_line())?; + return Ok(()); + } + if buf.iter().all(u8::is_ascii_whitespace) { + continue; + } + let response = match std::str::from_utf8(&buf) { + Ok(line) => handle_line(line, backend), + Err(e) => Response::err(Value::Null, codes::PARSE_ERROR, e.to_string()), + }; + writeln!(writer, "{}", response.to_line())?; + writer.flush()?; + } +} diff --git a/crates/control/tests/tcp.rs b/crates/control/tests/tcp.rs new file mode 100644 index 0000000..af9a771 --- /dev/null +++ b/crates/control/tests/tcp.rs @@ -0,0 +1,111 @@ +//! End-to-end test of the control channel over a real TCP socket. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)] + +use std::io::{BufRead, BufReader, Write}; +use std::net::TcpStream; +use std::sync::Arc; + +use lutra_control::protocol::MAX_LINE_BYTES; +use lutra_engine::Effect; +use lutra_testkit::EngineBackend; +use serde_json::{Value, json}; + +/// A connected client with line-based send and receive. +struct Client { + reader: BufReader, + writer: TcpStream, +} + +impl Client { + fn connect(backend: Arc) -> Self { + let server = lutra_control::start(0, backend).unwrap(); + let stream = TcpStream::connect(server.local_addr()).unwrap(); + Self { + writer: stream.try_clone().unwrap(), + reader: BufReader::new(stream), + } + } + + fn send_raw(&mut self, bytes: &[u8]) { + self.writer.write_all(bytes).unwrap(); + } + + fn recv(&mut self) -> Value { + let mut line = String::new(); + self.reader.read_line(&mut line).unwrap(); + serde_json::from_str(&line).unwrap() + } + + fn call(&mut self, request: Value) -> Value { + self.send_raw(format!("{request}\n").as_bytes()); + self.recv() + } +} + +#[test] +fn serves_requests_over_tcp() { + let backend = Arc::new(EngineBackend::new()); + let mut client = Client::connect(Arc::clone(&backend)); + + let r = client.call(json!({"id": 1, "method": "app.ping"})); + assert_eq!(r["id"], 1); + assert_eq!(r["result"]["pong"], true); + + let r = client.call(json!({"id": 2, "method": "engine.listCommands"})); + let ids: Vec<&str> = r["result"] + .as_array() + .unwrap() + .iter() + .map(|c| c["id"].as_str().unwrap()) + .collect(); + assert_eq!(ids, ["app.about", "app.quit"]); + + let r = client.call(json!({ + "id": "about", + "method": "engine.execute", + "params": {"command": "app.about", "params": {}} + })); + assert_eq!(r["result"]["slogan"], "An otterly perfect IDE"); + + let r = + client.call(json!({"id": 3, "method": "ui.screenshot", "params": {"path": "shot.png"}})); + assert_eq!(r["error"]["code"], "screenshot_failed"); + + client.send_raw(b"\r\n{broken\r\n"); + assert_eq!(client.recv()["error"]["code"], "parse_error"); + + client.send_raw(&[0xff, 0xfe, b'\n']); + assert_eq!(client.recv()["error"]["code"], "parse_error"); + + let r = client + .call(json!({"id": 4, "method": "engine.execute", "params": {"command": "app.quit"}})); + assert_eq!(r["result"], Value::Null); + assert_eq!(*backend.effects.lock().unwrap(), vec![Effect::Quit]); + assert_eq!(backend.screenshots.lock().unwrap().len(), 1); +} + +#[test] +fn rejects_oversized_lines_and_closes() { + let mut client = Client::connect(Arc::new(EngineBackend::new())); + let big = vec![b'x'; MAX_LINE_BYTES + 10]; + let writer = client.writer.try_clone().unwrap(); + let sender = std::thread::spawn(move || { + let mut writer = writer; + let _ = writer.write_all(&big); + let _ = writer.write_all(b"\n"); + }); + assert_eq!(client.recv()["error"]["code"], "line_too_long"); + let mut rest = String::new(); + let n = client.reader.read_line(&mut rest).unwrap_or(0); + assert_eq!(n, 0, "connection should be closed"); + sender.join().unwrap(); +} + +#[test] +fn reports_a_taken_port() { + let backend = Arc::new(EngineBackend::new()); + let first = lutra_control::start(0, backend.clone()).unwrap(); + let second = lutra_control::start(first.local_addr().port(), backend); + assert!(second.is_err()); +} diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index be5ae66..80f477f 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -12,6 +12,9 @@ publish.workspace = true layer = "tool" [dependencies] +lutra-control.workspace = true +lutra-engine.workspace = true +serde_json = "1.0.154" [lints] workspace = true diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index 06ac962..73810e7 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -1,3 +1,65 @@ //! Test helpers and fixtures for Lutra crates. //! -//! Used only as a dev-dependency; never part of a shipped binary. +//! Used only as a dev-dependency; never part of a shipped binary. Test code +//! may unwrap and panic, so the no-panic lints are allowed here. + +#![allow( + clippy::unwrap_used, + clippy::expect_used, + clippy::panic, + clippy::indexing_slicing +)] + +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +use lutra_control::Backend; +use lutra_engine::{CommandInfo, Effect, Engine, EngineError}; +use serde_json::Value; + +/// A control [`Backend`] over a bare engine, without a window. +/// +/// Effects are recorded instead of applied; screenshots write a tiny marker +/// file so that tests can check the path handling. +pub struct EngineBackend { + /// The engine, behind a lock like in the desktop app. + pub engine: Mutex, + /// Effects returned by executed commands, in order. + pub effects: Mutex>, + /// Paths passed to [`Backend::screenshot`]. + pub screenshots: Mutex>, +} + +impl EngineBackend { + /// A backend with the built-in commands. + pub fn new() -> Self { + Self { + engine: Mutex::new(Engine::new().unwrap()), + effects: Mutex::new(Vec::new()), + screenshots: Mutex::new(Vec::new()), + } + } +} + +impl Default for EngineBackend { + fn default() -> Self { + Self::new() + } +} + +impl Backend for EngineBackend { + fn execute(&self, command: &str, params: Value) -> Result { + let out = self.engine.lock().unwrap().execute(command, params)?; + self.effects.lock().unwrap().extend(out.effects); + Ok(out.value) + } + + fn list_commands(&self) -> Vec { + self.engine.lock().unwrap().list_commands() + } + + fn screenshot(&self, path: &Path) -> Result<(), String> { + self.screenshots.lock().unwrap().push(path.to_path_buf()); + Err("no window in tests".into()) + } +}