Lutra/crates/control/tests/tcp.rs
danny f1976c7d67 M1.3: engine workspace, file and buffer commands, event stream
State holds the open project (VFS project, watcher, watched directories)
and versioned buffers. New commands: project.open/close/children,
file.open/save/saveAll, buffer.get/edit/close. buffer.edit takes UTF-16
change sets based on a version and fails with the new stale_version code;
closing dirty buffers or projects without force fails with
unsaved_changes. Commands queue events (projectOpened, treeChanged,
bufferChanged, dirtyChanged, fileChangedOnDisk, ...) that the engine
returns in Outcome.events; Engine::pump_vfs maps changes on disk to
events and reloads clean buffers. project.children watches listed
directories, capped at 256 native / 32 polling, least recently listed
dropped first.

Control channel: events.subscribe streams {"event": ...} lines, with
bounded per-subscriber queues (lutra_control::Subscribers) and method docs
in methods.rs. testkit's EngineBackend and the desktop Host implement the
new Backend::subscribe. Verified with 14 engine integration tests, a TCP
events test and the running app over the control channel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 20:24:44 +02:00

112 lines
3.6 KiB
Rust

//! 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<TcpStream>,
writer: TcpStream,
}
impl Client {
fn connect(backend: Arc<EngineBackend>) -> 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[..2], ["app.about", "app.quit"]);
assert!(ids.contains(&"project.open") && ids.contains(&"buffer.edit"));
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());
}