diff --git a/backend/crates/core/src/model/board.rs b/backend/crates/core/src/model/board.rs index 2dc56b6b7..204ebf7e2 100644 --- a/backend/crates/core/src/model/board.rs +++ b/backend/crates/core/src/model/board.rs @@ -97,6 +97,27 @@ pub struct PodData { pub boards: HashMap, } +impl PodData { + /// The board's name as the ADJ declares it (`"HVSCU"`), or `None` if no + /// board has that id. + pub fn board_name(&self, id: BoardId) -> Option<&str> { + self.boards.get(&id).map(|board| board.name.as_str()) + } + + /// Which board each IP address belongs to: every board's + /// [`Board::ip`], pointing at its id. + /// + /// For whoever only knows where something came from, such as a + /// datagram's sender. Two boards declaring the same IP would leave only + /// one of them in the map; the ADJ gives every board its own. + pub fn boards_by_ip(&self) -> HashMap { + self.boards + .values() + .map(|board| (board.ip, board.id)) + .collect() + } +} + #[cfg(test)] mod tests { use super::*; @@ -147,4 +168,38 @@ mod tests { assert_eq!(measurements.len(), 1); assert_eq!(board.mac.to_string(), "00:11:22:33:44:55"); } + + fn two_boards() -> PodData { + let board = |id: u16, name: &str, last_octet: u8| Board { + id: BoardId(id), + name: name.to_string(), + ip: IpAddr::from([192, 168, 0, last_octet]), + mac: MacAddress([0; 6]), + packets: HashMap::new(), + }; + PodData { + boards: HashMap::from([ + (BoardId(1), board(1, "BCU", 10)), + (BoardId(2), board(2, "VCU", 11)), + ]), + } + } + + #[test] + fn a_board_is_named_as_the_adj_declares_it() { + let pod_data = two_boards(); + assert_eq!(pod_data.board_name(BoardId(2)), Some("VCU")); + assert_eq!(pod_data.board_name(BoardId(9)), None); + } + + #[test] + fn every_board_ip_points_at_its_board() { + let by_ip = two_boards().boards_by_ip(); + assert_eq!(by_ip.len(), 2); + assert_eq!( + by_ip.get(&IpAddr::from([192, 168, 0, 11])), + Some(&BoardId(2)) + ); + assert_eq!(by_ip.get(&IpAddr::from([192, 168, 0, 99])), None); + } } diff --git a/backend/crates/core/src/net/README.md b/backend/crates/core/src/net/README.md index dde1b5bd3..50b0f78dd 100644 --- a/backend/crates/core/src/net/README.md +++ b/backend/crates/core/src/net/README.md @@ -85,9 +85,10 @@ that it can afford to queue behind telemetry. `ErrorReport` carries **no board**, unlike a notification: the identity of what failed lives inside the `Error` variant, which is the only place that always has -it. A datagram that fails to decode resolves to no board at all — its id is not in -the ADJ, so there is no `PacketDef` to ask — and all that can be said about it is -the address it came from, which is what `udp::UdpError::Decode` holds. +it. A datagram that fails to decode has no id to resolve a board from — it is not +in the ADJ, so there is no `PacketDef` to ask — so `udp::UdpError::Decode` holds the +address it came from and the board that address belongs to, if it belongs to one +(`UdpConfig::boards`). `UdpError::Fault` carries the same two. ### `Error` — aggregation only @@ -104,7 +105,7 @@ submodule's own error: nobody outside knows which of its variants are fatal. | | `tcp` | `udp` | |---|---|---| | Entry point | `spawn(Config, Arc, Reporter) -> Handles` | `spawn_udp(UdpConfig, Arc, Reporter) -> Result, UdpError>` (binds first) | -| Inputs | its `Config` (boards, timeouts, backoff, keep-alive) | its `Config` (bind address, `SO_RCVBUF`) | +| Inputs | its `Config` (boards, timeouts, backoff, keep-alive) | its `UdpConfig` (bind address, `SO_RCVBUF`, IP → board) | | Role | client only; one connection per board, one task each | one shared socket, receive-only, one task | | Framing | buffer + `&mut Cursor` + advance by `cursor.position()`; bail out past 374 bytes | none — `recv_from` delivers a whole datagram into a reused 64 KiB buffer | | Writing | yes (orders, keep-alive); a single writer task per connection | no | @@ -123,7 +124,7 @@ reads `is_fatal()` and calls `Handles::propagate_fault()`, which puts the order with id 0 into every board's writer channel (the Go backend's `SendFault`). A *received* packet with id 0 is the same action requested by a board, and `station` answers it the same way. In `udp` it arrives on the error channel as -`UdpError::Fault { from }`: recognised by its id alone, before decoding, without +`UdpError::Fault { from, board }`: recognised by its id alone, before decoding, without looking at the ADJ. Three rules both follow: diff --git a/backend/crates/core/src/net/report.rs b/backend/crates/core/src/net/report.rs index 7ff356f1f..4ad86342f 100644 --- a/backend/crates/core/src/net/report.rs +++ b/backend/crates/core/src/net/report.rs @@ -53,11 +53,11 @@ pub struct Notification { /// /// Carries no identity of its own: whose failure it was travels inside /// the [`Error`]'s own variant, which is the only place that always has -/// it. A datagram that fails to decode, for instance, resolves to no -/// board at all — its id is not in the ADJ, so there is no -/// [`crate::model::PacketDef`] to ask — and all that can be said about -/// it is the address it came from, which is exactly what -/// [`super::udp::UdpError::Decode`] holds. +/// it. A datagram that fails to decode, for instance, has no id to resolve +/// a board from — it is not in the ADJ, so there is no +/// [`crate::model::PacketDef`] to ask — so +/// [`super::udp::UdpError::Decode`] holds the address it came from, and +/// the board that address belongs to only if it belongs to one. #[derive(Debug)] pub struct ErrorReport { /// The instant the failure was reported, on the same clock as @@ -345,15 +345,17 @@ mod tests { let addr = SocketAddr::new(IpAddr::from([192, 168, 1, 3]), 50400); let error = udp::UdpError::Decode { from: addr, + board: None, source: crate::protocol::DecodeError::UnknownId(AdjId(9999)), }; // The whole reason an error report carries no board: this one has // an address, and no board to attribute it to. - let Error::Udp(udp::UdpError::Decode { from, .. }) = Error::from(error) else { + let Error::Udp(udp::UdpError::Decode { from, board, .. }) = Error::from(error) else { unreachable!("a decode error should convert into Error::Udp"); }; assert_eq!(from, addr); + assert_eq!(board, None); } #[tokio::test] diff --git a/backend/crates/core/src/net/udp.rs b/backend/crates/core/src/net/udp.rs index e1be8f6cb..87eabcbb3 100644 --- a/backend/crates/core/src/net/udp.rs +++ b/backend/crates/core/src/net/udp.rs @@ -37,6 +37,13 @@ //! notification looks the same whichever transport brought it. That is //! one `HashMap` lookup per datagram, done here once rather than //! repeated by every consumer downstream. +//! - **An error names its board too, when it can.** A fault or a datagram +//! that will not decode has no id to resolve, so its board comes from +//! the address it was sent from, through [`UdpConfig::boards`]. Both +//! variants carry the address and that board (`None` if the address +//! belongs to no board), so the consumer gets the identity ready, as it +//! does from [`super::tcp`]. The lookup only happens on those two paths, +//! never for a datagram that decodes. //! - **A decode failure is reported as fatal** (see [`UdpError::is_fatal`]), //! but acting on it is not this module's call. Nothing corrupts a //! datagram in flight — UDP checksums it and the pod's network does not @@ -91,9 +98,10 @@ //! ``` use super::Reporter; -use crate::model::Packet; +use crate::model::{BoardId, Packet}; use crate::protocol::{DecodeError, Index}; -use std::net::SocketAddr; +use std::collections::HashMap; +use std::net::{IpAddr, SocketAddr}; use std::sync::Arc; use std::time::{Duration, Instant}; use tokio::task::JoinHandle; @@ -103,7 +111,7 @@ use tracing::{error, info, warn}; /// /// Everything here is resolved by `station` before `net` is reached: this /// module reads no config file and no ADJ of its own. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub struct UdpConfig { /// Where to bind: the backend's own address, `addresses["backend"]` /// and `ports["UDP"]` in the ADJ's `general_info.json`. @@ -134,6 +142,13 @@ pub struct UdpConfig { /// it at `net.core.rmem_max` — so [`spawn_udp`] reads the granted size back /// and warns when it is smaller than requested. pub recv_buffer: usize, + /// Which board each address belongs to, so that an error can name the + /// board it came from: [`UdpError::Decode`] and [`UdpError::Fault`]. + /// + /// Built from the ADJ with [`crate::model::PodData::boards_by_ip`]. An + /// address missing from it is not refused: its errors just carry no + /// board. + pub boards: HashMap, } /// Binds the shared socket and spawns the receive loop. @@ -160,13 +175,13 @@ pub fn spawn_udp( adj: Arc, reporter: Reporter, ) -> Result, UdpError> { - let socket = bind_telemetry_socket(config)?; - let handle = tokio::spawn(receive_telemetry(socket, adj, reporter)); + let socket = bind_telemetry_socket(&config)?; + let handle = tokio::spawn(receive_telemetry(socket, adj, config.boards, reporter)); Ok(handle) } /// Binds a UDP socket and configures its OS-level receive buffer size (`SO_RCVBUF`). -fn bind_telemetry_socket(config: UdpConfig) -> Result { +fn bind_telemetry_socket(config: &UdpConfig) -> Result { // Bind using the standard library socket first so we can configure non-blocking mode. let std_socket = std::net::UdpSocket::bind(config.addr).map_err(|source| UdpError::Bind { addr: config.addr, @@ -236,7 +251,12 @@ fn bind_telemetry_socket(config: UdpConfig) -> Result, reporter: Reporter) { +async fn receive_telemetry( + socket: tokio::net::UdpSocket, + adj: Arc, + boards: HashMap, + reporter: Reporter, +) { // Reusable 64 KiB buffer — a datagram can never be silently truncated. let mut buf = vec![0u8; 64 * 1024]; let mut traces = ReceiveTraces::default(); @@ -244,7 +264,11 @@ async fn receive_telemetry(socket: tokio::net::UdpSocket, adj: Arc, repor loop { match socket.recv_from(&mut buf).await { Ok((len, from)) => { - if !decode_and_report(&buf[..len], from, &adj, &reporter, &mut traces).await { + let lookups = Lookups { + adj: &adj, + boards: &boards, + }; + if !decode_and_report(&buf[..len], from, lookups, &reporter, &mut traces).await { // Downstream channels closed; exit cleanly. break; } @@ -268,33 +292,79 @@ async fn receive_telemetry(socket: tokio::net::UdpSocket, adj: Arc, repor /// raises a fault itself (`SendFault`). const FAULT_ID: [u8; 2] = 0u16.to_le_bytes(); -/// Decodes a single datagram slice against `adj` and forwards the result or error to `reporter`. +/// The two read-only tables the receive loop resolves a datagram against, +/// bundled so that [`decode_and_report`] takes one argument for both. +/// +/// They answer the same question, "which board is this from?", for two +/// kinds of datagram: +/// +/// - **One that decodes** carries an id, and the [`Index`] leads from the id +/// to its [`crate::model::PacketDef`], which names its board. +/// - **One that never gets an id**, a fault (packet id 0) or a datagram that +/// fails to decode, only has the sender's address. `boards` leads from +/// that address to its board, so that its error can still name the board +/// ([`UdpError::Fault`], [`UdpError::Decode`]). +/// +/// `boards` is the ADJ's own data, not a second definition of it: it is +/// built once from [`crate::model::PodData`] with +/// [`crate::model::PodData::boards_by_ip`], and comes in through +/// [`UdpConfig::boards`]. It is not in the [`Index`] because the index knows +/// nothing about addresses on purpose (see its docs), and it is not looked up +/// in `PodData` directly so that UDP gets only what it uses, not the whole +/// pod. +#[derive(Debug, Clone, Copy)] +struct Lookups<'a> { + /// A decoded id to its definition, and through it to its board. + adj: &'a Index, + /// A sender's IP to its board, for the datagrams that have no id. + boards: &'a HashMap, +} + +impl Lookups<'_> { + /// The board `from` belongs to, or `None` if its IP is no board's. Only + /// the IP counts: a board is identified by its address, not by the port + /// it sends from. + fn board_at(&self, from: SocketAddr) -> Option { + self.boards.get(&from.ip()).copied() + } +} + +/// Decodes a single datagram slice against the ADJ and forwards the result or error to `reporter`. /// /// A fault (packet id 0, see [`FAULT_ID`]) is reported before any of that, -/// without looking at `adj`. +/// without looking at the ADJ. /// /// Returns `false` if the downstream `reporter` channels have closed and the loop should stop. async fn decode_and_report( bytes: &[u8], from: SocketAddr, - adj: &Index, + lookups: Lookups<'_>, reporter: &Reporter, traces: &mut ReceiveTraces, ) -> bool { if bytes.starts_with(&FAULT_ID) { + let board = lookups.board_at(from); if let Some(suppressed) = traces.fault.should_trace(Instant::now()) { - error!(%from, suppressed, "a board signalled a fault (packet id 0)"); + error!(%from, ?board, suppressed, "a board signalled a fault (packet id 0)"); } - return reporter.report(UdpError::Fault { from }).await.is_ok(); + return reporter + .report(UdpError::Fault { from, board }) + .await + .is_ok(); } - let packet = match crate::protocol::udp::decode_datagram(bytes, adj) { + let packet = match crate::protocol::udp::decode_datagram(bytes, lookups.adj) { Ok(p) => p, Err(source) => { + let board = lookups.board_at(from); if let Some(suppressed) = traces.decode.should_trace(Instant::now()) { - error!(%from, %source, suppressed, "UDP datagram could not be decoded"); + error!(%from, ?board, %source, suppressed, "UDP datagram could not be decoded"); } - let error = UdpError::Decode { from, source }; + let error = UdpError::Decode { + from, + board, + source, + }; return reporter.report(error).await.is_ok(); } }; @@ -305,7 +375,7 @@ async fn decode_and_report( // run; it is handled rather than unwrapped because the decode lives // in another module. One extra `HashMap` lookup per datagram is not // worth changing `protocol`'s API to avoid. - let Some(packet_def) = adj.packet(packet.id) else { + let Some(packet_def) = lookups.adj.packet(packet.id) else { warn!(id = ?packet.id, "decoded packet id not in index"); return true; }; @@ -370,11 +440,11 @@ impl TraceRateLimit { /// Something that went wrong on the shared UDP socket, or that a board /// says went wrong ([`UdpError::Fault`]). /// -/// No [`crate::model::BoardId`] in any variant, on purpose: the socket -/// belongs to no board, and a datagram that fails to decode may not -/// resolve to one at all — [`UdpError::Decode`] and [`UdpError::Fault`] -/// carry the address the datagram came from, which is the only identity -/// that always exists. +/// [`UdpError::Decode`] and [`UdpError::Fault`] concern one datagram, so +/// they carry the address it came from, the only identity that always +/// exists, and the board that address belongs to, when it belongs to one +/// (see [`UdpConfig::boards`]). [`UdpError::Bind`] and [`UdpError::Recv`] +/// concern the socket, which belongs to no board. #[derive(Debug, thiserror::Error)] pub enum UdpError { /// The socket could not be bound, so no telemetry will arrive at all. @@ -400,9 +470,10 @@ pub enum UdpError { /// [`UdpError::is_fatal`]. #[error("could not decode a datagram from {from}")] Decode { - /// Where the datagram came from — there may be no board to - /// attribute it to. + /// Where the datagram came from. from: SocketAddr, + /// The board `from` belongs to; `None` if it belongs to none. + board: Option, /// What [`crate::protocol`] said about it. #[source] source: DecodeError, @@ -413,9 +484,11 @@ pub enum UdpError { /// arrived fine — but the pod telling the backend it is in trouble. #[error("the board at {from} signalled a fault (packet id 0)")] Fault { - /// Where the fault came from: the board's address, since a fault - /// carries nothing else that says which board sent it. + /// Where the fault came from. A fault carries nothing else that + /// says which board sent it. from: SocketAddr, + /// The board `from` belongs to; `None` if it belongs to none. + board: Option, }, } diff --git a/backend/crates/core/src/net/udp/manual_tests.rs b/backend/crates/core/src/net/udp/manual_tests.rs index eb890291d..a992487bd 100644 --- a/backend/crates/core/src/net/udp/manual_tests.rs +++ b/backend/crates/core/src/net/udp/manual_tests.rs @@ -155,7 +155,13 @@ async fn manual_udp_load() { let (socket, addr) = bind_on_loopback(recv_buffer); let granted = socket2::SockRef::from(&socket).recv_buffer_size().ok(); let (reporter, mut sinks) = Reporter::channels(8192, 16); - let receiver = tokio::spawn(receive_telemetry(socket, Arc::new(index), reporter)); + // No boards by address: the probe sends nothing that fails. + let receiver = tokio::spawn(receive_telemetry( + socket, + Arc::new(index), + HashMap::new(), + reporter, + )); // Counts until told the sender is done, then drains what is left. No // timer per message, so that the consumer costs as little as possible diff --git a/backend/crates/core/src/net/udp/test_support.rs b/backend/crates/core/src/net/udp/test_support.rs index aa8425133..11cfa9ff9 100644 --- a/backend/crates/core/src/net/udp/test_support.rs +++ b/backend/crates/core/src/net/udp/test_support.rs @@ -23,11 +23,25 @@ pub(super) const UNKNOWN_ID_DATAGRAM: [u8; 2] = [0xFF, 0xFF]; /// declare either — a fault is recognised without the ADJ. pub(super) const FAULT_DATAGRAM: [u8; 2] = [0x00, 0x00]; +/// The board every fixture here declares. +pub(super) const TEST_BOARD: BoardId = BoardId(1); + /// A board's address on the pod's network, for errors that carry one. pub(super) fn example_board_addr() -> SocketAddr { SocketAddr::new(IpAddr::from([192, 168, 1, 3]), 50400) } +/// An address that belongs to no board. +pub(super) fn stranger_addr() -> SocketAddr { + SocketAddr::new(IpAddr::from([192, 168, 1, 99]), 50400) +} + +/// [`UdpConfig::boards`] with a single entry: `ip` belongs to +/// [`TEST_BOARD`]. +pub(super) fn boards_at(ip: IpAddr) -> HashMap { + HashMap::from([(ip, TEST_BOARD)]) +} + /// `127.0.0.1` with port 0, so that the OS picks a free one. pub(super) fn any_loopback_port() -> SocketAddr { SocketAddr::new(IpAddr::from([127, 0, 0, 1]), 0) @@ -41,12 +55,12 @@ pub(super) fn any_loopback_port() -> SocketAddr { pub(super) fn index_with_empty_data_packet() -> Index { let packet = PacketDef { id: AdjId(1000), - board: BoardId(1), + board: TEST_BOARD, name: "test_data".to_string(), packet_type: PacketType::Data(vec![]), }; let board = Board { - id: BoardId(1), + id: TEST_BOARD, name: "TEST".to_string(), ip: IpAddr::from([192, 168, 0, 10]), mac: MacAddress([0; 6]), @@ -78,7 +92,7 @@ pub(super) async fn receive_error_report(sinks: &mut Sinks) -> ErrorReport { /// Asserts that `notification` is what [`EMPTY_DATA_DATAGRAM`] decodes to. pub(super) fn assert_is_empty_data_packet(notification: Notification) { - assert_eq!(notification.board, BoardId(1)); + assert_eq!(notification.board, TEST_BOARD); let Event::Received(Packet::Data(packet)) = notification.event else { unreachable!("a datagram should arrive as Event::Received(Packet::Data)"); }; @@ -92,8 +106,9 @@ pub(super) fn bind_on_loopback(recv_buffer: usize) -> (tokio::net::UdpSocket, So let config = UdpConfig { addr: any_loopback_port(), recv_buffer, + boards: HashMap::new(), }; - let Ok(socket) = bind_telemetry_socket(config) else { + let Ok(socket) = bind_telemetry_socket(&config) else { unreachable!("binding to a free loopback port should succeed"); }; let Ok(addr) = socket.local_addr() else { @@ -105,10 +120,14 @@ pub(super) fn bind_on_loopback(recv_buffer: usize) -> (tokio::net::UdpSocket, So /// Starts receiving on a free loopback port with /// [`index_with_empty_data_packet`], as [`spawn_udp`] does, and returns the /// address to send to along with the task's handle. +/// +/// `127.0.0.1`, where [`bind_fake_board`] sends from, belongs to +/// [`TEST_BOARD`]. pub(super) fn start_receiving_on_loopback(reporter: Reporter) -> (SocketAddr, JoinHandle<()>) { let (socket, addr) = bind_on_loopback(256 * 1024); let index = Arc::new(index_with_empty_data_packet()); - let handle = tokio::spawn(receive_telemetry(socket, index, reporter)); + let boards = boards_at(any_loopback_port().ip()); + let handle = tokio::spawn(receive_telemetry(socket, index, boards, reporter)); (addr, handle) } diff --git a/backend/crates/core/src/net/udp/tests.rs b/backend/crates/core/src/net/udp/tests.rs index b71efb004..01bcfe99c 100644 --- a/backend/crates/core/src/net/udp/tests.rs +++ b/backend/crates/core/src/net/udp/tests.rs @@ -13,6 +13,7 @@ use crate::model::AdjId; fn a_datagram_that_will_not_decode_faults_the_pod() { let error = UdpError::Decode { from: example_board_addr(), + board: Some(TEST_BOARD), source: DecodeError::UnknownId(AdjId(9999)), }; @@ -32,6 +33,7 @@ fn losing_the_socket_faults_the_pod_too() { fn a_decode_failure_says_where_it_came_from() { let error = UdpError::Decode { from: example_board_addr(), + board: Some(TEST_BOARD), source: DecodeError::UnknownId(AdjId(9999)), }; @@ -42,6 +44,7 @@ fn a_decode_failure_says_where_it_came_from() { fn a_board_signalling_a_fault_faults_the_pod() { let error = UdpError::Fault { from: example_board_addr(), + board: Some(TEST_BOARD), }; assert!(error.is_fatal()); @@ -51,6 +54,7 @@ fn a_board_signalling_a_fault_faults_the_pod() { fn a_fault_says_where_it_came_from() { let error = UdpError::Fault { from: example_board_addr(), + board: Some(TEST_BOARD), }; assert!(error.to_string().contains("192.168.1.3:50400")); @@ -64,12 +68,17 @@ fn a_fault_says_where_it_came_from() { async fn decode_and_report_notifies_a_valid_datagram() { let (reporter, mut sinks) = Reporter::channels(16, 16); let index = index_with_empty_data_packet(); + let boards = boards_at(example_board_addr().ip()); + let lookups = Lookups { + adj: &index, + boards: &boards, + }; let mut traces = ReceiveTraces::default(); let keep_going = decode_and_report( &EMPTY_DATA_DATAGRAM, example_board_addr(), - &index, + lookups, &reporter, &mut traces, ) @@ -84,15 +93,20 @@ async fn decode_and_report_notifies_a_valid_datagram() { } #[tokio::test] -async fn decode_and_report_reports_an_unknown_id() { +async fn decode_and_report_reports_an_unknown_id_with_its_board() { let (reporter, mut sinks) = Reporter::channels(16, 16); let index = index_with_empty_data_packet(); + let boards = boards_at(example_board_addr().ip()); + let lookups = Lookups { + adj: &index, + boards: &boards, + }; let mut traces = ReceiveTraces::default(); let keep_going = decode_and_report( &UNKNOWN_ID_DATAGRAM, example_board_addr(), - &index, + lookups, &reporter, &mut traces, ) @@ -100,10 +114,16 @@ async fn decode_and_report_reports_an_unknown_id() { assert!(keep_going); let report = receive_error_report(&mut sinks).await; - let crate::net::Error::Udp(UdpError::Decode { from, source }) = report.error else { + let crate::net::Error::Udp(UdpError::Decode { + from, + board, + source, + }) = report.error + else { unreachable!("an undecodable datagram should be reported as udp::UdpError::Decode"); }; assert_eq!(from, example_board_addr()); + assert_eq!(board, Some(TEST_BOARD), "resolved from the address"); assert!(matches!(source, DecodeError::UnknownId(AdjId(0xFFFF)))); assert!( sinks.notifications.try_recv().is_err(), @@ -116,12 +136,17 @@ async fn decode_and_report_reports_a_fault_without_looking_at_the_adj() { let (reporter, mut sinks) = Reporter::channels(16, 16); // Declares id 1000 only: id 0 is unknown to it, and yet it is a fault. let index = index_with_empty_data_packet(); + let boards = boards_at(example_board_addr().ip()); + let lookups = Lookups { + adj: &index, + boards: &boards, + }; let mut traces = ReceiveTraces::default(); let keep_going = decode_and_report( &FAULT_DATAGRAM, example_board_addr(), - &index, + lookups, &reporter, &mut traces, ) @@ -129,26 +154,72 @@ async fn decode_and_report_reports_a_fault_without_looking_at_the_adj() { assert!(keep_going); let report = receive_error_report(&mut sinks).await; - let crate::net::Error::Udp(UdpError::Fault { from }) = report.error else { + let crate::net::Error::Udp(UdpError::Fault { from, board }) = report.error else { unreachable!("a datagram with packet id 0 should be reported as udp::UdpError::Fault"); }; assert_eq!(from, example_board_addr()); + assert_eq!(board, Some(TEST_BOARD), "resolved from the address"); assert!( sinks.notifications.try_recv().is_err(), "should not have notified a packet" ); } +#[tokio::test] +async fn an_address_that_belongs_to_no_board_is_reported_without_one() { + let (reporter, mut sinks) = Reporter::channels(16, 16); + let index = index_with_empty_data_packet(); + let boards = boards_at(example_board_addr().ip()); + let lookups = Lookups { + adj: &index, + boards: &boards, + }; + let mut traces = ReceiveTraces::default(); + + decode_and_report( + &FAULT_DATAGRAM, + stranger_addr(), + lookups, + &reporter, + &mut traces, + ) + .await; + decode_and_report( + &UNKNOWN_ID_DATAGRAM, + stranger_addr(), + lookups, + &reporter, + &mut traces, + ) + .await; + + // Still reported, with the address: only the board is missing. + let fault = receive_error_report(&mut sinks).await; + let crate::net::Error::Udp(UdpError::Fault { from, board: None }) = fault.error else { + unreachable!("a fault from an unknown address should carry no board"); + }; + assert_eq!(from, stranger_addr()); + let decode = receive_error_report(&mut sinks).await; + let crate::net::Error::Udp(UdpError::Decode { board: None, .. }) = decode.error else { + unreachable!("a decode failure from an unknown address should carry no board"); + }; +} + #[tokio::test] async fn whatever_follows_the_fault_id_is_not_read() { let (reporter, mut sinks) = Reporter::channels(16, 16); let index = index_with_empty_data_packet(); + let boards = HashMap::new(); + let lookups = Lookups { + adj: &index, + boards: &boards, + }; let mut traces = ReceiveTraces::default(); decode_and_report( &[0x00, 0x00, 0xAB, 0xCD], example_board_addr(), - &index, + lookups, &reporter, &mut traces, ) @@ -165,13 +236,18 @@ async fn whatever_follows_the_fault_id_is_not_read() { async fn a_single_zero_byte_is_not_a_fault() { let (reporter, mut sinks) = Reporter::channels(16, 16); let index = index_with_empty_data_packet(); + let boards = HashMap::new(); + let lookups = Lookups { + adj: &index, + boards: &boards, + }; let mut traces = ReceiveTraces::default(); // An id takes two bytes: one zero byte is a truncated datagram. decode_and_report( &[0x00], example_board_addr(), - &index, + lookups, &reporter, &mut traces, ) @@ -188,6 +264,11 @@ async fn a_single_zero_byte_is_not_a_fault() { async fn decode_and_report_stops_once_nobody_listens() { let (reporter, sinks) = Reporter::channels(16, 16); let index = index_with_empty_data_packet(); + let boards = HashMap::new(); + let lookups = Lookups { + adj: &index, + boards: &boards, + }; let mut traces = ReceiveTraces::default(); drop(sinks); @@ -195,7 +276,7 @@ async fn decode_and_report_stops_once_nobody_listens() { let keep_going = decode_and_report( &UNKNOWN_ID_DATAGRAM, example_board_addr(), - &index, + lookups, &reporter, &mut traces, ) @@ -258,7 +339,7 @@ async fn a_datagram_sent_to_the_socket_arrives_as_a_notification() { } #[tokio::test] -async fn an_undecodable_datagram_is_reported_with_its_sender() { +async fn an_undecodable_datagram_is_reported_with_its_sender_and_board() { let (reporter, mut sinks) = Reporter::channels(16, 16); let (addr, handle) = start_receiving_on_loopback(reporter); let board = bind_fake_board().await; @@ -269,15 +350,16 @@ async fn an_undecodable_datagram_is_reported_with_its_sender() { send_datagram(&board, &UNKNOWN_ID_DATAGRAM, addr).await; let report = receive_error_report(&mut sinks).await; - let crate::net::Error::Udp(UdpError::Decode { from, .. }) = report.error else { + let crate::net::Error::Udp(UdpError::Decode { from, board, .. }) = report.error else { unreachable!("an undecodable datagram should be reported as udp::UdpError::Decode"); }; assert_eq!(from, board_addr); + assert_eq!(board, Some(TEST_BOARD)); handle.abort(); } #[tokio::test] -async fn a_fault_sent_to_the_socket_is_reported_with_its_sender() { +async fn a_fault_sent_to_the_socket_is_reported_with_its_sender_and_board() { let (reporter, mut sinks) = Reporter::channels(16, 16); let (addr, handle) = start_receiving_on_loopback(reporter); let board = bind_fake_board().await; @@ -288,10 +370,11 @@ async fn a_fault_sent_to_the_socket_is_reported_with_its_sender() { send_datagram(&board, &FAULT_DATAGRAM, addr).await; let report = receive_error_report(&mut sinks).await; - let crate::net::Error::Udp(UdpError::Fault { from }) = report.error else { + let crate::net::Error::Udp(UdpError::Fault { from, board }) = report.error else { unreachable!("a datagram with packet id 0 should be reported as udp::UdpError::Fault"); }; assert_eq!(from, board_addr); + assert_eq!(board, Some(TEST_BOARD)); handle.abort(); } @@ -315,9 +398,10 @@ async fn the_loop_stops_on_the_next_datagram_once_nobody_listens() { async fn binding_an_address_already_in_use_is_a_bind_error() { let (_first, taken) = bind_on_loopback(256 * 1024); - let second = bind_telemetry_socket(UdpConfig { + let second = bind_telemetry_socket(&UdpConfig { addr: taken, recv_buffer: 256 * 1024, + boards: HashMap::new(), }); let Err(UdpError::Bind { addr, .. }) = second else { diff --git a/backend/crates/station/src/event.rs b/backend/crates/station/src/event.rs new file mode 100644 index 000000000..5749e36b3 --- /dev/null +++ b/backend/crates/station/src/event.rs @@ -0,0 +1,358 @@ +//! The communication between station's modules. +//! +//! Every module runs in its own task and only talks to the others through +//! queues. This module prepares every one of those queues, in one call +//! ([`channels`]), and routes what goes through them ([`spawn`]): +//! +//! - **towards the front**, the routing loop takes what `net` reports and +//! every error, and hands it to `logging` and `pipeline`, reading errors +//! first, then TCP, then UDP; +//! - **towards the boards**, two workers write the front's orders and the +//! fault to TCP, so the routing loop never waits on a socket. +//! +//! The full design (the queues and their numbers, the error procedures, +//! how it stops, the contract with the other modules) is in +//! `event/README.md`; the numbers ①–⑧ below refer to its table. + +mod fault; +mod orders; +mod policy; +mod router; + +#[cfg(test)] +mod manual_tests; +#[cfg(test)] +mod tests; + +pub use policy::full_message; + +use std::future::Future; +use std::pin::Pin; +use std::sync::Arc; +use std::time::{Duration, SystemTime}; + +use software_core::model::{BoardId, OrderPacket, PodData}; +use software_core::net::{Notification, Reporter}; +use software_core::protocol::Index; +use tokio::sync::mpsc; +use tokio::task::{JoinHandle, JoinSet}; + +use self::fault::FAULT_QUEUE; +use self::router::{Router, RouterEnds}; + +/// A future that can be sent to another task, boxed so that [`TcpLink`] can +/// be used as a trait object. +pub type BoxFuture<'a, T> = Pin + Send + 'a>>; + +/// What `event` needs from the TCP client: writing an order to its board, +/// and sending the fault to every board. +/// +/// A trait rather than `net::tcp`'s own type so that the workers can be +/// tested against a fake, and so that `event` does not depend on the TCP +/// client's API beyond these two calls. +pub trait TcpLink: Send + Sync { + /// Writes `order` to the board it belongs to. + /// + /// Returns that board **once the order is written**, not once it is + /// queued; fails right away, with the reason, if the board is not + /// connected. + fn send(&self, order: OrderPacket) -> BoxFuture<'_, Result>; + + /// Sends the fault to every board. Fails with the boards it did not + /// reach. + fn send_fault(&self) -> BoxFuture<'_, Result<(), Vec>>; +} + +/// Sizes of every queue, and the two settings of the error rules. +/// +/// Every size is clamped to at least 1. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct EventConfig { + /// Slots in each of `net`'s error queues (①, one per transport). + pub errors_queue: usize, + /// Slots in ② (problems from station modules). + pub problems_queue: usize, + /// Slots in ③ (TCP notifications). + pub tcp_queue: usize, + /// Slots in ④ (UDP notifications). The only stretch of queue between the + /// UDP socket and the routing loop, so the widest. + pub udp_queue: usize, + /// Slots in ⑤ (to `logging`). + pub logging_queue: usize, + /// Slots in ⑥ (to `pipeline`). + pub pipeline_queue: usize, + /// Slots in ⑦ (orders from the front). + pub orders_queue: usize, + /// Send the fault a board sends to every other board as well. + pub propagate_fault: bool, + /// How long a fatal stop waits for the fault to be sent. + pub fault_timeout: Duration, +} + +impl Default for EventConfig { + // Default config + fn default() -> Self { + Self { + errors_queue: 16, + problems_queue: 16, + tcp_queue: 1024, + udp_queue: 8192, + logging_queue: 8192, + pipeline_queue: 8192, + orders_queue: 32, + propagate_fault: true, + fault_timeout: Duration::from_secs(2), + } + } +} + +/// Something the operator has to see. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Problem { + /// When it was detected. + pub at: SystemTime, + /// The board, if known. + pub board: Option, + /// What it means for the backend. + pub kind: ProblemKind, + /// The message with all its causes: "could not X: because Y: because Z" + /// (see [`full_message`]). + pub text: String, +} + +impl Problem { + /// A problem detected now. + pub fn now(kind: ProblemKind, board: Option, text: impl Into) -> Self { + Self { + at: SystemTime::now(), + board, + kind, + text: text.into(), + } + } +} + +/// What a [`Problem`] means for the backend. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ProblemKind { + /// Shown on the front; the backend keeps running. + Shown, + /// The fault is sent, it is shown on the front and the backend stops. + Fatal, + /// Only written to the trace: not shown, the backend keeps running. + Silent, +} + +/// What `logging` receives (⑤). +#[derive(Debug)] +pub enum ToLogging { + /// A notification, TCP or UDP, as soon as it arrives. `pipeline` gets the + /// same copy. + Received(Arc), + /// An order TCP confirmed it wrote. + OrderSent { + /// When the write was confirmed. + at: SystemTime, + /// The board it was written to; `None` for the fault, which goes to + /// every board. + board: Option, + /// The order. + order: OrderPacket, + }, +} + +/// What `pipeline` receives (⑥). +#[derive(Debug)] +pub enum ToPipeline { + /// A notification, TCP or UDP, as soon as it arrives. `logging` gets the + /// same copy. + Received(Arc), + /// Something the operator has to see. + Problem(Problem), + /// An order the front sent that went out: shown on the front as a message + /// from the backend. + OrderSent { + /// When the write was confirmed. + at: SystemTime, + /// The board it was written to; `None` for the fault, which goes to + /// every board. + board: Option, + /// The order. + order: OrderPacket, + }, + /// An order the front sent that did not go out: shown on the front as a + /// message from the backend, with the reason. + OrderFailed { + /// When it failed. + at: SystemTime, + /// The order. + order: OrderPacket, + /// Why. + reason: String, + }, +} + +/// Why `event` ended. `main` reads it and shuts everything down in order. +#[derive(Debug)] +pub enum Stop { + /// A fatal error: shown on the front, fault sent (or attempted). + Fatal(Problem), + /// `net`'s queues closed: UDP and TCP were stopped. + NetGone, +} + +/// The board's name for the operator, as the ADJ declares it, or its id if +/// the ADJ does not declare it. +fn board_name(pod_data: &PodData, board: BoardId) -> String { + pod_data + .board_name(board) + .map_or_else(|| format!("{board:?}"), str::to_owned) +} + +/// Every queue between modules, as [`channels`] hands them out. +#[derive(Debug)] +pub struct Channels { + /// For `net::udp`: reports on ① and ④. + pub udp: Reporter, + /// For `net::tcp`: reports on ① and ③. Drop it if TCP is not started. + pub tcp: Reporter, + /// `event`'s own ends, for [`spawn`]. + pub event: EventEnds, + /// ⑦, for websocket's order forwarder. + pub orders: mpsc::Sender, + /// ②, cloned for every station module that reports problems. + pub problems: mpsc::Sender, + /// ⑤, for `logging`. + pub logging: mpsc::Receiver, + /// ⑥, for `pipeline`. + pub pipeline: mpsc::Receiver, +} + +/// `event`'s own ends of the queues: the reading side of ① ② ③ ④ ⑦ and the +/// writing side of ⑤ ⑥. Only [`spawn`] opens it. +#[derive(Debug)] +pub struct EventEnds { + /// ① ② ③ ④ ⑤ ⑥: for the routing loop. + router: RouterEnds, + /// ⑦: for the orders worker. + orders: mpsc::Receiver, +} + +/// Creates every queue between modules. `main` calls it once, before +/// spawning anything, and hands each end to whoever uses it. +/// +/// `net`'s queues are built with `net`'s own [`Reporter::channels`], once per +/// transport: TCP and UDP each get their own notification queue, so that TCP +/// can be read first, and their own error queue. +pub fn channels(config: &EventConfig) -> Channels { + let errors = config.errors_queue.max(1); //max(1) to avoid 0-capacity channels + let tcp_capacity = config.tcp_queue.max(1); + let udp_capacity = config.udp_queue.max(1); + + // Channel creation + let (udp, udp_sinks) = Reporter::channels(udp_capacity, errors); + let (tcp, tcp_sinks) = Reporter::channels(tcp_capacity, errors); + let (problems_tx, problems_rx) = mpsc::channel(config.problems_queue.max(1)); + let (orders_tx, orders_rx) = mpsc::channel(config.orders_queue.max(1)); + let (logging_tx, logging_rx) = mpsc::channel(config.logging_queue.max(1)); + let (pipeline_tx, pipeline_rx) = mpsc::channel(config.pipeline_queue.max(1)); + + Channels { + udp, + tcp, + event: EventEnds { + router: RouterEnds { + udp: udp_sinks, + tcp: tcp_sinks, + problems: problems_rx, + logging: logging_tx, + pipeline: pipeline_tx, + tcp_capacity, + udp_capacity, + }, + orders: orders_rx, + }, + orders: orders_tx, + problems: problems_tx, + logging: logging_rx, + pipeline: pipeline_rx, + } +} + +/// Starts the routing loop and the two workers. +/// +/// `pod_data` is only read for the boards' names, which the texts shown on +/// the front and written to the trace use; `index` for which protections and +/// messages a board sends mean that it is in fault. +/// +/// Without a TCP client (`tcp: None`), every order fails with "TCP not +/// available" and the fault is only traced. +/// +/// The returned task ends with the reason it stopped, once the workers have +/// been stopped too: by then every sender of ⑤ and ⑥ is gone, so `logging` +/// and `pipeline` finish what they have queued and end on their own. +pub fn spawn( + config: EventConfig, + ends: EventEnds, + pod_data: Arc, + index: Arc, + tcp: Option>, +) -> JoinHandle { + tokio::spawn(run(config, ends, pod_data, index, tcp)) +} + +/// The body of the task [`spawn`] starts: the routing loop (towards the +/// front) and the orders and fault workers (towards the boards). +/// +/// Three tasks rather than one loop because writing to a socket can wait, and +/// the routing loop never must: while it waits, nobody reads `net`'s queues. +/// Returns why event stopped, once the workers have stopped too. +async fn run( + config: EventConfig, + ends: EventEnds, + pod_data: Arc, + index: Arc, + tcp: Option>, +) -> Stop { + // ⑦ goes straight to the orders worker, so an order never queues behind + // telemetry in the routing loop; everything else goes to the loop. + let EventEnds { + router: ends, + orders: orders_rx, + } = ends; + + // ⑧ never leaves event: its senders and its reader are all created here, + // so it needs no place in `channels`, and no other module can ask for a + // fault behind event's back. + let (fault_tx, fault_rx) = mpsc::channel(FAULT_QUEUE); + + // One set, so that both workers can be stopped together at the end. + let mut workers = JoinSet::new(); + workers.spawn(fault::run( + fault_rx, + tcp.clone(), // the same client (an `Arc`), not a second connection + ends.logging.clone(), + ends.pipeline.clone(), + pod_data.clone(), // for the boards' names in its messages + )); + workers.spawn(orders::run( + orders_rx, + tcp, + fault_tx.clone(), // order id 0 is the fault: passed on to the fault worker + ends.logging.clone(), + ends.pipeline.clone(), + )); + + // The loop keeps the original ⑧ sender, for the faults event decides on. + let router = Router::new(config, pod_data, index, ends, fault_tx); + + // Runs until it has to stop. It takes the router by value, so its ends of + // ⑤ ⑥ ⑧ are dropped when it returns. + let stop = router.route().await; + + // The workers would never end on their own (⑦ and ⑧ stay open), and their + // clones of ⑤ ⑥ would keep `logging` and `pipeline` waiting forever. + // Stopping them closes ⑤ ⑥, so those two finish what is queued and end. + workers.shutdown().await; + stop +} diff --git a/backend/crates/station/src/event/README.md b/backend/crates/station/src/event/README.md new file mode 100644 index 000000000..2963c706a --- /dev/null +++ b/backend/crates/station/src/event/README.md @@ -0,0 +1,556 @@ +# `event`: how station's modules talk to each other + +> `net::tcp` is not wired in yet: `main` starts `event` without a TCP client, +> so orders fail with "TCP not available" and the fault is only traced. + +Every module of the backend runs in **its own task**. A task is tokio's +lightweight thread: it runs on its own, at its own pace, and tokio spreads all +the tasks over a handful of OS threads (about one per CPU core). For this +document, think of each task as a thread. + +Modules **never call each other's functions** while running. They only talk +through **queues**: one module puts a message in, another takes it out. + +**`event` is that communication.** It is not "the UDP module" or "the orders +module": it is the switchboard every module goes through. It does two things: + +1. **It prepares every queue between modules**, in one place + ([`event::channels`](#who-creates-the-queues)), and `main` hands each end to + the module that uses it. +2. **It routes what goes through them**, in both directions: + - **towards the front**: what the boards send, and every error, goes to + `logging` (disk) and `pipeline` (front), in a fixed order of priority: + **errors, then TCP, then UDP**; + - **towards the boards**: orders from the front, and the fault, go to TCP. + +It does no work on the data. The real work (decoding, writing to disk, building +the front's JSON, writing to a socket) happens in the other tasks. + +## Overview + +`event` is three tasks: the **routing loop**, which handles everything going +towards the front, and two **workers**, which handle everything going towards +the boards. + +**Towards the front:** + +```text + ┌─ task ─────┐ ─① errors──────► ┌─ task ───────────────────┐ ─⑤─► ┌─ task ───┐ + │ net::udp │ ─④ UDP notif.──► │ event: routing loop │ │ logging │ → disk + └────────────┘ │ │ └──────────┘ + ┌─ task ─────┐ ─① errors──────► │ reads in this order: │ + │ net::tcp │ ─③ TCP notif.──► │ 1. ① ② errors │ ─⑥─► ┌─ task ───┐ + └────────────┘ │ 2. ③ TCP notifications │ │ pipeline │ → websocket → front + any station ─② problems─────► │ 3. ④ UDP notifications │ └──────────┘ + module └────────────┬─────────────┘ + │ ⑧ (fatal error, board fault) + ▼ + fault worker +``` + +**Towards the boards:** + +```text + front → websocket ─⑦ orders─► ┌─ task ──────────┐ ──► TCP: write to that board + │ orders worker │ ─⑤─► logging (sent) + │ one at a time │ ─⑥─► pipeline (sent or failed) + └───────┬─────────┘ + │ ⑧ (order id 0 = fault) + ▼ + routing loop ─⑧─────────────► ┌─ task ──────────┐ ──► TCP: fault to every board + │ fault worker │ ─⑤─► logging (front's fault sent) + │ every request │ ─⑥─► pipeline (front's fault sent or failed, + │ │ boards not reached) + └─────────────────┘ + + main: calls event::channels(), spawns every task with its ends, + waits for event's Stop, then shuts everything down in order +``` + +The circled numbers are the queues in [The queues](#the-queues). + +Why it is built like this: + +- **A slow module does not hold up the others.** Each one works at its own + pace. The only time one waits for another is when a queue is full, and that + is on purpose (see "wait, don't drop" below). +- **The two directions never get in each other's way.** An order is never + stuck behind thousands of telemetry packets, and a slow board never holds up + the telemetry: orders and the fault have their own tasks. +- **Each module can be tested alone**: fill its input queue by hand and look at + what comes out of its output queue. No sockets, no other modules. +- **The boundaries are explicit.** What one module can tell another is exactly + the type of the queue between them, and nothing else. +- **All the decisions are in one module.** What to do about an error, when to + send the fault and when to stop live in `event`, not scattered across modules. + `net`, in particular, leaves all of that out on purpose. + +## Words used here + +- **Queue** (`tokio::sync::mpsc`): a line with a fixed number of slots between + two tasks. One puts messages in at one end (`Sender`), the other takes them + out at the other end (`Receiver`). Each queue has a single reader; it can + have several writers (the `Sender` is cloned). +- **`Reporter` and `Sinks`**: how `net` delivers what happens: the `Reporter` is + the putting end, held by the UDP or TCP task; the `Sinks` are the taking end, + held by `event`. They carry **notifications** (`Notification`: "this packet + arrived", "this board connected") and **errors** (`ErrorReport`). See + [`net/report.rs`](../../../core/src/net/report.rs). +- **Worker**: a task owned by `event` that does one slow thing (writing an order + to TCP, sending the fault), so that the routing loop never waits on a socket. +- **Wait, don't drop**: when a queue is full, whoever is putting into it waits + until there is a free slot. That wait travels back up to the socket, so the + only thing that can be lost is what the operating system has not handed over + yet, which has not been decoded yet. `net` works the same way. +- **Shared copy** (`Arc`): one piece of data in memory that several readers use + without copying it. It is freed when the last one lets go of it. +- **`select!` in fixed order** (`biased`): `select!` waits on several queues at + once. With `biased`, when more than one has something, the first one in the + list always wins. That is how priorities are done. + +## Files + +``` +event.rs # module root: the public types, channels, spawn +event/ +├── router.rs # the routing loop: everything towards the front +├── policy.rs # what to do with each error +├── orders.rs # the orders worker +├── fault.rs # the fault worker +├── tests.rs # the routing loop and the workers, with a fake TCP client +├── manual_tests.rs # throughput probe, ignored by default +└── README.md +``` + +## The queues + +| # | Queue | From → to | Carries | +|---|---|---|---| +| ① | net errors (one queue per transport) | `net::udp`, `net::tcp` → routing loop | `ErrorReport` | +| ② | problems | any station module → routing loop | `Problem` | +| ③ | TCP notifications | `net::tcp` → routing loop | `Notification` (protections, messages, connected/disconnected) | +| ④ | UDP notifications | `net::udp` → routing loop | `Notification` (data) | +| ⑤ | to logging | routing loop, both workers → `logging` | `ToLogging` | +| ⑥ | to pipeline | routing loop, both workers → `pipeline` | `ToPipeline` | +| ⑦ | orders | `websocket` → orders worker | `OrderPacket` (id 0 = fault) | +| ⑧ | fault requests | routing loop, orders worker → fault worker | `FaultRequest` | + +**The routing loop reads ① to ④ in that order: errors, then TCP, then UDP.** + +- **Errors first**: an error is never stuck behind telemetry. +- **TCP before UDP**: a protection or a board's message is never stuck behind + thousands of telemetry packets. TCP carries little traffic, so reading it + first does not starve UDP. +- The order between a TCP and a UDP notification is not kept across the two + queues; each one carries the instant it was received (`at`), so anyone who + needs the real order can recover it. +- The order of priority applies **only towards the front**. Orders (⑦) go the + other way and are not read by the routing loop at all: the orders worker + reads them itself. + +## Who creates the queues + +**`event` does, all of them, in one call.** `main` calls it once before +spawning anything and hands each end to whoever uses it: + +```rust +let channels = event::channels(&config); + +spawn_udp(udp_config, index.clone(), channels.udp)?; // ① ④ +// the TCP client takes channels.tcp ① ③ +let event = event::spawn(config, channels.event, pod_data, index, tcp); // Arc, Arc, Option> +logging::spawn(channels.logging, ...); // ⑤ +pipeline::spawn(channels.pipeline, broker_client, ...); // ⑥ +OrderForwarder::new(index, channels.orders); // ⑦ (websocket) +// channels.problems is cloned for every station module that reports errors ② +``` + +Why one place, instead of each module creating its own input queue: + +- There are **circles**: `event` sends to `logging`, and `logging` reports its + own failures back to `event` (②); `event` asks TCP to write, and TCP reports + back to `event` (① ③). If every module created its own queue, someone would + need the other's end before it existed. Creating everything first, in one + call, removes the problem. +- **`event` defines the types of all its queues**, including the ones going to + `logging` and `pipeline`. So it can be written and tested alone, and + `logging`/`pipeline` depend on `event`, never the other way round. +- The fault requests queue (⑧) is created inside `event::spawn`: nobody outside + `event` ever sees it. +- `net`'s queues are built with `net`'s own `Reporter::channels` (`core` + cannot depend on `station`), called **once per transport**: `net::udp` and + `net::tcp` each get their own `Reporter`, with its own notification queue + (so that TCP can be read first) and its own error queue. `net` needs no + change for it. + +## Towards the front + +| What arrives | `logging` | `pipeline` | fault worker | +|---|---|---|---| +| TCP notification (③) | yes | yes | — | +| UDP notification (④) | yes | yes | — | +| Problem to show (②, or a non-fatal error from ①) | no (trace only) | yes | — | +| Fatal error | no (trace only) | yes, before stopping | yes | +| Fault from a board (packet id 0, ①) | no (trace only) | yes, the first one from each board | yes, every time, if `propagate_fault` is on | +| Protection with severity `Fault`, or message `Fault`/`Panic` (③) | yes | yes, as the notification it is | yes, every time, if `propagate_fault` is on | + +**How notifications travel.** One at a time, as soon as they arrive: the routing +loop puts each one in **one shared copy** (`Arc`) and sends that +same copy to both `logging` and `pipeline`. Nothing is duplicated in memory, +and each consumer takes what it needs (`logging` its selected measurements, +`pipeline` its counts and averages). `event` never looks inside. Each +`Notification` travels whole, so both times reach the consumers: when it was +received (`at`) and, for protections and messages, the board's own clock +(`ShortTimestamp`). + +**When ⑤ or ⑥ is full, `event` waits; it does not drop.** Everything decoded +reaches the disk, the same rule `net` follows. While the routing loop waits for +a free slot it does not handle errors either; this is accepted because the disk +is expected to keep up with the incoming rate (about 15–25 Mbit/s). + +## Towards the boards + +- **Orders.** `websocket` validates each order against the ADJ and puts it on + ⑦. The orders worker takes them **one at a time**: it writes the order and + waits for TCP to say it went out (or why not) before taking the next one. + - **"Sent" means written, not queued.** A sent order (`OrderSent`) goes to + `logging` (⑤) and to `pipeline` (⑥) only once TCP confirms the write. + - **A failed order** (`OrderFailed`) goes to `pipeline` (⑥), with the reason. + An order for a board that is not connected fails right away instead of + waiting in a queue. + - **The front sees both**: `pipeline` turns them into a message from the + backend (`message/update`), so the operator always knows whether an order + went out. +- **The fault.** The fault worker sends the fault (order id 0) to every board, + **once per request, every time it is asked**. It gets requests on ⑧ from + three places: + - **A fatal error**, from the routing loop, as the first step of stopping. + - **A board in fault**, from the routing loop, if `propagate_fault` is on + (the default): every fault a board sends is sent on to every board, each + time it arrives. A board is in fault when it sends the fault itself (packet + id 0), a protection the ADJ declares with severity `Fault`, or a message of + level `Fault` or `Panic`. The protection's severity comes from its + measurement's declaration and the message's level from `message_ids`, both + read through the `Index`. + - **The front**, from the orders worker (an order with id 0). It follows the + flow of any other order: sent to every board, and the front is told how it + went: `OrderSent` to `logging` and `pipeline` (with no board: it goes to + every board), or `OrderFailed` with the reason. Nothing else. + - **Boards it did not reach**: a fault that only half landed is exactly what + the operator has to know. For an automatic fault they go to `pipeline` as a + `Problem`; for the front's, they are the reason in `OrderFailed`. +- **Without TCP** (no TCP client running), every order fails with "TCP not + available", shown on the front, and an automatic fault is only traced. + +Neither worker is ever waited on by the routing loop, except when stopping on a +fatal error (see [Stopping](#stopping)): writing to a socket can take time (a +board that stops reading, a timeout), and the telemetry must not wait for it. + +## Errors + +**`event`** decides what an error means, not `net`: it looks at the error +itself and does not use `is_fatal()`. The decision lives in a function that +keeps no state between calls (`policy.rs`), so it can be tested on its own. + +There are three procedures, and every one of them ends up in the trace: + +1. **Not fatal, not shown**: trace only. Usually traced where it happens, + without reaching `event` (e.g. a failed reconnection with backoff); a + problem that does reach `event` this way is a `ProblemKind::Silent`, and + `event` only traces it. +2. **Not fatal, shown on the front**: e.g. an order to a board that is not + connected. +3. **Fatal, shown on the front**: send the fault, close TCP, shut the backend + down safely. + +| Error | What it means | Procedure | +|---|---|---| +| `UdpError::Decode` (any variant) | a datagram that cannot be decoded: the loaded ADJ does not match what the boards send | **3, fatal** | +| `UdpError::Recv` | the socket can no longer be read: telemetry from every board is gone | **3, fatal** | +| `UdpError::Fault { from, board }` | a board detected an error and says so (packet id 0) | **board fault**: shown (the first one from each board), sent to every board each time if `propagate_fault` is on; the backend **keeps running** | +| `UdpError::Bind` | the port could not be opened | never arrives: a startup failure, returned by `spawn_udp` | +| TCP frame that cannot be decoded | same as UDP | **3, fatal** | +| TCP fault (packet id 0 over TCP) | same as UDP | **board fault** | +| TCP connect or read failure | a board not up yet, or a connection that dropped | **1**, trace only; the `Disconnected` notification already tells the front | +| TCP keep-alive write failure | the keep-alive could not be written | **2, shown** | +| An order that could not be written | reported by the orders worker, not by `net` | **2, shown** | +| `Problem` from a station module (②) | whatever that module reports | what the module says: **1** (`Silent`), **2** (`Shown`) or **3** (`Fatal`) | +| `logging` or `pipeline` stops (⑤ or ⑥ closed) | nothing is recorded, or nothing is shown | **3, fatal** | + +Every decode error is fatal, not only an unknown id: a truncated datagram or an +enum value out of range also say the ADJ does not match the firmware, and +nothing corrupts a packet in flight. A dead `logging` means the run is not +recorded; a dead `pipeline` means the operator sees nothing. + +**Which board.** Every error from `net` names its board when there is one: +TCP errors always do, and `UdpError::Decode` and `UdpError::Fault` carry, next +to the address the datagram came from (`from`), the board that address belongs +to, which `net::udp` resolves itself from `UdpConfig::boards`. `event` only +puts the board's name in front of the text, read from the ADJ's `PodData` +(`PodData::board_name`), so the front says "HVSCU" rather than "127.0.0.7". An +address that belongs to no board arrives without a board, and the text carries +the address. + +**Board faults on the front.** A fault packet (id 0) arrives as an error, not +as a notification, so the front only sees it through `event`: the first one +from each board is shown, as a `Shown` problem whose text names the board; +repeats are not, since `net` already traces them (at most one line a second, +with how many were skipped). A `Fault` protection or a `Fault`/`Panic` message +reaches the front as the notification it is, so nothing extra is shown for it. +Either way, whether it is also sent to every board is set by `propagate_fault`, +on by default, and it is sent each time one arrives. + +**Traces.** Every error ends up in the trace (`tracing`), but never twice: the +module where it happens traces it, and `event` only traces what it decides +itself ("fatal, stopping", "fault sent to every board", "first fault from +HVSCU") and the `Silent` problems it is sent. + +## Stopping + +**On a fatal error**, the routing loop: + +1. Asks the fault worker for the fault, without waiting for it to go out: the + fault comes first, and the next steps happen while it is being written. +2. Sends the `Problem` to `pipeline`, so the operator sees it. +3. Empties whatever was already in ③ and ④ (at most their capacity) and passes + it on. Errors are read first, so the fatal error has overtaken the data that + arrived just before it, and that data is exactly what you want to understand + what happened. +4. Waits for the fault to have gone out, within `fault_timeout` from step 1 + (if it already has, the answer is immediate). +5. Ends by returning `Stop::Fatal(problem)`. + +If what stopped is `logging` or `pipeline`, step 3 is skipped. If it is +`logging`, `event` still tells `pipeline`. + +**On Ctrl+C:** `main` handles it, not `event`. `main` stops the UDP task +(`JoinHandle::abort`, see "Stopping" in [`net/udp.rs`](../../../core/src/net/udp.rs)) +and closes TCP. When those tasks end their `Reporter`s go with them, `net`'s +queues close, and the routing loop passes on whatever was left and ends with +`Stop::NetGone`. + +**Then `main` always does the same:** + +1. Stops UDP and closes TCP, if not done already. +2. When `event` ends, ⑤ and ⑥ close: `logging` and `pipeline` finish what they + have queued and end on their own (`logging` flushes its files to disk). +3. Waits for them, with a time limit of a few seconds. +4. Exits with code **1** after a fatal error and **0** after Ctrl+C. A + `Stop::NetGone` without Ctrl+C means `net` ended on its own, so that is 1 + as well. + +## Types + +```rust +/// Creates every queue between modules. `main` calls it once, before spawning +/// anything, and hands each end to whoever uses it. +pub fn channels(config: &EventConfig) -> Channels; + +pub struct Channels { + /// For net::udp: reports on ① and ④. + pub udp: Reporter, + /// For net::tcp: reports on ① and ③. Dropped if TCP is not started. + pub tcp: Reporter, + /// event's own ends (the reading side of ① ② ③ ④ ⑦, the writing side of + /// ⑤ ⑥), for `spawn`. Opaque. + pub event: EventEnds, + /// ⑦, for websocket's OrderForwarder. + pub orders: mpsc::Sender, + /// ②, cloned for every station module that reports problems. + pub problems: mpsc::Sender, + /// ⑤, for logging. + pub logging: mpsc::Receiver, + /// ⑥, for pipeline. + pub pipeline: mpsc::Receiver, +} + +/// Starts the routing loop and the two workers. Without a TCP client (`None`), +/// every order fails with "TCP not available" and the fault is only traced. +/// The task ends with the reason it stopped, once the workers have stopped +/// too, so that ⑤ and ⑥ close behind it. +pub fn spawn( + config: EventConfig, + ends: EventEnds, + pod_data: Arc, // only read for the boards' names + index: Arc, // which protections and messages mean fault + tcp: Option>, +) -> JoinHandle; + +/// What event needs from the TCP client. +pub trait TcpLink: Send + Sync { + /// Writes the order to its board; returns that board once written, or why + /// not (right away if the board is not connected). + fn send(&self, order: OrderPacket) -> BoxFuture<'_, Result>; + /// Sends the fault to every board; fails with the boards it did not reach. + fn send_fault(&self) -> BoxFuture<'_, Result<(), Vec>>; +} + +pub enum ToLogging { + /// A notification, the same copy pipeline gets. + Received(Arc), + /// An order TCP confirmed it wrote. `board` is `None` for the fault, which + /// goes to every board. + OrderSent { at: SystemTime, board: Option, order: OrderPacket }, +} + +pub enum ToPipeline { + /// A notification, the same copy logging gets. + Received(Arc), + Problem(Problem), + /// An order the front sent that went out, as in `ToLogging`. + OrderSent { at: SystemTime, board: Option, order: OrderPacket }, + /// An order the front sent that did not go out, and why. + OrderFailed { at: SystemTime, order: OrderPacket, reason: String }, +} + +/// Something the operator has to see. `Problem::now(kind, board, text)` +/// builds one stamped with the current time. +pub struct Problem { + pub at: SystemTime, + /// The board, if known. + pub board: Option, + pub kind: ProblemKind, + /// The message with all its causes: "could not X: because Y: because Z" + /// (`event::full_message` builds it from any error). + pub text: String, +} + +pub enum ProblemKind { + /// Procedure 2: shown, the backend keeps running. + Shown, + /// Procedure 3: the fault is sent, it is shown and the backend stops. + Fatal, + /// Procedure 1: only traced, not shown; the backend keeps running. + Silent, +} + +/// Why event ended. `main` reads it and shuts down in order. +pub enum Stop { + Fatal(Problem), + /// `net`'s queues closed: UDP and TCP were stopped. + NetGone, +} + +/// `EventConfig::default()` gives the values in brackets. Every size is +/// clamped to at least 1. +pub struct EventConfig { + pub errors_queue: usize, // each of net's two error queues, ① (16) + pub problems_queue: usize, // ② (16) + pub tcp_queue: usize, // ③ (1,024) + pub udp_queue: usize, // ④ (8,192) + pub logging_queue: usize, // ⑤ (8,192) + pub pipeline_queue: usize, // ⑥ (8,192) + pub orders_queue: usize, // ⑦ (32) + pub propagate_fault: bool, // send a board's fault to the other boards (true) + pub fault_timeout: Duration, // how long a fatal stop waits for the fault (2 s) +} +``` + +`TcpLink` is a trait rather than `net::tcp`'s own type so that the workers can +be tested against a fake, and so that `event` depends on the TCP client for +these two calls only. `FaultRequest` (⑧) is private to `event`. + +## The routing loop + +```text +loop, select! in fixed order (closed queues are no longer watched): + 1. ① UDP errors, ① TCP errors, then ② problems -> policy: + fatal -> stop (see "Stopping") + board fault -> propagate_fault? request to ⑧ (every time) + first from that board? Problem to ⑥ + shown -> Problem to ⑥ + silent -> trace only + 2. ③ TCP notifications.recv() -> fault protection or message? + propagate_fault? request to ⑧ + forward + 3. ④ UDP notifications.recv() -> forward (same check: telemetry never matches) + all four of net's queues (① ① ③ ④) closed -> return Stop::NetGone + +forward(notification): + shared = Arc::new(notification) + ⑤.send(Received(shared.clone())).await // on failure: fatal + ⑥.send(Received(shared)).await // on failure: fatal +``` + +## Performance + +The requirement is **25 Mbit/s in 76-byte packets, about 41,000 a second**: +under 24 µs per notification, everything included. On loopback, UDP alone loses +nothing, but a reader with one timer per message already loses 0.7 %. **The +bottleneck is whoever reads `net`'s queues, that is, the routing loop.** Hence: + +- one shared copy per notification for both consumers: a small allocation, and + the packet itself is never copied; +- no timer per notification; +- the routing loop does not look inside notifications: the expensive work + (picking measurements, computing averages, building JSON) is done by + `logging` and `pipeline`, each in its own task; +- anything that can wait on a socket is done by a worker, never by the routing + loop. + +Measured with `manual_event_throughput` (see [Tests](#tests)): about 950,000 +notifications a second through `event`, over 20 times the requirement. + +## Contract with the other modules + +- **`net`** needs no change: each transport reports through the `Reporter` it + is given, and `event::channels` hands out one per transport. +- **`net::udp`** reports data on ④, errors on ①, and a fault (packet id 0) as + `UdpError::Fault` on ①, recognised before decoding. +- **`net::tcp`** reports protections, messages and connected/disconnected on ③, + errors on ①, and on top of that: + - recognises packet id 0 as a fault before decoding, like `net::udp`; + - does not report reconnection failures (procedure 1: it traces them); + - `send` fails right away if the board is not connected, and returns only + once the order is written; + - can send the fault to every board and say which ones it did not reach; + - has an explicit stop, for the safe shutdown; + - is handed to `event` as a `TcpLink`, directly or through a thin adapter. +- **`websocket`** validates each order against the ADJ and puts it on ⑦ + (`OrderForwarder` takes `channels.orders`). The fault is one more order + there: the ADJ declares order id 0, so it passes that validation. The front's + logger requests + (`logger/enable`, variable selection) go straight to `logging`, not through + `event`. +- **`logging`** reads ⑤, picks which measurements to store following its own + selection, records the orders that went out, and reports its own failures + (e.g. the disk) on ②. +- **`pipeline`** reads ⑥ and turns it into what the front shows: a notification + into per-packet updates (counts, cycle time, averages) or protection and + message updates; a `Problem`, and an order that went out or failed + (`OrderSent`, `OrderFailed`), into a message from the backend + (`message/update`). It waits instead of dropping and does not decide anything + about errors. + +## Implementation notes + +- **`main` keeps no copy of a `Reporter`**: each one is moved into its task, + and `channels.tcp` is dropped if TCP is not started. A `Reporter` left alive + keeps its queues open, and the routing loop never ends. +- **A closed queue is no longer watched** in the `select!`. A closed queue + answers "closed" instantly, every time, so in fixed order it would win every + round and the queues below it would never be reached. Each branch has a + condition (`if open.udp_errors`, and so on). This does happen: at shutdown + UDP's ① closes while ④ may still have items in it, and without TCP ③ is + closed from the start. + +## Tests + +- `policy.rs`: the decision table, one test per row. +- `tests.rs`: the routing loop and the workers, with real queues and a fake + `TcpLink`, no sockets. Covers the order of priority, the shared copy, the + fatal stop (and that what was queued before the error still gets through), + board faults (packet id 0 shown once per board, and every fault, protection + or message sent to every board each time; warnings only forwarded), orders + with and without TCP and the front told either way, the fault from the front + (sent every time, the front told how it went), a consumer that stops, `net` + closing, and a fault that never finishes sending. Every wait is bounded, so a + broken expectation fails instead of hanging. +- `manual_tests.rs`: `manual_event_throughput`, ignored by default. It pushes + a million notifications through a `Reporter` into `event` and two readers + that only count. On a development machine, in release: about 950,000 a + second, over 20 times the requirement. + + ```sh + cargo test -p station --release manual_event -- --ignored --nocapture + ``` diff --git a/backend/crates/station/src/event/fault.rs b/backend/crates/station/src/event/fault.rs new file mode 100644 index 000000000..8bd2ccc51 --- /dev/null +++ b/backend/crates/station/src/event/fault.rs @@ -0,0 +1,138 @@ +//! The fault worker: sends the fault (order id 0) to every board, once per +//! request, every time it is asked. When the operator asked for it, the front +//! is told how it went, as for any order. + +use std::sync::Arc; +use std::time::SystemTime; + +use software_core::model::{AdjId, OrderPacket, PodData}; +use tokio::sync::{mpsc, oneshot}; +use tracing::{error, info, warn}; + +use super::orders::TCP_NOT_AVAILABLE; +use super::{Problem, ProblemKind, TcpLink, ToLogging, ToPipeline, board_name}; + +/// The fault's id on the wire: what a board sends when it detects an error, +/// and what the backend sends to every board to put the pod in fault. +pub(super) const FAULT_ID: AdjId = AdjId(0); + +/// Slots in the fault requests queue (⑧). Requests are rare; a full queue +/// means faults are already waiting to go out, so the routing loop drops a +/// board's request rather than wait (see `Router::propagate_fault`). +pub(super) const FAULT_QUEUE: usize = 8; + +/// A request to send the fault. +#[derive(Debug)] +pub(super) enum FaultRequest { + /// The backend's own decision: a fatal error, or a board's fault when + /// `propagate_fault` is on. + Automatic { + /// Told once the fault has gone out (or failed to): the routing loop + /// waits on it before stopping on a fatal error. + done: Option>, + }, + /// The operator asked for it from the front (order id 0). + FromFront { + /// The order as it came from the front. + order: OrderPacket, + }, +} + +/// Why the fault did not reach every board. +enum Undelivered { + /// There is no TCP client. + NoTcp, + /// Some boards did not get it: the text names them. + Missed(String), +} + +impl Undelivered { + fn reason(self) -> String { + match self { + Undelivered::NoTcp => TCP_NOT_AVAILABLE.to_string(), + Undelivered::Missed(text) => text, + } + } +} + +/// Runs the worker until its queue closes (or `event` stops it). +/// +/// Requests are sent one at a time, in the order they arrive: one that +/// arrives while the fault is being sent waits behind it. +/// +/// It never stops on its own when `logging` or `pipeline` are gone: that is +/// exactly when a fatal stop still needs it to send the fault. +pub(super) async fn run( + mut requests: mpsc::Receiver, + tcp: Option>, + logging: mpsc::Sender, + pipeline: mpsc::Sender, + pod_data: Arc, +) { + let tcp = tcp.as_deref(); + while let Some(request) = requests.recv().await { + match request { + FaultRequest::Automatic { done } => { + match send_fault(tcp, &pod_data).await { + Ok(()) => info!("fault sent to every board"), + Err(Undelivered::NoTcp) => { + warn!("the fault was not sent to the boards: {TCP_NOT_AVAILABLE}"); + } + Err(Undelivered::Missed(text)) => { + error!(%text); + // A fault that only half landed is exactly what the + // operator has to know. + let problem = Problem::now(ProblemKind::Shown, None, text); + let _ = pipeline.send(ToPipeline::Problem(problem)).await; + } + } + if let Some(done) = done { + // The one waiting may have given up already (its time limit). + let _ = done.send(()); + } + } + FaultRequest::FromFront { order } => { + let outcome = send_fault(tcp, &pod_data).await; + let at = SystemTime::now(); + match outcome { + Ok(()) => { + info!("fault sent to every board, as the front asked"); + let logged = ToLogging::OrderSent { + at, + board: None, + order: order.clone(), + }; + let _ = logging.send(logged).await; + let shown = ToPipeline::OrderSent { + at, + board: None, + order, + }; + let _ = pipeline.send(shown).await; + } + Err(undelivered) => { + let reason = undelivered.reason(); + warn!(%reason, "the fault the front asked for did not go out"); + let failed = ToPipeline::OrderFailed { at, order, reason }; + let _ = pipeline.send(failed).await; + } + } + } + } + } +} + +/// Sends the fault to every board. +async fn send_fault(tcp: Option<&dyn TcpLink>, pod_data: &PodData) -> Result<(), Undelivered> { + let tcp = tcp.ok_or(Undelivered::NoTcp)?; + tcp.send_fault().await.map_err(|unreached| { + let names: Vec = unreached + .iter() + .map(|&board| board_name(pod_data, board)) + .collect(); + Undelivered::Missed(format!( + "the fault did not reach these boards: {}", + names.join(", ") + )) + }) +} diff --git a/backend/crates/station/src/event/manual_tests.rs b/backend/crates/station/src/event/manual_tests.rs new file mode 100644 index 000000000..3ca606239 --- /dev/null +++ b/backend/crates/station/src/event/manual_tests.rs @@ -0,0 +1,88 @@ +//! A throughput probe for the routing loop, ignored by default: +//! +//! ```sh +//! cargo test -p station --release manual_event -- --ignored --nocapture +//! ``` +//! +//! The requirement is 25 Mbit/s in 76-byte packets, about 41,000 +//! notifications a second, and the routing loop is the bottleneck: on +//! loopback the UDP socket alone loses nothing. This pushes notifications +//! straight through a `Reporter`, with no socket, so what it measures is the +//! routing loop and its two queues. + +use super::*; +use software_core::model::{AdjId, DataPacket, Packet}; +use software_core::net::Event; +use std::error::Error; +use std::time::Instant; + +const NOTIFICATIONS: usize = 1_000_000; +const REQUIRED_PER_SECOND: f64 = 41_000.0; + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[ignore = "load probe: run it by hand, in release"] +async fn manual_event_throughput() -> Result<(), Box> { + let config = EventConfig::default(); + let Channels { + udp, + tcp, + event, + orders, + problems, + mut logging, + mut pipeline, + } = channels(&config); + drop((tcp, orders, problems)); + let event = spawn(config, event, Arc::default(), Arc::default(), None); + + let logged = tokio::spawn(async move { + let mut count = 0; + while let Some(message) = logging.recv().await { + if let ToLogging::Received(_) = message { + count += 1; + } + } + count + }); + let shown = tokio::spawn(async move { + let mut count = 0; + while let Some(message) = pipeline.recv().await { + if let ToPipeline::Received(_) = message { + count += 1; + } + } + count + }); + + let start = Instant::now(); + let producer = tokio::spawn(async move { + for _ in 0..NOTIFICATIONS { + let packet = DataPacket::new(AdjId(1000), vec![]); + if udp + .notify(BoardId(1), Event::Received(Packet::Data(packet))) + .await + .is_err() + { + break; + } + } + // `udp` is dropped here: event passes on what is left and stops. + }); + producer.await?; + let stop = event.await?; + let (logged, shown) = (logged.await?, shown.await?); + let elapsed = start.elapsed(); + + let per_second = NOTIFICATIONS as f64 / elapsed.as_secs_f64(); + println!( + "{NOTIFICATIONS} notifications in {elapsed:.2?}: {per_second:.0}/s \ + ({:.1}x the required {REQUIRED_PER_SECOND:.0}/s)", + per_second / REQUIRED_PER_SECOND + ); + + assert!(matches!(stop, Stop::NetGone)); + assert_eq!(logged, NOTIFICATIONS, "logging got every notification"); + assert_eq!(shown, NOTIFICATIONS, "pipeline got every notification"); + assert!(per_second > REQUIRED_PER_SECOND); + Ok(()) +} diff --git a/backend/crates/station/src/event/orders.rs b/backend/crates/station/src/event/orders.rs new file mode 100644 index 000000000..1caecd546 --- /dev/null +++ b/backend/crates/station/src/event/orders.rs @@ -0,0 +1,73 @@ +//! The orders worker: takes the front's orders (⑦) one at a time and writes +//! them to TCP, so that the routing loop never waits on a socket. + +use std::sync::Arc; +use std::time::SystemTime; + +use software_core::model::OrderPacket; +use tokio::sync::mpsc; +use tracing::{info, warn}; + +use super::fault::{FAULT_ID, FaultRequest}; +use super::{TcpLink, ToLogging, ToPipeline}; + +/// The reason given for every order when no TCP client is running. +pub(super) const TCP_NOT_AVAILABLE: &str = "TCP not available"; + +/// Runs the worker until its queue closes (or `event` stops it). +/// +/// - An order with id 0 is the fault: it goes to the fault worker (⑧), which +/// tells the front how it went. +/// - Any other order is written and waited for before the next one is +/// taken. Written: it goes to `logging` (⑤) and to `pipeline` (⑥), which +/// shows it on the front. Not written: it goes to `pipeline` with the +/// reason, and to the trace. +pub(super) async fn run( + mut orders: mpsc::Receiver, + tcp: Option>, + fault: mpsc::Sender, + logging: mpsc::Sender, + pipeline: mpsc::Sender, +) { + while let Some(order) = orders.recv().await { + if order.id == FAULT_ID { + info!("the front asked for the fault"); + if fault.send(FaultRequest::FromFront { order }).await.is_err() { + break; + } + continue; + } + + let outcome = match &tcp { + Some(tcp) => tcp.send(order.clone()).await, + None => Err(TCP_NOT_AVAILABLE.to_string()), + }; + + // Stamped once the outcome is known: "sent" means written. + let at = SystemTime::now(); + let delivered = match outcome { + Ok(board) => { + let board = Some(board); + let logged = ToLogging::OrderSent { + at, + board, + order: order.clone(), + }; + let shown = ToPipeline::OrderSent { at, board, order }; + logging.send(logged).await.is_ok() && pipeline.send(shown).await.is_ok() + } + Err(reason) => { + warn!(id = ?order.id, %reason, "order not sent"); + pipeline + .send(ToPipeline::OrderFailed { at, order, reason }) + .await + .is_ok() + } + }; + + // Nobody left to tell: event is stopping. + if !delivered { + break; + } + } +} diff --git a/backend/crates/station/src/event/policy.rs b/backend/crates/station/src/event/policy.rs new file mode 100644 index 000000000..074dd551d --- /dev/null +++ b/backend/crates/station/src/event/policy.rs @@ -0,0 +1,424 @@ +//! What each error means: the decision table of the README's "Errors" +//! section, as functions that keep no state, so it can be tested on its own. + +use std::error::Error; +use std::net::IpAddr; + +use software_core::model::{AdjId, BoardId, MessageLevel, Packet, PacketType, Severity}; +use software_core::net::{self, Event, tcp, udp::UdpError}; +use software_core::protocol::Index; + +use super::ProblemKind; + +/// What the routing loop does about an error. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum Action { + /// Procedure 3: show it, send the fault, stop. + Fatal, + /// A board sent a fault: show the first one from that board, forward + /// it to the others if configured, keep running. + BoardFault, + /// Procedure 2: show it, keep running. + Show, + /// Procedure 1: only written to the trace; not shown, keep running. + Silent, +} + +/// Decides what a `net` error means. `is_fatal()` is not consulted: the +/// decision is `event`'s, and it is made here, from the error itself. +pub(super) fn classify(error: &net::Error) -> Action { + match error { + net::Error::Udp(error) => match error { + // Nothing corrupts a datagram in flight, so any decode failure + // means the loaded ADJ does not match the firmware, whatever the + // variant: an unknown id, a truncated datagram, an enum value out + // of range. + UdpError::Decode { .. } => Action::Fatal, + // The socket is gone: every board's telemetry at once. + UdpError::Recv { .. } => Action::Fatal, + UdpError::Fault { .. } => Action::BoardFault, + // Never reaches the error queue (binding happens before the task + // starts). If it ever did, there would be no telemetry at all. + UdpError::Bind { .. } => Action::Fatal, + }, + net::Error::Tcp(error) => match error { + tcp::Error::Decode { .. } => Action::Fatal, + // A board not up yet: what the reconnection backoff is for. + tcp::Error::Connect { .. } => Action::Silent, + tcp::Error::Write { .. } => Action::Show, + }, + } +} + +/// Decides what a [`super::Problem`] from a station module means: whatever +/// the module that sent it says. +pub(super) fn for_problem(kind: ProblemKind) -> Action { + match kind { + ProblemKind::Fatal => Action::Fatal, + ProblemKind::Shown => Action::Show, + ProblemKind::Silent => Action::Silent, + } +} + +/// Whether a notification is a board saying it is in fault: a protection the +/// ADJ declares with severity `Fault`, or a message of level `Fault` or +/// `Panic`. Either one is sent to every board when `propagate_fault` is on. +/// +/// Only protections and messages are looked up, so the telemetry that makes +/// up nearly all the traffic costs one `match` and nothing else. +pub(super) fn is_board_fault(event: &Event, index: &Index) -> bool { + match event { + Event::Received(Packet::Protection(protection)) => { + protection_is_fault(protection.id, index) + } + Event::Received(Packet::Message(message)) => matches!( + index.packet(message.id).map(|def| &def.packet_type), + Some(PacketType::Message( + MessageLevel::Fault | MessageLevel::Panic + )) + ), + _ => false, + } +} + +/// Whether the protection a board reported under `id` is declared with +/// severity `Fault`. The compound id leads to the watched measurement, and +/// its position (the high 3 bits) to which of that measurement's protections +/// triggered. +fn protection_is_fault(id: AdjId, index: &Index) -> bool { + let Some(PacketType::Protection(measurement)) = index.packet(id).map(|def| &def.packet_type) + else { + return false; + }; + let position = AdjId(u16::from(id.protection_position())); + measurement + .protections + .iter() + .any(|protection| protection.id == position && protection.severity == Severity::Fault) +} + +/// Where an error comes from, as far as the error itself says. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) struct Source { + /// The board, when the error names it: TCP errors always do, UDP errors + /// when the address belongs to a board. + pub(super) board: Option, + /// The address a datagram came from (UDP errors about one datagram). + pub(super) ip: Option, +} + +/// Reads [`Source`] off an error. +pub(super) fn source(error: &net::Error) -> Source { + match error { + net::Error::Udp(error) => match error { + UdpError::Decode { from, board, .. } | UdpError::Fault { from, board } => Source { + board: *board, + ip: Some(from.ip()), + }, + UdpError::Recv { .. } | UdpError::Bind { .. } => Source { + board: None, + ip: None, + }, + }, + net::Error::Tcp(error) => match error { + tcp::Error::Connect { board, .. } + | tcp::Error::Decode { board, .. } + | tcp::Error::Write { board, .. } => Source { + board: Some(*board), + ip: None, + }, + }, + } +} + +/// The error with all its causes: "could not X: because Y: because Z". +/// +/// Some errors already include their cause in their own message and others +/// do not, so a cause that already appears is not repeated. +pub fn full_message(error: &dyn Error) -> String { + let mut message = error.to_string(); + let mut source = error.source(); + while let Some(cause) = source { + let text = cause.to_string(); + if !message.contains(&text) { + message.push_str(": "); + message.push_str(&text); + } + source = cause.source(); + } + message +} + +/// An ADJ with what [`is_board_fault`] looks at, for this file's tests and the +/// routing loop's: board 1 watches measurement 3000 with two protections, +/// position 1 a `Fault` and position 2 a `Warning`; message ids 2, 3, 4 and 5 +/// are `Fault`, `Panic`, `Warning` and `Info`. +#[cfg(test)] +pub(super) fn index_with_faults() -> Index { + use software_core::model::{ + Board, MacAddress, Measurement, MeasurementKind, PacketDef, PodData, Protection, + ProtectionKind, + }; + use std::collections::HashMap; + use std::time::Duration; + + let protection = |slot: u16, severity| Protection { + id: AdjId(slot), + kind: ProtectionKind::Above { limit: 1.0 }, + severity, + time: Duration::ZERO, + }; + let measurement = Measurement { + id: AdjId(3000), + alias: "temperature".to_string(), + name: "Temperature".to_string(), + display_units: "ºC".to_string(), + kind: MeasurementKind::Boolean, + protections: vec![ + protection(1, Severity::Fault), + protection(2, Severity::Warning), + ], + }; + let packets = [1, 2].map(|slot| { + let id = protection_id(slot); + let def = PacketDef { + id, + board: BoardId(1), + name: format!("temperature_protection_{slot}"), + packet_type: PacketType::Protection(measurement.clone()), + }; + (id, def) + }); + let board = Board { + id: BoardId(1), + name: "PCU".to_string(), + ip: IpAddr::from([127, 0, 0, 7]), + mac: MacAddress([0; 6]), + packets: HashMap::from(packets), + }; + let pod_data = PodData { + boards: HashMap::from([(board.id, board)]), + }; + let levels = HashMap::from([ + (AdjId(2), MessageLevel::Fault), + (AdjId(3), MessageLevel::Panic), + (AdjId(4), MessageLevel::Warning), + (AdjId(5), MessageLevel::Info), + ]); + Index::new(&pod_data, Some(&levels)) +} + +/// The compound id of measurement 3000's protection at `slot`, as a board +/// sends it. +#[cfg(test)] +fn protection_id(slot: u16) -> AdjId { + AdjId((slot << 13) | 3000) +} + +/// A board reporting that measurement 3000's protection at `slot` triggered. +#[cfg(test)] +pub(super) fn protection_triggered(slot: u16) -> Event { + use software_core::model::{ProtectionPacket, ShortTimestamp, Value}; + Event::Received(Packet::Protection(ProtectionPacket { + id: protection_id(slot), + timestamp: ShortTimestamp { + hour: 12, + minute: 0, + second: 0, + subsecond: 0, + }, + value: Value::Bool(true), + })) +} + +/// A board sending a message under message id `id`. +#[cfg(test)] +pub(super) fn message_sent(id: u16) -> Event { + use software_core::model::{MessagePacket, ShortTimestamp}; + Event::Received(Packet::Message(MessagePacket { + id: AdjId(id), + timestamp: ShortTimestamp { + hour: 12, + minute: 0, + second: 0, + subsecond: 0, + }, + origin: "main.c".to_string(), + message: "something happened".to_string(), + })) +} + +#[cfg(test)] +mod tests { + use super::*; + use software_core::model::DataPacket; + use software_core::protocol::DecodeError; + use std::net::SocketAddr; + + #[test] + fn a_protection_declared_as_a_fault_is_a_board_fault() { + let index = index_with_faults(); + assert!(is_board_fault(&protection_triggered(1), &index)); + assert!( + !is_board_fault(&protection_triggered(2), &index), + "a warning is not" + ); + } + + #[test] + fn fault_and_panic_messages_are_board_faults() { + let index = index_with_faults(); + assert!(is_board_fault(&message_sent(2), &index), "fault"); + assert!(is_board_fault(&message_sent(3), &index), "panic"); + assert!(!is_board_fault(&message_sent(4), &index), "warning"); + assert!(!is_board_fault(&message_sent(5), &index), "info"); + } + + #[test] + fn telemetry_and_connections_are_never_board_faults() { + let index = index_with_faults(); + let data = Event::Received(Packet::Data(DataPacket::new(AdjId(1000), vec![]))); + assert!(!is_board_fault(&data, &index)); + assert!(!is_board_fault(&Event::Connected, &index)); + } + + fn from() -> SocketAddr { + SocketAddr::new(IpAddr::from([127, 0, 0, 7]), 50400) + } + + fn io_error() -> std::io::Error { + std::io::Error::from(std::io::ErrorKind::ConnectionReset) + } + + fn udp(error: UdpError) -> net::Error { + net::Error::Udp(error) + } + + fn tcp(error: tcp::Error) -> net::Error { + net::Error::Tcp(error) + } + + #[test] + fn every_udp_decode_error_is_fatal_not_only_an_unknown_id() { + for source in [ + DecodeError::UnknownId(AdjId(9999)), + DecodeError::UnexpectedEof, + DecodeError::InvalidEnumValue { + index: 7, + options: 2, + }, + ] { + let error = udp(UdpError::Decode { + from: from(), + board: None, + source, + }); + assert_eq!(classify(&error), Action::Fatal, "{error}"); + } + } + + #[test] + fn losing_the_udp_socket_is_fatal() { + let error = udp(UdpError::Recv { source: io_error() }); + assert_eq!(classify(&error), Action::Fatal); + } + + #[test] + fn a_fault_from_a_board_does_not_stop_the_backend() { + let error = udp(UdpError::Fault { + from: from(), + board: Some(BoardId(7)), + }); + assert_eq!(classify(&error), Action::BoardFault); + } + + #[test] + fn tcp_errors_follow_the_three_procedures() { + let decode = tcp(tcp::Error::Decode { + board: BoardId(3), + source: DecodeError::UnknownId(AdjId(9999)), + }); + let connect = tcp(tcp::Error::Connect { + board: BoardId(3), + source: io_error(), + }); + let write = tcp(tcp::Error::Write { + board: BoardId(3), + source: io_error(), + }); + + assert_eq!(classify(&decode), Action::Fatal); + assert_eq!(classify(&connect), Action::Silent); + assert_eq!(classify(&write), Action::Show); + } + + #[test] + fn a_problem_means_what_its_module_says() { + assert_eq!(for_problem(ProblemKind::Fatal), Action::Fatal); + assert_eq!(for_problem(ProblemKind::Shown), Action::Show); + assert_eq!(for_problem(ProblemKind::Silent), Action::Silent); + } + + #[test] + fn udp_errors_carry_an_address_and_maybe_a_board_and_tcp_errors_a_board() { + let fault = udp(UdpError::Fault { + from: from(), + board: Some(BoardId(7)), + }); + assert_eq!( + source(&fault), + Source { + board: Some(BoardId(7)), + ip: Some(from().ip()) + } + ); + + // An address that belongs to no board keeps the address only. + let stranger = udp(UdpError::Fault { + from: from(), + board: None, + }); + assert_eq!( + source(&stranger), + Source { + board: None, + ip: Some(from().ip()) + } + ); + + let recv = udp(UdpError::Recv { source: io_error() }); + assert_eq!( + source(&recv), + Source { + board: None, + ip: None + } + ); + + let write = tcp(tcp::Error::Write { + board: BoardId(3), + source: io_error(), + }); + assert_eq!( + source(&write), + Source { + board: Some(BoardId(3)), + ip: None + } + ); + } + + #[test] + fn the_full_message_carries_every_cause_once() { + let error = udp(UdpError::Decode { + from: from(), + board: None, + source: DecodeError::UnknownId(AdjId(9999)), + }); + + let message = full_message(&error); + assert!(message.contains("127.0.0.7:50400"), "{message}"); + assert!(message.contains("unknown packet id"), "{message}"); + assert_eq!(message.matches("unknown packet id").count(), 1); + } +} diff --git a/backend/crates/station/src/event/router.rs b/backend/crates/station/src/event/router.rs new file mode 100644 index 000000000..8a5e817de --- /dev/null +++ b/backend/crates/station/src/event/router.rs @@ -0,0 +1,453 @@ +//! The routing loop: everything towards the front. +//! +//! Reads ① ② ③ ④ in fixed order (errors, problems, TCP, UDP), hands every +//! notification to `logging` and `pipeline` (⑤ ⑥), decides what each error +//! and each board fault means with [`super::policy`], and asks the fault +//! worker (⑧) for the fault. It never writes to a socket itself, so it never +//! waits on one. + +use std::collections::HashSet; +use std::net::IpAddr; +use std::sync::Arc; + +use software_core::model::PodData; +use software_core::net::{ErrorReport, Notification, Sinks}; +use software_core::protocol::Index; +use tokio::sync::{mpsc, oneshot}; +use tokio::time::Instant; +use tracing::{debug, error, warn}; + +use super::fault::FaultRequest; +use super::policy::{self, Action}; +use super::{ + EventConfig, Problem, ProblemKind, Stop, ToLogging, ToPipeline, board_name, full_message, +}; + +/// The routing loop's ends of the queues: the reading side of ① ② ③ ④ and +/// the writing side of ⑤ ⑥. +#[derive(Debug)] +pub(super) struct RouterEnds { + /// ① and ④: UDP's errors and notifications. + pub(super) udp: Sinks, + /// ① and ③: TCP's errors and notifications. + pub(super) tcp: Sinks, + /// ②: problems from station modules. + pub(super) problems: mpsc::Receiver, + /// ⑤: to `logging`. The workers get clones. + pub(super) logging: mpsc::Sender, + /// ⑥: to `pipeline`. The workers get clones. + pub(super) pipeline: mpsc::Sender, + /// Capacity of ③: how much a fatal stop drains at most. + pub(super) tcp_capacity: usize, + /// Capacity of ④: how much a fatal stop drains at most. + pub(super) udp_capacity: usize, +} + +/// Which transport a notification queue belongs to. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Transport { + Tcp, + Udp, +} + +/// A consumer of the routing loop that has stopped. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Consumer { + Logging, + Pipeline, +} + +/// Why the routing loop has to stop, before it does it. +#[derive(Debug)] +enum Halt { + Fatal(Problem), + Gone(Consumer), +} + +/// What one round of the `select!` got. +enum Step { + NetError(Transport, Option), + Problem(Option), + Notification(Transport, Option), +} + +/// Which input queues are still open. A closed queue answers "closed" +/// instantly, every time, so it is no longer watched: in fixed order it would +/// win every round and hide the queues below it. +#[derive(Debug, Clone, Copy)] +struct Open { + udp_errors: bool, + tcp_errors: bool, + problems: bool, + tcp_notifications: bool, + udp_notifications: bool, +} + +impl Default for Open { + fn default() -> Self { + Self { + udp_errors: true, + tcp_errors: true, + problems: true, + tcp_notifications: true, + udp_notifications: true, + } + } +} + +impl Open { + /// Whether any of `net`'s four queues is still open. The loop only ends + /// once all four are closed, so an error queued just before its + /// transport stopped is never lost. + fn net(&self) -> bool { + self.udp_errors || self.tcp_errors || self.tcp_notifications || self.udp_notifications + } +} + +/// The routing loop's state. +pub(super) struct Router { + config: EventConfig, + pod_data: Arc, + index: Arc, + udp: Sinks, + tcp: Sinks, + problems: mpsc::Receiver, + logging: mpsc::Sender, + pipeline: mpsc::Sender, + fault: mpsc::Sender, + open: Open, + tcp_capacity: usize, + udp_capacity: usize, + /// The addresses whose fault has already been shown. + faults_shown: HashSet, +} + +impl Router { + /// A routing loop over `ends`, that asks for the fault on `fault` (⑧). + /// `pod_data` is only read for the boards' names, `index` for which + /// protections and messages mean fault. + pub(super) fn new( + config: EventConfig, + pod_data: Arc, + index: Arc, + ends: RouterEnds, + fault: mpsc::Sender, + ) -> Self { + Self { + config, + pod_data, + index, + udp: ends.udp, + tcp: ends.tcp, + problems: ends.problems, + logging: ends.logging, + pipeline: ends.pipeline, + fault, + open: Open::default(), + tcp_capacity: ends.tcp_capacity, + udp_capacity: ends.udp_capacity, + faults_shown: HashSet::new(), + } + } + + /// Runs the loop until it has to stop, and says why. + /// + /// Takes the router by value: when it returns, the router's ends of ⑤ ⑥ + /// and ⑧ are dropped with it. + pub(super) async fn route(mut self) -> Stop { + loop { + // If all four of `net`'s queues are closed, the loop ends: it has nothing left to do. + if !self.open.net() { + return Stop::NetGone; + } + + let open = self.open; + // Fixed order: errors, then TCP, then UDP. + let step = tokio::select! { + biased; + // UDP has more priority than TCP, since TCP won't be sent if UDP is down: a UDP error is more urgent. + report = self.udp.errors.recv(), if open.udp_errors => { + Step::NetError(Transport::Udp, report) + } + report = self.tcp.errors.recv(), if open.tcp_errors => { + Step::NetError(Transport::Tcp, report) + } + problem = self.problems.recv(), if open.problems => Step::Problem(problem), + + // Then notifications after errrors + notification = self.tcp.notifications.recv(), if open.tcp_notifications => { + Step::Notification(Transport::Tcp, notification) + } + notification = self.udp.notifications.recv(), if open.udp_notifications => { + Step::Notification(Transport::Udp, notification) + } + else => return Stop::NetGone, + }; + + // handle of the error + let handled = match step { + // Errors + Step::NetError(Transport::Udp, None) => { + self.open.udp_errors = false; + Ok(()) + } + Step::NetError(Transport::Tcp, None) => { + self.open.tcp_errors = false; + Ok(()) + } + Step::NetError(_, Some(report)) => self.on_net_error(report).await, + Step::Problem(None) => { + self.open.problems = false; + Ok(()) + } + Step::Problem(Some(problem)) => self.on_problem(problem).await, + + // Notifications empty + Step::Notification(Transport::Tcp, None) => { + self.open.tcp_notifications = false; + Ok(()) + } + Step::Notification(Transport::Udp, None) => { + self.open.udp_notifications = false; + Ok(()) + } + + // Notifications with content + Step::Notification(_, Some(notification)) => { + // Before forwarding: asking for the fault never waits, + // forwarding may (a full ⑤ or ⑥). + if policy::is_board_fault(¬ification.event, &self.index) { + let board = board_name(&self.pod_data, notification.board); + self.propagate_fault(&board); + } + self.forward(notification).await.map_err(Halt::Gone) + } + }; + + match handled { + Ok(()) => {} + Err(Halt::Fatal(problem)) => return self.stop_fatal(problem).await, + Err(Halt::Gone(consumer)) => return self.stop_consumer_gone(consumer).await, + } + } + } + + /// Sends a notification to both consumers, as one shared copy. + async fn forward(&self, notification: Notification) -> Result<(), Consumer> { + let shared = Arc::new(notification); + + // Sent to logging + self.logging + .send(ToLogging::Received(shared.clone())) + .await + .map_err(|_| Consumer::Logging)?; + + // Send to pipeline, + self.pipeline + .send(ToPipeline::Received(shared)) + .await + .map_err(|_| Consumer::Pipeline) + } + + /// Handles a network error: classifies it, shows it if it has to, and + async fn on_net_error(&mut self, report: ErrorReport) -> Result<(), Halt> { + // + let action = policy::classify(&report.error); + let source = policy::source(&report.error); + let board = source.board; + + // A UDP error's message names the address, not the board: put the + // board's name in front. + let mut text = full_message(&report.error); + if let (Some(board), Some(_)) = (board, source.ip) { + text = format!("{}: {text}", board_name(&self.pod_data, board)); + } + + let kind = match action { + Action::Fatal => ProblemKind::Fatal, + Action::Silent => ProblemKind::Silent, + Action::Show | Action::BoardFault => ProblemKind::Shown, + }; + + // Defines the problem to show, or to send with the fault if it is fatal. + let problem = Problem { + at: report.at, + board, + kind, + text, + }; + + // What to do with it: show it, send the fault, or just trace it. + match action { + Action::Fatal => Err(Halt::Fatal(problem)), + Action::BoardFault => self.on_board_fault(problem, source.ip).await, + Action::Show => self.show(problem).await.map_err(Halt::Gone), + Action::Silent => { + self.trace_silent(&problem); + Ok(()) + } + } + } + + async fn on_problem(&mut self, problem: Problem) -> Result<(), Halt> { + match policy::for_problem(problem.kind) { + Action::Fatal => Err(Halt::Fatal(problem)), + Action::Silent => { + self.trace_silent(&problem); + Ok(()) + } + Action::Show | Action::BoardFault => self.show(problem).await.map_err(Halt::Gone), + } + } + + /// Procedure 1: written to the trace, and nothing else. + fn trace_silent(&self, problem: &Problem) { + let board = problem.board.map(|board| board_name(&self.pod_data, board)); + warn!(board = ?board, problem = %problem.text, "problem not shown on the front"); + } + + /// A fault (packet id 0) a board sent: sent to every board each time. + /// + /// It arrives as an error, not as a notification, so the front only sees + /// it if it is shown here: the first one from each address is, repeats + /// are not (`net` already traces them, rate-limited). + async fn on_board_fault(&mut self, problem: Problem, ip: Option) -> Result<(), Halt> { + let board = problem.board.map_or_else( + || "an unknown board".to_string(), + |board| board_name(&self.pod_data, board), + ); + self.propagate_fault(&board); + + let first = ip.is_none_or(|ip| self.faults_shown.insert(ip)); + if first { + warn!(fault = %problem.text, "first fault from this board"); + self.show(problem).await.map_err(Halt::Gone)?; + } + Ok(()) + } + + /// A board is in fault: sends the fault to every board, if + /// `propagate_fault` is on. Every time, like any fault that arrives. + fn propagate_fault(&self, board: &str) { + if !self.config.propagate_fault { + return; + } + // Never waits: if ⑧ is full, faults are already waiting to go out. + let request = FaultRequest::Automatic { done: None }; + match self.fault.try_send(request) { + Ok(()) => warn!(board, "fault from a board: sending it to every board"), + Err(error) => debug!(board, %error, "fault request not queued"), + } + } + + // sends to pipelne a Problem + async fn show(&self, problem: Problem) -> Result<(), Consumer> { + self.pipeline + .send(ToPipeline::Problem(problem)) + .await + .map_err(|_| Consumer::Pipeline) + } + + /// Procedure 3: send the fault, show the problem, pass on what was + /// already queued, stop. + /// + /// The fault is asked for first, since it has to reach the boards as soon + /// as possible; the rest happens while the fault worker writes it, and the + /// loop only stops once it has gone out. + async fn stop_fatal(mut self, problem: Problem) -> Stop { + error!(problem = %problem.text, "fatal error, stopping"); + let deadline = Instant::now() + self.config.fault_timeout; + let fault_sent = self.ask_for_fault(deadline).await; + + let pipeline_alive = self + .pipeline + .send(ToPipeline::Problem(problem.clone())) + .await + .is_ok(); + if pipeline_alive { + // Errors are read first, so this one has overtaken the data that + // arrived just before it: pass that on before stopping. If a + // consumer stops meanwhile, there is nothing left to do with it. + let _ = self.drain().await; + } + + self.wait_for_fault(fault_sent, deadline).await; + Stop::Fatal(problem) + } + + /// `logging` or `pipeline` stopped: nothing is recorded, or nothing is + /// shown. Fatal, without draining. + async fn stop_consumer_gone(self, consumer: Consumer) -> Stop { + let text = match consumer { + Consumer::Logging => "logging stopped: nothing is being recorded", + Consumer::Pipeline => "pipeline stopped: nothing reaches the front", + }; + let problem = Problem::now(ProblemKind::Fatal, None, text); + error!(problem = %problem.text, "fatal error, stopping"); + let deadline = Instant::now() + self.config.fault_timeout; + let fault_sent = self.ask_for_fault(deadline).await; + + if consumer == Consumer::Logging { + let _ = self + .pipeline + .send(ToPipeline::Problem(problem.clone())) + .await; + } + + self.wait_for_fault(fault_sent, deadline).await; + Stop::Fatal(problem) + } + + /// Passes on what is already in ③ and ④, at most their capacity each, so + /// that it cannot chase a queue that keeps filling up. + async fn drain(&mut self) -> Result<(), Consumer> { + for transport in [Transport::Tcp, Transport::Udp] { + let limit = match transport { + Transport::Tcp => self.tcp_capacity, + Transport::Udp => self.udp_capacity, + }; + for _ in 0..limit { + let queue = match transport { + Transport::Tcp => &mut self.tcp.notifications, + Transport::Udp => &mut self.udp.notifications, + }; + let Ok(notification) = queue.try_recv() else { + break; + }; + self.forward(notification).await?; + } + } + Ok(()) + } + + /// Asks the fault worker for the fault, without waiting for it to go out: + /// only for room in ⑧, and no later than `deadline`. Returns what tells + /// once it has gone out, or `None` if it could not be asked for. + async fn ask_for_fault(&self, deadline: Instant) -> Option> { + let (done_tx, done_rx) = oneshot::channel(); + let request = FaultRequest::Automatic { + done: Some(done_tx), + }; + match tokio::time::timeout_at(deadline, self.fault.send(request)).await { + Ok(Ok(())) => Some(done_rx), + _ => { + warn!("the fault could not be asked for; stopping without it"); + None + } + } + } + + /// Waits until the fault asked for has gone out, no later than `deadline` + /// ([`EventConfig::fault_timeout`] after it was asked for). + async fn wait_for_fault(&self, fault_sent: Option>, deadline: Instant) { + let Some(fault_sent) = fault_sent else { + return; + }; + if tokio::time::timeout_at(deadline, fault_sent).await.is_err() { + warn!( + timeout = ?self.config.fault_timeout, + "the fault was not confirmed in time; stopping anyway" + ); + } + } +} diff --git a/backend/crates/station/src/event/tests.rs b/backend/crates/station/src/event/tests.rs new file mode 100644 index 000000000..0fbfda463 --- /dev/null +++ b/backend/crates/station/src/event/tests.rs @@ -0,0 +1,659 @@ +//! Tests of the routing loop and the workers, with real queues and a fake +//! TCP client. No sockets. +//! +//! Every wait is bounded ([`next`], [`stops`], [`eventually`]), so that a +//! broken expectation fails instead of hanging. + +use super::*; +use software_core::model::{AdjId, Board, DataPacket, MacAddress, Packet}; +use software_core::net::Event; +use software_core::net::udp::UdpError; +use software_core::protocol::DecodeError; +use std::collections::HashMap; +use std::error::Error; +use std::net::{IpAddr, SocketAddr}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use tokio::time::{sleep, timeout}; + +type TestResult = Result<(), Box>; + +const WAIT: Duration = Duration::from_secs(1); +const HVSCU: BoardId = BoardId(1); +const VCU: BoardId = BoardId(2); + +fn hvscu_addr() -> SocketAddr { + SocketAddr::new(IpAddr::from([127, 0, 0, 7]), 50400) +} + +fn vcu_addr() -> SocketAddr { + SocketAddr::new(IpAddr::from([127, 0, 0, 8]), 50400) +} + +fn board(id: BoardId, name: &str, addr: SocketAddr) -> Board { + Board { + id, + name: name.to_string(), + ip: addr.ip(), + mac: MacAddress([0; 6]), + packets: HashMap::new(), + } +} + +/// The ADJ lookups: which protections and messages mean fault (see +/// [`policy::index_with_faults`]). +fn index() -> Arc { + Arc::new(policy::index_with_faults()) +} + +fn pod_data() -> Arc { + Arc::new(PodData { + boards: HashMap::from([ + (HVSCU, board(HVSCU, "HVSCU", hvscu_addr())), + (VCU, board(VCU, "VCU", vcu_addr())), + ]), + }) +} + +fn data() -> Event { + Event::Received(Packet::Data(DataPacket::new(AdjId(1000), vec![]))) +} + +/// A fault as `net::udp` reports it: with the address and the board it +/// resolved that address to. +fn fault_from(from: SocketAddr, board: BoardId) -> UdpError { + UdpError::Fault { + from, + board: Some(board), + } +} + +fn decode_error() -> UdpError { + UdpError::Decode { + from: hvscu_addr(), + board: Some(HVSCU), + source: DecodeError::UnknownId(AdjId(9999)), + } +} + +fn order(id: u16) -> OrderPacket { + OrderPacket::new(AdjId(id), vec![]) +} + +/// The next message on `queue`, failing if none arrives within [`WAIT`]. +async fn next(queue: &mut mpsc::Receiver) -> Result> { + timeout(WAIT, queue.recv()) + .await? + .ok_or_else(|| "the queue closed".into()) +} + +/// How `event` stopped, failing if it does not within [`WAIT`]. +async fn stops(event: JoinHandle) -> Result> { + Ok(timeout(WAIT, event).await??) +} + +/// Waits until `condition` holds, failing after [`WAIT`]. +async fn eventually(condition: impl Fn() -> bool) -> TestResult { + timeout(WAIT, async { + while !condition() { + sleep(Duration::from_millis(5)).await; + } + }) + .await?; + Ok(()) +} + +/// A TCP client that counts what it is asked to do. +#[derive(Debug, Default)] +struct FakeTcp { + orders: AtomicUsize, + faults: AtomicUsize, + /// Every order fails with this reason. + refuse_orders: Option<&'static str>, + /// The fault does not reach these boards. + unreachable: Vec, + /// The fault never finishes sending. + fault_hangs: bool, +} + +impl TcpLink for FakeTcp { + fn send(&self, _order: OrderPacket) -> BoxFuture<'_, Result> { + Box::pin(async move { + self.orders.fetch_add(1, Ordering::SeqCst); + match self.refuse_orders { + Some(reason) => Err(reason.to_string()), + None => Ok(HVSCU), + } + }) + } + + fn send_fault(&self) -> BoxFuture<'_, Result<(), Vec>> { + Box::pin(async move { + self.faults.fetch_add(1, Ordering::SeqCst); + if self.fault_hangs { + std::future::pending::<()>().await; + } + if self.unreachable.is_empty() { + Ok(()) + } else { + Err(self.unreachable.clone()) + } + }) + } +} + +fn as_link(fake: &Arc) -> Option> { + let link: Arc = fake.clone(); + Some(link) +} + +/// The next `n` notifications on `pipeline`, failing on anything else. +async fn shown( + pipeline: &mut mpsc::Receiver, + n: usize, +) -> Result>, Box> { + let mut notifications = Vec::with_capacity(n); + for _ in 0..n { + let ToPipeline::Received(notification) = next(pipeline).await? else { + return Err("expected a notification on pipeline".into()); + }; + notifications.push(notification); + } + Ok(notifications) +} + +/// The next `n` notifications on `logging`, failing on anything else. +async fn logged( + logging: &mut mpsc::Receiver, + n: usize, +) -> Result>, Box> { + let mut notifications = Vec::with_capacity(n); + for _ in 0..n { + let ToLogging::Received(notification) = next(logging).await? else { + return Err("expected a notification on logging".into()); + }; + notifications.push(notification); + } + Ok(notifications) +} + +#[tokio::test] +async fn each_notification_reaches_logging_and_pipeline_as_the_same_copy() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + for _ in 0..3 { + channels.udp.notify(HVSCU, data()).await?; + } + let _event = spawn(config, channels.event, pod_data(), index(), None); + + let logged = logged(&mut channels.logging, 3).await?; + let shown = shown(&mut channels.pipeline, 3).await?; + for (logged, shown) in logged.iter().zip(&shown) { + assert!(Arc::ptr_eq(logged, shown), "one copy, shared"); + } + Ok(()) +} + +#[tokio::test] +async fn errors_come_first_then_tcp_then_udp() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + // Queued in the opposite order to the one they must come out in. + channels.udp.notify(HVSCU, data()).await?; + channels.tcp.notify(VCU, Event::Connected).await?; + channels.udp.report(fault_from(hvscu_addr(), HVSCU)).await?; + let _event = spawn(config, channels.event, pod_data(), index(), None); + + let ToPipeline::Problem(problem) = next(&mut channels.pipeline).await? else { + unreachable!("the error comes first"); + }; + assert!( + problem.text.contains("signalled a fault"), + "{}", + problem.text + ); + + let ToPipeline::Received(tcp) = next(&mut channels.pipeline).await? else { + unreachable!("then the TCP notification"); + }; + assert!(matches!(tcp.event, Event::Connected)); + + let ToPipeline::Received(udp) = next(&mut channels.pipeline).await? else { + unreachable!("then the UDP notification"); + }; + assert!(matches!(udp.event, Event::Received(Packet::Data(_)))); + Ok(()) +} + +#[tokio::test] +async fn a_fatal_error_passes_on_what_was_queued_and_stops() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + channels.udp.notify(HVSCU, data()).await?; + channels.udp.notify(HVSCU, data()).await?; + channels.udp.report(decode_error()).await?; + let event = spawn(config, channels.event, pod_data(), index(), None); + + let ToPipeline::Problem(problem) = next(&mut channels.pipeline).await? else { + unreachable!("the fatal error is shown first"); + }; + assert_eq!(problem.kind, ProblemKind::Fatal); + assert_eq!(problem.board, Some(HVSCU), "the board the error carries"); + assert!(problem.text.starts_with("HVSCU: "), "{}", problem.text); + + // The data that arrived before the error still gets through, to both. + shown(&mut channels.pipeline, 2).await?; + logged(&mut channels.logging, 2).await?; + + let Stop::Fatal(stopped_by) = stops(event).await? else { + unreachable!("a decode error is fatal"); + }; + assert_eq!(stopped_by, problem); + Ok(()) +} + +#[tokio::test] +async fn a_board_fault_is_shown_once_per_board_and_sent_to_every_board_each_time() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + let fake = Arc::new(FakeTcp::default()); + let event = spawn(config, channels.event, pod_data(), index(), as_link(&fake)); + + for _ in 0..3 { + channels.udp.report(fault_from(hvscu_addr(), HVSCU)).await?; + } + channels.udp.report(fault_from(vcu_addr(), VCU)).await?; + // A marker: whatever comes before it on pipeline is all there is. + channels.udp.notify(HVSCU, data()).await?; + + let ToPipeline::Problem(first) = next(&mut channels.pipeline).await? else { + unreachable!("HVSCU's first fault is shown"); + }; + let ToPipeline::Problem(second) = next(&mut channels.pipeline).await? else { + unreachable!("VCU's first fault is shown"); + }; + let ToPipeline::Received(_) = next(&mut channels.pipeline).await? else { + unreachable!("HVSCU's repeats are not shown"); + }; + assert_eq!(first.board, Some(HVSCU)); + assert_eq!(second.board, Some(VCU)); + assert_eq!(first.kind, ProblemKind::Shown); + + // Four faults arrived, so the fault goes out four times. + eventually(|| fake.faults.load(Ordering::SeqCst) == 4).await?; + assert!( + !event.is_finished(), + "a board fault does not stop the backend" + ); + Ok(()) +} + +#[tokio::test] +async fn a_fault_protection_or_message_is_forwarded_and_sent_to_every_board() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + let fake = Arc::new(FakeTcp::default()); + let _event = spawn(config, channels.event, pod_data(), index(), as_link(&fake)); + + channels + .tcp + .notify(HVSCU, policy::protection_triggered(1)) + .await?; + channels.tcp.notify(HVSCU, policy::message_sent(2)).await?; + channels.tcp.notify(HVSCU, policy::message_sent(3)).await?; + + // They still reach the front as what they are, not as extra problems. + shown(&mut channels.pipeline, 3).await?; + logged(&mut channels.logging, 3).await?; + eventually(|| fake.faults.load(Ordering::SeqCst) == 3).await?; + Ok(()) +} + +#[tokio::test] +async fn a_warning_protection_or_message_is_only_forwarded() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + let fake = Arc::new(FakeTcp::default()); + let _event = spawn(config, channels.event, pod_data(), index(), as_link(&fake)); + + channels + .tcp + .notify(HVSCU, policy::protection_triggered(2)) + .await?; + channels.tcp.notify(HVSCU, policy::message_sent(4)).await?; + channels.tcp.notify(HVSCU, policy::message_sent(5)).await?; + + shown(&mut channels.pipeline, 3).await?; + sleep(Duration::from_millis(50)).await; + assert_eq!(fake.faults.load(Ordering::SeqCst), 0); + Ok(()) +} + +#[tokio::test] +async fn a_fault_from_the_front_does_not_stop_a_board_fault_from_going_out() -> TestResult { + let config = EventConfig::default(); + let channels = channels(&config); + let fake = Arc::new(FakeTcp::default()); + let _event = spawn(config, channels.event, pod_data(), index(), as_link(&fake)); + + channels.orders.send(order(0)).await?; + eventually(|| fake.faults.load(Ordering::SeqCst) == 1).await?; + + channels + .tcp + .notify(HVSCU, policy::protection_triggered(1)) + .await?; + eventually(|| fake.faults.load(Ordering::SeqCst) == 2).await?; + Ok(()) +} + +#[tokio::test] +async fn propagating_a_board_fault_can_be_turned_off() -> TestResult { + let config = EventConfig { + propagate_fault: false, + ..EventConfig::default() + }; + let mut channels = channels(&config); + let fake = Arc::new(FakeTcp::default()); + let _event = spawn(config, channels.event, pod_data(), index(), as_link(&fake)); + + channels.udp.report(fault_from(hvscu_addr(), HVSCU)).await?; + let ToPipeline::Problem(_) = next(&mut channels.pipeline).await? else { + unreachable!("the fault is still shown"); + }; + channels + .tcp + .notify(HVSCU, policy::protection_triggered(1)) + .await?; + shown(&mut channels.pipeline, 1).await?; + sleep(Duration::from_millis(50)).await; + assert_eq!(fake.faults.load(Ordering::SeqCst), 0); + Ok(()) +} + +#[tokio::test] +async fn closed_queues_do_not_hide_the_others() -> TestResult { + let config = EventConfig::default(); + let Channels { + udp, + tcp, + event, + orders, + problems, + mut logging, + pipeline: _pipeline, + } = channels(&config); + drop((tcp, orders, problems)); + let _event = spawn(config, event, pod_data(), index(), None); + + udp.notify(HVSCU, data()).await?; + let ToLogging::Received(notification) = next(&mut logging).await? else { + unreachable!("the UDP notification gets through"); + }; + assert!(matches!(notification.event, Event::Received(_))); + Ok(()) +} + +#[tokio::test] +async fn without_tcp_an_order_fails() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + let _event = spawn(config, channels.event, pod_data(), index(), None); + + channels.orders.send(order(5)).await?; + let ToPipeline::OrderFailed { order, reason, .. } = next(&mut channels.pipeline).await? else { + unreachable!("the order fails"); + }; + assert_eq!(order.id, AdjId(5)); + assert_eq!(reason, orders::TCP_NOT_AVAILABLE); + Ok(()) +} + +#[tokio::test] +async fn a_written_order_is_logged_and_shown() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + let fake = Arc::new(FakeTcp::default()); + let _event = spawn(config, channels.event, pod_data(), index(), as_link(&fake)); + + channels.orders.send(order(5)).await?; + let ToLogging::OrderSent { board, order, .. } = next(&mut channels.logging).await? else { + unreachable!("the order is logged"); + }; + assert_eq!(board, Some(HVSCU)); + assert_eq!(order.id, AdjId(5)); + + let ToPipeline::OrderSent { board, order, .. } = next(&mut channels.pipeline).await? else { + unreachable!("the front is told the order went out"); + }; + assert_eq!(board, Some(HVSCU)); + assert_eq!(order.id, AdjId(5)); + Ok(()) +} + +#[tokio::test] +async fn an_order_that_was_not_written_is_shown() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + let fake = Arc::new(FakeTcp { + refuse_orders: Some("board not connected"), + ..FakeTcp::default() + }); + let _event = spawn(config, channels.event, pod_data(), index(), as_link(&fake)); + + channels.orders.send(order(5)).await?; + let ToPipeline::OrderFailed { reason, .. } = next(&mut channels.pipeline).await? else { + unreachable!("the order is shown as failed"); + }; + assert_eq!(reason, "board not connected"); + Ok(()) +} + +#[tokio::test] +async fn order_id_0_is_the_fault_and_the_front_is_told() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + let fake = Arc::new(FakeTcp::default()); + let _event = spawn(config, channels.event, pod_data(), index(), as_link(&fake)); + + channels.orders.send(order(0)).await?; + let ToPipeline::OrderSent { board, order, .. } = next(&mut channels.pipeline).await? else { + unreachable!("the front is told the fault went out"); + }; + assert_eq!(board, None, "the fault goes to every board"); + assert_eq!(order.id, AdjId(0)); + let ToLogging::OrderSent { board: None, .. } = next(&mut channels.logging).await? else { + unreachable!("the fault is logged"); + }; + + assert_eq!(fake.faults.load(Ordering::SeqCst), 1); + assert_eq!( + fake.orders.load(Ordering::SeqCst), + 0, + "not written as an order" + ); + Ok(()) +} + +#[tokio::test] +async fn a_fault_from_the_front_goes_out_even_if_one_was_sent_already() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + let fake = Arc::new(FakeTcp::default()); + let _event = spawn(config, channels.event, pod_data(), index(), as_link(&fake)); + + // An automatic fault first: a board's, propagated to the others. + channels.udp.report(fault_from(hvscu_addr(), HVSCU)).await?; + eventually(|| fake.faults.load(Ordering::SeqCst) == 1).await?; + + channels.orders.send(order(0)).await?; + let ToPipeline::Problem(_) = next(&mut channels.pipeline).await? else { + unreachable!("the board's fault is shown first"); + }; + let ToPipeline::OrderSent { .. } = next(&mut channels.pipeline).await? else { + unreachable!("then the front's fault, which went out again"); + }; + assert_eq!(fake.faults.load(Ordering::SeqCst), 2); + Ok(()) +} + +#[tokio::test] +async fn without_tcp_a_fault_from_the_front_fails() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + let _event = spawn(config, channels.event, pod_data(), index(), None); + + channels.orders.send(order(0)).await?; + let ToPipeline::OrderFailed { order, reason, .. } = next(&mut channels.pipeline).await? else { + unreachable!("the front is told the fault did not go out"); + }; + assert_eq!(order.id, AdjId(0)); + assert_eq!(reason, orders::TCP_NOT_AVAILABLE); + Ok(()) +} + +#[tokio::test] +async fn a_fault_from_the_front_that_misses_boards_fails() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + let fake = Arc::new(FakeTcp { + unreachable: vec![VCU], + ..FakeTcp::default() + }); + let _event = spawn(config, channels.event, pod_data(), index(), as_link(&fake)); + + channels.orders.send(order(0)).await?; + let ToPipeline::OrderFailed { reason, .. } = next(&mut channels.pipeline).await? else { + unreachable!("the front is told which boards it missed"); + }; + assert!(reason.contains("VCU"), "{reason}"); + Ok(()) +} + +#[tokio::test] +async fn a_fault_that_misses_boards_is_shown() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + let fake = Arc::new(FakeTcp { + unreachable: vec![VCU], + ..FakeTcp::default() + }); + let _event = spawn(config, channels.event, pod_data(), index(), as_link(&fake)); + + channels.udp.report(fault_from(hvscu_addr(), HVSCU)).await?; + let ToPipeline::Problem(fault) = next(&mut channels.pipeline).await? else { + unreachable!("the board's fault is shown"); + }; + let ToPipeline::Problem(missed) = next(&mut channels.pipeline).await? else { + unreachable!("then the boards the fault did not reach"); + }; + assert!(fault.text.contains("signalled a fault"), "{}", fault.text); + assert_eq!(missed.kind, ProblemKind::Shown); + assert!(missed.text.contains("VCU"), "{}", missed.text); + Ok(()) +} + +#[tokio::test] +async fn a_station_problem_is_traced_shown_or_stops_as_its_module_says() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + let event = spawn(config, channels.event, pod_data(), index(), None); + + let silent = Problem::now(ProblemKind::Silent, None, "only for the trace"); + let shown = Problem::now(ProblemKind::Shown, None, "something to show"); + channels.problems.send(silent).await?; + channels.problems.send(shown.clone()).await?; + let ToPipeline::Problem(problem) = next(&mut channels.pipeline).await? else { + unreachable!("a shown problem reaches pipeline"); + }; + // The silent one went first, but only to the trace. + assert_eq!(problem, shown); + + let fatal = Problem::now(ProblemKind::Fatal, None, "the disk is full"); + channels.problems.send(fatal.clone()).await?; + let Stop::Fatal(stopped_by) = stops(event).await? else { + unreachable!("a fatal problem stops event"); + }; + assert_eq!(stopped_by, fatal); + Ok(()) +} + +#[tokio::test] +async fn when_logging_stops_event_stops_and_tells_pipeline() -> TestResult { + let config = EventConfig::default(); + let Channels { + udp, + tcp: _tcp, + event, + orders: _orders, + problems: _problems, + logging, + mut pipeline, + } = channels(&config); + drop(logging); + let event = spawn(config, event, pod_data(), index(), None); + + udp.notify(HVSCU, data()).await?; + let ToPipeline::Problem(problem) = next(&mut pipeline).await? else { + unreachable!("pipeline is told that logging stopped"); + }; + assert_eq!(problem.kind, ProblemKind::Fatal); + assert!(problem.text.contains("logging"), "{}", problem.text); + + let Stop::Fatal(_) = stops(event).await? else { + unreachable!("losing logging is fatal"); + }; + Ok(()) +} + +#[tokio::test] +async fn when_net_closes_what_was_left_is_passed_on_and_event_stops() -> TestResult { + let config = EventConfig::default(); + let Channels { + udp, + tcp, + event, + orders: _orders, + problems: _problems, + mut logging, + pipeline: _pipeline, + } = channels(&config); + udp.notify(HVSCU, data()).await?; + udp.notify(HVSCU, data()).await?; + drop((udp, tcp)); + let event = spawn(config, event, pod_data(), index(), None); + + // What was queued gets through. + logged(&mut logging, 2).await?; + + let Stop::NetGone = stops(event).await? else { + unreachable!("both transports are gone"); + }; + // Once event has stopped, logging's queue closes: logging can finish. + assert!(timeout(WAIT, logging.recv()).await?.is_none()); + Ok(()) +} + +#[tokio::test] +async fn a_fault_that_never_goes_out_does_not_block_the_stop() -> TestResult { + let config = EventConfig { + fault_timeout: Duration::from_millis(50), + ..EventConfig::default() + }; + let channels = channels(&config); + let fake = Arc::new(FakeTcp { + fault_hangs: true, + ..FakeTcp::default() + }); + let event = spawn(config, channels.event, pod_data(), index(), as_link(&fake)); + + channels.udp.report(decode_error()).await?; + let Stop::Fatal(_) = stops(event).await? else { + unreachable!("a decode error is fatal"); + }; + assert_eq!( + fake.faults.load(Ordering::SeqCst), + 1, + "the fault was attempted" + ); + Ok(()) +} diff --git a/backend/crates/station/src/lib.rs b/backend/crates/station/src/lib.rs new file mode 100644 index 000000000..9eb696501 --- /dev/null +++ b/backend/crates/station/src/lib.rs @@ -0,0 +1,12 @@ +//! The station backend's modules. +//! +//! Every module lives here, so that each one compiles and is tested on its +//! own while it is being built, whether or not `main` wires it in yet. +//! `main.rs` only starts them and connects them. +//! +//! - [`event`]: the communication between the modules (see +//! `src/event/README.md`). +//! - [`http`]: the HTTP API (ADJ catalogs and the WebSocket upgrade). + +pub mod event; +pub mod http; diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index d872008d1..bf39e02bd 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -1,13 +1,359 @@ -//! Ejecutable mínimo para demostrar la integración con `software-core`. +//! The station backend, as far as it goes today: downloads the ADJ, opens the +//! UDP port the ADJ names and runs `event` (see `src/event/README.md`) +//! between UDP and two stand-ins for `logging` and `pipeline`, which do not +//! exist yet: +//! +//! - the **logging stand-in** counts the packets it would record and writes a +//! summary every second (and every packet, with `RUST_LOG=station=debug`); +//! - the **pipeline stand-in** writes to the log what the front would show: +//! problems and failed orders. +//! +//! There is no TCP and no websocket yet: their queues are closed at start. +//! +//! From `backend/`: +//! +//! ```sh +//! cargo run -p station --release # a summary every second +//! RUST_LOG=info,station=debug cargo run -p station --release # and every packet +//! ``` +//! +//! It stops on Ctrl+C (exit code 0) or on a fatal error (exit code 1), such +//! as a datagram that cannot be decoded. A fault sent by a board is shown and +//! does not stop it. +//! +//! The ADJ goes into `core::git`'s default folder +//! (`~/.cache/hyperloop-control-station/adj` on Linux), the same one the Go +//! backend uses: whatever was there is replaced by the [`ADJ_BRANCH`] branch. +//! Offline, whatever is in that folder is used, whichever branch it is. +use std::collections::HashMap; +use std::net::SocketAddr; +use std::path::PathBuf; +use std::process::ExitCode; +use std::sync::Arc; +use std::time::{Duration, SystemTime}; + +use software_core::adj::{self, Adj, LoadError}; +use software_core::git::{self, GitError}; +use software_core::model::{BoardId, Packet, PodData}; +use software_core::net::udp::{UdpConfig, UdpError, spawn_udp}; +use software_core::net::{Event, Notification}; +use software_core::protocol::Index; +use tokio::sync::mpsc; +use tokio::task::JoinError; +use tokio::time::MissedTickBehavior; +use tracing::{debug, error, info, warn}; use tracing_subscriber::EnvFilter; -fn main() { +use station::event::{self, ProblemKind, Stop, ToLogging, ToPipeline}; + +/// Branch of the ADJ repository that is downloaded. +const ADJ_BRANCH: &str = "adjv3-software"; + +/// `SO_RCVBUF` requested from the OS: see `UdpConfig::recv_buffer`. +const RECV_BUFFER: usize = 2 * 1024 * 1024; + +/// How often the logging stand-in writes its summary. +const SUMMARY_EVERY: Duration = Duration::from_secs(1); + +/// How long the stand-ins get to finish what they have queued when stopping. +const SHUTDOWN_GRACE: Duration = Duration::from_secs(5); + +/// Everything that stops the program before `event` has a say. +#[derive(Debug, thiserror::Error)] +enum StartError { + #[error("could not get the ADJ (branch {ADJ_BRANCH})")] + Download(#[source] GitError), + #[error("the downloaded ADJ has no working directory")] + NoWorkdir, + #[error("could not load the ADJ from {path}")] + Load { + path: PathBuf, + #[source] + source: LoadError, + }, + #[error("the ADJ's general_info.json has no `{0}`")] + MissingInAdj(&'static str), + #[error("could not start tokio")] + Runtime(#[source] std::io::Error), + #[error("could not listen for Ctrl+C")] + CtrlC(#[source] std::io::Error), + #[error("could not open the UDP port")] + Bind(#[source] UdpError), + #[error("the event task failed")] + Event(#[source] JoinError), +} + +fn main() -> ExitCode { let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); tracing_subscriber::fmt().with_env_filter(filter).init(); - tracing::info!("iniciando demo de station"); - let name = std::env::args().nth(1).unwrap_or_else(|| "World".into()); - let _greeting = software_core::hello_world::greet(&name); - tracing::info!("demo finalizada"); + match run() { + Ok(code) => code, + Err(error) => { + error!(error = %event::full_message(&error), "stopping"); + ExitCode::FAILURE + } + } +} + +fn run() -> Result { + let adj = download_adj()?; + let addr = udp_addr(&adj)?; + let index = Arc::new(Index::new(&adj.pod_data, Some(&adj.info.message_levels))); + let pod_data = Arc::new(adj.pod_data); + + let runtime = tokio::runtime::Runtime::new().map_err(StartError::Runtime)?; + runtime.block_on(serve(addr, index, pod_data)) +} + +/// Downloads the [`ADJ_BRANCH`] branch and loads it. +/// +/// `update_adj` blocks while downloading (network and disk), so it is called +/// before tokio starts. +fn download_adj() -> Result { + let commit = git::update_adj(None, ADJ_BRANCH).map_err(StartError::Download)?; + + // `update_adj` does not return the folder; it is read from the repository. + let repo = git::open_repo(None).map_err(StartError::Download)?; + let path = repo.workdir().ok_or(StartError::NoWorkdir)?.to_path_buf(); + + let adj = adj::load_from_dir(&path).map_err(|source| StartError::Load { + path: path.clone(), + source, + })?; + info!( + branch = ADJ_BRANCH, + %commit, + path = %path.display(), + boards = adj.pod_data.boards.len(), + "ADJ loaded" + ); + Ok(adj) +} + +/// Where to listen: the backend's IP and the UDP port, as the ADJ gives them. +fn udp_addr(adj: &Adj) -> Result { + let ip = adj + .info + .addresses + .get("backend") + .ok_or(StartError::MissingInAdj("addresses.backend"))?; + let port = adj + .info + .ports + .get("UDP") + .ok_or(StartError::MissingInAdj("ports.UDP"))?; + Ok(SocketAddr::new(*ip, port.0)) +} + +/// Creates every queue, spawns every task, and shuts everything down in order +/// when `event` stops or on Ctrl+C. +async fn serve( + addr: SocketAddr, + index: Arc, + pod_data: Arc, +) -> Result { + let config = event::EventConfig::default(); + let event::Channels { + udp, + tcp, + event: ends, + orders, + problems, + logging, + pipeline, + } = event::channels(&config); + + // Not built yet: TCP, websocket, and modules that report problems. + // Dropping their ends closes those queues, and event stops watching them. + drop((tcp, orders, problems)); + + let udp_task = spawn_udp( + UdpConfig { + addr, + recv_buffer: RECV_BUFFER, + boards: pod_data.boards_by_ip(), + }, + index.clone(), + udp, + ) + .map_err(StartError::Bind)?; + info!(%addr, "listening on UDP (Ctrl+C to stop)"); + + let logging_task = tokio::spawn(stand_in_logging(logging, pod_data.clone())); + let pipeline_task = tokio::spawn(stand_in_pipeline(pipeline, pod_data.clone())); + let mut event_task = event::spawn(config, ends, pod_data, index, None); + + let (stop, by_ctrl_c) = tokio::select! { + stop = &mut event_task => (stop, false), + signal = tokio::signal::ctrl_c() => { + signal.map_err(StartError::CtrlC)?; + info!("Ctrl+C, stopping"); + // Stopping UDP closes its queues: event passes on what is left + // and stops with `Stop::NetGone`. + udp_task.abort(); + (event_task.await, true) + } + }; + udp_task.abort(); + + // event is done, so logging's and pipeline's queues are closed: they + // finish what they have and end on their own. + let finished = tokio::time::timeout(SHUTDOWN_GRACE, async { + let _ = logging_task.await; + let _ = pipeline_task.await; + }) + .await; + if finished.is_err() { + warn!(grace = ?SHUTDOWN_GRACE, "logging and pipeline did not finish in time"); + } + + match stop.map_err(StartError::Event)? { + Stop::Fatal(problem) => { + info!(reason = %problem.text, "stopped after a fatal error"); + Ok(ExitCode::FAILURE) + } + Stop::NetGone if by_ctrl_c => { + info!("stopped"); + Ok(ExitCode::SUCCESS) + } + Stop::NetGone => { + error!("UDP stopped on its own"); + Ok(ExitCode::FAILURE) + } + } +} + +/// Stands in for `logging`: counts what it would record, per board, and +/// writes a summary every second. +async fn stand_in_logging(mut queue: mpsc::Receiver, pod_data: Arc) { + let mut summary = tokio::time::interval(SUMMARY_EVERY); + summary.set_missed_tick_behavior(MissedTickBehavior::Delay); + let mut counts: HashMap = HashMap::new(); + + loop { + tokio::select! { + // The summary first, or under load it would never get its turn. + biased; + _ = summary.tick() => log_summary(&mut counts, &pod_data), + message = queue.recv() => match message { + None => break, + Some(ToLogging::Received(notification)) => { + count_and_trace(¬ification, &mut counts, &pod_data); + } + Some(ToLogging::OrderSent { at, board, order }) => { + let to = order_target(board, &pod_data); + info!(to, id = ?order.id, at = %clock(at), "order sent"); + } + }, + } + } + log_summary(&mut counts, &pod_data); +} + +/// Stands in for `pipeline`: writes to the log what the front would show. +async fn stand_in_pipeline(mut queue: mpsc::Receiver, pod_data: Arc) { + let mut received: u64 = 0; + while let Some(message) = queue.recv().await { + match message { + // The front would get counts, cycle times and averages; here + // packets are only counted, to check that nothing went missing. + ToPipeline::Received(notification) => { + received += 1; + let board = name(&pod_data, notification.board); + match notification.event { + Event::Connected => info!(board, "front: board connected"), + Event::Disconnected => warn!(board, "front: board disconnected"), + Event::Received(_) => {} + } + } + ToPipeline::Problem(problem) => { + let board = problem.board.map(|board| name(&pod_data, board)); + match problem.kind { + ProblemKind::Fatal => { + error!(board = ?board, text = %problem.text, "front: fatal error"); + } + ProblemKind::Shown => { + warn!(board = ?board, text = %problem.text, "front: problem") + } + // event only traces these: they never reach pipeline. + ProblemKind::Silent => {} + } + } + // The front shows both as a message from the backend. + ToPipeline::OrderSent { at, board, order } => { + let to = order_target(board, &pod_data); + info!(to, id = ?order.id, at = %clock(at), "front: order sent"); + } + ToPipeline::OrderFailed { at, order, reason } => { + warn!(id = ?order.id, %reason, at = %clock(at), "front: order not sent"); + } + } + } + info!(notifications = received, "pipeline stand-in finished"); +} + +/// Who an order went to: its board, or every board for the fault. +fn order_target(board: Option, pod_data: &PodData) -> String { + match board { + Some(board) => name(pod_data, board), + None => "every board".to_string(), + } +} + +/// The board's name as the ADJ declares it, or its id if it does not. +fn name(pod_data: &PodData, board: BoardId) -> String { + pod_data + .board_name(board) + .map_or_else(|| format!("{board:?}"), str::to_owned) +} + +/// `at` as seconds since the Unix epoch, with milliseconds, for the log. +fn clock(at: SystemTime) -> String { + match at.duration_since(SystemTime::UNIX_EPOCH) { + Ok(since) => format!("{}.{:03}", since.as_secs(), since.subsec_millis()), + Err(_) => "before 1970".to_string(), + } +} + +/// Counts the notification for the summary and, with `RUST_LOG=debug`, +/// writes it. +fn count_and_trace( + notification: &Notification, + counts: &mut HashMap, + pod_data: &PodData, +) { + *counts.entry(notification.board).or_insert(0) += 1; + + // `debug!`'s fields are only computed when debug is enabled. + match ¬ification.event { + Event::Received(Packet::Data(packet)) => debug!( + board = %name(pod_data, notification.board), + id = ?packet.id, + values = ?packet.values, + "packet" + ), + other => debug!( + board = %name(pod_data, notification.board), + event = ?other, + "notification" + ), + } +} + +/// Writes how many packets arrived from each board since the last summary. +/// Writes nothing if none did. +fn log_summary(counts: &mut HashMap, pod_data: &PodData) { + let total: u64 = counts.values().sum(); + if total == 0 { + return; + } + let mut per_board: Vec = counts + .iter() + .map(|(&board, count)| format!("{}={count}", name(pod_data, board))) + .collect(); + per_board.sort(); + info!(total, boards = %per_board.join(" "), "packets in the last second"); + counts.clear(); }