diff --git a/.github/workflows/rust-tests.yaml b/.github/workflows/rust-tests.yaml index 6ab44a9ce..b3ebd6fc6 100644 --- a/.github/workflows/rust-tests.yaml +++ b/.github/workflows/rust-tests.yaml @@ -13,7 +13,14 @@ jobs: strategy: fail-fast: false matrix: - crate: [software-core, station] + include: + # software-core's modules sit behind features (net, git, logger, + # ntp, http...) that are all off by default: without + # --all-features none of their tests would run, UDP's included. + - crate: software-core + flags: --all-features + - crate: station + flags: "" steps: - uses: actions/checkout@v4 @@ -27,4 +34,4 @@ jobs: - name: Run tests working-directory: backend - run: cargo test --package ${{ matrix.crate }} + run: cargo test --package ${{ matrix.crate }} ${{ matrix.flags }} diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 356fa5ac0..b54c46b90 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -2938,6 +2938,7 @@ dependencies = [ "rlimit", "serde", "serde_json", + "socket2", "tempfile", "thiserror", "tokio", diff --git a/backend/crates/core/Cargo.toml b/backend/crates/core/Cargo.toml index ac855d65f..08324ed3f 100644 --- a/backend/crates/core/Cargo.toml +++ b/backend/crates/core/Cargo.toml @@ -12,8 +12,8 @@ repository.workspace = true default = [] # NTP server ntp = ["dep:tokio", "dep:ntp_usg-server", "dep:tracing-subscriber"] -# TCP/UDP transport (pulls in tokio) -net = ["dep:tokio"] +# TCP/UDP transport (pulls in tokio and socket2 for SO_RCVBUF) +net = ["dep:tokio", "dep:socket2"] # ADJ download through git git = ["dep:tempfile", "dep:dirs", "dep:gix"] # Packet sniffing through pcap (dependency added when the module is written) @@ -40,7 +40,15 @@ serde.workspace = true serde_json.workspace = true thiserror.workspace = true tracing.workspace = true -tokio = { workspace = true, optional = true, features = ["macros", "rt-multi-thread"] } +# `io-util` is what `net` needs on top of the workspace's own list +# (`net`, `sync`, `time`...): `AsyncReadExt`/`AsyncWriteExt`, i.e. reading +# a TCP stream into a buffer at all. +tokio = { workspace = true, optional = true, features = [ + "macros", + "rt-multi-thread", + "io-util", +] } +socket2 = { version = "0.6", optional = true } tracing-subscriber = { workspace = true, optional = true , features = ["env-filter", "fmt"]} tracing-appender = { workspace = true, optional = true } gix = { version = "0.87.1", optional = true, features = ["blocking-http-transport-reqwest-rust-tls", "blocking-network-client", "worktree-mutation"] } diff --git a/backend/crates/core/src/lib.rs b/backend/crates/core/src/lib.rs index d7d151506..a0644a70c 100644 --- a/backend/crates/core/src/lib.rs +++ b/backend/crates/core/src/lib.rs @@ -3,7 +3,7 @@ pub mod hello_world; /// # Git module -/// Handles updates and changes within the ADJ. +/// Handles updates and changes within the ADJ. /// Checks the ADJ Github repository and #[cfg(feature = "git")] pub mod git; @@ -26,6 +26,11 @@ pub mod adj; /// [`protocol::tcp`], [`protocol::udp`]. pub mod protocol; +/// Owns the real tokio sockets and reports what arrives on them, calling +/// into [`protocol`] to decode. See [`net::tcp`], [`net::udp`]. +#[cfg(feature = "net")] +pub mod net; + // Utils module pub(crate) mod utils; /// Everything a recording needs on disk: writing CSV, text and JSON 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.rs b/backend/crates/core/src/net.rs new file mode 100644 index 000000000..3ba454472 --- /dev/null +++ b/backend/crates/core/src/net.rs @@ -0,0 +1,45 @@ +//! Real sockets, on top of tokio (feature `net`). +//! +//! Two submodules do the actual I/O: [`crate::net::tcp`], a client that +//! keeps one task per board and recovers frames out of a byte stream, +//! and [`crate::net::udp`], a single shared receive-only socket. This module opens nothing. It defines only what +//! both of them need to agree on: [`crate::net::Event`] (what happened on +//! a link, carried by a [`crate::net::Notification`]) and +//! [`crate::net::Reporter`] (the two sinks they report through — one for +//! notifications, one for errors). +//! +//! Everything that reaches a [`crate::net::Reporter`] has already been +//! decoded by [`crate::protocol`], which this module layers on top of: +//! `protocol` turns bytes into packets and never touches a socket, `net` +//! owns the socket and calls into it. A sniffer or a simulator can use +//! `protocol` on its own, against a capture, without any of this. +//! +//! # Identity +//! +//! Everything that travels down the notification channel carries its +//! board: [`crate::net::Notification`] holds a +//! [`crate::model::BoardId`] next to the timestamp, whatever the event +//! is. No consumer ever has to go and look up whose packet it just got. +//! +//! It is never a second source of truth, though — it is resolved from +//! what the ADJ already says, once, here. A TCP task was spawned for one +//! board and knows it without asking; [`crate::net::udp`] resolves it +//! from the decoded packet's id through [`crate::protocol::Index`] (every +//! [`crate::model::PacketDef`] carries its `board`), which is one +//! `HashMap` lookup per datagram instead of one per consumer downstream. +//! +//! A board id is all the identity there is: one connection per board, and +//! one shared socket for UDP, so nothing needs telling apart beyond it. +//! +//! Addresses are for the operator, not for the domain types: they show +//! up interpolated in each submodule's error messages (`tcp::Error`, +//! `udp::UdpError`), which is where somebody actually reads them. + +mod error; +mod report; + +pub mod tcp; +pub mod udp; + +pub use error::Error; +pub use report::{Closed, ErrorReport, Event, Notification, Reporter, Sinks}; diff --git a/backend/crates/core/src/net/README.md b/backend/crates/core/src/net/README.md new file mode 100644 index 000000000..50b0f78dd --- /dev/null +++ b/backend/crates/core/src/net/README.md @@ -0,0 +1,184 @@ +# `net` — Real Sockets (feature `net`) + +Owns the actual tokio sockets. `protocol` turns bytes into packets and never +touches a socket; `net` owns the socket and calls into `protocol`. Nothing above +`net` (WebSocket, disk, aggregation) is known here. + +Two submodules do the I/O, and **this directory's shared part opens nothing**: + +``` +net/ +├── net.rs # module root: docs and re-exports +├── report.rs # Event, Notification, ErrorReport, Reporter — what is reported +├── error.rs # Error — aggregates tcp::Error / udp::UdpError, nothing else +├── tcp.rs # the TCP client (not written yet: error type + contract) +├── udp.rs # the shared UDP socket +└── udp/ # its tests: tests.rs, test_support.rs, manual_tests.rs (load probe) +``` + +## The shared part + +### Identity: the board travels with everything + +Every notification carries its board, whatever the event: + +```rust +Notification { board: BoardId, at: SystemTime, event: Event } +``` + +It is never a second source of truth, though — it is resolved from what the ADJ +already says, once, inside `net`. A TCP task was spawned for one board and knows +it without asking; `udp` resolves it from the decoded packet's id through `Index` +(every `PacketDef` carries its `board`), which is one `HashMap` lookup per +datagram instead of one per consumer downstream. + +And the board is all the identity there is: one connection per board, one shared +socket for UDP, so nothing needs telling apart beyond it. + +Addresses are for the operator, not for the domain types: they show up +interpolated in `tcp::Error`/`udp::UdpError` messages, which is where somebody +actually reads them. + +### `Event` and `Notification` — what happened, and when + +```rust +enum Event { + Connected, // TCP only + Disconnected, // TCP only + Received(model::Packet), +} +``` + +`Event::Received` leans on the existing `model::Packet` umbrella +(`Data | Order | Protection | Message`) rather than repeating that split with one +variant per packet type. Its `Order` variant is never produced while receiving — +it is there for an eventual "the order really did go out on the wire" report, +which only `net` can make. + +`board` and `at` sit in the envelope rather than inside the variants so that +**everything** that travels down the channel carries them, and so a notification +**cannot be built without a timestamp**. `Reporter::notify` is the only thing that +stamps it. That +matters: a queue adds delay under load, so a date taken when the record is +*written* would be wrong by exactly that delay, precisely when the data matters +most. It is also the only full date a record can have — the board clock on +protections and messages (`ShortTimestamp`) is a time of day with no date. + +### `Reporter` — the two sinks + +```rust +let (reporter, sinks) = Reporter::channels(notifications, errors); + +reporter.notify(board, event).await?; // notification channel +reporter.report(tcp_or_udp_error).await?; // error channel +``` + +Cloneable, and meant to be cloned: one copy per TCP connection task, one for the +UDP loop, all feeding the same two channels. + +Two channels, not one, because the rules differ. **A notification is never +dropped**: `notify` waits when the channel is full, so the backpressure reaches +the read loop and the kernel's receive buffer becomes the only place anything can +be lost — and whatever is lost there is lost *before* being decoded, so +"everything decoded gets through" stays literally true. An error is rare enough +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 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 + +`net::Error` adds no identity and no message of its own; both variants are +`#[error(transparent)]`, so `to_string()` is the submodule's own message with its +identity already interpolated, and `source()` still reaches the original +`io::Error` or `DecodeError`. Each submodule owns its error type and puts the +board or address **inside the variant** — the Go backend lost exactly +that when an error crossed its channel. `is_fatal()`, if needed, belongs to each +submodule's own error: nobody outside knows which of its variants are fatal. + +## The contract for the two submodules + +| | `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 `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 | +| On a decode error | report it; **fatal**, and close/reopen the connection (the stream cannot be resynchronised) | report it; **fatal**, and keep receiving | +| `Connected`/`Disconnected` | per board | never | +| Fault | writes it: `Handles::propagate_fault()`, id 0 to every board | cannot write; a received id 0 is reported as `UdpError::Fault`, before decoding | + +Both take the same two things besides their own `Config`: an `Arc` — the +only part of the ADJ `net` needs, owned by `station` and read-only here — and a +`Reporter`. Neither reads a config file, and neither reads the ADJ itself: the +addresses `tcp` connects to are resolved by `station` and arrive in `Config`, +which is also what lets a test point it at a fake peer. + +`net` never decides to fault the pod, but `tcp` is what can write one: `station` +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, board }`: recognised by its id alone, before decoding, without +looking at the ADJ. + +Three rules both follow: + +1. The timestamp comes from `Reporter`, never by hand. +2. Decode and report, nothing else — no disk, no WebSocket, no aggregation. +3. What to do about an error is decided locally; only the report goes up. + +### What "fatal" means + +`tcp::Error::is_fatal`/`udp::UdpError::is_fatal` are about the **pod**: they say +the pod has to be sent to fault. They are a hint, not a decision — what happens +next (the fault, closing the connections, shutting the backend down safely) is +decided by whoever consumes the error channel (`station`). Nothing in `net` ever +calls `std::process::exit`. + +On either transport, a decode failure is fatal, and this is a deliberate +departure from Go. Nothing corrupts a frame or a datagram in flight (both +transports checksum, TCP retransmits, and the pod's network does not fragment), so +something that will not decode means the loaded ADJ does not describe what the +firmware is sending — which reconnecting cannot fix. A failed connect or write is +*not* fatal: that is what the backoff is for. + +Two more are fatal in `udp`: losing the socket (`UdpError::Recv`), which is every +board's telemetry gone at once, and a fault sent by a board (`UdpError::Fault`, +packet id 0), which is a board asking for exactly that. + +`net` never raises the fault itself — neither transport does. It logs, it reports, +and `is_fatal()` is the classification whoever consumes the error channel acts on. +That is deliberate: a mismatched ADJ fails on every frame that follows, thousands +a second, so the fault has to be broadcast **once**, and the guard for that lives +in one place instead of one per transport. + +## Why TCP needs a buffer and UDP does not + +TCP is a byte stream and preserves no write boundaries, so one read can deliver +half a frame or two frames glued together — both are normal, and the glued case is +the frequent one. Our frames carry no length prefix: a protection's length is +fixed but derivable only from the ADJ (`2 + 4 + 2 + the watched measurement's wire +width`), and a message ends at the second NUL byte of its two variable-length +strings. So a frame's end is never known in advance, only deduced by parsing it — +which is why the loop tries, and retries with more bytes when it fails. + +The Go backend never faced this because it read straight off the connection, where +a blocking read simply waits mid-frame. That state has to live somewhere: in Go it +lived in the blocked goroutine's stack, and here it lives in an explicit buffer — +which is also what lets `protocol` stay synchronous and socket-free, reusable by a +sniffer against a capture. + +UDP has none of it: the kernel hands over a whole datagram or nothing. + +## Open questions + +- Who raises the fault on `is_fatal()`, and where its "only once" guard lives. + Not in `net`: both transports only report. +- Whether an order's write is reported back as + `Event::Received(Packet::Order(..))`, or `station` just assumes it went out. diff --git a/backend/crates/core/src/net/error.rs b/backend/crates/core/src/net/error.rs new file mode 100644 index 000000000..1588e2043 --- /dev/null +++ b/backend/crates/core/src/net/error.rs @@ -0,0 +1,28 @@ +//! The one error type an [`super::ErrorReport`] can carry. + +use super::{tcp, udp}; + +/// Anything that went wrong in `net`. +/// +/// Aggregation only: this enum adds no identity and no message of its +/// own. Each submodule owns its own error type and puts the identity of +/// whatever failed — the board, or the peer address — +/// *inside* the variant, not just in its text, so that the identity +/// survives being sent down a channel. The Go backend lost it exactly +/// there: the log line before the send had the board, the error value +/// that travelled did not. +/// +/// Both variants are `#[error(transparent)]`, so `to_string()` on this +/// enum is the submodule's own message, identity interpolated and all — +/// which is what gets shown to the operator — and `source()` still walks +/// down to the original `io::Error` or +/// [`crate::protocol::DecodeError`]. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// On a board's TCP connection. + #[error(transparent)] + Tcp(#[from] tcp::Error), + /// On the shared UDP socket. + #[error(transparent)] + Udp(#[from] udp::UdpError), +} diff --git a/backend/crates/core/src/net/report.rs b/backend/crates/core/src/net/report.rs new file mode 100644 index 000000000..4ad86342f --- /dev/null +++ b/backend/crates/core/src/net/report.rs @@ -0,0 +1,369 @@ +//! What [`super::tcp`]/[`super::udp`] report, and the sinks they report +//! through. +//! +//! Two separate channels, both bounded. Notifications +//! ([`Notification`]) carry everything that happened on a link, errors +//! ([`ErrorReport`]) everything that went wrong. They are separate +//! because their rules differ: a notification must never be dropped, +//! while an error is rare enough that it can afford to wait behind a +//! queue of telemetry. +//! +//! Both sinks apply backpressure rather than dropping: see +//! [`Reporter::notify`]. + +use super::Error; +use crate::model::{BoardId, Packet}; +use std::time::SystemTime; +use tokio::sync::mpsc; + +/// Something that happened on a link: which board it concerns, when, +/// and what. +/// +/// Both `board` and `at` live in this envelope rather than inside the +/// variants of [`Event`], so that **everything** that travels down the +/// channel carries them — there is no event whose board the consumer has +/// to go and look up, and none that can be built without a timestamp. +/// [`Reporter::notify`] is the only thing that stamps `at`. +#[derive(Debug)] +pub struct Notification { + /// The board this concerns. + /// + /// Always known by the time anything is reported: a TCP task was + /// spawned for one board and knows it without asking, and [`super::udp`] + /// resolves it from the decoded packet's id through + /// [`crate::protocol::Index`] — `index.packet(id)` gives a + /// [`crate::model::PacketDef`], which carries its `board` — so that a + /// notification looks the same whichever transport brought it. + pub board: BoardId, + /// The instant the bytes came off the socket. + /// + /// Stamped when the event is reported, never by whoever writes it to + /// disk later: a queue adds delay under load, so a date taken at + /// write time would be wrong by exactly that delay, at exactly the + /// moment the data matters most. The frames that carry a board clock + /// of their own ([`crate::model::ShortTimestamp`], on protections and + /// messages) only carry a time of day, with no date, so this is also + /// the only full date a record can have. + pub at: SystemTime, + /// What happened. + pub event: Event, +} + +/// Something that went wrong, and when. +/// +/// 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, 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 + /// [`Notification::at`]. + pub at: SystemTime, + /// What went wrong, identity included. + pub error: Error, +} + +/// What happened on a link. +#[derive(Debug)] +pub enum Event { + /// The board's connection came up, and it can now be talked to. + /// Which board is in the [`Notification`] around this, which is all + /// the identity there is: one connection per board. + /// + /// TCP only: there is nothing to connect in UDP, whose socket is + /// bound once and belongs to no single board. + Connected, + /// The board's connection went down, whatever the reason. If the + /// cause was worth reporting, it already went out as an + /// [`ErrorReport`] — but on the other channel, so nothing orders the + /// two against each other. + /// + /// TCP only, same as [`Event::Connected`]. + Disconnected, + /// A packet arrived and was decoded. Whose it is, is in the + /// [`Notification`] around it. + /// + /// [`Packet`] is the whole umbrella, so this one variant covers data, + /// protections and messages alike, with no second enum repeating that + /// split. Its [`Packet::Order`] variant is never produced while + /// receiving; it is what an eventual "the order really did go out on + /// the wire" report would use, which only `net` is in a position to + /// make. + Received(Packet), +} + +/// The receiving ends of a [`Reporter`]'s two channels, handed to +/// whoever consumes them (`station`). +#[derive(Debug)] +pub struct Sinks { + /// Everything that happened, in the order it happened. + pub notifications: mpsc::Receiver, + /// Everything that went wrong. + pub errors: mpsc::Receiver, +} + +/// The sinks [`super::tcp`] and [`super::udp`] report through. +/// +/// Cloneable, and meant to be cloned: every task gets its own copy — one +/// per TCP connection, one for the UDP loop — and they all feed the same +/// two channels. +#[derive(Debug, Clone)] +pub struct Reporter { + notifications: mpsc::Sender, + errors: mpsc::Sender, +} + +/// The consumer is gone, so there is nobody left to report to. +/// +/// The only failure either sink has, and a signal to stop rather than +/// something to retry. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +#[error("the receiving end is gone")] +pub struct Closed; + +impl Reporter { + /// Builds both channels with the given capacities, and returns the + /// sending half to hand to the submodules plus the receiving halves + /// to hand to the consumer. + /// + /// Both are bounded on purpose: see [`Reporter::notify`] for what + /// happens when the notification channel fills up. + pub fn channels(notifications: usize, errors: usize) -> (Self, Sinks) { + let (notification_tx, notification_rx) = mpsc::channel(notifications); + let (error_tx, error_rx) = mpsc::channel(errors); + + ( + Self { + notifications: notification_tx, + errors: error_tx, + }, + Sinks { + notifications: notification_rx, + errors: error_rx, + }, + ) + } + + /// Stamps the instant and queues `event`. + /// + /// **Waits** if the channel is full, rather than dropping anything: + /// a packet that has already been decoded always reaches the + /// consumer. What that costs is backpressure — the wait reaches back + /// to the read loop, which stops reading, and the kernel's own + /// receive buffer becomes the only place anything can be lost. That + /// is deliberate: whatever is dropped there is dropped *before* being + /// decoded, so "everything decoded gets through" stays literally + /// true. + /// + /// The instant is taken before the wait, not after, so a full queue + /// delays the notification without distorting its timestamp. + pub async fn notify(&self, board: BoardId, event: Event) -> Result<(), Closed> { + let notification = Notification { + board, + at: SystemTime::now(), + event, + }; + + self.notifications + .send(notification) + .await + .map_err(|_| Closed) + } + + /// Stamps the instant and queues an error, on the error channel. + /// + /// Takes anything that converts into [`Error`], so a submodule + /// reports its own error type directly: + /// `reporter.report(tcp::Error::Connect { .. }).await`. + /// + /// Reporting is not deciding: by the time an error gets here its + /// submodule has already done whatever it was going to do about it + /// (reconnect, carry on with the next datagram), and has already + /// logged it through `tracing`. This channel is only for telling the + /// operator, through the frontend. + pub async fn report(&self, error: impl Into) -> Result<(), Closed> { + let report = ErrorReport { + at: SystemTime::now(), + error: error.into(), + }; + + self.errors.send(report).await.map_err(|_| Closed) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::{AdjId, DataPacket}; + use crate::net::udp; + use std::net::{IpAddr, SocketAddr}; + use std::time::Duration; + + fn a_packet() -> Event { + Event::Received(Packet::Data(DataPacket::new(AdjId(1000), vec![]))) + } + + fn an_error() -> udp::UdpError { + udp::UdpError::Recv { + source: std::io::Error::from(std::io::ErrorKind::ConnectionReset), + } + } + + #[tokio::test] + async fn a_notification_arrives_stamped() { + let (reporter, mut sinks) = Reporter::channels(4, 4); + + let before = SystemTime::now(); + let Ok(()) = reporter.notify(BoardId(3), a_packet()).await else { + unreachable!("the receiver is still alive"); + }; + let after = SystemTime::now(); + + let Some(notification) = sinks.notifications.recv().await else { + unreachable!("exactly one notification was sent"); + }; + assert!(notification.at >= before && notification.at <= after); + assert_eq!( + notification.board, + BoardId(3), + "the board travels with every notification, received packets included" + ); + } + + #[tokio::test] + async fn a_connection_event_names_its_board() { + let (reporter, mut sinks) = Reporter::channels(4, 4); + + // The one identity that cannot be derived from a packet: there is + // no packet here at all. + let Ok(()) = reporter.notify(BoardId(3), Event::Disconnected).await else { + unreachable!("the receiver is still alive"); + }; + + let Some(notification) = sinks.notifications.recv().await else { + unreachable!("exactly one notification was sent"); + }; + // The board is the whole identity: one connection per board. + assert_eq!(notification.board, BoardId(3)); + let Event::Disconnected = notification.event else { + unreachable!("a disconnection should arrive as Event::Disconnected"); + }; + } + + #[tokio::test] + async fn a_full_channel_makes_the_reporter_wait_instead_of_dropping() { + let (reporter, mut sinks) = Reporter::channels(1, 1); + + // Fill the single slot, then start a second report that cannot + // fit yet. + let Ok(()) = reporter.notify(BoardId(3), a_packet()).await else { + unreachable!("the first one fits"); + }; + let blocked = tokio::spawn({ + let reporter = reporter.clone(); + async move { reporter.notify(BoardId(3), a_packet()).await } + }); + + // It is still waiting: nothing was dropped, and nothing got + // through either. + tokio::time::sleep(Duration::from_millis(50)).await; + assert!( + !blocked.is_finished(), + "the second report should be waiting" + ); + + // Draining one slot lets it through, so both are delivered. + let Some(_first) = sinks.notifications.recv().await else { + unreachable!("the first notification was sent"); + }; + let Ok(Ok(())) = blocked.await else { + unreachable!("once a slot frees up, the second one goes through"); + }; + let Some(_second) = sinks.notifications.recv().await else { + unreachable!("the second notification went through"); + }; + } + + #[tokio::test] + async fn waiting_on_a_full_channel_does_not_delay_the_timestamp() { + let (reporter, mut sinks) = Reporter::channels(1, 1); + + let Ok(()) = reporter.notify(BoardId(3), a_packet()).await else { + unreachable!("the first one fits"); + }; + let blocked = tokio::spawn({ + let reporter = reporter.clone(); + async move { reporter.notify(BoardId(3), a_packet()).await } + }); + + // Let the second report sit in the queue for a while before + // anything drains it. + tokio::time::sleep(Duration::from_millis(50)).await; + let after_the_wait = SystemTime::now(); + + let Some(_first) = sinks.notifications.recv().await else { + unreachable!("the first notification was sent"); + }; + let Ok(Ok(())) = blocked.await else { + unreachable!("the second one goes through once there is room"); + }; + let Some(second) = sinks.notifications.recv().await else { + unreachable!("the second notification went through"); + }; + + // Stamped when it was reported, not when it finally fit. + assert!( + second.at <= after_the_wait, + "the timestamp should predate the end of the wait" + ); + } + + #[tokio::test] + async fn an_error_arrives_on_its_own_channel() { + let (reporter, mut sinks) = Reporter::channels(4, 4); + + let Ok(()) = reporter.report(an_error()).await else { + unreachable!("the receiver is still alive"); + }; + + let Some(report) = sinks.errors.recv().await else { + unreachable!("exactly one error was reported"); + }; + let Error::Udp(udp::UdpError::Recv { .. }) = report.error else { + unreachable!("a udp error should arrive as Error::Udp"); + }; + // Nothing reached the notification channel. + assert!(sinks.notifications.try_recv().is_err()); + } + + #[test] + fn a_udp_decode_error_keeps_the_address_it_cannot_resolve_to_a_board() { + 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, board, .. }) = Error::from(error) else { + unreachable!("a decode error should convert into Error::Udp"); + }; + assert_eq!(from, addr); + assert_eq!(board, None); + } + + #[tokio::test] + async fn reporting_once_the_consumer_is_gone_says_so() { + let (reporter, sinks) = Reporter::channels(4, 4); + drop(sinks); + + assert_eq!(reporter.notify(BoardId(3), a_packet()).await, Err(Closed)); + assert_eq!(reporter.report(an_error()).await, Err(Closed)); + } +} diff --git a/backend/crates/core/src/net/tcp.rs b/backend/crates/core/src/net/tcp.rs new file mode 100644 index 000000000..297923dc1 --- /dev/null +++ b/backend/crates/core/src/net/tcp.rs @@ -0,0 +1,375 @@ +//! The TCP client: one connection per board, one task each. +//! +//! **Not written yet.** This file currently holds only the error type +//! [`super::Error`] aggregates, plus the contract below, so that the rest +//! of `net` compiles and whoever implements this module knows what the +//! shared part expects of it. See [`super`] and `net/README.md`. +//! +//! # What this module is +//! +//! The backend is the **client**: it connects out to each board's +//! `TCP_SERVER` port, and never listens. One connection per board, each +//! one its own task with its own framing buffer and its own reconnection +//! state. That connection carries protections and messages inbound, and +//! orders and the keep-alive outbound. +//! +//! # Entry point +//! +//! [`spawn`], taking [`Config`], an `Arc` and a +//! [`super::Reporter`], and returning [`Handles`] — the API is written +//! out below, with its reasoning on the items themselves. One call opens +//! **every** connection: one task per entry in [`Config::boards`], so the +//! per-board bookkeeping stays here and `station` only ever asks for +//! "write this to that board". +//! +//! # Contract +//! +//! - **Framing is this module's job.** TCP is a byte stream: a frame can +//! arrive split across reads, and two frames can arrive glued together +//! in one read — both are normal, and the second is the common case. +//! So: accumulate into a per-connection buffer, run +//! [`crate::protocol::tcp::decode_next`] against a `&mut Cursor` over +//! it, and on success advance the buffer by `cursor.position()`. Never +//! consume from the buffer unless a frame parsed in full, or the stream +//! is permanently misaligned. A failed parse means "not enough bytes +//! yet"; the one safeguard is that no frame can exceed 374 bytes +//! (`2 + 4 + 48 + 320`), so a buffer that grows past that without +//! yielding a frame is out of step rather than waiting, and the +//! connection should be dropped and reopened. +//! - **One writer task per connection.** Orders, the keep-alive and the +//! fault all share the socket, so a single task must own the write +//! half, or two half-written frames can interleave on the wire. That +//! task is what [`super::Reporter`]-side callers reach through the +//! board's channel in `Handles`. +//! - **Be ready to be told to propagate the fault.** `station` is what +//! decides (it is the one consuming the error channel and reading +//! [`Error::is_fatal`]); this module is what can actually write, so it +//! exposes `Handles::propagate_fault`, which puts **the order with id +//! 0** — the fault, same as the Go backend's `SendFault` — into every +//! board's writer channel at once, bounded by `write_timeout` per +//! write. It reports back which boards it could not reach instead of +//! collapsing them into one opaque error, since a fault that only +//! half-landed is exactly what the operator has to know. The same path +//! covers the other case the Go backend had under `propagate_fault`: a +//! *received* packet with id 0 is a board announcing a fault, and +//! `station` answers it by calling this, so that logic does not have to +//! exist twice. +//! - Reconnection with exponential backoff and unlimited retries, the +//! OS-level keep-alive disabled (there is an application-level one), +//! `linger = 0` so a dropped connection frees its fixed local port +//! immediately instead of sitting in `TIME_WAIT`. +//! - Report through [`super::Reporter`] only: [`super::Event::Connected`] +//! and [`super::Event::Disconnected`] per connection, +//! [`super::Event::Received`] per frame, and [`Error`] on the error +//! channel. Never stamp a timestamp by hand — [`super::Reporter::notify`] +//! does it. Never touch disk, WebSocket or aggregation. +//! - **A decode failure is fatal**: see [`Error::is_fatal`]. Log it and +//! report it on the error channel — and that is all this module does +//! about it. Sending the pod to fault is not `net`'s call to make: +//! whoever consumes the error channel reads [`Error::is_fatal`] and +//! decides, which also keeps the "fault once" guard in one place +//! instead of one per transport. The stream cannot be resynchronised +//! mid-frame, though, so this module does close the connection and let +//! the reconnection loop reopen it — reconnecting will not fix a +//! mismatched ADJ, so expect the same frame to fail again. +//! - Everything else is decided here, locally: a failed connect or write +//! is what the backoff is for, and only the report goes up. + +use super::Reporter; +use crate::model::{AdjId, BoardId, OrderPacket}; +use crate::protocol::{DecodeError, Index}; +use std::net::SocketAddr; +use std::sync::Arc; +use std::time::Duration; + +/// One board to keep a connection to. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct BoardLink { + /// Whose connection this is. Every report about it names this board, + /// which is the whole identity of a link. + pub board: BoardId, + /// Where to connect: the board's `ip` + its `ports["TCP_SERVER"]`. + pub addr: SocketAddr, + /// The fixed local port to bind the client side to (`TCP_CLIENT + i` + /// in the Go backend). Being fixed is why `linger = 0` matters: a + /// dropped connection must not leave this port in `TIME_WAIT`. + pub local_port: u16, +} + +/// How long to wait between reconnection attempts. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Backoff { + /// The first wait after a connection fails or drops. + pub initial: Duration, + /// The ceiling the doubling stops at. Retries are unlimited: a board + /// that is not up yet is the normal state before a test, not an + /// error to give up on. + pub max: Duration, +} + +/// How to run the TCP client. +/// +/// Everything here is resolved by `station` before `net` is reached: this +/// module reads no config file, and it does not read the ADJ to find its +/// peers either. That is also what lets a test point it at a fake peer. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Config { + /// One entry per board to connect to, already filtered by what the + /// config file lists: a board the ADJ declares but the config does + /// not name gets no client at all. + pub boards: Vec, + /// Bound on each connection attempt. + pub connect_timeout: Duration, + /// What to wait between attempts. + pub backoff: Backoff, + /// Period of the application-level keep-alive this module sends on + /// its own. The OS-level keep-alive is + /// disabled precisely because this one exists. + pub keep_alive: Duration, + /// Bound on each write, so that a peer that stops reading cannot park + /// a writer task for good (1 s in the Go backend). + pub write_timeout: Duration, +} + +/// Opens a connection to every board in `config.boards`. +/// +/// One call, one task per board: the per-connection bookkeeping stays in +/// this module, and `station` only ever asks for "write this to that +/// board" through the [`Handles`] that come back. +/// +/// `adj` is the only part of the ADJ this module needs: it decodes +/// inbound frames and encodes outbound orders against it. `station` owns +/// it and hands out clones; it is read-only here, and a reload of the ADJ +/// is a new [`Index`] with new tasks, never a mutation of this one. +/// +/// Connecting is *not* done before spawning, unlike [`super::udp`]: a +/// board that is not up yet is normal, so a failed attempt is a report +/// and a retry, never a startup failure. +pub fn spawn(config: Config, adj: Arc, reporter: Reporter) -> Handles { + let _ = (config, adj, reporter); + todo!("the TCP client is not written yet: see this module's contract") +} + +/// The writing side of every connection [`spawn`] opened. +/// +/// The representation is left to the implementation — a writer channel +/// per board and the task handles — so that this file states the API and +/// nothing else. +#[derive(Debug)] +pub struct Handles {} + +impl Handles { + /// The handle for one board, or `None` if the config did not list it. + #[must_use] + pub fn board(&self, board: BoardId) -> Option<&BoardHandle> { + let _ = board; + todo!("the TCP client is not written yet: see this module's contract") + } + + /// Hands an order to the board it belongs to, resolved by its id + /// through the [`Index`]. + /// + /// Returns once the order is queued on that board's writer, not once + /// it is on the wire — the write itself is bounded by + /// [`Config::write_timeout`] and reported through [`Error::Write`]. + /// + /// # Errors + /// + /// See [`SendError`]: an id no ADJ declares, a board with no client, + /// or a connection task that is gone. + pub async fn send(&self, order: OrderPacket) -> Result<(), SendError> { + let _ = order; + todo!("the TCP client is not written yet: see this module's contract") + } + + /// Sends the fault — the order with id 0 — to every board at once. + /// + /// This module does not decide to fault the pod; `station` does, by + /// reading [`Error::is_fatal`] off the error channel. This is only + /// the one place that can actually write it, so it is where the + /// fan-out lives. A *received* packet with id 0 is a board asking for + /// the same thing, and `station` answers it by calling this, so that + /// logic does not exist twice. + /// + /// # Errors + /// + /// [`Unreachable`], naming the boards the fault did not reach rather + /// than collapsing them into one opaque failure: a fault that only + /// half landed is exactly what the operator has to be told. + pub async fn propagate_fault(&self) -> Result<(), Unreachable> { + todo!("the TCP client is not written yet: see this module's contract") + } + + /// Closes every connection and waits for its task to finish. + pub async fn shutdown(self) { + todo!("the TCP client is not written yet: see this module's contract") + } +} + +/// The writing side of one board's connection. +/// +/// The representation is left to the implementation, same as +/// [`Handles`]. +#[derive(Debug)] +pub struct BoardHandle {} + +impl BoardHandle { + /// Hands an order to this board's writer, without consulting the + /// order's id — [`Handles::send`] is what routes. + /// + /// # Errors + /// + /// [`SendError::Gone`] if this connection's task is no longer there. + pub async fn send(&self, order: OrderPacket) -> Result<(), SendError> { + let _ = order; + todo!("the TCP client is not written yet: see this module's contract") + } +} + +/// Why an order could not be handed to a writer. +/// +/// Returned to the caller, not reported through [`super::Reporter`]: it +/// says something about the order that was asked for, not about the state +/// of a connection. [`Error`] is the one that travels on the error +/// channel. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +pub enum SendError { + /// No order with this id is declared in the loaded ADJ. + #[error("no order is declared with id {0:?}")] + UnknownId(AdjId), + /// The order resolves to a board the config did not list, so no + /// client was ever opened for it. + #[error("board {0:?} has no TCP client: the config does not list it")] + NoClient(BoardId), + /// The board's connection task is no longer running. + #[error("board {0:?}: its connection task is gone")] + Gone(BoardId), +} + +/// The boards a fault broadcast did not reach. +/// +/// Never empty: a broadcast that reached everybody returns `Ok`. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("the fault did not reach these boards: {0:?}")] +pub struct Unreachable(pub Vec); + +/// Something that went wrong on a board's TCP connection. +/// +/// Every variant names its board, which is the whole identity of a link: +/// one connection per board. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// The connection could not be opened. + #[error("board {board:?}: could not connect")] + Connect { + /// The board that was being connected to. + board: BoardId, + /// The underlying I/O failure. + #[source] + source: std::io::Error, + }, + + /// A frame could not be decoded, which means the loaded ADJ does not + /// describe what the board is sending. Fatal: see + /// [`Error::is_fatal`]. + #[error("board {board:?}: could not decode a frame")] + Decode { + /// The board whose frame failed. + board: BoardId, + /// What [`crate::protocol`] said about it. + #[source] + source: DecodeError, + }, + + /// An order or a keep-alive could not be written. + #[error("board {board:?}: could not write")] + Write { + /// The board that was being written to. + board: BoardId, + /// The underlying I/O failure. + #[source] + source: std::io::Error, + }, +} + +impl Error { + /// Whether this error means the pod has to be sent to fault. + /// + /// "Fatal" is about the **pod**, not about this process: the backend + /// stays up — still reading its other connections, still serving the + /// frontend, still recording — so that whoever is operating the pod + /// can see what happened. Nothing here ever calls + /// `std::process::exit`. + /// + /// Only [`Error::Decode`] qualifies, and this is the one place where + /// the behaviour deliberately departs from the Go backend. Go treated + /// an undecodable frame as a connection that had fallen out of step, + /// and reconnecting was the remedy. But nothing corrupts a frame in + /// flight — TCP checksums and retransmits — so a frame that will not + /// decode means the loaded ADJ does not match what the firmware is + /// sending, and reopening the connection cannot fix that. The stream + /// still cannot be resynchronised mid-frame, so the connection is + /// closed and reopened anyway; what changes is that the pod is also + /// sent to fault instead of carrying on as if a retry would help. + /// + /// [`Error::Connect`] and [`Error::Write`] are not fatal: a board + /// that is not up yet, or a write that failed on a connection that + /// just dropped, is exactly what the reconnection loop with its + /// backoff is for. Losing a board for good is reported through + /// [`super::Event::Disconnected`], not through this. + pub fn is_fatal(&self) -> bool { + match self { + Error::Decode { .. } => true, + Error::Connect { .. } | Error::Write { .. } => false, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn io_error() -> std::io::Error { + std::io::Error::from(std::io::ErrorKind::ConnectionRefused) + } + + #[test] + fn a_frame_that_will_not_decode_faults_the_pod() { + let error = Error::Decode { + board: BoardId(3), + source: DecodeError::UnknownId(crate::model::AdjId(9999)), + }; + + // Not a desynchronised stream to retry: the ADJ does not match + // the firmware, and reconnecting cannot fix that. + assert!(error.is_fatal()); + } + + #[test] + fn a_board_that_is_not_up_yet_does_not_fault_the_pod() { + let connect = Error::Connect { + board: BoardId(3), + source: io_error(), + }; + let write = Error::Write { + board: BoardId(3), + source: io_error(), + }; + + // That is what the reconnection backoff is for. + assert!(!connect.is_fatal()); + assert!(!write.is_fatal()); + } + + #[test] + fn an_error_says_which_board_it_was() { + let error = Error::Write { + board: BoardId(3), + source: io_error(), + }; + + // The identity survives being formatted, which is what reaches + // the operator. + assert!(error.to_string().contains("BoardId(3)")); + } +} diff --git a/backend/crates/core/src/net/udp.rs b/backend/crates/core/src/net/udp.rs new file mode 100644 index 000000000..87eabcbb3 --- /dev/null +++ b/backend/crates/core/src/net/udp.rs @@ -0,0 +1,536 @@ +//! The shared UDP socket: one socket, receive-only, every board's +//! telemetry. +//! +//! # What this module is +//! +//! One socket bound to the backend's own address, carrying `Data` packets +//! from every board, and the fault (packet id 0) any of them may send. +//! Nothing is ever sent from it. +//! +//! # Entry point +//! +//! [`spawn_udp`], taking [`UdpConfig`], an `Arc` and a +//! [`super::Reporter`] — written out with its reasoning on the items +//! themselves. No handle comes back beyond the `JoinHandle`: there is no +//! writing side. +//! +//! # Contract +//! +//! - **No framing.** A datagram arrives whole or not at all, so +//! `recv_from` already delivers exactly one packet and its length — +//! none of [`super::tcp`]'s buffer applies here. Read into one reused +//! 64 KiB buffer and a datagram can never be silently truncated, +//! whatever the ADJ grows to. +//! - The loop does three things and nothing else: decode with +//! [`crate::protocol::udp::decode_datagram`], resolve the board, report +//! (a fault skips the first two, see below). No disk, no WebSocket, no +//! aggregation. +//! - **Packet id 0 is a fault** ([`UdpError::Fault`]): what a board sends +//! when it has detected an error. It is recognised by its id alone, +//! **before** decoding: it is not in the ADJ, the [`crate::protocol::Index`] +//! is not consulted and nothing after the id is read. It goes down the +//! error channel with the address it came from, the only thing that +//! says which board sent it. +//! - [`super::Notification::board`] comes from the decoded packet's id, +//! through [`crate::protocol::Index`] — every +//! [`crate::model::PacketDef`] carries its `board` — so that a +//! 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 +//! fragment it — so a datagram that will not decode most likely means +//! the ADJ this backend loaded does not describe what the boards are +//! actually sending. This module traces it and reports it on the error +//! channel, exactly as [`super::tcp`] does — and that is all. Whoever +//! consumes the error channel decides what happens next (sending the +//! pod to fault, shutting down), which also keeps the "fault once" guard +//! in one place rather than one per transport. +//! - **Every failure is reported, but the trace is rate-limited.** A +//! mismatched ADJ fails on every datagram that follows, several thousand +//! a second. Each one still goes down the error channel, so the consumer +//! sees them all; the trace gets the first one and then at most one line +//! a second, carrying how many were left out since the previous line. +//! Decode failures and faults are limited separately, so a burst of one +//! never hides the other. +//! - [`super::Event::Connected`]/[`super::Event::Disconnected`] are never +//! emitted: there is no connection to come up or go down. +//! - Binding happens **before** the task is spawned, so a bad address is +//! a startup failure returned to whoever is composing the backend +//! (`station`), not something reported once +//! everything is already running. Hence the entry point returns +//! `Result, UdpError>`. +//! +//! # Stopping +//! +//! The loop stops on its own when a report fails because the consumer is +//! gone — but it only finds out the next time it has something to report, +//! that is, on the next datagram. With no telemetry arriving (boards off, +//! cable out), closing the [`super::Sinks`] alone leaves the task waiting +//! on the socket. +//! +//! To stop it at a moment of the caller's choosing (a shutdown), call +//! [`JoinHandle::abort`] on the handle [`spawn_udp`] returns. That is safe: +//! the task holds nothing that needs flushing, and all that is lost is +//! whatever was still sitting in the kernel's receive buffer. +//! +//! # Tests +//! +//! Kept out of this file, next to it in `udp/`: +//! +//! - `tests.rs` — unit tests, and tests through a real socket on loopback. +//! - `test_support.rs` — the fixtures both share: a minimal ADJ index, +//! loopback sockets, and waits on the reporter's channels that fail +//! instead of hanging. +//! - `manual_tests.rs` — `manual_udp_load`, an ignored load probe that +//! checks the loop keeps up with 25 Mbit/s of 76-byte datagrams: +//! +//! ```sh +//! cargo test -p software-core --features net --release manual_udp_load -- --ignored --nocapture +//! ``` + +use super::Reporter; +use crate::model::{BoardId, Packet}; +use crate::protocol::{DecodeError, Index}; +use std::collections::HashMap; +use std::net::{IpAddr, SocketAddr}; +use std::sync::Arc; +use std::time::{Duration, Instant}; +use tokio::task::JoinHandle; +use tracing::{error, info, warn}; + +/// How to set the shared socket up. +/// +/// 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, 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`. + pub addr: SocketAddr, + /// `SO_RCVBUF` to request, in bytes. + /// + /// The only thing absorbing a stall of the receive loop, since the + /// kernel drops the tail silently once it is full. + /// + /// The margin it buys is counted in **datagrams**, not bytes: the + /// kernel charges each datagram its bookkeeping on top of its payload. + /// Measured on Linux over loopback, a 76-byte datagram (the average of + /// the H11 packets) takes about 960 bytes of buffer, so 2 MiB requested + /// (4 MiB granted, see below) holds about 4,400 datagrams — roughly + /// 0.1 s at 25 Mbit/s of 76-byte datagrams (~41,000 a second). A real + /// network card's driver may charge a different amount; measure on the + /// station's own machine. + /// + /// **This margin can be widened** by requesting more and raising the OS + /// limit so that the request is granted. On Linux, with + /// `sudo sysctl -w net.core.rmem_max=16777216` (16 MiB) and 16 MiB + /// requested here, 32 MiB are granted: by the figure above about 35,000 + /// datagrams, roughly 0.8 s at that rate. `sysctl -w` is lost on reboot; + /// to keep it, put `net.core.rmem_max = 16777216` in a file under + /// `/etc/sysctl.d/`. The limits on Windows and macOS have not been checked. + /// + /// The operating system may grant less than this — Linux silently caps + /// 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. +/// +/// Binding happens here, **before** the task, so that a bad address is a +/// startup failure handed back to whoever is composing the backend rather +/// than something reported once everything is already running. +/// +/// `adj` is the only part of the ADJ this module needs: it maps a decoded +/// id to its [`crate::model::PacketDef`], for the decode itself and for +/// the `board` every [`super::Notification`] carries. `station` owns it +/// and hands out clones; it is read-only here, and a reload of the ADJ is +/// a new [`Index`] with a new task, never a mutation of this one. +/// +/// The returned handle is also how to stop the task: see the module's +/// "Stopping" section. +/// +/// # Errors +/// +/// [`UdpError::Bind`] only — every later failure goes out through +/// `reporter`, since by then there is nobody left to return it to. +pub fn spawn_udp( + config: UdpConfig, + adj: Arc, + reporter: Reporter, +) -> Result, UdpError> { + 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 { + // 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, + source, + })?; + + // Tokio requires the underlying std socket to be in non-blocking mode. + std_socket + .set_nonblocking(true) + .map_err(|source| UdpError::Bind { + addr: config.addr, + source, + })?; + + // Convert the standard socket into an async Tokio UdpSocket. + let socket = tokio::net::UdpSocket::from_std(std_socket).map_err(|source| UdpError::Bind { + addr: config.addr, + source, + })?; + + // Asking is not getting: Linux caps the request at `net.core.rmem_max` + // without returning an error, so the size actually granted has to be + // read back. Linux also reports back twice what it granted (it reserves + // the other half for bookkeeping, see socket(7)): with `rmem_max` at + // 4 MiB, asking for 2 MiB reads back 4 MiB and asking for 16 MiB reads + // back 8 MiB. So on Linux a full grant reads back as twice the request, + // and anything less means the request was capped. Elsewhere the value + // read back is compared with the request as is. + let full_grant = if cfg!(target_os = "linux") { + config.recv_buffer.saturating_mul(2) + } else { + config.recv_buffer + }; + let sock_ref = socket2::SockRef::from(&socket); + let granted = sock_ref + .set_recv_buffer_size(config.recv_buffer) + .and_then(|()| sock_ref.recv_buffer_size()); + match granted { + Ok(granted) if granted >= full_grant => { + info!( + addr = %config.addr, + requested = config.recv_buffer, + granted, + "SO_RCVBUF set" + ); + } + Ok(granted) => { + warn!( + addr = %config.addr, + requested = config.recv_buffer, + granted, + "SO_RCVBUF is smaller than requested, so a stall loses datagrams sooner; \ + raise the OS limit (net.core.rmem_max on Linux) for more margin" + ); + } + Err(e) => { + warn!( + addr = %config.addr, + requested = config.recv_buffer, + %e, + "could not set SO_RCVBUF, using system default" + ); + } + } + + Ok(socket) +} + +/// Main UDP loop: reads datagrams into a reusable 64 KiB buffer, decodes in-place, and reports. +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(); + + loop { + match socket.recv_from(&mut buf).await { + Ok((len, from)) => { + 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; + } + } + Err(source) => { + // Socket-level receive failure: log, report as fatal to the backend, and stop. + let err = UdpError::Recv { source }; + error!(%err, "UDP receive error"); + let _ = reporter.report(err).await; + break; + } + } + } +} + +/// The first two bytes of a fault datagram: packet id 0, little-endian +/// like every id on the wire. +/// +/// A board that has detected an error sends it. It is not declared in the +/// ADJ, and the Go backend broadcasts the same id to every board when it +/// raises a fault itself (`SendFault`). +const FAULT_ID: [u8; 2] = 0u16.to_le_bytes(); + +/// 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 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, + 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, ?board, suppressed, "a board signalled a fault (packet id 0)"); + } + return reporter + .report(UdpError::Fault { from, board }) + .await + .is_ok(); + } + + 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, ?board, %source, suppressed, "UDP datagram could not be decoded"); + } + let error = UdpError::Decode { + from, + board, + source, + }; + return reporter.report(error).await.is_ok(); + } + }; + + // A second lookup of the id `decode_datagram` has just resolved: it + // returns the packet, not its definition. Decoding already rejected + // any id the index does not know, so this branch is not expected to + // 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) = lookups.adj.packet(packet.id) else { + warn!(id = ?packet.id, "decoded packet id not in index"); + return true; + }; + + let board = packet_def.board; + + reporter + .notify(board, super::Event::Received(Packet::Data(packet))) + .await + .is_ok() +} + +/// How often, at most, each kind of failure reaches the trace. +const TRACE_INTERVAL: Duration = Duration::from_secs(1); + +/// The receive loop's trace rate limits, one per kind of failure, so that +/// a burst of decode failures never hides a fault from the trace, nor the +/// other way round. +#[derive(Debug, Default)] +struct ReceiveTraces { + /// Datagrams that would not decode. + decode: TraceRateLimit, + /// Faults (packet id 0). + fault: TraceRateLimit, +} + +/// Rate limit for tracing one kind of failure. +/// +/// Only the trace is limited: every failure is still reported down the +/// error channel. A burst that stops is summed up by the next failure +/// that gets traced, so if no further failure ever comes, its count is +/// only in the error channel — which already had every one of them. +#[derive(Debug, Default)] +struct TraceRateLimit { + /// Failures not traced since the last one that was. + suppressed: u64, + /// When a failure was last traced. + last: Option, +} + +impl TraceRateLimit { + /// Decides whether the failure seen at `now` is traced. + /// + /// `Some(n)` means trace it, `n` being how many were left out since the + /// previous traced one (`0` for the first). `None` means count it + /// only. `now` is a parameter rather than read here so that the + /// decision can be tested without waiting for real time to pass. + fn should_trace(&mut self, now: Instant) -> Option { + match self.last { + Some(last) if now.saturating_duration_since(last) < TRACE_INTERVAL => { + self.suppressed += 1; + None + } + _ => { + self.last = Some(now); + Some(std::mem::take(&mut self.suppressed)) + } + } + } +} + +/// Something that went wrong on the shared UDP socket, or that a board +/// says went wrong ([`UdpError::Fault`]). +/// +/// [`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. + #[error("could not bind the shared UDP socket to {addr}")] + Bind { + /// The address it was being bound to. + addr: SocketAddr, + /// The underlying I/O failure. + #[source] + source: std::io::Error, + }, + + /// Receiving on the socket failed. + #[error("could not receive on the shared UDP socket")] + Recv { + /// The underlying I/O failure. + #[source] + source: std::io::Error, + }, + + /// A datagram could not be decoded, which most likely means the loaded + /// ADJ does not describe what the boards are sending. See + /// [`UdpError::is_fatal`]. + #[error("could not decode a datagram from {from}")] + Decode { + /// 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, + }, + + /// A board has detected an error and said so with a fault: a datagram + /// whose packet id is 0. Not a failure of this socket — the datagram + /// 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. 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, + }, +} + +impl UdpError { + /// Whether this module considers the error serious enough to send the + /// pod to fault. + /// + /// A **hint** for whoever consumes the error channel, not a decision: + /// `net` never raises the fault and never stops the process. What to + /// do about a fatal error — sending the pod to fault, shutting the + /// backend down, or something else — is decided by the application + /// (`station`), which may also look at the error's details (such as + /// the [`DecodeError`] variant) rather than at this answer alone. + /// + /// Both runtime failures of this socket qualify, and for the same + /// reason: neither can be true of a single datagram. + /// [`UdpError::Decode`] most likely means the loaded ADJ does not describe + /// what the boards are sending, and [`UdpError::Recv`] means the socket + /// itself is no longer usable, which is every board's telemetry gone + /// at once. Neither is something a retry fixes. + /// + /// [`UdpError::Fault`] is fatal by definition: it is a board asking for + /// the pod to go to fault. + /// + /// [`UdpError::Bind`] never reaches the error channel: binding happens + /// before the task is spawned, so it is a startup failure handed back + /// to whoever composes the backend. + pub fn is_fatal(&self) -> bool { + match self { + UdpError::Bind { .. } + | UdpError::Recv { .. } + | UdpError::Decode { .. } + | UdpError::Fault { .. } => true, + } + } +} + +#[cfg(test)] +mod manual_tests; + +#[cfg(test)] +mod test_support; + +#[cfg(test)] +mod tests; diff --git a/backend/crates/core/src/net/udp/manual_tests.rs b/backend/crates/core/src/net/udp/manual_tests.rs new file mode 100644 index 000000000..a992487bd --- /dev/null +++ b/backend/crates/core/src/net/udp/manual_tests.rs @@ -0,0 +1,231 @@ +//! Manual load probe: can the receive loop keep up with the pod's +//! telemetry? +//! +//! Ignored by a normal `cargo test`. It sends 76-byte datagrams over +//! loopback at `UDP_LOAD_MBIT` Mbit/s (default 25, about 41,000 datagrams +//! a second) for `UDP_LOAD_SECS` seconds (default 10), through the real +//! socket, decode and reporter, into a consumer that only counts. It fails +//! if any datagram is lost or fails to decode. `UDP_LOAD_RCVBUF` sets the +//! `SO_RCVBUF` requested (default 2 MiB). Run it in release, which is how +//! the station runs: +//! +//! ```sh +//! cargo test -p software-core --features net --release manual_udp_load -- --ignored --nocapture +//! UDP_LOAD_MBIT=40 cargo test -p software-core --features net --release manual_udp_load -- --ignored --nocapture +//! ``` +//! +//! What it does **not** tell: the cost of the real consumer (`station`'s +//! event loop), which comes on top — a consumer that only adds a timer per +//! message was already enough to lose 0.7 % at 25 Mbit/s. And loopback is +//! not the pod's network: sender and receiver share this machine's CPUs, +//! and there is no network card. + +use super::test_support::{any_loopback_port, bind_on_loopback}; +use super::*; +use crate::model::{ + AdjId, Board, BoardId, DataPacket, MacAddress, Measurement, MeasurementKind, NumericKind, + PacketDef, PacketType, PodData, Value, +}; +use std::collections::HashMap; +use std::net::IpAddr; + +/// Bytes of one datagram in the probe: 2 of id and 74 of values. +const PROBE_DATAGRAM_LEN: usize = 76; + +fn measurement_with_id(id: u16, kind: MeasurementKind) -> Measurement { + Measurement { + id: AdjId(id), + alias: format!("m{id}"), + name: format!("measurement {id}"), + display_units: String::new(), + kind, + protections: vec![], + } +} + +/// An index with one `Data` packet (id 1000, board 1) whose datagram is +/// [`PROBE_DATAGRAM_LEN`] bytes, mixing value types the way board telemetry +/// does — floats, integers, enums (which decode into a `String`) and +/// booleans — together with the bytes of one such datagram. +fn telemetry_index_and_datagram() -> (Index, Vec) { + let mut measurements = Vec::new(); + let mut values = Vec::new(); + let mut add = |kind: MeasurementKind, value: Value, count: usize| { + for _ in 0..count { + let id = u16::try_from(measurements.len() + 1).unwrap_or(u16::MAX); + measurements.push(measurement_with_id(id, kind.clone())); + values.push(value.clone()); + } + }; + let numeric = |wire_type| MeasurementKind::Numeric { wire_type }; + let options = vec!["Idle".to_string(), "Running".into(), "Fault".into()]; + + add(numeric(NumericKind::F32), Value::Number(21.5), 14); // 56 bytes + add(numeric(NumericKind::U16), Value::Number(1234.0), 4); // 8 bytes + add(numeric(NumericKind::U8), Value::Number(7.0), 6); // 6 bytes + add(MeasurementKind::Enum { options }, Value::Number(1.0), 2); // 2 bytes + add(MeasurementKind::Boolean, Value::Bool(true), 2); // 2 bytes + + let packet = PacketDef { + id: AdjId(1000), + board: BoardId(1), + name: "telemetry".to_string(), + packet_type: PacketType::Data(measurements), + }; + let board = Board { + id: BoardId(1), + name: "TEST".to_string(), + ip: IpAddr::from([127, 0, 0, 1]), + mac: MacAddress([0; 6]), + packets: HashMap::from([(packet.id, packet)]), + }; + let index = Index::new( + &PodData { + boards: HashMap::from([(board.id, board)]), + }, + None, + ); + + let datagram = + crate::protocol::packet::data_order::encode(&DataPacket::new(AdjId(1000), values), &index); + let Ok(datagram) = datagram else { + unreachable!("the probe's telemetry packet should encode"); + }; + assert_eq!(datagram.len(), PROBE_DATAGRAM_LEN); + (index, datagram) +} + +/// Sends `datagram` to `to` at `per_second` for `duration`, paced in short +/// bursts as a board's network would deliver it. Returns how many were +/// sent and how many sends failed. +fn send_at_rate( + to: SocketAddr, + datagram: &[u8], + per_second: f64, + duration: Duration, +) -> (u64, u64) { + let Ok(socket) = std::net::UdpSocket::bind(any_loopback_port()) else { + unreachable!("binding the probe's sending socket should succeed"); + }; + let start = Instant::now(); + let (mut sent, mut failed) = (0u64, 0u64); + while start.elapsed() < duration { + let due = (start.elapsed().as_secs_f64() * per_second) as u64; + while sent + failed < due { + match socket.send_to(datagram, to) { + Ok(_) => sent += 1, + Err(_) => failed += 1, + } + } + std::thread::sleep(Duration::from_micros(200)); + } + (sent, failed) +} + +/// The kernel's count of UDP datagrams dropped for lack of receive buffer, +/// system-wide (`RcvbufErrors` in `/proc/net/snmp`). Linux only. +fn kernel_rcvbuf_errors() -> Option { + let snmp = std::fs::read_to_string("/proc/net/snmp").ok()?; + let mut udp = snmp.lines().filter(|line| line.starts_with("Udp:")); + let header = udp.next()?; + let values = udp.next()?; + let column = header + .split_whitespace() + .position(|c| c == "RcvbufErrors")?; + values.split_whitespace().nth(column)?.parse().ok() +} + +/// The environment variable `name` parsed as `T`, or `default`. +fn env_var_or(name: &str, default: T) -> T { + std::env::var(name) + .ok() + .and_then(|value| value.parse().ok()) + .unwrap_or(default) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "load probe: run in release with --ignored --nocapture"] +async fn manual_udp_load() { + let mbit: f64 = env_var_or("UDP_LOAD_MBIT", 25.0); + let secs: u64 = env_var_or("UDP_LOAD_SECS", 10); + let recv_buffer: usize = env_var_or("UDP_LOAD_RCVBUF", 2 * 1024 * 1024); + let per_second = mbit * 1_000_000.0 / 8.0 / PROBE_DATAGRAM_LEN as f64; + let (index, datagram) = telemetry_index_and_datagram(); + + 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); + // 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 + // and what is measured is this module. + let (done_tx, mut done_rx) = tokio::sync::oneshot::channel::<()>(); + let consumer = tokio::spawn(async move { + let (mut received, mut errors) = (0u64, 0u64); + loop { + tokio::select! { + biased; + Some(_) = sinks.notifications.recv() => received += 1, + Some(_) = sinks.errors.recv() => errors += 1, + _ = &mut done_rx => break, + } + } + while let Ok(Some(_)) = + tokio::time::timeout(Duration::from_millis(200), sinks.notifications.recv()).await + { + received += 1; + } + while sinks.errors.try_recv().is_ok() { + errors += 1; + } + (received, errors) + }); + + let drops_before = kernel_rcvbuf_errors(); + let started = Instant::now(); + let sender = tokio::task::spawn_blocking(move || { + send_at_rate(addr, &datagram, per_second, Duration::from_secs(secs)) + }); + let Ok((sent, failed)) = sender.await else { + unreachable!("the sender thread should not panic"); + }; + let send_time = started.elapsed(); + let _ = done_tx.send(()); + let Ok((received, errors)) = consumer.await else { + unreachable!("the consumer task should not panic"); + }; + let drops = match (drops_before, kernel_rcvbuf_errors()) { + (Some(before), Some(after)) => format!("+{}", after.saturating_sub(before)), + _ => "unavailable".to_string(), + }; + receiver.abort(); + + let lost = sent.saturating_sub(received); + println!( + "UDP load probe: {mbit} Mbit/s in {PROBE_DATAGRAM_LEN}-byte datagrams \ + = {per_second:.0} datagrams/s, for {secs} s" + ); + println!( + " sent {sent} in {:.2} s ({:.0}/s), {failed} sends failed", + send_time.as_secs_f64(), + sent as f64 / send_time.as_secs_f64() + ); + println!( + " received {received}, lost {lost} ({:.4} %), decode errors {errors}", + 100.0 * lost as f64 / sent.max(1) as f64 + ); + println!( + " SO_RCVBUF requested {recv_buffer} bytes, read back {granted:?}; \ + kernel RcvbufErrors (system-wide): {drops}" + ); + + assert_eq!(errors, 0, "every datagram should decode"); + assert_eq!(lost, 0, "every datagram sent should be received"); +} diff --git a/backend/crates/core/src/net/udp/test_support.rs b/backend/crates/core/src/net/udp/test_support.rs new file mode 100644 index 000000000..11cfa9ff9 --- /dev/null +++ b/backend/crates/core/src/net/udp/test_support.rs @@ -0,0 +1,148 @@ +//! Fixtures shared by `tests.rs` and `manual_tests.rs`: a minimal ADJ +//! index, loopback sockets, and waits on the reporter's channels that fail +//! instead of hanging. + +use super::*; +use crate::model::{AdjId, Board, BoardId, MacAddress, PacketDef, PacketType, PodData}; +use crate::net::{ErrorReport, Event, Notification, Sinks}; +use std::collections::HashMap; +use std::net::IpAddr; + +/// How long a test waits for something to arrive before failing, so that +/// a broken expectation fails instead of hanging forever. +pub(super) const RECEIVE_TIMEOUT: Duration = Duration::from_secs(1); + +/// Id 1000, little-endian, with no measurements after it: the one packet +/// [`index_with_empty_data_packet`] declares. +pub(super) const EMPTY_DATA_DATAGRAM: [u8; 2] = [0xE8, 0x03]; + +/// Id 0xFFFF, which [`index_with_empty_data_packet`] does not declare. +pub(super) const UNKNOWN_ID_DATAGRAM: [u8; 2] = [0xFF, 0xFF]; + +/// A fault: packet id 0, which [`index_with_empty_data_packet`] does not +/// 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) +} + +/// An index with a single `Data` packet, id 1000 on board 1, that carries +/// no measurements. +/// +/// It has to be `Data`: that is the only type a UDP datagram can carry, +/// and decoding rejects any other with `WrongPacketType`. +pub(super) fn index_with_empty_data_packet() -> Index { + let packet = PacketDef { + id: AdjId(1000), + board: TEST_BOARD, + name: "test_data".to_string(), + packet_type: PacketType::Data(vec![]), + }; + let board = Board { + id: TEST_BOARD, + name: "TEST".to_string(), + ip: IpAddr::from([192, 168, 0, 10]), + mac: MacAddress([0; 6]), + packets: HashMap::from([(packet.id, packet)]), + }; + let pod_data = PodData { + boards: HashMap::from([(board.id, board)]), + }; + Index::new(&pod_data, None) +} + +/// The next notification, or a test failure after [`RECEIVE_TIMEOUT`]. +pub(super) async fn receive_notification(sinks: &mut Sinks) -> Notification { + let Ok(Some(notification)) = + tokio::time::timeout(RECEIVE_TIMEOUT, sinks.notifications.recv()).await + else { + unreachable!("a notification should have arrived within {RECEIVE_TIMEOUT:?}"); + }; + notification +} + +/// The next error report, or a test failure after [`RECEIVE_TIMEOUT`]. +pub(super) async fn receive_error_report(sinks: &mut Sinks) -> ErrorReport { + let Ok(Some(report)) = tokio::time::timeout(RECEIVE_TIMEOUT, sinks.errors.recv()).await else { + unreachable!("an error report should have arrived within {RECEIVE_TIMEOUT:?}"); + }; + report +} + +/// Asserts that `notification` is what [`EMPTY_DATA_DATAGRAM`] decodes to. +pub(super) fn assert_is_empty_data_packet(notification: Notification) { + 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)"); + }; + assert_eq!(packet.id, AdjId(1000)); + assert!(packet.values.is_empty()); +} + +/// Binds the telemetry socket on a free loopback port, as [`spawn_udp`] does on +/// the backend's own address, and returns it with the port the OS picked. +pub(super) fn bind_on_loopback(recv_buffer: usize) -> (tokio::net::UdpSocket, SocketAddr) { + let config = UdpConfig { + addr: any_loopback_port(), + recv_buffer, + boards: HashMap::new(), + }; + let Ok(socket) = bind_telemetry_socket(&config) else { + unreachable!("binding to a free loopback port should succeed"); + }; + let Ok(addr) = socket.local_addr() else { + unreachable!("a bound socket has a local address"); + }; + (socket, addr) +} + +/// 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 boards = boards_at(any_loopback_port().ip()); + let handle = tokio::spawn(receive_telemetry(socket, index, boards, reporter)); + (addr, handle) +} + +/// A socket standing in for a board that sends telemetry. +pub(super) async fn bind_fake_board() -> tokio::net::UdpSocket { + let Ok(socket) = tokio::net::UdpSocket::bind(any_loopback_port()).await else { + unreachable!("binding the fake board's socket should succeed"); + }; + socket +} + +/// Sends `bytes` as one datagram from `from` to `to`. +pub(super) async fn send_datagram(from: &tokio::net::UdpSocket, bytes: &[u8], to: SocketAddr) { + let Ok(sent) = from.send_to(bytes, to).await else { + unreachable!("sending on loopback should succeed"); + }; + assert_eq!(sent, bytes.len()); +} diff --git a/backend/crates/core/src/net/udp/tests.rs b/backend/crates/core/src/net/udp/tests.rs new file mode 100644 index 000000000..01bcfe99c --- /dev/null +++ b/backend/crates/core/src/net/udp/tests.rs @@ -0,0 +1,411 @@ +//! Unit tests of the receive path, and tests through a real socket on +//! loopback. Fixtures live in `test_support.rs`. + +use super::test_support::*; +use super::*; +use crate::model::AdjId; + +// --------------------------------------------------------------------------- +// Error classification +// --------------------------------------------------------------------------- + +#[test] +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)), + }; + + assert!(error.is_fatal()); +} + +#[test] +fn losing_the_socket_faults_the_pod_too() { + let error = UdpError::Recv { + source: std::io::Error::from(std::io::ErrorKind::ConnectionReset), + }; + + assert!(error.is_fatal()); +} + +#[test] +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)), + }; + + assert!(error.to_string().contains("192.168.1.3:50400")); +} + +#[test] +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()); +} + +#[test] +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")); +} + +// --------------------------------------------------------------------------- +// decode_and_report, without a socket +// --------------------------------------------------------------------------- + +#[tokio::test] +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(), + lookups, + &reporter, + &mut traces, + ) + .await; + assert!(keep_going); + + assert_is_empty_data_packet(receive_notification(&mut sinks).await); + assert!( + sinks.errors.try_recv().is_err(), + "should not have reported an error" + ); +} + +#[tokio::test] +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(), + lookups, + &reporter, + &mut traces, + ) + .await; + assert!(keep_going); + + let report = receive_error_report(&mut sinks).await; + 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(), + "should not have notified a packet" + ); +} + +#[tokio::test] +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(), + lookups, + &reporter, + &mut traces, + ) + .await; + assert!(keep_going); + + let report = receive_error_report(&mut sinks).await; + 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(), + lookups, + &reporter, + &mut traces, + ) + .await; + + let report = receive_error_report(&mut sinks).await; + assert!(matches!( + report.error, + crate::net::Error::Udp(UdpError::Fault { .. }) + )); +} + +#[tokio::test] +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(), + lookups, + &reporter, + &mut traces, + ) + .await; + + let report = receive_error_report(&mut sinks).await; + let crate::net::Error::Udp(UdpError::Decode { source, .. }) = report.error else { + unreachable!("a one-byte datagram should be a decode failure, not a fault"); + }; + assert!(matches!(source, DecodeError::UnexpectedEof)); +} + +#[tokio::test] +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); + + // With the receivers gone, reporting tells the loop to stop (false). + let keep_going = decode_and_report( + &UNKNOWN_ID_DATAGRAM, + example_board_addr(), + lookups, + &reporter, + &mut traces, + ) + .await; + assert!(!keep_going); +} + +// --------------------------------------------------------------------------- +// Rate limit of the decode-failure trace +// --------------------------------------------------------------------------- + +#[test] +fn decode_failures_are_traced_at_most_once_a_second() { + let mut trace = TraceRateLimit::default(); + let t0 = Instant::now(); + let at = |ms: u64| t0 + Duration::from_millis(ms); + + assert_eq!( + trace.should_trace(at(0)), + Some(0), + "the first one is traced" + ); + assert_eq!( + trace.should_trace(at(300)), + None, + "within the second: counted" + ); + assert_eq!( + trace.should_trace(at(900)), + None, + "within the second: counted" + ); + assert_eq!( + trace.should_trace(at(1100)), + Some(2), + "after a second: traced, with the two left out" + ); + assert_eq!(trace.should_trace(at(1500)), None); + assert_eq!( + trace.should_trace(at(2200)), + Some(1), + "the window restarts at the last traced one" + ); +} + +// --------------------------------------------------------------------------- +// Through a real socket on loopback +// --------------------------------------------------------------------------- + +#[tokio::test] +async fn a_datagram_sent_to_the_socket_arrives_as_a_notification() { + let (reporter, mut sinks) = Reporter::channels(16, 16); + let (addr, handle) = start_receiving_on_loopback(reporter); + let board = bind_fake_board().await; + + send_datagram(&board, &EMPTY_DATA_DATAGRAM, addr).await; + + assert_is_empty_data_packet(receive_notification(&mut sinks).await); + handle.abort(); +} + +#[tokio::test] +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; + let Ok(board_addr) = board.local_addr() else { + unreachable!("a bound socket has a local address"); + }; + + send_datagram(&board, &UNKNOWN_ID_DATAGRAM, addr).await; + + let report = receive_error_report(&mut sinks).await; + 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_and_board() { + let (reporter, mut sinks) = Reporter::channels(16, 16); + let (addr, handle) = start_receiving_on_loopback(reporter); + let board = bind_fake_board().await; + let Ok(board_addr) = board.local_addr() else { + unreachable!("a bound socket has a local address"); + }; + + send_datagram(&board, &FAULT_DATAGRAM, addr).await; + + let report = receive_error_report(&mut sinks).await; + 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(); +} + +#[tokio::test] +async fn the_loop_stops_on_the_next_datagram_once_nobody_listens() { + let (reporter, sinks) = Reporter::channels(16, 16); + let (addr, handle) = start_receiving_on_loopback(reporter); + drop(sinks); + let board = bind_fake_board().await; + + // Without a datagram the loop would keep waiting on the socket: it only + // notices the consumer is gone when it tries to report. + send_datagram(&board, &EMPTY_DATA_DATAGRAM, addr).await; + + let Ok(Ok(())) = tokio::time::timeout(RECEIVE_TIMEOUT, handle).await else { + unreachable!("the loop should end once a report finds nobody listening"); + }; +} + +#[tokio::test] +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 { + addr: taken, + recv_buffer: 256 * 1024, + boards: HashMap::new(), + }); + + let Err(UdpError::Bind { addr, .. }) = second else { + unreachable!("binding an address already in use should fail with UdpError::Bind"); + }; + assert_eq!(addr, taken); +} 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 index b7e482da0..20d297fb6 100644 --- a/backend/crates/station/src/lib.rs +++ b/backend/crates/station/src/lib.rs @@ -1,4 +1,15 @@ +//! 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; mod vehicle; pub mod websocket; -pub mod payload; \ No newline at end of file +pub mod payload; diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index 305824231..bf39e02bd 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -1,16 +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(); - // TODO(event): When starting the backend here, give websocket a clone of - // channels.problems so it reports FrontendDisconnected to event itself - // (see the TODO in websocket::run). - 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(); }