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:
parent
07adedadbd
commit
a3f83102f1
9 changed files with 979 additions and 3 deletions
328
crates/control/src/protocol.rs
Normal file
328
crates/control/src/protocol.rs
Normal 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue