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 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-14 06:47:30 +02:00
parent 07adedadbd
commit a3f83102f1
9 changed files with 979 additions and 3 deletions

View file

@ -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<Value, EngineError>;
/// Lists every command with its current enabled state.
fn list_commands(&self) -> Vec<CommandInfo>;
/// 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>;
}

View file

@ -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};

View file

@ -0,0 +1,328 @@
//! The line protocol: one JSON request in, one JSON response out.
//!
//! Requests are `{"id": <number|string>, "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<Value>,
/// The error on failure.
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<ErrorObject>,
}
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<String>) -> 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<Request, Response> {
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::<ExecuteParams>(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::<ScreenshotParams>(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<Engine>,
effects: Mutex<Vec<Effect>>,
}
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<Value, EngineError> {
let out = self.engine.lock().unwrap().execute(command, params)?;
self.effects.lock().unwrap().extend(out.effects);
Ok(out.value)
}
fn list_commands(&self) -> Vec<CommandInfo> {
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());
}
}
}

View file

@ -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<dyn Backend>) -> io::Result<ServerHandle> {
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<dyn Backend>) {
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()?;
}
}