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>
This commit is contained in:
parent
a63ab4ac45
commit
f1976c7d67
30 changed files with 2235 additions and 46 deletions
|
|
@ -1,15 +1,30 @@
|
|||
//! The TCP side: a listener on the loopback interface, one thread per
|
||||
//! connection, JSON lines in and out.
|
||||
//!
|
||||
//! A connection that sent `events.subscribe` also gets a forwarder thread
|
||||
//! that writes event lines. Responses and events share one writer behind a
|
||||
//! lock and each line is written whole, so lines never interleave. The
|
||||
//! forwarder stops when the connection closes or the host drops the
|
||||
//! subscription.
|
||||
|
||||
use std::io::{self, BufRead, BufReader, Read, Write};
|
||||
use std::net::{Ipv4Addr, SocketAddr, TcpListener, TcpStream};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{Receiver, RecvTimeoutError, sync_channel};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::Value;
|
||||
use lutra_engine::Event;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Backend;
|
||||
use crate::protocol::{MAX_LINE_BYTES, Response, codes, handle_line};
|
||||
use crate::backend::EVENT_QUEUE;
|
||||
use crate::methods::EVENTS_SUBSCRIBE;
|
||||
use crate::protocol::{MAX_LINE_BYTES, Response, codes, handle_line, parse_request};
|
||||
|
||||
/// How often an idle forwarder checks whether its connection closed.
|
||||
const FORWARDER_TICK: Duration = Duration::from_millis(250);
|
||||
|
||||
/// A running control server.
|
||||
#[derive(Debug)]
|
||||
|
|
@ -54,6 +69,22 @@ fn accept_loop(listener: &TcpListener, backend: &Arc<dyn Backend>) {
|
|||
}
|
||||
}
|
||||
|
||||
/// The write side of a connection, shared by the reader and the forwarder.
|
||||
type SharedWriter = Arc<Mutex<TcpStream>>;
|
||||
|
||||
/// Writes one line, holding the lock for the whole line.
|
||||
///
|
||||
/// # Errors
|
||||
/// The write error.
|
||||
fn write_line(writer: &SharedWriter, line: &str) -> io::Result<()> {
|
||||
let mut stream = writer.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut bytes = Vec::with_capacity(line.len() + 1);
|
||||
bytes.extend_from_slice(line.as_bytes());
|
||||
bytes.push(b'\n');
|
||||
stream.write_all(&bytes)?;
|
||||
stream.flush()
|
||||
}
|
||||
|
||||
/// 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.
|
||||
|
|
@ -61,9 +92,26 @@ fn accept_loop(listener: &TcpListener, backend: &Arc<dyn Backend>) {
|
|||
/// # Errors
|
||||
/// The first read or write error.
|
||||
fn serve_connection(stream: TcpStream, backend: &dyn Backend) -> io::Result<()> {
|
||||
let mut writer = stream.try_clone()?;
|
||||
let writer: SharedWriter = Arc::new(Mutex::new(stream.try_clone()?));
|
||||
let closed = Arc::new(AtomicBool::new(false));
|
||||
let result = read_loop(stream, backend, &writer, &closed);
|
||||
closed.store(true, Ordering::Relaxed);
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads and answers request lines.
|
||||
///
|
||||
/// # Errors
|
||||
/// The first read or write error.
|
||||
fn read_loop(
|
||||
stream: TcpStream,
|
||||
backend: &dyn Backend,
|
||||
writer: &SharedWriter,
|
||||
closed: &Arc<AtomicBool>,
|
||||
) -> io::Result<()> {
|
||||
let mut reader = BufReader::new(stream);
|
||||
let mut buf = Vec::new();
|
||||
let mut subscribed = false;
|
||||
loop {
|
||||
buf.clear();
|
||||
let limit = u64::try_from(MAX_LINE_BYTES)
|
||||
|
|
@ -83,17 +131,69 @@ fn serve_connection(stream: TcpStream, backend: &dyn Backend) -> io::Result<()>
|
|||
codes::LINE_TOO_LONG,
|
||||
format!("request lines are limited to {MAX_LINE_BYTES} bytes"),
|
||||
);
|
||||
writeln!(writer, "{}", response.to_line())?;
|
||||
write_line(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),
|
||||
Ok(line) => match parse_request(line) {
|
||||
Ok(request) if request.method == EVENTS_SUBSCRIBE => {
|
||||
if !subscribed {
|
||||
subscribe(backend, writer, closed)?;
|
||||
subscribed = true;
|
||||
}
|
||||
Response::ok(request.id, json!({ "subscribed": true }))
|
||||
}
|
||||
_ => handle_line(line, backend),
|
||||
},
|
||||
Err(e) => Response::err(Value::Null, codes::PARSE_ERROR, e.to_string()),
|
||||
};
|
||||
writeln!(writer, "{}", response.to_line())?;
|
||||
writer.flush()?;
|
||||
write_line(writer, &response.to_line())?;
|
||||
}
|
||||
}
|
||||
|
||||
/// Registers a subscription with the backend and starts its forwarder.
|
||||
///
|
||||
/// # Errors
|
||||
/// If the forwarder thread cannot be spawned.
|
||||
fn subscribe(
|
||||
backend: &dyn Backend,
|
||||
writer: &SharedWriter,
|
||||
closed: &Arc<AtomicBool>,
|
||||
) -> io::Result<()> {
|
||||
let (sink, events) = sync_channel(EVENT_QUEUE);
|
||||
let writer = Arc::clone(writer);
|
||||
let closed = Arc::clone(closed);
|
||||
thread::Builder::new()
|
||||
.name("lutra-control-events".into())
|
||||
.spawn(move || forward(&events, &writer, &closed))?;
|
||||
backend.subscribe(sink);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Writes events to the connection until it closes or the host drops the
|
||||
/// subscription; in the latter case a final `subscriptionLost` line tells
|
||||
/// the client. Write errors end forwarding because the peer is gone.
|
||||
fn forward(events: &Receiver<Event>, writer: &SharedWriter, closed: &AtomicBool) {
|
||||
loop {
|
||||
if closed.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
match events.recv_timeout(FORWARDER_TICK) {
|
||||
Ok(event) => {
|
||||
let line = json!({ "event": event }).to_string();
|
||||
if write_line(writer, &line).is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
Err(RecvTimeoutError::Timeout) => {}
|
||||
Err(RecvTimeoutError::Disconnected) => {
|
||||
let line = json!({ "event": { "kind": "subscriptionLost" } }).to_string();
|
||||
let _ = write_line(writer, &line);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue