//! 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::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 lutra_engine::Event; use serde_json::{Value, json}; use crate::Backend; 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)] 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) -> io::Result { 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) { 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); } } /// The write side of a connection, shared by the reader and the forwarder. type SharedWriter = Arc>; /// 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. /// /// # Errors /// The first read or write error. fn serve_connection(stream: TcpStream, backend: &dyn Backend) -> io::Result<()> { 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, ) -> 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) .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"), ); 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) => 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()), }; 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, ) -> 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, 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; } } } }