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,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()?;
}
}