From c6679ce1a96cd71a7495f7bd5900e04b82a2a151 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sun, 18 Oct 2026 22:21:23 +0200 Subject: [PATCH 01/14] wip: net --- backend/crates/core/src/lib.rs | 11 +- backend/crates/core/src/net.rs | 45 ++++ backend/crates/core/src/net/README.md | 175 ++++++++++++ backend/crates/core/src/net/error.rs | 28 ++ backend/crates/core/src/net/report.rs | 367 +++++++++++++++++++++++++ backend/crates/core/src/net/tcp.rs | 375 ++++++++++++++++++++++++++ backend/crates/core/src/net/udp.rs | 217 +++++++++++++++ 7 files changed, 1215 insertions(+), 3 deletions(-) create mode 100644 backend/crates/core/src/net.rs create mode 100644 backend/crates/core/src/net/README.md create mode 100644 backend/crates/core/src/net/error.rs create mode 100644 backend/crates/core/src/net/report.rs create mode 100644 backend/crates/core/src/net/tcp.rs create mode 100644 backend/crates/core/src/net/udp.rs diff --git a/backend/crates/core/src/lib.rs b/backend/crates/core/src/lib.rs index fb8d888bf..573dd787e 100644 --- a/backend/crates/core/src/lib.rs +++ b/backend/crates/core/src/lib.rs @@ -2,12 +2,12 @@ pub mod hello_world; -/// NTP server -#[cfg(feature = "ntp")] -pub mod ntp; /// Basic domain types: identifiers, values, measurements, protections, /// packets and boards. pub mod model; +/// NTP server +#[cfg(feature = "ntp")] +pub mod ntp; /// Parses an ADJ (Architecture Description JSON) directory into /// [`model::PodData`], plus backend-session metadata not modeled as @@ -18,3 +18,8 @@ pub mod adj; /// [`adj`] declares as the schema. See [`protocol::wire`], /// [`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; diff --git a/backend/crates/core/src/net.rs b/backend/crates/core/src/net.rs new file mode 100644 index 000000000..ff2824e13 --- /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::Error`), 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..f5f9cd5f3 --- /dev/null +++ b/backend/crates/core/src/net/README.md @@ -0,0 +1,175 @@ +# `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::Error, nothing else +├── tcp.rs # the TCP client (not written yet: error type + contract) +└── udp.rs # the shared UDP socket (not written yet: error type + contract) +``` + +## 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::Error` 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 resolves to no board at all — its id is not in +the ADJ, so there is no `PacketDef` to ask — and all that can be said about it is +the address it came from, which is what `udp::Error::Decode` holds. + +### `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(Config, Arc, Reporter) -> Result, Error>` (binds first) | +| Inputs | its `Config` (boards, timeouts, backoff, keep-alive) | its `Config` (bind address, `SO_RCVBUF`) | +| 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; only reports | + +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. + +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::Error::is_fatal` are about the **pod**, not about +this process: it means the pod has to be sent to fault, and the backend +**stays up** — still reading, still serving the frontend, still recording — so the +operator can see why. Nothing in `net` ever calls `std::process::exit`. + +Only a decode failure is fatal, on either transport, 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. + +`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..64109a954 --- /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::Error), +} diff --git a/backend/crates/core/src/net/report.rs b/backend/crates/core/src/net/report.rs new file mode 100644 index 000000000..35f7dc16c --- /dev/null +++ b/backend/crates/core/src/net/report.rs @@ -0,0 +1,367 @@ +//! 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, resolves to no +/// board at all — its id is not in the ADJ, so there is no +/// [`crate::model::PacketDef`] to ask — and all that can be said about +/// it is the address it came from, which is exactly what +/// [`super::udp::Error::Decode`] holds. +#[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::Error { + udp::Error::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::Error::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::Error::Decode { + from: addr, + 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::Error::Decode { from, .. }) = Error::from(error) else { + unreachable!("a decode error should convert into Error::Udp"); + }; + assert_eq!(from, addr); + } + + #[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..e8048507b --- /dev/null +++ b/backend/crates/core/src/net/udp.rs @@ -0,0 +1,217 @@ +//! The shared UDP socket: one socket, receive-only, every board's +//! telemetry. +//! +//! **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 +//! +//! One socket bound to the backend's own address, carrying `Data` packets +//! from every board. Nothing is ever sent from it. One task is enough: +//! there is no per-board state to keep. +//! +//! # Entry point +//! +//! [`spawn`], taking [`Config`], 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: receive, decode with +//! [`crate::protocol::udp::decode_datagram`], report. No disk, no +//! WebSocket, no aggregation — the socket's receive buffer is where +//! packets get dropped if this task falls behind, and the kernel drops +//! them silently, so this loop stays as short as it can be. Raising +//! `SO_RCVBUF` is part of setting the socket up. +//! - [`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. +//! - **A decode failure is fatal**: see [`Error::is_fatal`]. 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 +//! means the ADJ this backend loaded does not describe what the boards +//! are actually sending, and every datagram after it is suspect for the +//! same reason. So: log it and report it on the error channel, exactly +//! as [`super::tcp`] does — and that is all. This socket writes +//! nothing, and sending the pod to fault is not `net`'s call anyway: +//! whoever consumes the error channel reads [`Error::is_fatal`] and +//! decides, which also keeps the "fault once" guard in one place +//! rather than one per transport. Keep receiving meanwhile: a +//! mismatched ADJ fails on every datagram that follows, several +//! thousand a second, and each one is reported, not acted on. +//! - [`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::vehicle::bootstrap`), not something reported once +//! everything is already running. Hence the entry point returns +//! `Result, Error>`. + +use super::Reporter; +use crate::protocol::{DecodeError, Index}; +use std::net::SocketAddr; +use std::sync::Arc; +use tokio::task::JoinHandle; + +/// 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, Copy, PartialEq, Eq)] +pub struct Config { + /// Where to bind: the backend's own address, `backend_ip` + + /// `ports["UDP"]` in the ADJ's general info. + pub addr: SocketAddr, + /// `SO_RCVBUF`, in bytes. + /// + /// The only thing absorbing a stall of the receive loop, since the + /// kernel drops the tail silently once it is full: 2 MiB is about + /// 0.8 s of margin at 20 Mbit/s. + pub recv_buffer: usize, +} + +/// 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. +/// +/// # Errors +/// +/// [`Error::Bind`] only — every later failure goes out through +/// `reporter`, since by then there is nobody left to return it to. +pub fn spawn(config: Config, adj: Arc, reporter: Reporter) -> Result, Error> { + let _ = (config, adj, reporter); + todo!("the UDP socket is not written yet: see this module's contract") +} + +/// Something that went wrong on the shared UDP socket. +/// +/// No [`crate::model::BoardId`] in any variant, on purpose: the socket +/// belongs to no board, and a datagram that fails to decode may not +/// resolve to one at all — [`Error::Decode`] carries the address it came +/// from, which is the only identity that always exists. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// 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 means the loaded ADJ does + /// not describe what the boards are sending. Fatal: see + /// [`Error::is_fatal`]. + #[error("could not decode a datagram from {from}")] + Decode { + /// Where the datagram came from — there may be no board to + /// attribute it to. + from: SocketAddr, + /// What [`crate::protocol`] said about it. + #[source] + source: DecodeError, + }, +} + +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, still serving the frontend, still + /// recording — so that whoever is operating the pod can see what + /// happened. Nothing here ever calls `std::process::exit`. + /// + /// Both runtime failures of this socket qualify, and for the same + /// reason: neither can be true of a single datagram. + /// [`Error::Decode`] means the loaded ADJ does not describe what the + /// boards are sending, and [`Error::Recv`] means the socket itself is + /// no longer usable, which is every board's telemetry gone at once. + /// Neither is something a retry fixes. + /// + /// [`Error::Bind`] never reaches this: 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 { + // Matched exhaustively rather than just returning `true`: a + // variant added later has to say which it is instead of + // inheriting this answer in silence. + match self { + Error::Bind { .. } | Error::Recv { .. } | Error::Decode { .. } => true, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::AdjId; + use std::net::IpAddr; + + fn peer() -> SocketAddr { + SocketAddr::new(IpAddr::from([192, 168, 1, 3]), 50400) + } + + #[test] + fn a_datagram_that_will_not_decode_faults_the_pod() { + let error = Error::Decode { + from: peer(), + source: DecodeError::UnknownId(AdjId(9999)), + }; + + // Nothing corrupts a datagram in flight, so this is a mismatched + // ADJ, not noise to skip over. + assert!(error.is_fatal()); + } + + #[test] + fn losing_the_socket_faults_the_pod_too() { + let error = Error::Recv { + source: std::io::Error::from(std::io::ErrorKind::ConnectionReset), + }; + + // Every board's telemetry at once. + assert!(error.is_fatal()); + } + + #[test] + fn a_decode_failure_says_where_it_came_from() { + let error = Error::Decode { + from: peer(), + source: DecodeError::UnknownId(AdjId(9999)), + }; + + // The only identity it has: there is no board to attribute an + // undeclared id to. + assert!(error.to_string().contains("192.168.1.3:50400")); + } +} From 7b98b80f9bfafd26a3f5168a3fbdcb645b21c76b Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sun, 18 Oct 2026 22:21:59 +0200 Subject: [PATCH 02/14] wip(backend, net): upload cargo.toml --- backend/crates/core/Cargo.toml | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/backend/crates/core/Cargo.toml b/backend/crates/core/Cargo.toml index e9eabc177..0a3e434e8 100644 --- a/backend/crates/core/Cargo.toml +++ b/backend/crates/core/Cargo.toml @@ -29,7 +29,14 @@ 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", +] } tracing-subscriber = { workspace = true, optional = true , features = ["env-filter", "fmt"]} tracing-appender = { workspace = true, optional = true } ntp_usg-server = { version = "5.0.0", optional = true, features = ["ipv4", "tokio"] } From 7f1ad4498f7e01df20d6fe95badf648f0720d20f Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Sun, 8 Nov 2026 14:48:47 +0100 Subject: [PATCH 03/14] Feat(backend, net, udp): Add UDP module supporting socket binding with configurable OS-level `SO_RCVBUF` size. Implement a two-stage receive architecture using a bounded Tokio `mpsc` channel to decouple the fast network read loop from the processing path. Add robust decoding against the ADJ `Index`, with fatal error reporting for malformed datagrams or socket resets. Include a comprehensive unit test suite covering valid datagram decoding, unknown packet ID error reporting, EOF handling, and `Copy` semantics for configuration. --- backend/Cargo.lock | 1 + backend/crates/core/Cargo.toml | 5 +- backend/crates/core/src/net/udp.rs | 310 ++++++++++++++++++++++++----- 3 files changed, 269 insertions(+), 47 deletions(-) diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 5f25ff681..0b5bf8656 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -316,6 +316,7 @@ dependencies = [ "ntp_usg-server", "serde", "serde_json", + "socket2", "thiserror", "tokio", "tracing", diff --git a/backend/crates/core/Cargo.toml b/backend/crates/core/Cargo.toml index 0a3e434e8..6daeb36de 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 (dependency added when the module is written) git = [] # Packet sniffing through pcap (dependency added when the module is written) @@ -37,6 +37,7 @@ tokio = { workspace = true, optional = true, features = [ "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 } ntp_usg-server = { version = "5.0.0", optional = true, features = ["ipv4", "tokio"] } diff --git a/backend/crates/core/src/net/udp.rs b/backend/crates/core/src/net/udp.rs index e8048507b..069219dfc 100644 --- a/backend/crates/core/src/net/udp.rs +++ b/backend/crates/core/src/net/udp.rs @@ -1,16 +1,27 @@ //! The shared UDP socket: one socket, receive-only, every board's //! telemetry. //! -//! **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 //! //! One socket bound to the backend's own address, carrying `Data` packets -//! from every board. Nothing is ever sent from it. One task is enough: -//! there is no per-board state to keep. +//! from every board. Nothing is ever sent from it. +//! +//! # Architecture: two-stage receive with bounded channel +//! +//! Boards send thousands of packets per second, sometimes in bursts that +//! overwhelm a single processing loop. To handle this, the module uses a +//! two-stage design: +//! +//! 1. **Receive loop** — a fast task that only reads datagrams from the +//! socket and pushes them into a bounded `mpsc` channel. +//! 2. **Processing loop** — drains the channel, decodes each datagram +//! using [`crate::protocol::udp::decode_datagram`], resolves the board +//! id, and reports through [`super::Reporter`]. +//! +//! The channel (`RING_CAPACITY` = 8192) absorbs bursts so the receive +//! loop stays responsive. If the channel fills, the receive loop waits for +//! space rather than dropping — the kernel socket buffer (`SO_RCVBUF`) is +//! the first line of defense, and this channel is the second. //! //! # Entry point //! @@ -26,12 +37,9 @@ //! 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: receive, decode with -//! [`crate::protocol::udp::decode_datagram`], report. No disk, no -//! WebSocket, no aggregation — the socket's receive buffer is where -//! packets get dropped if this task falls behind, and the kernel drops -//! them silently, so this loop stays as short as it can be. Raising -//! `SO_RCVBUF` is part of setting the socket up. +//! - The processing loop does three things and nothing else: decode with +//! [`crate::protocol::udp::decode_datagram`], resolve the board, report. +//! No disk, no WebSocket, no aggregation. //! - [`super::Notification::board`] comes from the decoded packet's id, //! through [`crate::protocol::Index`] — every //! [`crate::model::PacketDef`] carries its `board` — so that a @@ -60,10 +68,13 @@ //! `Result, Error>`. use super::Reporter; +use crate::model::Packet; use crate::protocol::{DecodeError, Index}; use std::net::SocketAddr; use std::sync::Arc; +use tokio::sync::mpsc; use tokio::task::JoinHandle; +use tracing::{error, warn}; /// How to set the shared socket up. /// @@ -82,25 +93,167 @@ pub struct Config { pub recv_buffer: usize, } -/// Binds the shared socket and spawns the receive loop. +/// A queued datagram entry: raw payload bytes and the sender's address. +#[derive(Debug)] +struct Datagram { + /// The raw datagram bytes copied from the socket receive buffer. + bytes: Box<[u8]>, + /// The sender's socket address (used for error attribution if decoding fails). + from: SocketAddr, +} + +/// Channel capacity — the number of datagrams that can be queued +/// between the fast receive loop and the decode/report path. +/// +/// Boards send thousands of packets per second. This buffer absorbs +/// bursts so the receive loop stays responsive while `SO_RCVBUF` acts +/// as the first line of defense in the OS kernel. +const RING_CAPACITY: usize = 8192; + +/// Binds the shared socket and spawns the receive and processing loops. /// /// 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. -/// /// # Errors /// /// [`Error::Bind`] only — every later failure goes out through /// `reporter`, since by then there is nobody left to return it to. pub fn spawn(config: Config, adj: Arc, reporter: Reporter) -> Result, Error> { - let _ = (config, adj, reporter); - todo!("the UDP socket is not written yet: see this module's contract") + // 1. Bind the UDP socket synchronously before spawning async tasks. + let socket = bind_socket(config)?; + + // 2. Create the bounded channel connecting the receive loop to the processor. + let (ring_tx, ring_rx) = mpsc::channel(RING_CAPACITY); + + let recv_reporter = reporter.clone(); + + // 3. Spawn a supervising task that runs both the receiver and processor, + // ensuring clean shutdown of the processor when the receiver exits. + let handle = tokio::spawn(async move { + let processor = tokio::spawn(process_loop(ring_rx, adj, reporter)); + receive_loop(socket, ring_tx, recv_reporter).await; + // Once receive_loop exits, `ring_tx` is dropped, causing `process_loop` + // to drain remaining items and finish. + let _ = processor.await; + }); + + Ok(handle) +} + +/// Binds a UDP socket and configures its OS-level receive buffer size (`SO_RCVBUF`). +fn bind_socket(config: Config) -> 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| Error::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| Error::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| Error::Bind { + addr: config.addr, + source, + })?; + + // Attempt to enlarge the kernel's SO_RCVBUF to handle high-frequency telemetry bursts. + let sock_ref = socket2::SockRef::from(&socket); + if let Err(e) = sock_ref.set_recv_buffer_size(config.recv_buffer) { + warn!( + %config.addr, + buffer = config.recv_buffer, + %e, + "could not set SO_RCVBUF, using system default" + ); + } + + Ok(socket) +} + +/// Fast receive loop: reads raw datagrams from the socket and pushes them into the channel. +async fn receive_loop( + socket: tokio::net::UdpSocket, + ring_tx: mpsc::Sender, + reporter: Reporter, +) { + // Allocate a single 64 KiB buffer (maximum possible UDP datagram size) + // so no incoming packet can ever be truncated. + let mut buf = vec![0u8; 64 * 1024]; + + loop { + match socket.recv_from(&mut buf).await { + Ok((len, from)) => { + // Copy only the valid bytes of this datagram into a boxed slice. + let datagram = Datagram { + bytes: buf[..len].into(), + from, + }; + + // Forward to the processing task. If the receiver dropped, exit cleanly. + if ring_tx.send(datagram).await.is_err() { + break; + } + } + Err(source) => { + // Socket-level receive failure: log, report as fatal to the backend, and stop. + let err = Error::Recv { source }; + error!(%err, "UDP receive error"); + let _ = reporter.report(err).await; + break; + } + } + } +} + +/// Processing loop: drains the channel, decodes datagrams against the ADJ `Index`, and notifies downstream. +async fn process_loop( + mut ring_rx: mpsc::Receiver, + adj: Arc, + reporter: Reporter, +) { + // Pull datagrams one by one until `ring_tx` is closed and the queue is empty. + while let Some(datagram) = ring_rx.recv().await { + let Datagram { bytes, from } = datagram; + + // Decode raw bytes into a DataPacket using the ADJ lookup index. + let packet = match crate::protocol::udp::decode_datagram(&bytes, &adj) { + Ok(p) => p, + Err(source) => { + // A decode failure indicates an ADJ mismatch; report it to the error channel + // and continue draining subsequent packets. + let error = Error::Decode { from, source }; + error!(%error, "UDP decode error"); + if reporter.report(error).await.is_err() { + break; + } + continue; + } + }; + + // Look up the packet definition to find out which board sent this packet. + let Some(packet_def) = adj.packet(packet.id) else { + warn!(id = ?packet.id, "decoded packet id not in index"); + continue; + }; + + let board = packet_def.board; + + // Broadcast the decoded telemetry packet to the event bus. + if reporter + .notify(board, super::Event::Received(Packet::Data(packet))) + .await + .is_err() + { + // Downstream event receiver closed; exit loop. + break; + } + } } /// Something that went wrong on the shared UDP socket. @@ -145,26 +298,7 @@ pub enum 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, still serving the frontend, still - /// recording — so that whoever is operating the pod can see what - /// happened. Nothing here ever calls `std::process::exit`. - /// - /// Both runtime failures of this socket qualify, and for the same - /// reason: neither can be true of a single datagram. - /// [`Error::Decode`] means the loaded ADJ does not describe what the - /// boards are sending, and [`Error::Recv`] means the socket itself is - /// no longer usable, which is every board's telemetry gone at once. - /// Neither is something a retry fixes. - /// - /// [`Error::Bind`] never reaches this: 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 { - // Matched exhaustively rather than just returning `true`: a - // variant added later has to say which it is instead of - // inheriting this answer in silence. match self { Error::Bind { .. } | Error::Recv { .. } | Error::Decode { .. } => true, } @@ -174,9 +308,11 @@ impl Error { #[cfg(test)] mod tests { use super::*; - use crate::model::AdjId; + use crate::model::{AdjId, Board, BoardId, MacAddress, MessageLevel, PacketDef, PacketType, PodData}; + use std::collections::HashMap; use std::net::IpAddr; + /// Helper returning a dummy sender SocketAddr for tests. fn peer() -> SocketAddr { SocketAddr::new(IpAddr::from([192, 168, 1, 3]), 50400) } @@ -185,7 +321,7 @@ mod tests { fn a_datagram_that_will_not_decode_faults_the_pod() { let error = Error::Decode { from: peer(), - source: DecodeError::UnknownId(AdjId(9999)), + source: crate::protocol::DecodeError::UnknownId(AdjId(9999)), }; // Nothing corrupts a datagram in flight, so this is a mismatched @@ -207,11 +343,95 @@ mod tests { fn a_decode_failure_says_where_it_came_from() { let error = Error::Decode { from: peer(), - source: DecodeError::UnknownId(AdjId(9999)), + source: crate::protocol::DecodeError::UnknownId(AdjId(9999)), }; // The only identity it has: there is no board to attribute an // undeclared id to. assert!(error.to_string().contains("192.168.1.3:50400")); } -} + + /// Builds a minimal Index with one empty Data packet (ID 1000) on Board 1. + fn sample_index() -> Index { + let packet = PacketDef { + id: AdjId(1000), + board: BoardId(1), + name: "test_data".to_string(), + packet_type: PacketType::Message(MessageLevel::Info),// I don't know what packet type to use here + }; + let board = Board { + id: BoardId(1), + 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) // I am not sure what to do here + } + + #[test] + fn ring_capacity_is_positive() { + // Sanity: the channel must hold at least one entry. + assert!(RING_CAPACITY > 0); + } + + #[tokio::test] + async fn process_loop_reports_error_on_unknown_id() { + let (reporter, mut sinks) = Reporter::channels(16, 16); + let index = Arc::new(sample_index()); + let (ring_tx, ring_rx) = mpsc::channel(RING_CAPACITY); + + let processor = tokio::spawn(process_loop(ring_rx, index, reporter)); + + // Send a datagram with an unknown id (0xFFFF = 65535) — should trigger a decode error. + let datagram = Datagram { + bytes: vec![0xFF, 0xFF].into(), + from: peer(), + }; + ring_tx.send(datagram).await.expect("processor is alive"); + + // Drop the sender so the processor exits. + drop(ring_tx); + processor.await.expect("processor should finish"); + + // The processor should have reported a decode error. + let error_report = sinks.errors.recv().await; + assert!(error_report.is_some(), "should have reported a decode error"); + } + + #[tokio::test] + async fn process_loop_exits_when_ring_closes() { + let (reporter, sinks) = Reporter::channels(16, 16); + let index = Arc::new(sample_index()); + let (ring_tx, ring_rx) = mpsc::channel(RING_CAPACITY); + + let processor = tokio::spawn(process_loop(ring_rx, index, reporter)); + + // Send an incomplete 1-byte datagram (fails with UnexpectedEof), then close the channel. + let datagram = Datagram { + bytes: vec![0x00].into(), + from: peer(), + }; + ring_tx.send(datagram).await.expect("processor is alive"); + drop(ring_tx); + + // Wait for the processor to finish cleanly. + processor.await.expect("processor should finish cleanly"); + drop(sinks); + } + + #[test] + fn config_is_copy() { + let config = Config { + addr: SocketAddr::new(IpAddr::from([127, 0, 0, 1]), 0), + recv_buffer: 2 * 1024 * 1024, + }; + let _copy = config; + // Config is still usable after assignment — it implements Copy. + let _addr = config.addr; + let _buf = config.recv_buffer; + } +} \ No newline at end of file From ba36feab3769aabe1c6f24e345c48890c97e9e38 Mon Sep 17 00:00:00 2001 From: GaziH Date: Tue, 17 Nov 2026 22:21:44 +0100 Subject: [PATCH 04/14] Feat(backend, net, udp): Amended implementation to ditch the use of a ring buffer. --- backend/crates/core/src/net/udp.rs | 232 ++++++++++------------------- 1 file changed, 81 insertions(+), 151 deletions(-) diff --git a/backend/crates/core/src/net/udp.rs b/backend/crates/core/src/net/udp.rs index 069219dfc..c85972214 100644 --- a/backend/crates/core/src/net/udp.rs +++ b/backend/crates/core/src/net/udp.rs @@ -6,23 +6,6 @@ //! One socket bound to the backend's own address, carrying `Data` packets //! from every board. Nothing is ever sent from it. //! -//! # Architecture: two-stage receive with bounded channel -//! -//! Boards send thousands of packets per second, sometimes in bursts that -//! overwhelm a single processing loop. To handle this, the module uses a -//! two-stage design: -//! -//! 1. **Receive loop** — a fast task that only reads datagrams from the -//! socket and pushes them into a bounded `mpsc` channel. -//! 2. **Processing loop** — drains the channel, decodes each datagram -//! using [`crate::protocol::udp::decode_datagram`], resolves the board -//! id, and reports through [`super::Reporter`]. -//! -//! The channel (`RING_CAPACITY` = 8192) absorbs bursts so the receive -//! loop stays responsive. If the channel fills, the receive loop waits for -//! space rather than dropping — the kernel socket buffer (`SO_RCVBUF`) is -//! the first line of defense, and this channel is the second. -//! //! # Entry point //! //! [`spawn`], taking [`Config`], an `Arc` and a @@ -37,7 +20,7 @@ //! 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 processing loop does three things and nothing else: decode with +//! - The loop does three things and nothing else: decode with //! [`crate::protocol::udp::decode_datagram`], resolve the board, report. //! No disk, no WebSocket, no aggregation. //! - [`super::Notification::board`] comes from the decoded packet's id, @@ -72,7 +55,6 @@ use crate::model::Packet; use crate::protocol::{DecodeError, Index}; use std::net::SocketAddr; use std::sync::Arc; -use tokio::sync::mpsc; use tokio::task::JoinHandle; use tracing::{error, warn}; @@ -93,52 +75,25 @@ pub struct Config { pub recv_buffer: usize, } -/// A queued datagram entry: raw payload bytes and the sender's address. -#[derive(Debug)] -struct Datagram { - /// The raw datagram bytes copied from the socket receive buffer. - bytes: Box<[u8]>, - /// The sender's socket address (used for error attribution if decoding fails). - from: SocketAddr, -} - -/// Channel capacity — the number of datagrams that can be queued -/// between the fast receive loop and the decode/report path. -/// -/// Boards send thousands of packets per second. This buffer absorbs -/// bursts so the receive loop stays responsive while `SO_RCVBUF` acts -/// as the first line of defense in the OS kernel. -const RING_CAPACITY: usize = 8192; - -/// Binds the shared socket and spawns the receive and processing loops. +/// 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. +/// /// # Errors /// /// [`Error::Bind`] only — every later failure goes out through /// `reporter`, since by then there is nobody left to return it to. pub fn spawn(config: Config, adj: Arc, reporter: Reporter) -> Result, Error> { - // 1. Bind the UDP socket synchronously before spawning async tasks. let socket = bind_socket(config)?; - - // 2. Create the bounded channel connecting the receive loop to the processor. - let (ring_tx, ring_rx) = mpsc::channel(RING_CAPACITY); - - let recv_reporter = reporter.clone(); - - // 3. Spawn a supervising task that runs both the receiver and processor, - // ensuring clean shutdown of the processor when the receiver exits. - let handle = tokio::spawn(async move { - let processor = tokio::spawn(process_loop(ring_rx, adj, reporter)); - receive_loop(socket, ring_tx, recv_reporter).await; - // Once receive_loop exits, `ring_tx` is dropped, causing `process_loop` - // to drain remaining items and finish. - let _ = processor.await; - }); - + let handle = tokio::spawn(run_loop(socket, adj, reporter)); Ok(handle) } @@ -162,7 +117,6 @@ fn bind_socket(config: Config) -> Result { source, })?; - // Attempt to enlarge the kernel's SO_RCVBUF to handle high-frequency telemetry bursts. let sock_ref = socket2::SockRef::from(&socket); if let Err(e) = sock_ref.set_recv_buffer_size(config.recv_buffer) { warn!( @@ -176,27 +130,20 @@ fn bind_socket(config: Config) -> Result { Ok(socket) } -/// Fast receive loop: reads raw datagrams from the socket and pushes them into the channel. -async fn receive_loop( +/// Main UDP loop: reads datagrams into a reusable 64 KiB buffer, decodes in-place, and reports. +async fn run_loop( socket: tokio::net::UdpSocket, - ring_tx: mpsc::Sender, + adj: Arc, reporter: Reporter, ) { - // Allocate a single 64 KiB buffer (maximum possible UDP datagram size) - // so no incoming packet can ever be truncated. + // Reusable 64 KiB buffer — a datagram can never be silently truncated. let mut buf = vec![0u8; 64 * 1024]; loop { match socket.recv_from(&mut buf).await { Ok((len, from)) => { - // Copy only the valid bytes of this datagram into a boxed slice. - let datagram = Datagram { - bytes: buf[..len].into(), - from, - }; - - // Forward to the processing task. If the receiver dropped, exit cleanly. - if ring_tx.send(datagram).await.is_err() { + if !handle_datagram(&buf[..len], from, &adj, &reporter).await { + // Downstream channels closed; exit cleanly. break; } } @@ -211,49 +158,35 @@ async fn receive_loop( } } -/// Processing loop: drains the channel, decodes datagrams against the ADJ `Index`, and notifies downstream. -async fn process_loop( - mut ring_rx: mpsc::Receiver, - adj: Arc, - reporter: Reporter, -) { - // Pull datagrams one by one until `ring_tx` is closed and the queue is empty. - while let Some(datagram) = ring_rx.recv().await { - let Datagram { bytes, from } = datagram; - - // Decode raw bytes into a DataPacket using the ADJ lookup index. - let packet = match crate::protocol::udp::decode_datagram(&bytes, &adj) { - Ok(p) => p, - Err(source) => { - // A decode failure indicates an ADJ mismatch; report it to the error channel - // and continue draining subsequent packets. - let error = Error::Decode { from, source }; - error!(%error, "UDP decode error"); - if reporter.report(error).await.is_err() { - break; - } - continue; - } - }; +/// Decodes a single datagram slice against `adj` and forwards the result or error to `reporter`. +/// +/// Returns `false` if the downstream `reporter` channels have closed and the loop should stop. +async fn handle_datagram( + bytes: &[u8], + from: SocketAddr, + adj: &Index, + reporter: &Reporter, +) -> bool { + let packet = match crate::protocol::udp::decode_datagram(bytes, adj) { + Ok(p) => p, + Err(source) => { + let error = Error::Decode { from, source }; + error!(%error, "UDP decode error"); + return reporter.report(error).await.is_ok(); + } + }; - // Look up the packet definition to find out which board sent this packet. - let Some(packet_def) = adj.packet(packet.id) else { - warn!(id = ?packet.id, "decoded packet id not in index"); - continue; - }; + let Some(packet_def) = adj.packet(packet.id) else { + warn!(id = ?packet.id, "decoded packet id not in index"); + return true; + }; - let board = packet_def.board; + let board = packet_def.board; - // Broadcast the decoded telemetry packet to the event bus. - if reporter - .notify(board, super::Event::Received(Packet::Data(packet))) - .await - .is_err() - { - // Downstream event receiver closed; exit loop. - break; - } - } + reporter + .notify(board, super::Event::Received(Packet::Data(packet))) + .await + .is_ok() } /// Something that went wrong on the shared UDP socket. @@ -298,6 +231,22 @@ pub enum 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, still serving the frontend, still + /// recording — so that whoever is operating the pod can see what + /// happened. Nothing here ever calls `std::process::exit`. + /// + /// Both runtime failures of this socket qualify, and for the same + /// reason: neither can be true of a single datagram. + /// [`Error::Decode`] means the loaded ADJ does not describe what the + /// boards are sending, and [`Error::Recv`] means the socket itself is + /// no longer usable, which is every board's telemetry gone at once. + /// Neither is something a retry fixes. + /// + /// [`Error::Bind`] never reaches this: 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 { Error::Bind { .. } | Error::Recv { .. } | Error::Decode { .. } => true, @@ -312,7 +261,6 @@ mod tests { use std::collections::HashMap; use std::net::IpAddr; - /// Helper returning a dummy sender SocketAddr for tests. fn peer() -> SocketAddr { SocketAddr::new(IpAddr::from([192, 168, 1, 3]), 50400) } @@ -324,8 +272,6 @@ mod tests { source: crate::protocol::DecodeError::UnknownId(AdjId(9999)), }; - // Nothing corrupts a datagram in flight, so this is a mismatched - // ADJ, not noise to skip over. assert!(error.is_fatal()); } @@ -335,7 +281,6 @@ mod tests { source: std::io::Error::from(std::io::ErrorKind::ConnectionReset), }; - // Every board's telemetry at once. assert!(error.is_fatal()); } @@ -346,8 +291,6 @@ mod tests { source: crate::protocol::DecodeError::UnknownId(AdjId(9999)), }; - // The only identity it has: there is no board to attribute an - // undeclared id to. assert!(error.to_string().contains("192.168.1.3:50400")); } @@ -369,58 +312,45 @@ mod tests { let pod_data = PodData { boards: HashMap::from([(board.id, board)]), }; - Index::new(&pod_data) // I am not sure what to do here - } - - #[test] - fn ring_capacity_is_positive() { - // Sanity: the channel must hold at least one entry. - assert!(RING_CAPACITY > 0); + Index::new(&pod_data, None) } #[tokio::test] - async fn process_loop_reports_error_on_unknown_id() { + async fn handle_datagram_decodes_valid_packet_and_notifies() { let (reporter, mut sinks) = Reporter::channels(16, 16); - let index = Arc::new(sample_index()); - let (ring_tx, ring_rx) = mpsc::channel(RING_CAPACITY); + let index = sample_index(); - let processor = tokio::spawn(process_loop(ring_rx, index, reporter)); + // 1000 in little-endian u16 is [0xE8, 0x03], with 0 measurements. + let keep_going = handle_datagram(&[0xE8, 0x03], peer(), &index, &reporter).await; + assert!(keep_going); - // Send a datagram with an unknown id (0xFFFF = 65535) — should trigger a decode error. - let datagram = Datagram { - bytes: vec![0xFF, 0xFF].into(), - from: peer(), - }; - ring_tx.send(datagram).await.expect("processor is alive"); + let notification = sinks.notifications.recv().await; + assert!(notification.is_some(), "should have emitted a packet event"); + assert!(sinks.errors.try_recv().is_err(), "should not have reported an error"); + } + + #[tokio::test] + async fn handle_datagram_reports_error_on_unknown_id() { + let (reporter, mut sinks) = Reporter::channels(16, 16); + let index = sample_index(); - // Drop the sender so the processor exits. - drop(ring_tx); - processor.await.expect("processor should finish"); + // Unknown ID 0xFFFF (65535) + let keep_going = handle_datagram(&[0xFF, 0xFF], peer(), &index, &reporter).await; + assert!(keep_going); - // The processor should have reported a decode error. let error_report = sinks.errors.recv().await; assert!(error_report.is_some(), "should have reported a decode error"); } #[tokio::test] - async fn process_loop_exits_when_ring_closes() { + async fn handle_datagram_stops_when_sinks_are_dropped() { let (reporter, sinks) = Reporter::channels(16, 16); - let index = Arc::new(sample_index()); - let (ring_tx, ring_rx) = mpsc::channel(RING_CAPACITY); - - let processor = tokio::spawn(process_loop(ring_rx, index, reporter)); - - // Send an incomplete 1-byte datagram (fails with UnexpectedEof), then close the channel. - let datagram = Datagram { - bytes: vec![0x00].into(), - from: peer(), - }; - ring_tx.send(datagram).await.expect("processor is alive"); - drop(ring_tx); - - // Wait for the processor to finish cleanly. - processor.await.expect("processor should finish cleanly"); + let index = sample_index(); drop(sinks); + + // With receivers dropped, reporting should signal the loop to exit (false). + let keep_going = handle_datagram(&[0xFF, 0xFF], peer(), &index, &reporter).await; + assert!(!keep_going); } #[test] From c11853cff8cbe98d7f18215ee378ea8b38008706 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Wed, 25 Nov 2026 02:16:30 +0100 Subject: [PATCH 05/14] refactor(backend, udp) --- backend/crates/core/src/net.rs | 2 +- backend/crates/core/src/net/README.md | 32 +- backend/crates/core/src/net/error.rs | 2 +- backend/crates/core/src/net/report.rs | 12 +- backend/crates/core/src/net/udp.rs | 462 +++++++++++------- .../crates/core/src/net/udp/manual_tests.rs | 225 +++++++++ .../crates/core/src/net/udp/test_support.rs | 129 +++++ backend/crates/core/src/net/udp/tests.rs | 327 +++++++++++++ 8 files changed, 988 insertions(+), 203 deletions(-) create mode 100644 backend/crates/core/src/net/udp/manual_tests.rs create mode 100644 backend/crates/core/src/net/udp/test_support.rs create mode 100644 backend/crates/core/src/net/udp/tests.rs diff --git a/backend/crates/core/src/net.rs b/backend/crates/core/src/net.rs index ff2824e13..3ba454472 100644 --- a/backend/crates/core/src/net.rs +++ b/backend/crates/core/src/net.rs @@ -33,7 +33,7 @@ //! //! Addresses are for the operator, not for the domain types: they show //! up interpolated in each submodule's error messages (`tcp::Error`, -//! `udp::Error`), which is where somebody actually reads them. +//! `udp::UdpError`), which is where somebody actually reads them. mod error; mod report; diff --git a/backend/crates/core/src/net/README.md b/backend/crates/core/src/net/README.md index f5f9cd5f3..dde1b5bd3 100644 --- a/backend/crates/core/src/net/README.md +++ b/backend/crates/core/src/net/README.md @@ -10,9 +10,10 @@ 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::Error, nothing else +├── 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 (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 @@ -35,7 +36,7 @@ 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::Error` messages, which is where somebody +interpolated in `tcp::Error`/`udp::UdpError` messages, which is where somebody actually reads them. ### `Event` and `Notification` — what happened, and when @@ -86,7 +87,7 @@ that it can afford to queue behind telemetry. failed lives inside the `Error` variant, which is the only place that always has it. A datagram that fails to decode resolves to no board at all — its id is not in the ADJ, so there is no `PacketDef` to ask — and all that can be said about it is -the address it came from, which is what `udp::Error::Decode` holds. +the address it came from, which is what `udp::UdpError::Decode` holds. ### `Error` — aggregation only @@ -102,14 +103,14 @@ submodule's own error: nobody outside knows which of its variants are fatal. | | `tcp` | `udp` | |---|---|---| -| Entry point | `spawn(Config, Arc, Reporter) -> Handles` | `spawn(Config, Arc, Reporter) -> Result, Error>` (binds first) | +| Entry point | `spawn(Config, Arc, Reporter) -> Handles` | `spawn_udp(UdpConfig, Arc, Reporter) -> Result, UdpError>` (binds first) | | Inputs | its `Config` (boards, timeouts, backoff, keep-alive) | its `Config` (bind address, `SO_RCVBUF`) | | 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; only reports | +| 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 @@ -121,7 +122,9 @@ which is also what lets a test point it at a fake peer. 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. +`station` answers it the same way. In `udp` it arrives on the error channel as +`UdpError::Fault { from }`: recognised by its id alone, before decoding, without +looking at the ADJ. Three rules both follow: @@ -131,18 +134,23 @@ Three rules both follow: ### What "fatal" means -`tcp::Error::is_fatal`/`udp::Error::is_fatal` are about the **pod**, not about -this process: it means the pod has to be sent to fault, and the backend -**stays up** — still reading, still serving the frontend, still recording — so the -operator can see why. Nothing in `net` ever calls `std::process::exit`. +`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`. -Only a decode failure is fatal, on either transport, and this is a deliberate +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 diff --git a/backend/crates/core/src/net/error.rs b/backend/crates/core/src/net/error.rs index 64109a954..1588e2043 100644 --- a/backend/crates/core/src/net/error.rs +++ b/backend/crates/core/src/net/error.rs @@ -24,5 +24,5 @@ pub enum Error { Tcp(#[from] tcp::Error), /// On the shared UDP socket. #[error(transparent)] - Udp(#[from] udp::Error), + Udp(#[from] udp::UdpError), } diff --git a/backend/crates/core/src/net/report.rs b/backend/crates/core/src/net/report.rs index 35f7dc16c..7ff356f1f 100644 --- a/backend/crates/core/src/net/report.rs +++ b/backend/crates/core/src/net/report.rs @@ -57,7 +57,7 @@ pub struct Notification { /// board at all — its id is not in the ADJ, so there is no /// [`crate::model::PacketDef`] to ask — and all that can be said about /// it is the address it came from, which is exactly what -/// [`super::udp::Error::Decode`] holds. +/// [`super::udp::UdpError::Decode`] holds. #[derive(Debug)] pub struct ErrorReport { /// The instant the failure was reported, on the same clock as @@ -207,8 +207,8 @@ mod tests { Event::Received(Packet::Data(DataPacket::new(AdjId(1000), vec![]))) } - fn an_error() -> udp::Error { - udp::Error::Recv { + fn an_error() -> udp::UdpError { + udp::UdpError::Recv { source: std::io::Error::from(std::io::ErrorKind::ConnectionReset), } } @@ -333,7 +333,7 @@ mod tests { let Some(report) = sinks.errors.recv().await else { unreachable!("exactly one error was reported"); }; - let Error::Udp(udp::Error::Recv { .. }) = report.error else { + let Error::Udp(udp::UdpError::Recv { .. }) = report.error else { unreachable!("a udp error should arrive as Error::Udp"); }; // Nothing reached the notification channel. @@ -343,14 +343,14 @@ mod tests { #[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::Error::Decode { + let error = udp::UdpError::Decode { from: addr, 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::Error::Decode { from, .. }) = Error::from(error) else { + let Error::Udp(udp::UdpError::Decode { from, .. }) = Error::from(error) else { unreachable!("a decode error should convert into Error::Udp"); }; assert_eq!(from, addr); diff --git a/backend/crates/core/src/net/udp.rs b/backend/crates/core/src/net/udp.rs index c85972214..e1be8f6cb 100644 --- a/backend/crates/core/src/net/udp.rs +++ b/backend/crates/core/src/net/udp.rs @@ -4,11 +4,12 @@ //! # What this module is //! //! One socket bound to the backend's own address, carrying `Data` packets -//! from every board. Nothing is ever sent from it. +//! from every board, and the fault (packet id 0) any of them may send. +//! Nothing is ever sent from it. //! //! # Entry point //! -//! [`spawn`], taking [`Config`], an `Arc` and a +//! [`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. @@ -21,57 +22,117 @@ //! 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. -//! No disk, no WebSocket, no aggregation. +//! [`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. -//! - **A decode failure is fatal**: see [`Error::is_fatal`]. 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 -//! means the ADJ this backend loaded does not describe what the boards -//! are actually sending, and every datagram after it is suspect for the -//! same reason. So: log it and report it on the error channel, exactly -//! as [`super::tcp`] does — and that is all. This socket writes -//! nothing, and sending the pod to fault is not `net`'s call anyway: -//! whoever consumes the error channel reads [`Error::is_fatal`] and -//! decides, which also keeps the "fault once" guard in one place -//! rather than one per transport. Keep receiving meanwhile: a -//! mismatched ADJ fails on every datagram that follows, several -//! thousand a second, and each one is reported, not acted on. +//! - **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::vehicle::bootstrap`), not something reported once +//! (`station`), not something reported once //! everything is already running. Hence the entry point returns -//! `Result, Error>`. +//! `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::Packet; use crate::protocol::{DecodeError, Index}; use std::net::SocketAddr; use std::sync::Arc; +use std::time::{Duration, Instant}; use tokio::task::JoinHandle; -use tracing::{error, warn}; +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, Copy, PartialEq, Eq)] -pub struct Config { - /// Where to bind: the backend's own address, `backend_ip` + - /// `ports["UDP"]` in the ADJ's general info. +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`, in bytes. + /// `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: 2 MiB is about - /// 0.8 s of margin at 20 Mbit/s. + /// 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, } @@ -87,69 +148,110 @@ pub struct Config { /// 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 /// -/// [`Error::Bind`] only — every later failure goes out through +/// [`UdpError::Bind`] only — every later failure goes out through /// `reporter`, since by then there is nobody left to return it to. -pub fn spawn(config: Config, adj: Arc, reporter: Reporter) -> Result, Error> { - let socket = bind_socket(config)?; - let handle = tokio::spawn(run_loop(socket, adj, reporter)); +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, reporter)); Ok(handle) } /// Binds a UDP socket and configures its OS-level receive buffer size (`SO_RCVBUF`). -fn bind_socket(config: Config) -> Result { +fn bind_telemetry_socket(config: UdpConfig) -> Result { // Bind using the standard library socket first so we can configure non-blocking mode. - let std_socket = std::net::UdpSocket::bind(config.addr).map_err(|source| Error::Bind { + 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| Error::Bind { - addr: config.addr, - source, - })?; + 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| Error::Bind { + 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); - if let Err(e) = sock_ref.set_recv_buffer_size(config.recv_buffer) { - warn!( - %config.addr, - buffer = config.recv_buffer, - %e, - "could not set SO_RCVBUF, using system default" - ); + 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 run_loop( - socket: tokio::net::UdpSocket, - adj: Arc, - reporter: Reporter, -) { +async fn receive_telemetry(socket: tokio::net::UdpSocket, adj: Arc, 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)) => { - if !handle_datagram(&buf[..len], from, &adj, &reporter).await { + if !decode_and_report(&buf[..len], from, &adj, &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 = Error::Recv { source }; + let err = UdpError::Recv { source }; error!(%err, "UDP receive error"); let _ = reporter.report(err).await; break; @@ -158,24 +260,51 @@ async fn run_loop( } } +/// 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(); + /// Decodes a single datagram slice against `adj` and forwards the result or error to `reporter`. /// +/// A fault (packet id 0, see [`FAULT_ID`]) is reported before any of that, +/// without looking at `adj`. +/// /// Returns `false` if the downstream `reporter` channels have closed and the loop should stop. -async fn handle_datagram( +async fn decode_and_report( bytes: &[u8], from: SocketAddr, adj: &Index, reporter: &Reporter, + traces: &mut ReceiveTraces, ) -> bool { + if bytes.starts_with(&FAULT_ID) { + if let Some(suppressed) = traces.fault.should_trace(Instant::now()) { + error!(%from, suppressed, "a board signalled a fault (packet id 0)"); + } + return reporter.report(UdpError::Fault { from }).await.is_ok(); + } + let packet = match crate::protocol::udp::decode_datagram(bytes, adj) { Ok(p) => p, Err(source) => { - let error = Error::Decode { from, source }; - error!(%error, "UDP decode error"); + if let Some(suppressed) = traces.decode.should_trace(Instant::now()) { + error!(%from, %source, suppressed, "UDP datagram could not be decoded"); + } + let error = UdpError::Decode { from, 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) = adj.packet(packet.id) else { warn!(id = ?packet.id, "decoded packet id not in index"); return true; @@ -189,14 +318,65 @@ async fn handle_datagram( .is_ok() } -/// Something that went wrong on the shared UDP socket. +/// 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`]). /// /// No [`crate::model::BoardId`] in any variant, on purpose: the socket /// belongs to no board, and a datagram that fails to decode may not -/// resolve to one at all — [`Error::Decode`] carries the address it came -/// from, which is the only identity that always exists. +/// resolve to one at all — [`UdpError::Decode`] and [`UdpError::Fault`] +/// carry the address the datagram came from, which is the only identity +/// that always exists. #[derive(Debug, thiserror::Error)] -pub enum 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 { @@ -215,9 +395,9 @@ pub enum Error { source: std::io::Error, }, - /// A datagram could not be decoded, which means the loaded ADJ does - /// not describe what the boards are sending. Fatal: see - /// [`Error::is_fatal`]. + /// 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 — there may be no board to @@ -227,141 +407,57 @@ pub enum Error { #[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: the board's address, since a fault + /// carries nothing else that says which board sent it. + from: SocketAddr, + }, } -impl Error { - /// Whether this error means the pod has to be sent to fault. +impl UdpError { + /// Whether this module considers the error serious enough to send the + /// pod to fault. /// - /// "Fatal" is about the **pod**, not about this process: the backend - /// stays up — still reading, still serving the frontend, still - /// recording — so that whoever is operating the pod can see what - /// happened. Nothing here ever calls `std::process::exit`. + /// 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. - /// [`Error::Decode`] means the loaded ADJ does not describe what the - /// boards are sending, and [`Error::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::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. /// - /// [`Error::Bind`] never reaches this: binding happens before the - /// task is spawned, so it is a startup failure handed back to - /// whoever composes the backend. + /// [`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 { - Error::Bind { .. } | Error::Recv { .. } | Error::Decode { .. } => true, + UdpError::Bind { .. } + | UdpError::Recv { .. } + | UdpError::Decode { .. } + | UdpError::Fault { .. } => true, } } } #[cfg(test)] -mod tests { - use super::*; - use crate::model::{AdjId, Board, BoardId, MacAddress, MessageLevel, PacketDef, PacketType, PodData}; - use std::collections::HashMap; - use std::net::IpAddr; - - fn peer() -> SocketAddr { - SocketAddr::new(IpAddr::from([192, 168, 1, 3]), 50400) - } - - #[test] - fn a_datagram_that_will_not_decode_faults_the_pod() { - let error = Error::Decode { - from: peer(), - source: crate::protocol::DecodeError::UnknownId(AdjId(9999)), - }; - - assert!(error.is_fatal()); - } - - #[test] - fn losing_the_socket_faults_the_pod_too() { - let error = Error::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 = Error::Decode { - from: peer(), - source: crate::protocol::DecodeError::UnknownId(AdjId(9999)), - }; +mod manual_tests; - assert!(error.to_string().contains("192.168.1.3:50400")); - } - - /// Builds a minimal Index with one empty Data packet (ID 1000) on Board 1. - fn sample_index() -> Index { - let packet = PacketDef { - id: AdjId(1000), - board: BoardId(1), - name: "test_data".to_string(), - packet_type: PacketType::Message(MessageLevel::Info),// I don't know what packet type to use here - }; - let board = Board { - id: BoardId(1), - 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) - } - - #[tokio::test] - async fn handle_datagram_decodes_valid_packet_and_notifies() { - let (reporter, mut sinks) = Reporter::channels(16, 16); - let index = sample_index(); - - // 1000 in little-endian u16 is [0xE8, 0x03], with 0 measurements. - let keep_going = handle_datagram(&[0xE8, 0x03], peer(), &index, &reporter).await; - assert!(keep_going); - - let notification = sinks.notifications.recv().await; - assert!(notification.is_some(), "should have emitted a packet event"); - assert!(sinks.errors.try_recv().is_err(), "should not have reported an error"); - } - - #[tokio::test] - async fn handle_datagram_reports_error_on_unknown_id() { - let (reporter, mut sinks) = Reporter::channels(16, 16); - let index = sample_index(); - - // Unknown ID 0xFFFF (65535) - let keep_going = handle_datagram(&[0xFF, 0xFF], peer(), &index, &reporter).await; - assert!(keep_going); - - let error_report = sinks.errors.recv().await; - assert!(error_report.is_some(), "should have reported a decode error"); - } - - #[tokio::test] - async fn handle_datagram_stops_when_sinks_are_dropped() { - let (reporter, sinks) = Reporter::channels(16, 16); - let index = sample_index(); - drop(sinks); - - // With receivers dropped, reporting should signal the loop to exit (false). - let keep_going = handle_datagram(&[0xFF, 0xFF], peer(), &index, &reporter).await; - assert!(!keep_going); - } +#[cfg(test)] +mod test_support; - #[test] - fn config_is_copy() { - let config = Config { - addr: SocketAddr::new(IpAddr::from([127, 0, 0, 1]), 0), - recv_buffer: 2 * 1024 * 1024, - }; - let _copy = config; - // Config is still usable after assignment — it implements Copy. - let _addr = config.addr; - let _buf = config.recv_buffer; - } -} \ No newline at end of file +#[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..eb890291d --- /dev/null +++ b/backend/crates/core/src/net/udp/manual_tests.rs @@ -0,0 +1,225 @@ +//! 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); + let receiver = tokio::spawn(receive_telemetry(socket, Arc::new(index), 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..aa8425133 --- /dev/null +++ b/backend/crates/core/src/net/udp/test_support.rs @@ -0,0 +1,129 @@ +//! 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]; + +/// 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) +} + +/// `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: BoardId(1), + name: "test_data".to_string(), + packet_type: PacketType::Data(vec![]), + }; + let board = Board { + id: BoardId(1), + 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, BoardId(1)); + 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, + }; + 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. +pub(super) fn start_receiving_on_loopback(reporter: Reporter) -> (SocketAddr, JoinHandle<()>) { + let (socket, addr) = bind_on_loopback(256 * 1024); + let index = Arc::new(index_with_empty_data_packet()); + let handle = tokio::spawn(receive_telemetry(socket, index, reporter)); + (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..b71efb004 --- /dev/null +++ b/backend/crates/core/src/net/udp/tests.rs @@ -0,0 +1,327 @@ +//! 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(), + 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(), + 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(), + }; + + assert!(error.is_fatal()); +} + +#[test] +fn a_fault_says_where_it_came_from() { + let error = UdpError::Fault { + from: example_board_addr(), + }; + + 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 mut traces = ReceiveTraces::default(); + + let keep_going = decode_and_report( + &EMPTY_DATA_DATAGRAM, + example_board_addr(), + &index, + &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() { + let (reporter, mut sinks) = Reporter::channels(16, 16); + let index = index_with_empty_data_packet(); + let mut traces = ReceiveTraces::default(); + + let keep_going = decode_and_report( + &UNKNOWN_ID_DATAGRAM, + example_board_addr(), + &index, + &reporter, + &mut traces, + ) + .await; + assert!(keep_going); + + let report = receive_error_report(&mut sinks).await; + let crate::net::Error::Udp(UdpError::Decode { from, source }) = report.error else { + unreachable!("an undecodable datagram should be reported as udp::UdpError::Decode"); + }; + assert_eq!(from, example_board_addr()); + 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 mut traces = ReceiveTraces::default(); + + let keep_going = decode_and_report( + &FAULT_DATAGRAM, + example_board_addr(), + &index, + &reporter, + &mut traces, + ) + .await; + assert!(keep_going); + + let report = receive_error_report(&mut sinks).await; + let crate::net::Error::Udp(UdpError::Fault { from }) = report.error else { + unreachable!("a datagram with packet id 0 should be reported as udp::UdpError::Fault"); + }; + assert_eq!(from, example_board_addr()); + assert!( + sinks.notifications.try_recv().is_err(), + "should not have notified a packet" + ); +} + +#[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 mut traces = ReceiveTraces::default(); + + decode_and_report( + &[0x00, 0x00, 0xAB, 0xCD], + example_board_addr(), + &index, + &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 mut traces = ReceiveTraces::default(); + + // An id takes two bytes: one zero byte is a truncated datagram. + decode_and_report( + &[0x00], + example_board_addr(), + &index, + &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 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(), + &index, + &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() { + 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, .. }) = report.error else { + unreachable!("an undecodable datagram should be reported as udp::UdpError::Decode"); + }; + assert_eq!(from, board_addr); + handle.abort(); +} + +#[tokio::test] +async fn a_fault_sent_to_the_socket_is_reported_with_its_sender() { + 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 }) = report.error else { + unreachable!("a datagram with packet id 0 should be reported as udp::UdpError::Fault"); + }; + assert_eq!(from, board_addr); + 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, + }); + + let Err(UdpError::Bind { addr, .. }) = second else { + unreachable!("binding an address already in use should fail with UdpError::Bind"); + }; + assert_eq!(addr, taken); +} From 0c586d7ca1ca4ad7791bebc24bddea0bbc4f8984 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Wed, 25 Nov 2026 02:20:27 +0100 Subject: [PATCH 06/14] chore: update CI to test all features --- .github/workflows/rust-tests.yaml | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) 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 }} From a1faca9553874b547b54deeb451bc6e919e5b9c0 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Wed, 25 Nov 2026 19:48:03 +0100 Subject: [PATCH 07/14] wip: event --- backend/crates/station/src/event.rs | 715 ++++++++++++++++++ backend/crates/station/src/event/README.md | 539 +++++++++++++ backend/crates/station/src/event/fault.rs | 77 ++ .../crates/station/src/event/manual_tests.rs | 88 +++ backend/crates/station/src/event/orders.rs | 65 ++ backend/crates/station/src/event/policy.rs | 238 ++++++ backend/crates/station/src/event/tests.rs | 499 ++++++++++++ 7 files changed, 2221 insertions(+) create mode 100644 backend/crates/station/src/event.rs create mode 100644 backend/crates/station/src/event/README.md create mode 100644 backend/crates/station/src/event/fault.rs create mode 100644 backend/crates/station/src/event/manual_tests.rs create mode 100644 backend/crates/station/src/event/orders.rs create mode 100644 backend/crates/station/src/event/policy.rs create mode 100644 backend/crates/station/src/event/tests.rs diff --git a/backend/crates/station/src/event.rs b/backend/crates/station/src/event.rs new file mode 100644 index 000000000..e28a64d55 --- /dev/null +++ b/backend/crates/station/src/event.rs @@ -0,0 +1,715 @@ +//! 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; + +#[cfg(test)] +mod manual_tests; +#[cfg(test)] +mod tests; + +pub use policy::full_message; + +use std::collections::{HashMap, HashSet}; +use std::future::Future; +use std::net::IpAddr; +use std::pin::Pin; +use std::sync::Arc; +use std::time::{Duration, SystemTime}; + +use software_core::model::{BoardId, OrderPacket, PodData}; +use software_core::net::{ErrorReport, Notification, Reporter, Sinks}; +use tokio::sync::{mpsc, oneshot}; +use tokio::task::{JoinHandle, JoinSet}; +use tracing::{debug, error, warn}; + +use self::fault::{FAULT_QUEUE, FaultRequest}; +use self::policy::Action; + +/// A batch of notifications, shared by `logging` and `pipeline` without +/// copying it: one allocation per batch, freed when both have let go of it. +pub type Batch = Arc<[Notification]>; + +/// 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 { + /// Most notifications taken out of ③ or ④ at once. + pub batch: usize, + /// 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 ⑤, counted in **batches**, not notifications. + pub logging_queue: usize, + /// Slots in ⑥, counted in **batches**, not notifications. + pub pipeline_queue: usize, + /// Slots in ⑦ (orders from the front). + pub orders_queue: usize, + /// Forward a board's fault to the other boards. + pub forward_board_faults: 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 { + batch: 512, + errors_queue: 16, + problems_queue: 16, + tcp_queue: 1024, + udp_queue: 8192, + logging_queue: 64, + pipeline_queue: 64, + orders_queue: 32, + forward_board_faults: 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, + /// Shown on the front; the fault is sent 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 batch of notifications, TCP or UDP. + Received(Batch), + /// An order TCP confirmed it wrote. + OrderSent { + /// When the write was confirmed. + at: SystemTime, + /// The board it was written to. + board: BoardId, + /// The order. + order: OrderPacket, + }, +} + +/// What `pipeline` receives (⑥). +#[derive(Debug)] +pub enum ToPipeline { + /// A batch of notifications, TCP or UDP. + Received(Batch), + /// Something the operator has to see. + Problem(Problem), + /// An order that did not go out. + 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 boards as `event` needs them: who an IP belongs to, and what each +/// board is called. Built once from the ADJ. +#[derive(Debug, Clone, Default)] +pub struct Boards { + by_ip: HashMap, + names: HashMap, +} + +impl Boards { + /// Reads every board's IP and name. + pub fn from_pod_data(pod_data: &PodData) -> Self { + let by_ip = pod_data + .boards + .values() + .map(|board| (board.ip, board.id)) + .collect(); + let names = pod_data + .boards + .values() + .map(|board| (board.id, board.name.clone())) + .collect(); + Self { by_ip, names } + } + + /// The board at `ip`, if any. + pub fn by_ip(&self, ip: IpAddr) -> Option { + self.by_ip.get(&ip).copied() + } + + /// The board's name, or its id if the ADJ does not declare it. + pub fn name(&self, board: BoardId) -> String { + self.names + .get(&board) + .cloned() + .unwrap_or_else(|| format!("{board:?}")) + } +} + +/// 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 { + udp: Sinks, + tcp: Sinks, + problems: mpsc::Receiver, + orders: mpsc::Receiver, + logging: mpsc::Sender, + pipeline: mpsc::Sender, + /// Capacities of ③ and ④: how much a fatal stop drains at most. + tcp_capacity: usize, + udp_capacity: usize, +} + +/// 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); + let tcp_capacity = config.tcp_queue.max(1); + let udp_capacity = config.udp_queue.max(1); + + 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 { + udp: udp_sinks, + tcp: tcp_sinks, + problems: problems_rx, + orders: orders_rx, + logging: logging_tx, + pipeline: pipeline_tx, + tcp_capacity, + udp_capacity, + }, + orders: orders_tx, + problems: problems_tx, + logging: logging_rx, + pipeline: pipeline_rx, + } +} + +/// Starts the routing loop and the two workers. +/// +/// 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, + boards: Boards, + tcp: Option>, +) -> JoinHandle { + tokio::spawn(run(config, ends, boards, tcp)) +} + +async fn run( + config: EventConfig, + ends: EventEnds, + boards: Boards, + tcp: Option>, +) -> Stop { + let boards = Arc::new(boards); + let (fault_tx, fault_rx) = mpsc::channel(FAULT_QUEUE); + + let mut workers = JoinSet::new(); + workers.spawn(fault::run( + fault_rx, + tcp.clone(), + ends.pipeline.clone(), + boards.clone(), + )); + workers.spawn(orders::run( + ends.orders, + tcp, + fault_tx.clone(), + ends.logging.clone(), + ends.pipeline.clone(), + )); + + let batch = config.batch.max(1); + let router = Router { + config, + batch, + boards, + udp: ends.udp, + tcp: ends.tcp, + problems: ends.problems, + logging: ends.logging, + pipeline: ends.pipeline, + fault: fault_tx, + open: Open::default(), + tcp_batch: Vec::with_capacity(batch), + udp_batch: Vec::with_capacity(batch), + tcp_capacity: ends.tcp_capacity, + udp_capacity: ends.udp_capacity, + faults_shown: HashSet::new(), + }; + + // The router's senders are dropped when `route` returns; the workers' + // when they are stopped here. + let stop = router.route().await; + workers.shutdown().await; + stop +} + +/// 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), + Notifications(Transport, usize), +} + +/// 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: everything towards the front. +struct Router { + config: EventConfig, + batch: usize, + boards: Arc, + udp: Sinks, + tcp: Sinks, + problems: mpsc::Receiver, + logging: mpsc::Sender, + pipeline: mpsc::Sender, + fault: mpsc::Sender, + open: Open, + /// One reused buffer per notification queue (the two are read in the + /// same `select!`, so they cannot share one). + tcp_batch: Vec, + udp_batch: Vec, + tcp_capacity: usize, + udp_capacity: usize, + /// The addresses whose fault has already been shown. + faults_shown: HashSet, +} + +impl Router { + async fn route(mut self) -> Stop { + loop { + if !self.open.net() { + return Stop::NetGone; + } + + let limit = self.batch; + let open = self.open; + // Fixed order: errors, then TCP, then UDP. + let step = tokio::select! { + biased; + 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), + n = self.tcp.notifications.recv_many(&mut self.tcp_batch, limit), + if open.tcp_notifications => Step::Notifications(Transport::Tcp, n), + n = self.udp.notifications.recv_many(&mut self.udp_batch, limit), + if open.udp_notifications => Step::Notifications(Transport::Udp, n), + else => return Stop::NetGone, + }; + + let handled = match step { + 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, + // 0 only once the queue is closed and empty. + Step::Notifications(Transport::Tcp, 0) => { + self.open.tcp_notifications = false; + Ok(()) + } + Step::Notifications(Transport::Udp, 0) => { + self.open.udp_notifications = false; + Ok(()) + } + Step::Notifications(transport, _) => { + self.forward(transport).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 the batch just taken from `transport`'s queue to both consumers, + /// as one shared copy. + async fn forward(&mut self, transport: Transport) -> Result<(), Consumer> { + let batch = match transport { + Transport::Tcp => &mut self.tcp_batch, + Transport::Udp => &mut self.udp_batch, + }; + // One allocation; the buffer keeps its capacity for the next batch. + let shared: Batch = batch.drain(..).collect(); + + self.logging + .send(ToLogging::Received(shared.clone())) + .await + .map_err(|_| Consumer::Logging)?; + self.pipeline + .send(ToPipeline::Received(shared)) + .await + .map_err(|_| Consumer::Pipeline) + } + + 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 + .or_else(|| source.ip.and_then(|ip| self.boards.by_ip(ip))); + + // UDP errors only carry an address: 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}", self.boards.name(board)); + } + + let kind = match action { + Action::Fatal => ProblemKind::Fatal, + Action::Silent => ProblemKind::Silent, + Action::Show | Action::BoardFault => ProblemKind::Shown, + }; + let problem = Problem { + at: report.at, + board, + kind, + text, + }; + + 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| self.boards.name(board)); + warn!(board = ?board, problem = %problem.text, "problem not shown on the front"); + } + + /// The first fault from each address is shown and forwarded; repeats are + /// not (`net` already traces them, rate-limited). + async fn on_board_fault(&mut self, problem: Problem, ip: Option) -> Result<(), Halt> { + let first = ip.is_none_or(|ip| self.faults_shown.insert(ip)); + if !first { + return Ok(()); + } + + warn!(fault = %problem.text, "first fault from this board"); + self.show(problem).await.map_err(Halt::Gone)?; + + if self.config.forward_board_faults { + // Never waits: if the queue is full a request is already pending, + // and the fault goes out only once anyway. + if let Err(error) = self.fault.try_send(FaultRequest { done: None }) { + debug!(%error, "fault request not queued"); + } + } + Ok(()) + } + + async fn show(&self, problem: Problem) -> Result<(), Consumer> { + self.pipeline + .send(ToPipeline::Problem(problem)) + .await + .map_err(|_| Consumer::Pipeline) + } + + /// Procedure 3: show it, pass on what was already queued, send the fault, + /// stop. + async fn stop_fatal(mut self, problem: Problem) -> Stop { + error!(problem = %problem.text, "fatal error, stopping"); + + 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.send_fault_and_wait().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"); + + if consumer == Consumer::Logging { + let _ = self + .pipeline + .send(ToPipeline::Problem(problem.clone())) + .await; + } + + self.send_fault_and_wait().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 mut left = match transport { + Transport::Tcp => self.tcp_capacity, + Transport::Udp => self.udp_capacity, + }; + while left > 0 { + let (queue, batch) = match transport { + Transport::Tcp => (&mut self.tcp.notifications, &mut self.tcp_batch), + Transport::Udp => (&mut self.udp.notifications, &mut self.udp_batch), + }; + let limit = self.batch.min(left); + while batch.len() < limit { + match queue.try_recv() { + Ok(notification) => batch.push(notification), + Err(_) => break, + } + } + if batch.is_empty() { + break; + } + left -= batch.len(); + self.forward(transport).await?; + } + } + Ok(()) + } + + /// Asks the fault worker for the fault and waits until it has gone out + /// (or had gone out already), within [`Config::fault_timeout`]. + async fn send_fault_and_wait(&self) { + let (done_tx, done_rx) = oneshot::channel(); + let request = FaultRequest { + done: Some(done_tx), + }; + let wait = async { + if self.fault.send(request).await.is_ok() { + let _ = done_rx.await; + } + }; + if tokio::time::timeout(self.config.fault_timeout, wait) + .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/README.md b/backend/crates/station/src/event/README.md new file mode 100644 index 000000000..1ce4af010 --- /dev/null +++ b/backend/crates/station/src/event/README.md @@ -0,0 +1,539 @@ +# `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 (failed) + └───────┬─────────┘ + │ ⑧ (order id 0 = fault) + ▼ + routing loop ─⑧─────────────► ┌─ task ──────────┐ ──► TCP: fault to every board + │ fault worker │ ─⑥─► pipeline (boards not reached) + │ "only once" │ + └─────────────────┘ + + 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. +- **Batch**: several notifications taken out at once (`recv_many`) instead of + one at a time. +- **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: channels, spawn, the routing loop, Stop +event/ +├── 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, orders worker → `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 boards = Boards::from_pod_data(&adj.pod_data); +let event = event::spawn(config, channels.event, boards, tcp); // tcp: 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 | +|---|---|---|---| +| Batch of TCP notifications (③) | yes | yes | — | +| Batch of UDP notifications (④) | 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, if forwarding is on | + +**How notifications travel.** The routing loop takes up to 512 at once from a +queue, puts them in **one shared copy** (`Arc<[Notification]>`) 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 goes to `logging` (⑤) + only once TCP confirms the write. + - **A failed order 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 fault.** The fault worker sends the fault (order id 0) to every board. + It gets requests on ⑧ from three places: the routing loop on a fatal error, + the routing loop on the first fault from each board (if forwarding is on), and the + orders worker when the front asks for one (an order with id 0). + - **Only once per session.** The fault worker sends it on the first request + and only acknowledges the later ones. It is the one place that keeps that + flag, whoever asks. + - **Boards it did not reach** go to `pipeline` (⑥): a fault that only half + landed is exactly what the operator has to know. +- **Without TCP** (no TCP client running), every order fails with "TCP not + available", shown on the front, and the 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 }` | a board detected an error and says so (packet id 0) | **board fault**: shown, forwarded to the other boards; 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.** UDP errors carry the address the datagram came from (`from`), +not the board. At startup `event` gets an IP → `BoardId` map built from the ADJ +(every `Board` has its `ip`, see [`model/board.rs`](../../../core/src/model/board.rs)), +so the front says "HVSCU" rather than "127.0.0.7". An IP that belongs to no +board stays without a board, and the text carries the address. + +**Board faults on the front.** The first fault 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). Forwarding a board's fault to the others is +configurable and on by default. + +**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. Sends the `Problem` to `pipeline`, so the operator sees it. +2. 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. +3. Asks the fault worker to send the fault and waits for it to finish, with a + time limit (if it was already sent, the answer is immediate). +4. Ends by returning `Stop::Fatal(problem)`. + +If what stopped is `logging` or `pipeline`, step 2 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 +/// A batch of notifications, shared by logging and pipeline without copying. +pub type Batch = Arc<[Notification]>; + +/// Creates every queue between modules. `main` calls it once, before spawning +/// anything, and hands each end to whoever uses it. +pub fn channels(config: &Config) -> 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: Config, + ends: EventEnds, + boards: Boards, + 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>>; +} + +/// Who an IP belongs to and what each board is called, built from the ADJ. +pub struct Boards { /* ... */ } +impl Boards { + pub fn from_pod_data(pod_data: &PodData) -> Self; + pub fn by_ip(&self, ip: IpAddr) -> Option; + pub fn name(&self, board: BoardId) -> String; +} + +pub enum ToLogging { + Received(Batch), + /// An order TCP confirmed it wrote. + OrderSent { at: SystemTime, board: BoardId, order: OrderPacket }, +} + +pub enum ToPipeline { + Received(Batch), + Problem(Problem), + /// An order 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: shown, the fault is sent 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, +} + +/// `Config::default()` gives the sizes in brackets. Every size is clamped to +/// at least 1. +pub struct Config { + pub batch: usize, // most notifications per batch (512) + 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, // ⑤, in batches (64) + pub pipeline_queue: usize, // ⑥, in batches (64) + pub orders_queue: usize, // ⑦ (32) + pub forward_board_faults: bool, // (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 -> first from that board? Problem to ⑥ + forwarding on? request to ⑧ + shown -> Problem to ⑥ + silent -> trace only + 2. ③ TCP notifications.recv_many(batch, config.batch) -> forward + 3. ④ UDP notifications.recv_many(batch, config.batch) -> forward + all four of net's queues (① ① ③ ④) closed -> return Stop::NetGone + +forward: + shared = batch.drain(..).collect::>() + ⑤.send(Received(shared.clone())).await // on failure: fatal + ⑥.send(Received(shared)).await // on failure: fatal +``` + +`batch.drain(..).collect()` allocates once per batch, and the `batch` `Vec` +keeps its capacity for the next one. + +## 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: + +- notifications in batches, one memory allocation per batch, not per + notification; +- 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. + +## 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 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, and reports its own failures (e.g. the disk) on ②. +- **`pipeline`** reads ⑥ and turns it into what the front shows: a batch into + per-packet updates (counts, cycle time, averages) or protection and message + updates, a `Problem` or a failed order into a message. 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 ① closes once both + `Reporter`s are gone 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 batch, the + fatal stop (and that what was queued before the error still gets through), + board faults shown once per board and the fault sent once, orders with and + without TCP, order id 0, 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 4.9 million a + second, over 100 times the requirement. + + ```sh + cargo test -p station --release manual_event -- --ignored --nocapture + ``` + +## Open questions + +- **Fault from the front.** `websocket` validates orders against the ADJ, and id + 0 is not in it, so today a fault asked for from the front is rejected before + reaching ⑦. +- **Order echo.** Whether a sent order is also shown on the front, not only + logged. diff --git a/backend/crates/station/src/event/fault.rs b/backend/crates/station/src/event/fault.rs new file mode 100644 index 000000000..e3a143cd8 --- /dev/null +++ b/backend/crates/station/src/event/fault.rs @@ -0,0 +1,77 @@ +//! The fault worker: sends the fault (order id 0) to every board, once per +//! session, whoever asks for it. + +use std::sync::Arc; + +use software_core::model::AdjId; +use tokio::sync::{mpsc, oneshot}; +use tracing::{error, info, warn}; + +use super::{Boards, Problem, ProblemKind, TcpLink, ToPipeline}; + +/// 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, and once the +/// fault has been sent every later one is a no-op, so a full queue only +/// means a request is already pending. +pub(super) const FAULT_QUEUE: usize = 8; + +/// A request to send the fault. +#[derive(Debug)] +pub(super) struct FaultRequest { + /// Told once the fault has been sent, or was already sent before: the + /// routing loop waits on it before stopping on a fatal error. + pub(super) done: Option>, +} + +/// Runs the worker until its queue closes (or `event` stops it). +/// +/// The "only once" flag lives here and nowhere else: a fatal error, a board's +/// fault and the front all end up in this queue. A request that arrives while +/// the fault is being sent waits behind it, so it is only acknowledged once +/// the fault has really gone out. +pub(super) async fn run( + mut requests: mpsc::Receiver, + tcp: Option>, + pipeline: mpsc::Sender, + boards: Arc, +) { + let mut sent = false; + while let Some(request) = requests.recv().await { + if !sent { + sent = true; + send_fault(tcp.as_deref(), &pipeline, &boards).await; + } + if let Some(done) = request.done { + // The one waiting may have given up already (its time limit). + let _ = done.send(()); + } + } +} + +/// Sends the fault and tells the front about the boards it did not reach. +async fn send_fault( + tcp: Option<&dyn TcpLink>, + pipeline: &mpsc::Sender, + boards: &Boards, +) { + let Some(tcp) = tcp else { + warn!("the fault was not sent to the boards: TCP not available"); + return; + }; + + match tcp.send_fault().await { + Ok(()) => info!("fault sent to every board"), + Err(unreached) => { + let names: Vec = unreached.iter().map(|&board| boards.name(board)).collect(); + let text = format!("the fault did not reach these boards: {}", names.join(", ")); + error!(%text); + // A fault that only half landed is exactly what the operator has + // to know. If pipeline is gone, event is stopping anyway. + let problem = Problem::now(ProblemKind::Shown, None, text); + let _ = pipeline.send(ToPipeline::Problem(problem)).await; + } + } +} 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..3c3da9895 --- /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, Boards::default(), None); + + let logged = tokio::spawn(async move { + let mut count = 0; + while let Some(message) = logging.recv().await { + if let ToLogging::Received(batch) = message { + count += batch.len(); + } + } + count + }); + let shown = tokio::spawn(async move { + let mut count = 0; + while let Some(message) = pipeline.recv().await { + if let ToPipeline::Received(batch) = message { + count += batch.len(); + } + } + 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..f3b2a6303 --- /dev/null +++ b/backend/crates/station/src/event/orders.rs @@ -0,0 +1,65 @@ +//! 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 (⑧). +/// - Any other order is written and waited for before the next one is +/// taken. Written: it goes to `logging` (⑤). 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 { done: None }).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) => logging + .send(ToLogging::OrderSent { at, board, order }) + .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..4fb8d2b86 --- /dev/null +++ b/backend/crates/station/src/event/policy.rs @@ -0,0 +1,238 @@ +//! 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::BoardId; +use software_core::net::{self, tcp, udp::UdpError}; + +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, + } +} + +/// 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 do). + pub(super) board: Option, + /// The address a datagram came from, when that is all there is (UDP). + 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, .. } | UdpError::Fault { from } => Source { + board: None, + 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 +} + +#[cfg(test)] +mod tests { + use super::*; + use software_core::model::AdjId; + use software_core::protocol::DecodeError; + use std::net::SocketAddr; + + 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(), + 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() }); + 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_tcp_errors_a_board() { + let fault = udp(UdpError::Fault { from: from() }); + assert_eq!( + source(&fault), + 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(), + 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/tests.rs b/backend/crates/station/src/event/tests.rs new file mode 100644 index 000000000..b32518285 --- /dev/null +++ b/backend/crates/station/src/event/tests.rs @@ -0,0 +1,499 @@ +//! 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::error::Error; +use std::net::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(), + } +} + +fn boards() -> Boards { + let pod_data = PodData { + boards: HashMap::from([ + (HVSCU, board(HVSCU, "HVSCU", hvscu_addr())), + (VCU, board(VCU, "VCU", vcu_addr())), + ]), + }; + Boards::from_pod_data(&pod_data) +} + +fn data() -> Event { + Event::Received(Packet::Data(DataPacket::new(AdjId(1000), vec![]))) +} + +fn fault_from(from: SocketAddr) -> UdpError { + UdpError::Fault { from } +} + +fn decode_error() -> UdpError { + UdpError::Decode { + from: hvscu_addr(), + 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) +} + +#[tokio::test] +async fn a_batch_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, boards(), None); + + let ToLogging::Received(logged) = next(&mut channels.logging).await? else { + unreachable!("the first thing logging gets is the batch"); + }; + let ToPipeline::Received(shown) = next(&mut channels.pipeline).await? else { + unreachable!("the first thing pipeline gets is the batch"); + }; + assert_eq!(logged.len(), 3); + 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())).await?; + let _event = spawn(config, channels.event, boards(), 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[0].event, Event::Connected)); + + let ToPipeline::Received(udp) = next(&mut channels.pipeline).await? else { + unreachable!("then the UDP notification"); + }; + assert!(matches!(udp[0].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, boards(), 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), "resolved from the address"); + assert!(problem.text.starts_with("HVSCU: "), "{}", problem.text); + + // The data that arrived before the error still gets through. + let ToPipeline::Received(shown) = next(&mut channels.pipeline).await? else { + unreachable!("then what was queued"); + }; + let ToLogging::Received(logged) = next(&mut channels.logging).await? else { + unreachable!("logging gets what was queued too"); + }; + assert_eq!(shown.len(), 2); + assert_eq!(logged.len(), 2); + + 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_the_fault_sent_once() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + let fake = Arc::new(FakeTcp::default()); + let event = spawn(config, channels.event, boards(), as_link(&fake)); + + for _ in 0..3 { + channels.udp.report(fault_from(hvscu_addr())).await?; + } + channels.udp.report(fault_from(vcu_addr())).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); + + eventually(|| fake.faults.load(Ordering::SeqCst) == 1).await?; + sleep(Duration::from_millis(50)).await; + assert_eq!( + fake.faults.load(Ordering::SeqCst), + 1, + "the fault goes out once" + ); + assert!( + !event.is_finished(), + "a board fault does not stop the backend" + ); + Ok(()) +} + +#[tokio::test] +async fn forwarding_a_board_fault_can_be_turned_off() -> TestResult { + let config = EventConfig { + forward_board_faults: false, + ..EventConfig::default() + }; + let mut channels = channels(&config); + let fake = Arc::new(FakeTcp::default()); + let _event = spawn(config, channels.event, boards(), as_link(&fake)); + + channels.udp.report(fault_from(hvscu_addr())).await?; + let ToPipeline::Problem(_) = next(&mut channels.pipeline).await? else { + unreachable!("the fault is still shown"); + }; + 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, boards(), None); + + udp.notify(HVSCU, data()).await?; + let ToLogging::Received(batch) = next(&mut logging).await? else { + unreachable!("the UDP notification gets through"); + }; + assert_eq!(batch.len(), 1); + 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, boards(), 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() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + let fake = Arc::new(FakeTcp::default()); + let _event = spawn(config, channels.event, boards(), 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, 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, boards(), 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() -> TestResult { + let config = EventConfig::default(); + let channels = channels(&config); + let fake = Arc::new(FakeTcp::default()); + let _event = spawn(config, channels.event, boards(), as_link(&fake)); + + channels.orders.send(order(0)).await?; + eventually(|| fake.faults.load(Ordering::SeqCst) == 1).await?; + assert_eq!( + fake.orders.load(Ordering::SeqCst), + 0, + "not written as an order" + ); + 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, boards(), as_link(&fake)); + + channels.udp.report(fault_from(hvscu_addr())).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, boards(), 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, boards(), 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, boards(), None); + + let ToLogging::Received(batch) = next(&mut logging).await? else { + unreachable!("what was queued gets through"); + }; + assert_eq!(batch.len(), 2); + + 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, boards(), 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(()) +} From 7c5bc2b622e4c15790ad927de8caa9be95af7d22 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Tue, 1 Dec 2026 10:45:07 +0100 Subject: [PATCH 08/14] feat(backend, model): relaction functions --- backend/crates/core/src/model/board.rs | 55 ++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) 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); + } } From bba52df2198f773f972da6bc2170db821dfe3129 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Tue, 1 Dec 2026 10:48:24 +0100 Subject: [PATCH 09/14] feat(backend, udp): obtain board on errors --- backend/crates/core/src/net/README.md | 11 +- backend/crates/core/src/net/report.rs | 14 ++- backend/crates/core/src/net/udp.rs | 104 ++++++++++++---- .../crates/core/src/net/udp/manual_tests.rs | 8 +- .../crates/core/src/net/udp/test_support.rs | 29 ++++- backend/crates/core/src/net/udp/tests.rs | 112 +++++++++++++++--- 6 files changed, 221 insertions(+), 57 deletions(-) diff --git a/backend/crates/core/src/net/README.md b/backend/crates/core/src/net/README.md index dde1b5bd3..50b0f78dd 100644 --- a/backend/crates/core/src/net/README.md +++ b/backend/crates/core/src/net/README.md @@ -85,9 +85,10 @@ that it can afford to queue behind telemetry. `ErrorReport` carries **no board**, unlike a notification: the identity of what failed lives inside the `Error` variant, which is the only place that always has -it. A datagram that fails to decode resolves to no board at all — its id is not in -the ADJ, so there is no `PacketDef` to ask — and all that can be said about it is -the address it came from, which is what `udp::UdpError::Decode` holds. +it. A datagram that fails to decode has no id to resolve a board from — it is not +in the ADJ, so there is no `PacketDef` to ask — so `udp::UdpError::Decode` holds the +address it came from and the board that address belongs to, if it belongs to one +(`UdpConfig::boards`). `UdpError::Fault` carries the same two. ### `Error` — aggregation only @@ -104,7 +105,7 @@ submodule's own error: nobody outside knows which of its variants are fatal. | | `tcp` | `udp` | |---|---|---| | Entry point | `spawn(Config, Arc, Reporter) -> Handles` | `spawn_udp(UdpConfig, Arc, Reporter) -> Result, UdpError>` (binds first) | -| Inputs | its `Config` (boards, timeouts, backoff, keep-alive) | its `Config` (bind address, `SO_RCVBUF`) | +| Inputs | its `Config` (boards, timeouts, backoff, keep-alive) | its `UdpConfig` (bind address, `SO_RCVBUF`, IP → board) | | Role | client only; one connection per board, one task each | one shared socket, receive-only, one task | | Framing | buffer + `&mut Cursor` + advance by `cursor.position()`; bail out past 374 bytes | none — `recv_from` delivers a whole datagram into a reused 64 KiB buffer | | Writing | yes (orders, keep-alive); a single writer task per connection | no | @@ -123,7 +124,7 @@ reads `is_fatal()` and calls `Handles::propagate_fault()`, which puts the order with id 0 into every board's writer channel (the Go backend's `SendFault`). A *received* packet with id 0 is the same action requested by a board, and `station` answers it the same way. In `udp` it arrives on the error channel as -`UdpError::Fault { from }`: recognised by its id alone, before decoding, without +`UdpError::Fault { from, board }`: recognised by its id alone, before decoding, without looking at the ADJ. Three rules both follow: diff --git a/backend/crates/core/src/net/report.rs b/backend/crates/core/src/net/report.rs index 7ff356f1f..4ad86342f 100644 --- a/backend/crates/core/src/net/report.rs +++ b/backend/crates/core/src/net/report.rs @@ -53,11 +53,11 @@ pub struct Notification { /// /// Carries no identity of its own: whose failure it was travels inside /// the [`Error`]'s own variant, which is the only place that always has -/// it. A datagram that fails to decode, for instance, resolves to no -/// board at all — its id is not in the ADJ, so there is no -/// [`crate::model::PacketDef`] to ask — and all that can be said about -/// it is the address it came from, which is exactly what -/// [`super::udp::UdpError::Decode`] holds. +/// it. A datagram that fails to decode, for instance, has no id to resolve +/// a board from — it is not in the ADJ, so there is no +/// [`crate::model::PacketDef`] to ask — so +/// [`super::udp::UdpError::Decode`] holds the address it came from, and +/// the board that address belongs to only if it belongs to one. #[derive(Debug)] pub struct ErrorReport { /// The instant the failure was reported, on the same clock as @@ -345,15 +345,17 @@ mod tests { let addr = SocketAddr::new(IpAddr::from([192, 168, 1, 3]), 50400); let error = udp::UdpError::Decode { from: addr, + board: None, source: crate::protocol::DecodeError::UnknownId(AdjId(9999)), }; // The whole reason an error report carries no board: this one has // an address, and no board to attribute it to. - let Error::Udp(udp::UdpError::Decode { from, .. }) = Error::from(error) else { + let Error::Udp(udp::UdpError::Decode { from, board, .. }) = Error::from(error) else { unreachable!("a decode error should convert into Error::Udp"); }; assert_eq!(from, addr); + assert_eq!(board, None); } #[tokio::test] diff --git a/backend/crates/core/src/net/udp.rs b/backend/crates/core/src/net/udp.rs index e1be8f6cb..a4c719387 100644 --- a/backend/crates/core/src/net/udp.rs +++ b/backend/crates/core/src/net/udp.rs @@ -37,6 +37,13 @@ //! notification looks the same whichever transport brought it. That is //! one `HashMap` lookup per datagram, done here once rather than //! repeated by every consumer downstream. +//! - **An error names its board too, when it can.** A fault or a datagram +//! that will not decode has no id to resolve, so its board comes from +//! the address it was sent from, through [`UdpConfig::boards`]. Both +//! variants carry the address and that board (`None` if the address +//! belongs to no board), so the consumer gets the identity ready, as it +//! does from [`super::tcp`]. The lookup only happens on those two paths, +//! never for a datagram that decodes. //! - **A decode failure is reported as fatal** (see [`UdpError::is_fatal`]), //! but acting on it is not this module's call. Nothing corrupts a //! datagram in flight — UDP checksums it and the pod's network does not @@ -91,9 +98,10 @@ //! ``` use super::Reporter; -use crate::model::Packet; +use crate::model::{BoardId, Packet}; use crate::protocol::{DecodeError, Index}; -use std::net::SocketAddr; +use std::collections::HashMap; +use std::net::{IpAddr, SocketAddr}; use std::sync::Arc; use std::time::{Duration, Instant}; use tokio::task::JoinHandle; @@ -103,7 +111,7 @@ use tracing::{error, info, warn}; /// /// Everything here is resolved by `station` before `net` is reached: this /// module reads no config file and no ADJ of its own. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub struct UdpConfig { /// Where to bind: the backend's own address, `addresses["backend"]` /// and `ports["UDP"]` in the ADJ's `general_info.json`. @@ -134,6 +142,13 @@ pub struct UdpConfig { /// it at `net.core.rmem_max` — so [`spawn_udp`] reads the granted size back /// and warns when it is smaller than requested. pub recv_buffer: usize, + /// Which board each address belongs to, so that an error can name the + /// board it came from: [`UdpError::Decode`] and [`UdpError::Fault`]. + /// + /// Built from the ADJ with [`crate::model::PodData::boards_by_ip`]. An + /// address missing from it is not refused: its errors just carry no + /// board. + pub boards: HashMap, } /// Binds the shared socket and spawns the receive loop. @@ -160,13 +175,13 @@ pub fn spawn_udp( adj: Arc, reporter: Reporter, ) -> Result, UdpError> { - let socket = bind_telemetry_socket(config)?; - let handle = tokio::spawn(receive_telemetry(socket, adj, reporter)); + let socket = bind_telemetry_socket(&config)?; + let handle = tokio::spawn(receive_telemetry(socket, adj, config.boards, reporter)); Ok(handle) } /// Binds a UDP socket and configures its OS-level receive buffer size (`SO_RCVBUF`). -fn bind_telemetry_socket(config: UdpConfig) -> Result { +fn bind_telemetry_socket(config: &UdpConfig) -> Result { // Bind using the standard library socket first so we can configure non-blocking mode. let std_socket = std::net::UdpSocket::bind(config.addr).map_err(|source| UdpError::Bind { addr: config.addr, @@ -236,7 +251,12 @@ fn bind_telemetry_socket(config: UdpConfig) -> Result, reporter: Reporter) { +async fn receive_telemetry( + socket: tokio::net::UdpSocket, + adj: Arc, + boards: HashMap, + reporter: Reporter, +) { // Reusable 64 KiB buffer — a datagram can never be silently truncated. let mut buf = vec![0u8; 64 * 1024]; let mut traces = ReceiveTraces::default(); @@ -244,7 +264,11 @@ async fn receive_telemetry(socket: tokio::net::UdpSocket, adj: Arc, repor loop { match socket.recv_from(&mut buf).await { Ok((len, from)) => { - if !decode_and_report(&buf[..len], from, &adj, &reporter, &mut traces).await { + let lookups = Lookups { + adj: &adj, + boards: &boards, + }; + if !decode_and_report(&buf[..len], from, lookups, &reporter, &mut traces).await { // Downstream channels closed; exit cleanly. break; } @@ -268,33 +292,58 @@ async fn receive_telemetry(socket: tokio::net::UdpSocket, adj: Arc, repor /// raises a fault itself (`SendFault`). const FAULT_ID: [u8; 2] = 0u16.to_le_bytes(); -/// Decodes a single datagram slice against `adj` and forwards the result or error to `reporter`. +/// What the receive loop looks things up in, both read-only. +#[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 address to its board, for errors: see [`UdpConfig::boards`]. + boards: &'a HashMap, +} + +impl Lookups<'_> { + /// The board `from` belongs to, if any. + fn board_at(&self, from: SocketAddr) -> Option { + self.boards.get(&from.ip()).copied() + } +} + +/// Decodes a single datagram slice against the ADJ and forwards the result or error to `reporter`. /// /// A fault (packet id 0, see [`FAULT_ID`]) is reported before any of that, -/// without looking at `adj`. +/// without looking at the ADJ. /// /// Returns `false` if the downstream `reporter` channels have closed and the loop should stop. async fn decode_and_report( bytes: &[u8], from: SocketAddr, - adj: &Index, + lookups: Lookups<'_>, reporter: &Reporter, traces: &mut ReceiveTraces, ) -> bool { if bytes.starts_with(&FAULT_ID) { + let board = lookups.board_at(from); if let Some(suppressed) = traces.fault.should_trace(Instant::now()) { - error!(%from, suppressed, "a board signalled a fault (packet id 0)"); + error!(%from, ?board, suppressed, "a board signalled a fault (packet id 0)"); } - return reporter.report(UdpError::Fault { from }).await.is_ok(); + return reporter + .report(UdpError::Fault { from, board }) + .await + .is_ok(); } - let packet = match crate::protocol::udp::decode_datagram(bytes, adj) { + let packet = match crate::protocol::udp::decode_datagram(bytes, lookups.adj) { Ok(p) => p, Err(source) => { + let board = lookups.board_at(from); if let Some(suppressed) = traces.decode.should_trace(Instant::now()) { - error!(%from, %source, suppressed, "UDP datagram could not be decoded"); + error!(%from, ?board, %source, suppressed, "UDP datagram could not be decoded"); } - let error = UdpError::Decode { from, source }; + let error = UdpError::Decode { + from, + board, + source, + }; return reporter.report(error).await.is_ok(); } }; @@ -305,7 +354,7 @@ async fn decode_and_report( // run; it is handled rather than unwrapped because the decode lives // in another module. One extra `HashMap` lookup per datagram is not // worth changing `protocol`'s API to avoid. - let Some(packet_def) = adj.packet(packet.id) else { + let Some(packet_def) = lookups.adj.packet(packet.id) else { warn!(id = ?packet.id, "decoded packet id not in index"); return true; }; @@ -370,11 +419,11 @@ impl TraceRateLimit { /// Something that went wrong on the shared UDP socket, or that a board /// says went wrong ([`UdpError::Fault`]). /// -/// No [`crate::model::BoardId`] in any variant, on purpose: the socket -/// belongs to no board, and a datagram that fails to decode may not -/// resolve to one at all — [`UdpError::Decode`] and [`UdpError::Fault`] -/// carry the address the datagram came from, which is the only identity -/// that always exists. +/// [`UdpError::Decode`] and [`UdpError::Fault`] concern one datagram, so +/// they carry the address it came from, the only identity that always +/// exists, and the board that address belongs to, when it belongs to one +/// (see [`UdpConfig::boards`]). [`UdpError::Bind`] and [`UdpError::Recv`] +/// concern the socket, which belongs to no board. #[derive(Debug, thiserror::Error)] pub enum UdpError { /// The socket could not be bound, so no telemetry will arrive at all. @@ -400,9 +449,10 @@ pub enum UdpError { /// [`UdpError::is_fatal`]. #[error("could not decode a datagram from {from}")] Decode { - /// Where the datagram came from — there may be no board to - /// attribute it to. + /// Where the datagram came from. from: SocketAddr, + /// The board `from` belongs to; `None` if it belongs to none. + board: Option, /// What [`crate::protocol`] said about it. #[source] source: DecodeError, @@ -413,9 +463,11 @@ pub enum UdpError { /// arrived fine — but the pod telling the backend it is in trouble. #[error("the board at {from} signalled a fault (packet id 0)")] Fault { - /// Where the fault came from: the board's address, since a fault - /// carries nothing else that says which board sent it. + /// Where the fault came from. A fault carries nothing else that + /// says which board sent it. from: SocketAddr, + /// The board `from` belongs to; `None` if it belongs to none. + board: Option, }, } diff --git a/backend/crates/core/src/net/udp/manual_tests.rs b/backend/crates/core/src/net/udp/manual_tests.rs index eb890291d..a992487bd 100644 --- a/backend/crates/core/src/net/udp/manual_tests.rs +++ b/backend/crates/core/src/net/udp/manual_tests.rs @@ -155,7 +155,13 @@ async fn manual_udp_load() { let (socket, addr) = bind_on_loopback(recv_buffer); let granted = socket2::SockRef::from(&socket).recv_buffer_size().ok(); let (reporter, mut sinks) = Reporter::channels(8192, 16); - let receiver = tokio::spawn(receive_telemetry(socket, Arc::new(index), reporter)); + // No boards by address: the probe sends nothing that fails. + let receiver = tokio::spawn(receive_telemetry( + socket, + Arc::new(index), + HashMap::new(), + reporter, + )); // Counts until told the sender is done, then drains what is left. No // timer per message, so that the consumer costs as little as possible diff --git a/backend/crates/core/src/net/udp/test_support.rs b/backend/crates/core/src/net/udp/test_support.rs index aa8425133..11cfa9ff9 100644 --- a/backend/crates/core/src/net/udp/test_support.rs +++ b/backend/crates/core/src/net/udp/test_support.rs @@ -23,11 +23,25 @@ pub(super) const UNKNOWN_ID_DATAGRAM: [u8; 2] = [0xFF, 0xFF]; /// declare either — a fault is recognised without the ADJ. pub(super) const FAULT_DATAGRAM: [u8; 2] = [0x00, 0x00]; +/// The board every fixture here declares. +pub(super) const TEST_BOARD: BoardId = BoardId(1); + /// A board's address on the pod's network, for errors that carry one. pub(super) fn example_board_addr() -> SocketAddr { SocketAddr::new(IpAddr::from([192, 168, 1, 3]), 50400) } +/// An address that belongs to no board. +pub(super) fn stranger_addr() -> SocketAddr { + SocketAddr::new(IpAddr::from([192, 168, 1, 99]), 50400) +} + +/// [`UdpConfig::boards`] with a single entry: `ip` belongs to +/// [`TEST_BOARD`]. +pub(super) fn boards_at(ip: IpAddr) -> HashMap { + HashMap::from([(ip, TEST_BOARD)]) +} + /// `127.0.0.1` with port 0, so that the OS picks a free one. pub(super) fn any_loopback_port() -> SocketAddr { SocketAddr::new(IpAddr::from([127, 0, 0, 1]), 0) @@ -41,12 +55,12 @@ pub(super) fn any_loopback_port() -> SocketAddr { pub(super) fn index_with_empty_data_packet() -> Index { let packet = PacketDef { id: AdjId(1000), - board: BoardId(1), + board: TEST_BOARD, name: "test_data".to_string(), packet_type: PacketType::Data(vec![]), }; let board = Board { - id: BoardId(1), + id: TEST_BOARD, name: "TEST".to_string(), ip: IpAddr::from([192, 168, 0, 10]), mac: MacAddress([0; 6]), @@ -78,7 +92,7 @@ pub(super) async fn receive_error_report(sinks: &mut Sinks) -> ErrorReport { /// Asserts that `notification` is what [`EMPTY_DATA_DATAGRAM`] decodes to. pub(super) fn assert_is_empty_data_packet(notification: Notification) { - assert_eq!(notification.board, BoardId(1)); + assert_eq!(notification.board, TEST_BOARD); let Event::Received(Packet::Data(packet)) = notification.event else { unreachable!("a datagram should arrive as Event::Received(Packet::Data)"); }; @@ -92,8 +106,9 @@ pub(super) fn bind_on_loopback(recv_buffer: usize) -> (tokio::net::UdpSocket, So let config = UdpConfig { addr: any_loopback_port(), recv_buffer, + boards: HashMap::new(), }; - let Ok(socket) = bind_telemetry_socket(config) else { + let Ok(socket) = bind_telemetry_socket(&config) else { unreachable!("binding to a free loopback port should succeed"); }; let Ok(addr) = socket.local_addr() else { @@ -105,10 +120,14 @@ pub(super) fn bind_on_loopback(recv_buffer: usize) -> (tokio::net::UdpSocket, So /// Starts receiving on a free loopback port with /// [`index_with_empty_data_packet`], as [`spawn_udp`] does, and returns the /// address to send to along with the task's handle. +/// +/// `127.0.0.1`, where [`bind_fake_board`] sends from, belongs to +/// [`TEST_BOARD`]. pub(super) fn start_receiving_on_loopback(reporter: Reporter) -> (SocketAddr, JoinHandle<()>) { let (socket, addr) = bind_on_loopback(256 * 1024); let index = Arc::new(index_with_empty_data_packet()); - let handle = tokio::spawn(receive_telemetry(socket, index, reporter)); + let boards = boards_at(any_loopback_port().ip()); + let handle = tokio::spawn(receive_telemetry(socket, index, boards, reporter)); (addr, handle) } diff --git a/backend/crates/core/src/net/udp/tests.rs b/backend/crates/core/src/net/udp/tests.rs index b71efb004..01bcfe99c 100644 --- a/backend/crates/core/src/net/udp/tests.rs +++ b/backend/crates/core/src/net/udp/tests.rs @@ -13,6 +13,7 @@ use crate::model::AdjId; fn a_datagram_that_will_not_decode_faults_the_pod() { let error = UdpError::Decode { from: example_board_addr(), + board: Some(TEST_BOARD), source: DecodeError::UnknownId(AdjId(9999)), }; @@ -32,6 +33,7 @@ fn losing_the_socket_faults_the_pod_too() { fn a_decode_failure_says_where_it_came_from() { let error = UdpError::Decode { from: example_board_addr(), + board: Some(TEST_BOARD), source: DecodeError::UnknownId(AdjId(9999)), }; @@ -42,6 +44,7 @@ fn a_decode_failure_says_where_it_came_from() { fn a_board_signalling_a_fault_faults_the_pod() { let error = UdpError::Fault { from: example_board_addr(), + board: Some(TEST_BOARD), }; assert!(error.is_fatal()); @@ -51,6 +54,7 @@ fn a_board_signalling_a_fault_faults_the_pod() { fn a_fault_says_where_it_came_from() { let error = UdpError::Fault { from: example_board_addr(), + board: Some(TEST_BOARD), }; assert!(error.to_string().contains("192.168.1.3:50400")); @@ -64,12 +68,17 @@ fn a_fault_says_where_it_came_from() { async fn decode_and_report_notifies_a_valid_datagram() { let (reporter, mut sinks) = Reporter::channels(16, 16); let index = index_with_empty_data_packet(); + let boards = boards_at(example_board_addr().ip()); + let lookups = Lookups { + adj: &index, + boards: &boards, + }; let mut traces = ReceiveTraces::default(); let keep_going = decode_and_report( &EMPTY_DATA_DATAGRAM, example_board_addr(), - &index, + lookups, &reporter, &mut traces, ) @@ -84,15 +93,20 @@ async fn decode_and_report_notifies_a_valid_datagram() { } #[tokio::test] -async fn decode_and_report_reports_an_unknown_id() { +async fn decode_and_report_reports_an_unknown_id_with_its_board() { let (reporter, mut sinks) = Reporter::channels(16, 16); let index = index_with_empty_data_packet(); + let boards = boards_at(example_board_addr().ip()); + let lookups = Lookups { + adj: &index, + boards: &boards, + }; let mut traces = ReceiveTraces::default(); let keep_going = decode_and_report( &UNKNOWN_ID_DATAGRAM, example_board_addr(), - &index, + lookups, &reporter, &mut traces, ) @@ -100,10 +114,16 @@ async fn decode_and_report_reports_an_unknown_id() { assert!(keep_going); let report = receive_error_report(&mut sinks).await; - let crate::net::Error::Udp(UdpError::Decode { from, source }) = report.error else { + let crate::net::Error::Udp(UdpError::Decode { + from, + board, + source, + }) = report.error + else { unreachable!("an undecodable datagram should be reported as udp::UdpError::Decode"); }; assert_eq!(from, example_board_addr()); + assert_eq!(board, Some(TEST_BOARD), "resolved from the address"); assert!(matches!(source, DecodeError::UnknownId(AdjId(0xFFFF)))); assert!( sinks.notifications.try_recv().is_err(), @@ -116,12 +136,17 @@ async fn decode_and_report_reports_a_fault_without_looking_at_the_adj() { let (reporter, mut sinks) = Reporter::channels(16, 16); // Declares id 1000 only: id 0 is unknown to it, and yet it is a fault. let index = index_with_empty_data_packet(); + let boards = boards_at(example_board_addr().ip()); + let lookups = Lookups { + adj: &index, + boards: &boards, + }; let mut traces = ReceiveTraces::default(); let keep_going = decode_and_report( &FAULT_DATAGRAM, example_board_addr(), - &index, + lookups, &reporter, &mut traces, ) @@ -129,26 +154,72 @@ async fn decode_and_report_reports_a_fault_without_looking_at_the_adj() { assert!(keep_going); let report = receive_error_report(&mut sinks).await; - let crate::net::Error::Udp(UdpError::Fault { from }) = report.error else { + let crate::net::Error::Udp(UdpError::Fault { from, board }) = report.error else { unreachable!("a datagram with packet id 0 should be reported as udp::UdpError::Fault"); }; assert_eq!(from, example_board_addr()); + assert_eq!(board, Some(TEST_BOARD), "resolved from the address"); assert!( sinks.notifications.try_recv().is_err(), "should not have notified a packet" ); } +#[tokio::test] +async fn an_address_that_belongs_to_no_board_is_reported_without_one() { + let (reporter, mut sinks) = Reporter::channels(16, 16); + let index = index_with_empty_data_packet(); + let boards = boards_at(example_board_addr().ip()); + let lookups = Lookups { + adj: &index, + boards: &boards, + }; + let mut traces = ReceiveTraces::default(); + + decode_and_report( + &FAULT_DATAGRAM, + stranger_addr(), + lookups, + &reporter, + &mut traces, + ) + .await; + decode_and_report( + &UNKNOWN_ID_DATAGRAM, + stranger_addr(), + lookups, + &reporter, + &mut traces, + ) + .await; + + // Still reported, with the address: only the board is missing. + let fault = receive_error_report(&mut sinks).await; + let crate::net::Error::Udp(UdpError::Fault { from, board: None }) = fault.error else { + unreachable!("a fault from an unknown address should carry no board"); + }; + assert_eq!(from, stranger_addr()); + let decode = receive_error_report(&mut sinks).await; + let crate::net::Error::Udp(UdpError::Decode { board: None, .. }) = decode.error else { + unreachable!("a decode failure from an unknown address should carry no board"); + }; +} + #[tokio::test] async fn whatever_follows_the_fault_id_is_not_read() { let (reporter, mut sinks) = Reporter::channels(16, 16); let index = index_with_empty_data_packet(); + let boards = HashMap::new(); + let lookups = Lookups { + adj: &index, + boards: &boards, + }; let mut traces = ReceiveTraces::default(); decode_and_report( &[0x00, 0x00, 0xAB, 0xCD], example_board_addr(), - &index, + lookups, &reporter, &mut traces, ) @@ -165,13 +236,18 @@ async fn whatever_follows_the_fault_id_is_not_read() { async fn a_single_zero_byte_is_not_a_fault() { let (reporter, mut sinks) = Reporter::channels(16, 16); let index = index_with_empty_data_packet(); + let boards = HashMap::new(); + let lookups = Lookups { + adj: &index, + boards: &boards, + }; let mut traces = ReceiveTraces::default(); // An id takes two bytes: one zero byte is a truncated datagram. decode_and_report( &[0x00], example_board_addr(), - &index, + lookups, &reporter, &mut traces, ) @@ -188,6 +264,11 @@ async fn a_single_zero_byte_is_not_a_fault() { async fn decode_and_report_stops_once_nobody_listens() { let (reporter, sinks) = Reporter::channels(16, 16); let index = index_with_empty_data_packet(); + let boards = HashMap::new(); + let lookups = Lookups { + adj: &index, + boards: &boards, + }; let mut traces = ReceiveTraces::default(); drop(sinks); @@ -195,7 +276,7 @@ async fn decode_and_report_stops_once_nobody_listens() { let keep_going = decode_and_report( &UNKNOWN_ID_DATAGRAM, example_board_addr(), - &index, + lookups, &reporter, &mut traces, ) @@ -258,7 +339,7 @@ async fn a_datagram_sent_to_the_socket_arrives_as_a_notification() { } #[tokio::test] -async fn an_undecodable_datagram_is_reported_with_its_sender() { +async fn an_undecodable_datagram_is_reported_with_its_sender_and_board() { let (reporter, mut sinks) = Reporter::channels(16, 16); let (addr, handle) = start_receiving_on_loopback(reporter); let board = bind_fake_board().await; @@ -269,15 +350,16 @@ async fn an_undecodable_datagram_is_reported_with_its_sender() { send_datagram(&board, &UNKNOWN_ID_DATAGRAM, addr).await; let report = receive_error_report(&mut sinks).await; - let crate::net::Error::Udp(UdpError::Decode { from, .. }) = report.error else { + let crate::net::Error::Udp(UdpError::Decode { from, board, .. }) = report.error else { unreachable!("an undecodable datagram should be reported as udp::UdpError::Decode"); }; assert_eq!(from, board_addr); + assert_eq!(board, Some(TEST_BOARD)); handle.abort(); } #[tokio::test] -async fn a_fault_sent_to_the_socket_is_reported_with_its_sender() { +async fn a_fault_sent_to_the_socket_is_reported_with_its_sender_and_board() { let (reporter, mut sinks) = Reporter::channels(16, 16); let (addr, handle) = start_receiving_on_loopback(reporter); let board = bind_fake_board().await; @@ -288,10 +370,11 @@ async fn a_fault_sent_to_the_socket_is_reported_with_its_sender() { send_datagram(&board, &FAULT_DATAGRAM, addr).await; let report = receive_error_report(&mut sinks).await; - let crate::net::Error::Udp(UdpError::Fault { from }) = report.error else { + let crate::net::Error::Udp(UdpError::Fault { from, board }) = report.error else { unreachable!("a datagram with packet id 0 should be reported as udp::UdpError::Fault"); }; assert_eq!(from, board_addr); + assert_eq!(board, Some(TEST_BOARD)); handle.abort(); } @@ -315,9 +398,10 @@ async fn the_loop_stops_on_the_next_datagram_once_nobody_listens() { async fn binding_an_address_already_in_use_is_a_bind_error() { let (_first, taken) = bind_on_loopback(256 * 1024); - let second = bind_telemetry_socket(UdpConfig { + let second = bind_telemetry_socket(&UdpConfig { addr: taken, recv_buffer: 256 * 1024, + boards: HashMap::new(), }); let Err(UdpError::Bind { addr, .. }) = second else { From 7689c9157c9f897053538c2548546e2c0ffca990 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Tue, 1 Dec 2026 12:52:09 +0100 Subject: [PATCH 10/14] refactor(backend, event): incoporate fault --- backend/crates/station/src/event.rs | 547 +++--------------- backend/crates/station/src/event/README.md | 231 ++++---- backend/crates/station/src/event/fault.rs | 153 +++-- .../crates/station/src/event/manual_tests.rs | 10 +- backend/crates/station/src/event/orders.rs | 24 +- backend/crates/station/src/event/policy.rs | 206 ++++++- backend/crates/station/src/event/router.rs | 453 +++++++++++++++ backend/crates/station/src/event/tests.rs | 298 +++++++--- 8 files changed, 1225 insertions(+), 697 deletions(-) create mode 100644 backend/crates/station/src/event/router.rs diff --git a/backend/crates/station/src/event.rs b/backend/crates/station/src/event.rs index e28a64d55..5749e36b3 100644 --- a/backend/crates/station/src/event.rs +++ b/backend/crates/station/src/event.rs @@ -17,6 +17,7 @@ mod fault; mod orders; mod policy; +mod router; #[cfg(test)] mod manual_tests; @@ -25,25 +26,19 @@ mod tests; pub use policy::full_message; -use std::collections::{HashMap, HashSet}; use std::future::Future; -use std::net::IpAddr; use std::pin::Pin; use std::sync::Arc; use std::time::{Duration, SystemTime}; use software_core::model::{BoardId, OrderPacket, PodData}; -use software_core::net::{ErrorReport, Notification, Reporter, Sinks}; -use tokio::sync::{mpsc, oneshot}; +use software_core::net::{Notification, Reporter}; +use software_core::protocol::Index; +use tokio::sync::mpsc; use tokio::task::{JoinHandle, JoinSet}; -use tracing::{debug, error, warn}; -use self::fault::{FAULT_QUEUE, FaultRequest}; -use self::policy::Action; - -/// A batch of notifications, shared by `logging` and `pipeline` without -/// copying it: one allocation per batch, freed when both have let go of it. -pub type Batch = Arc<[Notification]>; +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. @@ -73,8 +68,6 @@ pub trait TcpLink: Send + Sync { /// Every size is clamped to at least 1. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct EventConfig { - /// Most notifications taken out of ③ or ④ at once. - pub batch: usize, /// Slots in each of `net`'s error queues (①, one per transport). pub errors_queue: usize, /// Slots in ② (problems from station modules). @@ -84,14 +77,14 @@ pub struct EventConfig { /// 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 ⑤, counted in **batches**, not notifications. + /// Slots in ⑤ (to `logging`). pub logging_queue: usize, - /// Slots in ⑥, counted in **batches**, not notifications. + /// Slots in ⑥ (to `pipeline`). pub pipeline_queue: usize, /// Slots in ⑦ (orders from the front). pub orders_queue: usize, - /// Forward a board's fault to the other boards. - pub forward_board_faults: bool, + /// 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, } @@ -100,15 +93,14 @@ impl Default for EventConfig { // Default config fn default() -> Self { Self { - batch: 512, errors_queue: 16, problems_queue: 16, tcp_queue: 1024, udp_queue: 8192, - logging_queue: 64, - pipeline_queue: 64, + logging_queue: 8192, + pipeline_queue: 8192, orders_queue: 32, - forward_board_faults: true, + propagate_fault: true, fault_timeout: Duration::from_secs(2), } } @@ -145,7 +137,7 @@ impl Problem { pub enum ProblemKind { /// Shown on the front; the backend keeps running. Shown, - /// Shown on the front; the fault is sent and the backend stops. + /// 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, @@ -154,14 +146,16 @@ pub enum ProblemKind { /// What `logging` receives (⑤). #[derive(Debug)] pub enum ToLogging { - /// A batch of notifications, TCP or UDP. - Received(Batch), + /// 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. - board: BoardId, + /// The board it was written to; `None` for the fault, which goes to + /// every board. + board: Option, /// The order. order: OrderPacket, }, @@ -170,11 +164,24 @@ pub enum ToLogging { /// What `pipeline` receives (⑥). #[derive(Debug)] pub enum ToPipeline { - /// A batch of notifications, TCP or UDP. - Received(Batch), + /// 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 that did not go out. + /// 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, @@ -194,42 +201,12 @@ pub enum Stop { NetGone, } -/// The boards as `event` needs them: who an IP belongs to, and what each -/// board is called. Built once from the ADJ. -#[derive(Debug, Clone, Default)] -pub struct Boards { - by_ip: HashMap, - names: HashMap, -} - -impl Boards { - /// Reads every board's IP and name. - pub fn from_pod_data(pod_data: &PodData) -> Self { - let by_ip = pod_data - .boards - .values() - .map(|board| (board.ip, board.id)) - .collect(); - let names = pod_data - .boards - .values() - .map(|board| (board.id, board.name.clone())) - .collect(); - Self { by_ip, names } - } - - /// The board at `ip`, if any. - pub fn by_ip(&self, ip: IpAddr) -> Option { - self.by_ip.get(&ip).copied() - } - - /// The board's name, or its id if the ADJ does not declare it. - pub fn name(&self, board: BoardId) -> String { - self.names - .get(&board) - .cloned() - .unwrap_or_else(|| format!("{board:?}")) - } +/// 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. @@ -255,15 +232,10 @@ pub struct Channels { /// writing side of ⑤ ⑥. Only [`spawn`] opens it. #[derive(Debug)] pub struct EventEnds { - udp: Sinks, - tcp: Sinks, - problems: mpsc::Receiver, + /// ① ② ③ ④ ⑤ ⑥: for the routing loop. + router: RouterEnds, + /// ⑦: for the orders worker. orders: mpsc::Receiver, - logging: mpsc::Sender, - pipeline: mpsc::Sender, - /// Capacities of ③ and ④: how much a fatal stop drains at most. - tcp_capacity: usize, - udp_capacity: usize, } /// Creates every queue between modules. `main` calls it once, before @@ -273,10 +245,11 @@ pub struct EventEnds { /// 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); + 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)); @@ -288,14 +261,16 @@ pub fn channels(config: &EventConfig) -> Channels { udp, tcp, event: EventEnds { - udp: udp_sinks, - tcp: tcp_sinks, - problems: problems_rx, + router: RouterEnds { + udp: udp_sinks, + tcp: tcp_sinks, + problems: problems_rx, + logging: logging_tx, + pipeline: pipeline_tx, + tcp_capacity, + udp_capacity, + }, orders: orders_rx, - logging: logging_tx, - pipeline: pipeline_tx, - tcp_capacity, - udp_capacity, }, orders: orders_tx, problems: problems_tx, @@ -306,6 +281,10 @@ pub fn channels(config: &EventConfig) -> Channels { /// 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. /// @@ -315,401 +294,65 @@ pub fn channels(config: &EventConfig) -> Channels { pub fn spawn( config: EventConfig, ends: EventEnds, - boards: Boards, + pod_data: Arc, + index: Arc, tcp: Option>, ) -> JoinHandle { - tokio::spawn(run(config, ends, boards, tcp)) + 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, - boards: Boards, + pod_data: Arc, + index: Arc, tcp: Option>, ) -> Stop { - let boards = Arc::new(boards); + // ⑦ 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(), + tcp.clone(), // the same client (an `Arc`), not a second connection + ends.logging.clone(), ends.pipeline.clone(), - boards.clone(), + pod_data.clone(), // for the boards' names in its messages )); workers.spawn(orders::run( - ends.orders, + orders_rx, tcp, - fault_tx.clone(), + fault_tx.clone(), // order id 0 is the fault: passed on to the fault worker ends.logging.clone(), ends.pipeline.clone(), )); - let batch = config.batch.max(1); - let router = Router { - config, - batch, - boards, - udp: ends.udp, - tcp: ends.tcp, - problems: ends.problems, - logging: ends.logging, - pipeline: ends.pipeline, - fault: fault_tx, - open: Open::default(), - tcp_batch: Vec::with_capacity(batch), - udp_batch: Vec::with_capacity(batch), - tcp_capacity: ends.tcp_capacity, - udp_capacity: ends.udp_capacity, - faults_shown: HashSet::new(), - }; + // The loop keeps the original ⑧ sender, for the faults event decides on. + let router = Router::new(config, pod_data, index, ends, fault_tx); - // The router's senders are dropped when `route` returns; the workers' - // when they are stopped here. + // 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 } - -/// 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), - Notifications(Transport, usize), -} - -/// 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: everything towards the front. -struct Router { - config: EventConfig, - batch: usize, - boards: Arc, - udp: Sinks, - tcp: Sinks, - problems: mpsc::Receiver, - logging: mpsc::Sender, - pipeline: mpsc::Sender, - fault: mpsc::Sender, - open: Open, - /// One reused buffer per notification queue (the two are read in the - /// same `select!`, so they cannot share one). - tcp_batch: Vec, - udp_batch: Vec, - tcp_capacity: usize, - udp_capacity: usize, - /// The addresses whose fault has already been shown. - faults_shown: HashSet, -} - -impl Router { - async fn route(mut self) -> Stop { - loop { - if !self.open.net() { - return Stop::NetGone; - } - - let limit = self.batch; - let open = self.open; - // Fixed order: errors, then TCP, then UDP. - let step = tokio::select! { - biased; - 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), - n = self.tcp.notifications.recv_many(&mut self.tcp_batch, limit), - if open.tcp_notifications => Step::Notifications(Transport::Tcp, n), - n = self.udp.notifications.recv_many(&mut self.udp_batch, limit), - if open.udp_notifications => Step::Notifications(Transport::Udp, n), - else => return Stop::NetGone, - }; - - let handled = match step { - 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, - // 0 only once the queue is closed and empty. - Step::Notifications(Transport::Tcp, 0) => { - self.open.tcp_notifications = false; - Ok(()) - } - Step::Notifications(Transport::Udp, 0) => { - self.open.udp_notifications = false; - Ok(()) - } - Step::Notifications(transport, _) => { - self.forward(transport).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 the batch just taken from `transport`'s queue to both consumers, - /// as one shared copy. - async fn forward(&mut self, transport: Transport) -> Result<(), Consumer> { - let batch = match transport { - Transport::Tcp => &mut self.tcp_batch, - Transport::Udp => &mut self.udp_batch, - }; - // One allocation; the buffer keeps its capacity for the next batch. - let shared: Batch = batch.drain(..).collect(); - - self.logging - .send(ToLogging::Received(shared.clone())) - .await - .map_err(|_| Consumer::Logging)?; - self.pipeline - .send(ToPipeline::Received(shared)) - .await - .map_err(|_| Consumer::Pipeline) - } - - 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 - .or_else(|| source.ip.and_then(|ip| self.boards.by_ip(ip))); - - // UDP errors only carry an address: 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}", self.boards.name(board)); - } - - let kind = match action { - Action::Fatal => ProblemKind::Fatal, - Action::Silent => ProblemKind::Silent, - Action::Show | Action::BoardFault => ProblemKind::Shown, - }; - let problem = Problem { - at: report.at, - board, - kind, - text, - }; - - 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| self.boards.name(board)); - warn!(board = ?board, problem = %problem.text, "problem not shown on the front"); - } - - /// The first fault from each address is shown and forwarded; repeats are - /// not (`net` already traces them, rate-limited). - async fn on_board_fault(&mut self, problem: Problem, ip: Option) -> Result<(), Halt> { - let first = ip.is_none_or(|ip| self.faults_shown.insert(ip)); - if !first { - return Ok(()); - } - - warn!(fault = %problem.text, "first fault from this board"); - self.show(problem).await.map_err(Halt::Gone)?; - - if self.config.forward_board_faults { - // Never waits: if the queue is full a request is already pending, - // and the fault goes out only once anyway. - if let Err(error) = self.fault.try_send(FaultRequest { done: None }) { - debug!(%error, "fault request not queued"); - } - } - Ok(()) - } - - async fn show(&self, problem: Problem) -> Result<(), Consumer> { - self.pipeline - .send(ToPipeline::Problem(problem)) - .await - .map_err(|_| Consumer::Pipeline) - } - - /// Procedure 3: show it, pass on what was already queued, send the fault, - /// stop. - async fn stop_fatal(mut self, problem: Problem) -> Stop { - error!(problem = %problem.text, "fatal error, stopping"); - - 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.send_fault_and_wait().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"); - - if consumer == Consumer::Logging { - let _ = self - .pipeline - .send(ToPipeline::Problem(problem.clone())) - .await; - } - - self.send_fault_and_wait().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 mut left = match transport { - Transport::Tcp => self.tcp_capacity, - Transport::Udp => self.udp_capacity, - }; - while left > 0 { - let (queue, batch) = match transport { - Transport::Tcp => (&mut self.tcp.notifications, &mut self.tcp_batch), - Transport::Udp => (&mut self.udp.notifications, &mut self.udp_batch), - }; - let limit = self.batch.min(left); - while batch.len() < limit { - match queue.try_recv() { - Ok(notification) => batch.push(notification), - Err(_) => break, - } - } - if batch.is_empty() { - break; - } - left -= batch.len(); - self.forward(transport).await?; - } - } - Ok(()) - } - - /// Asks the fault worker for the fault and waits until it has gone out - /// (or had gone out already), within [`Config::fault_timeout`]. - async fn send_fault_and_wait(&self) { - let (done_tx, done_rx) = oneshot::channel(); - let request = FaultRequest { - done: Some(done_tx), - }; - let wait = async { - if self.fault.send(request).await.is_ok() { - let _ = done_rx.await; - } - }; - if tokio::time::timeout(self.config.fault_timeout, wait) - .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/README.md b/backend/crates/station/src/event/README.md index 1ce4af010..2963c706a 100644 --- a/backend/crates/station/src/event/README.md +++ b/backend/crates/station/src/event/README.md @@ -53,13 +53,14 @@ the boards. ```text front → websocket ─⑦ orders─► ┌─ task ──────────┐ ──► TCP: write to that board │ orders worker │ ─⑤─► logging (sent) - │ one at a time │ ─⑥─► pipeline (failed) + │ one at a time │ ─⑥─► pipeline (sent or failed) └───────┬─────────┘ │ ⑧ (order id 0 = fault) ▼ routing loop ─⑧─────────────► ┌─ task ──────────┐ ──► TCP: fault to every board - │ fault worker │ ─⑥─► pipeline (boards not reached) - │ "only once" │ + │ 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, @@ -97,8 +98,6 @@ Why it is built like this: [`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. -- **Batch**: several notifications taken out at once (`recv_many`) instead of - one at a time. - **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 @@ -112,8 +111,9 @@ Why it is built like this: ## Files ``` -event.rs # module root: channels, spawn, the routing loop, Stop +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 @@ -130,7 +130,7 @@ event/ | ② | 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, orders worker → `logging` | `ToLogging` | +| ⑤ | 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` | @@ -158,8 +158,7 @@ let channels = event::channels(&config); spawn_udp(udp_config, index.clone(), channels.udp)?; // ① ④ // the TCP client takes channels.tcp ① ③ -let boards = Boards::from_pod_data(&adj.pod_data); -let event = event::spawn(config, channels.event, boards, tcp); // tcp: Option> +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) @@ -188,14 +187,15 @@ Why one place, instead of each module creating its own input queue: | What arrives | `logging` | `pipeline` | fault worker | |---|---|---|---| -| Batch of TCP notifications (③) | yes | yes | — | -| Batch of UDP notifications (④) | yes | yes | — | +| 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, if forwarding is on | +| 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.** The routing loop takes up to 512 at once from a -queue, puts them in **one shared copy** (`Arc<[Notification]>`) and sends that +**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 @@ -213,21 +213,34 @@ is expected to keep up with the incoming rate (about 15–25 Mbit/s). - **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 goes to `logging` (⑤) - only once TCP confirms the write. - - **A failed order 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 fault.** The fault worker sends the fault (order id 0) to every board. - It gets requests on ⑧ from three places: the routing loop on a fatal error, - the routing loop on the first fault from each board (if forwarding is on), and the - orders worker when the front asks for one (an order with id 0). - - **Only once per session.** The fault worker sends it on the first request - and only acknowledges the later ones. It is the one place that keeps that - flag, whoever asks. - - **Boards it did not reach** go to `pipeline` (⑥): a fault that only half - landed is exactly what the operator has to know. + - **"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 the fault is only traced. + 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 @@ -254,7 +267,7 @@ There are three procedures, and every one of them ends up in the trace: |---|---|---| | `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 }` | a board detected an error and says so (packet id 0) | **board fault**: shown, forwarded to the other boards; the backend **keeps running** | +| `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** | @@ -269,16 +282,23 @@ 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.** UDP errors carry the address the datagram came from (`from`), -not the board. At startup `event` gets an IP → `BoardId` map built from the ADJ -(every `Board` has its `ip`, see [`model/board.rs`](../../../core/src/model/board.rs)), -so the front says "HVSCU" rather than "127.0.0.7". An IP that belongs to no -board stays without a board, and the text carries the address. - -**Board faults on the front.** The first fault 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). Forwarding a board's fault to the others is -configurable and on by default. +**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 @@ -289,16 +309,18 @@ HVSCU") and the `Silent` problems it is sent. **On a fatal error**, the routing loop: -1. Sends the `Problem` to `pipeline`, so the operator sees it. -2. Empties whatever was already in ③ and ④ (at most their capacity) and passes +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. -3. Asks the fault worker to send the fault and waits for it to finish, with a - time limit (if it was already sent, the answer is immediate). -4. Ends by returning `Stop::Fatal(problem)`. +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 2 is skipped. If it is +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 @@ -320,12 +342,9 @@ queues close, and the routing loop passes on whatever was left and ends with ## Types ```rust -/// A batch of notifications, shared by logging and pipeline without copying. -pub type Batch = Arc<[Notification]>; - /// Creates every queue between modules. `main` calls it once, before spawning /// anything, and hands each end to whoever uses it. -pub fn channels(config: &Config) -> Channels; +pub fn channels(config: &EventConfig) -> Channels; pub struct Channels { /// For net::udp: reports on ① and ④. @@ -350,9 +369,10 @@ pub struct Channels { /// The task ends with the reason it stopped, once the workers have stopped /// too, so that ⑤ and ⑥ close behind it. pub fn spawn( - config: Config, + config: EventConfig, ends: EventEnds, - boards: Boards, + pod_data: Arc, // only read for the boards' names + index: Arc, // which protections and messages mean fault tcp: Option>, ) -> JoinHandle; @@ -365,24 +385,21 @@ pub trait TcpLink: Send + Sync { fn send_fault(&self) -> BoxFuture<'_, Result<(), Vec>>; } -/// Who an IP belongs to and what each board is called, built from the ADJ. -pub struct Boards { /* ... */ } -impl Boards { - pub fn from_pod_data(pod_data: &PodData) -> Self; - pub fn by_ip(&self, ip: IpAddr) -> Option; - pub fn name(&self, board: BoardId) -> String; -} - pub enum ToLogging { - Received(Batch), - /// An order TCP confirmed it wrote. - OrderSent { at: SystemTime, board: BoardId, order: OrderPacket }, + /// 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 { - Received(Batch), + /// A notification, the same copy logging gets. + Received(Arc), Problem(Problem), - /// An order that did not go out, and why. + /// 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 }, } @@ -401,7 +418,7 @@ pub struct Problem { pub enum ProblemKind { /// Procedure 2: shown, the backend keeps running. Shown, - /// Procedure 3: shown, the fault is sent and the backend stops. + /// 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, @@ -414,18 +431,17 @@ pub enum Stop { NetGone, } -/// `Config::default()` gives the sizes in brackets. Every size is clamped to -/// at least 1. -pub struct Config { - pub batch: usize, // most notifications per batch (512) +/// `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, // ⑤, in batches (64) - pub pipeline_queue: usize, // ⑥, in batches (64) + pub logging_queue: usize, // ⑤ (8,192) + pub pipeline_queue: usize, // ⑥ (8,192) pub orders_queue: usize, // ⑦ (32) - pub forward_board_faults: bool, // (true) + 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) } ``` @@ -440,23 +456,22 @@ these two calls only. `FaultRequest` (⑧) is private to `event`. 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 -> first from that board? Problem to ⑥ - forwarding on? request to ⑧ + board fault -> propagate_fault? request to ⑧ (every time) + first from that board? Problem to ⑥ shown -> Problem to ⑥ silent -> trace only - 2. ③ TCP notifications.recv_many(batch, config.batch) -> forward - 3. ④ UDP notifications.recv_many(batch, config.batch) -> forward + 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: - shared = batch.drain(..).collect::>() +forward(notification): + shared = Arc::new(notification) ⑤.send(Received(shared.clone())).await // on failure: fatal ⑥.send(Received(shared)).await // on failure: fatal ``` -`batch.drain(..).collect()` allocates once per batch, and the `batch` `Vec` -keeps its capacity for the next one. - ## Performance The requirement is **25 Mbit/s in 76-byte packets, about 41,000 a second**: @@ -464,8 +479,8 @@ 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: -- notifications in batches, one memory allocation per batch, not per - notification; +- 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 @@ -473,6 +488,9 @@ bottleneck is whoever reads `net`'s queues, that is, the routing loop.** Hence: - 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 @@ -489,15 +507,20 @@ bottleneck is whoever reads `net`'s queues, that is, the routing loop.** Hence: - 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 front's logger requests + (`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, and reports its own failures (e.g. the disk) on ②. -- **`pipeline`** reads ⑥ and turns it into what the front shows: a batch into - per-packet updates (counts, cycle time, averages) or protection and message - updates, a `Problem` or a failed order into a message. It waits instead of - dropping and does not decide anything about errors. + 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 @@ -507,33 +530,27 @@ bottleneck is whoever reads `net`'s queues, that is, the routing loop.** Hence: - **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 ① closes once both - `Reporter`s are gone while ④ may still have items in it, and without TCP ③ - is closed from the start. + 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 batch, the + `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 shown once per board and the fault sent once, orders with and - without TCP, order id 0, 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. + 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 4.9 million a - second, over 100 times the requirement. + 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 ``` - -## Open questions - -- **Fault from the front.** `websocket` validates orders against the ADJ, and id - 0 is not in it, so today a fault asked for from the front is rejected before - reaching ⑦. -- **Order echo.** Whether a sent order is also shown on the front, not only - logged. diff --git a/backend/crates/station/src/event/fault.rs b/backend/crates/station/src/event/fault.rs index e3a143cd8..8bd2ccc51 100644 --- a/backend/crates/station/src/event/fault.rs +++ b/backend/crates/station/src/event/fault.rs @@ -1,77 +1,138 @@ //! The fault worker: sends the fault (order id 0) to every board, once per -//! session, whoever asks for it. +//! 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; +use software_core::model::{AdjId, OrderPacket, PodData}; use tokio::sync::{mpsc, oneshot}; use tracing::{error, info, warn}; -use super::{Boards, Problem, ProblemKind, TcpLink, ToPipeline}; +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, and once the -/// fault has been sent every later one is a no-op, so a full queue only -/// means a request is already pending. +/// 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) struct FaultRequest { - /// Told once the fault has been sent, or was already sent before: the - /// routing loop waits on it before stopping on a fatal error. - pub(super) done: Option>, +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). /// -/// The "only once" flag lives here and nowhere else: a fatal error, a board's -/// fault and the front all end up in this queue. A request that arrives while -/// the fault is being sent waits behind it, so it is only acknowledged once -/// the fault has really gone out. +/// 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, - boards: Arc, + pod_data: Arc, ) { - let mut sent = false; + let tcp = tcp.as_deref(); while let Some(request) = requests.recv().await { - if !sent { - sent = true; - send_fault(tcp.as_deref(), &pipeline, &boards).await; - } - if let Some(done) = request.done { - // The one waiting may have given up already (its time limit). - let _ = done.send(()); + 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 and tells the front about the boards it did not reach. -async fn send_fault( - tcp: Option<&dyn TcpLink>, - pipeline: &mpsc::Sender, - boards: &Boards, -) { - let Some(tcp) = tcp else { - warn!("the fault was not sent to the boards: TCP not available"); - return; - }; - - match tcp.send_fault().await { - Ok(()) => info!("fault sent to every board"), - Err(unreached) => { - let names: Vec = unreached.iter().map(|&board| boards.name(board)).collect(); - let text = format!("the fault did not reach these boards: {}", names.join(", ")); - error!(%text); - // A fault that only half landed is exactly what the operator has - // to know. If pipeline is gone, event is stopping anyway. - let problem = Problem::now(ProblemKind::Shown, None, text); - let _ = pipeline.send(ToPipeline::Problem(problem)).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 index 3c3da9895..3ca606239 100644 --- a/backend/crates/station/src/event/manual_tests.rs +++ b/backend/crates/station/src/event/manual_tests.rs @@ -33,13 +33,13 @@ async fn manual_event_throughput() -> Result<(), Box> { mut pipeline, } = channels(&config); drop((tcp, orders, problems)); - let event = spawn(config, event, Boards::default(), None); + 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(batch) = message { - count += batch.len(); + if let ToLogging::Received(_) = message { + count += 1; } } count @@ -47,8 +47,8 @@ async fn manual_event_throughput() -> Result<(), Box> { let shown = tokio::spawn(async move { let mut count = 0; while let Some(message) = pipeline.recv().await { - if let ToPipeline::Received(batch) = message { - count += batch.len(); + if let ToPipeline::Received(_) = message { + count += 1; } } count diff --git a/backend/crates/station/src/event/orders.rs b/backend/crates/station/src/event/orders.rs index f3b2a6303..1caecd546 100644 --- a/backend/crates/station/src/event/orders.rs +++ b/backend/crates/station/src/event/orders.rs @@ -16,10 +16,12 @@ 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 (⑧). +/// - 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` (⑤). Not written: it goes to -/// `pipeline` (⑥) with the reason, and to the trace. +/// 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>, @@ -30,7 +32,7 @@ pub(super) async fn run( while let Some(order) = orders.recv().await { if order.id == FAULT_ID { info!("the front asked for the fault"); - if fault.send(FaultRequest { done: None }).await.is_err() { + if fault.send(FaultRequest::FromFront { order }).await.is_err() { break; } continue; @@ -44,10 +46,16 @@ pub(super) async fn run( // Stamped once the outcome is known: "sent" means written. let at = SystemTime::now(); let delivered = match outcome { - Ok(board) => logging - .send(ToLogging::OrderSent { at, board, order }) - .await - .is_ok(), + 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 diff --git a/backend/crates/station/src/event/policy.rs b/backend/crates/station/src/event/policy.rs index 4fb8d2b86..074dd551d 100644 --- a/backend/crates/station/src/event/policy.rs +++ b/backend/crates/station/src/event/policy.rs @@ -4,8 +4,9 @@ use std::error::Error; use std::net::IpAddr; -use software_core::model::BoardId; -use software_core::net::{self, tcp, udp::UdpError}; +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; @@ -59,12 +60,50 @@ pub(super) fn for_problem(kind: ProblemKind) -> Action { } } +/// 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 do). + /// 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, when that is all there is (UDP). + /// The address a datagram came from (UDP errors about one datagram). pub(super) ip: Option, } @@ -72,8 +111,8 @@ pub(super) struct Source { pub(super) fn source(error: &net::Error) -> Source { match error { net::Error::Udp(error) => match error { - UdpError::Decode { from, .. } | UdpError::Fault { from } => Source { - board: None, + UdpError::Decode { from, board, .. } | UdpError::Fault { from, board } => Source { + board: *board, ip: Some(from.ip()), }, UdpError::Recv { .. } | UdpError::Bind { .. } => Source { @@ -110,13 +149,139 @@ pub fn full_message(error: &dyn Error) -> String { 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::AdjId; + 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) } @@ -145,6 +310,7 @@ mod tests { ] { let error = udp(UdpError::Decode { from: from(), + board: None, source, }); assert_eq!(classify(&error), Action::Fatal, "{error}"); @@ -159,7 +325,10 @@ mod tests { #[test] fn a_fault_from_a_board_does_not_stop_the_backend() { - let error = udp(UdpError::Fault { from: from() }); + let error = udp(UdpError::Fault { + from: from(), + board: Some(BoardId(7)), + }); assert_eq!(classify(&error), Action::BoardFault); } @@ -191,10 +360,26 @@ mod tests { } #[test] - fn udp_errors_carry_an_address_and_tcp_errors_a_board() { - let fault = udp(UdpError::Fault { from: from() }); + 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()) @@ -227,6 +412,7 @@ mod tests { fn the_full_message_carries_every_cause_once() { let error = udp(UdpError::Decode { from: from(), + board: None, source: DecodeError::UnknownId(AdjId(9999)), }); 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 index b32518285..0fbfda463 100644 --- a/backend/crates/station/src/event/tests.rs +++ b/backend/crates/station/src/event/tests.rs @@ -9,8 +9,9 @@ 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::SocketAddr; +use std::net::{IpAddr, SocketAddr}; use std::sync::atomic::{AtomicUsize, Ordering}; use tokio::time::{sleep, timeout}; @@ -38,27 +39,38 @@ fn board(id: BoardId, name: &str, addr: SocketAddr) -> Board { } } -fn boards() -> Boards { - let pod_data = PodData { +/// 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())), ]), - }; - Boards::from_pod_data(&pod_data) + }) } fn data() -> Event { Event::Received(Packet::Data(DataPacket::new(AdjId(1000), vec![]))) } -fn fault_from(from: SocketAddr) -> UdpError { - UdpError::Fault { from } +/// 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)), } } @@ -134,23 +146,50 @@ fn as_link(fake: &Arc) -> Option> { 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 a_batch_reaches_logging_and_pipeline_as_the_same_copy() -> TestResult { +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, boards(), None); + let _event = spawn(config, channels.event, pod_data(), index(), None); - let ToLogging::Received(logged) = next(&mut channels.logging).await? else { - unreachable!("the first thing logging gets is the batch"); - }; - let ToPipeline::Received(shown) = next(&mut channels.pipeline).await? else { - unreachable!("the first thing pipeline gets is the batch"); - }; - assert_eq!(logged.len(), 3); - assert!(Arc::ptr_eq(&logged, &shown), "one copy, shared"); + 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(()) } @@ -161,8 +200,8 @@ async fn errors_come_first_then_tcp_then_udp() -> TestResult { // 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())).await?; - let _event = spawn(config, channels.event, boards(), None); + 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"); @@ -176,12 +215,12 @@ async fn errors_come_first_then_tcp_then_udp() -> TestResult { let ToPipeline::Received(tcp) = next(&mut channels.pipeline).await? else { unreachable!("then the TCP notification"); }; - assert!(matches!(tcp[0].event, Event::Connected)); + assert!(matches!(tcp.event, Event::Connected)); let ToPipeline::Received(udp) = next(&mut channels.pipeline).await? else { unreachable!("then the UDP notification"); }; - assert!(matches!(udp[0].event, Event::Received(Packet::Data(_)))); + assert!(matches!(udp.event, Event::Received(Packet::Data(_)))); Ok(()) } @@ -192,24 +231,18 @@ async fn a_fatal_error_passes_on_what_was_queued_and_stops() -> TestResult { channels.udp.notify(HVSCU, data()).await?; channels.udp.notify(HVSCU, data()).await?; channels.udp.report(decode_error()).await?; - let event = spawn(config, channels.event, boards(), None); + 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), "resolved from the address"); + 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. - let ToPipeline::Received(shown) = next(&mut channels.pipeline).await? else { - unreachable!("then what was queued"); - }; - let ToLogging::Received(logged) = next(&mut channels.logging).await? else { - unreachable!("logging gets what was queued too"); - }; - assert_eq!(shown.len(), 2); - assert_eq!(logged.len(), 2); + // 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"); @@ -219,16 +252,16 @@ async fn a_fatal_error_passes_on_what_was_queued_and_stops() -> TestResult { } #[tokio::test] -async fn a_board_fault_is_shown_once_per_board_and_the_fault_sent_once() -> TestResult { +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, boards(), as_link(&fake)); + let event = spawn(config, channels.event, pod_data(), index(), as_link(&fake)); for _ in 0..3 { - channels.udp.report(fault_from(hvscu_addr())).await?; + channels.udp.report(fault_from(hvscu_addr(), HVSCU)).await?; } - channels.udp.report(fault_from(vcu_addr())).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?; @@ -245,13 +278,8 @@ async fn a_board_fault_is_shown_once_per_board_and_the_fault_sent_once() -> Test assert_eq!(second.board, Some(VCU)); assert_eq!(first.kind, ProblemKind::Shown); - eventually(|| fake.faults.load(Ordering::SeqCst) == 1).await?; - sleep(Duration::from_millis(50)).await; - assert_eq!( - fake.faults.load(Ordering::SeqCst), - 1, - "the fault goes out once" - ); + // 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" @@ -260,19 +288,83 @@ async fn a_board_fault_is_shown_once_per_board_and_the_fault_sent_once() -> Test } #[tokio::test] -async fn forwarding_a_board_fault_can_be_turned_off() -> TestResult { +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 { - forward_board_faults: false, + propagate_fault: false, ..EventConfig::default() }; let mut channels = channels(&config); let fake = Arc::new(FakeTcp::default()); - let _event = spawn(config, channels.event, boards(), as_link(&fake)); + let _event = spawn(config, channels.event, pod_data(), index(), as_link(&fake)); - channels.udp.report(fault_from(hvscu_addr())).await?; + 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(()) @@ -291,13 +383,13 @@ async fn closed_queues_do_not_hide_the_others() -> TestResult { pipeline: _pipeline, } = channels(&config); drop((tcp, orders, problems)); - let _event = spawn(config, event, boards(), None); + let _event = spawn(config, event, pod_data(), index(), None); udp.notify(HVSCU, data()).await?; - let ToLogging::Received(batch) = next(&mut logging).await? else { + let ToLogging::Received(notification) = next(&mut logging).await? else { unreachable!("the UDP notification gets through"); }; - assert_eq!(batch.len(), 1); + assert!(matches!(notification.event, Event::Received(_))); Ok(()) } @@ -305,7 +397,7 @@ async fn closed_queues_do_not_hide_the_others() -> TestResult { async fn without_tcp_an_order_fails() -> TestResult { let config = EventConfig::default(); let mut channels = channels(&config); - let _event = spawn(config, channels.event, boards(), None); + 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 { @@ -317,17 +409,23 @@ async fn without_tcp_an_order_fails() -> TestResult { } #[tokio::test] -async fn a_written_order_is_logged() -> TestResult { +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, boards(), as_link(&fake)); + 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, HVSCU); + 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(()) } @@ -340,7 +438,7 @@ async fn an_order_that_was_not_written_is_shown() -> TestResult { refuse_orders: Some("board not connected"), ..FakeTcp::default() }); - let _event = spawn(config, channels.event, boards(), as_link(&fake)); + 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 { @@ -351,14 +449,23 @@ async fn an_order_that_was_not_written_is_shown() -> TestResult { } #[tokio::test] -async fn order_id_0_is_the_fault() -> TestResult { +async fn order_id_0_is_the_fault_and_the_front_is_told() -> TestResult { let config = EventConfig::default(); - let channels = channels(&config); + let mut channels = channels(&config); let fake = Arc::new(FakeTcp::default()); - let _event = spawn(config, channels.event, boards(), as_link(&fake)); + 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?; + 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, @@ -367,6 +474,61 @@ async fn order_id_0_is_the_fault() -> TestResult { 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(); @@ -375,9 +537,9 @@ async fn a_fault_that_misses_boards_is_shown() -> TestResult { unreachable: vec![VCU], ..FakeTcp::default() }); - let _event = spawn(config, channels.event, boards(), as_link(&fake)); + let _event = spawn(config, channels.event, pod_data(), index(), as_link(&fake)); - channels.udp.report(fault_from(hvscu_addr())).await?; + 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"); }; @@ -394,7 +556,7 @@ async fn a_fault_that_misses_boards_is_shown() -> TestResult { 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, boards(), None); + 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"); @@ -428,7 +590,7 @@ async fn when_logging_stops_event_stops_and_tells_pipeline() -> TestResult { mut pipeline, } = channels(&config); drop(logging); - let event = spawn(config, event, boards(), None); + let event = spawn(config, event, pod_data(), index(), None); udp.notify(HVSCU, data()).await?; let ToPipeline::Problem(problem) = next(&mut pipeline).await? else { @@ -458,12 +620,10 @@ async fn when_net_closes_what_was_left_is_passed_on_and_event_stops() -> TestRes udp.notify(HVSCU, data()).await?; udp.notify(HVSCU, data()).await?; drop((udp, tcp)); - let event = spawn(config, event, boards(), None); + let event = spawn(config, event, pod_data(), index(), None); - let ToLogging::Received(batch) = next(&mut logging).await? else { - unreachable!("what was queued gets through"); - }; - assert_eq!(batch.len(), 2); + // What was queued gets through. + logged(&mut logging, 2).await?; let Stop::NetGone = stops(event).await? else { unreachable!("both transports are gone"); @@ -484,7 +644,7 @@ async fn a_fault_that_never_goes_out_does_not_block_the_stop() -> TestResult { fault_hangs: true, ..FakeTcp::default() }); - let event = spawn(config, channels.event, boards(), as_link(&fake)); + 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 { From 6c0ea2b06f4f061183da294e47861dde4d5ad660 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Tue, 1 Dec 2026 12:57:44 +0100 Subject: [PATCH 11/14] feat(backend, station): run UDP through event in main, with stand-ins for logging and pipeline --- backend/crates/station/README.md | 8 + backend/crates/station/src/main.rs | 360 ++++++++++++++++++++++++++++- backend/readme-demo.md | 70 ++++-- 3 files changed, 410 insertions(+), 28 deletions(-) diff --git a/backend/crates/station/README.md b/backend/crates/station/README.md index 00e8661df..aefa4aca6 100644 --- a/backend/crates/station/README.md +++ b/backend/crates/station/README.md @@ -15,3 +15,11 @@ cargo run -p station -- --config ./dev-config.toml *(Pendiente: crear `dev-config.toml` y `config.toml`, portados de `backend_old/cmd/`.)* +Mientras tanto, `src/main.rs` descarga el ADJ, escucha en el puerto UDP y +pasa lo que llega por `event` a dos sustitutos de `logging` y `pipeline`: +`cargo run -p station --release`. Ver +[`../../readme-demo.md`](../../readme-demo.md). + +`event`, la comunicación entre los módulos de station, está documentado en +[`src/event/README.md`](src/event/README.md). + diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index d872008d1..911ea49b4 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -1,13 +1,361 @@ -//! 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. +mod event; + +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 event::{ProblemKind, Stop, ToLogging, ToPipeline}; + +/// Branch of the ADJ repository that is downloaded. +const ADJ_BRANCH: &str = "adjv3-software"; + +/// `SO_RCVBUF` requested from the OS: see `UdpConfig::recv_buffer`. +const RECV_BUFFER: usize = 2 * 1024 * 1024; + +/// How often the logging stand-in writes its summary. +const SUMMARY_EVERY: Duration = Duration::from_secs(1); + +/// How long the stand-ins get to finish what they have queued when stopping. +const SHUTDOWN_GRACE: Duration = Duration::from_secs(5); + +/// Everything that stops the program before `event` has a say. +#[derive(Debug, thiserror::Error)] +enum StartError { + #[error("could not get the ADJ (branch {ADJ_BRANCH})")] + Download(#[source] GitError), + #[error("the downloaded ADJ has no working directory")] + NoWorkdir, + #[error("could not load the ADJ from {path}")] + Load { + path: PathBuf, + #[source] + source: LoadError, + }, + #[error("the ADJ's general_info.json has no `{0}`")] + MissingInAdj(&'static str), + #[error("could not start tokio")] + Runtime(#[source] std::io::Error), + #[error("could not listen for Ctrl+C")] + CtrlC(#[source] std::io::Error), + #[error("could not open the UDP port")] + Bind(#[source] UdpError), + #[error("the event task failed")] + Event(#[source] JoinError), +} + +fn main() -> ExitCode { let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); tracing_subscriber::fmt().with_env_filter(filter).init(); - tracing::info!("iniciando demo de station"); - let name = std::env::args().nth(1).unwrap_or_else(|| "World".into()); - let _greeting = software_core::hello_world::greet(&name); - tracing::info!("demo finalizada"); + match run() { + Ok(code) => code, + Err(error) => { + error!(error = %event::full_message(&error), "stopping"); + ExitCode::FAILURE + } + } +} + +fn run() -> Result { + let adj = download_adj()?; + let addr = udp_addr(&adj)?; + let index = Arc::new(Index::new(&adj.pod_data, Some(&adj.info.message_levels))); + let pod_data = Arc::new(adj.pod_data); + + let runtime = tokio::runtime::Runtime::new().map_err(StartError::Runtime)?; + runtime.block_on(serve(addr, index, pod_data)) +} + +/// Downloads the [`ADJ_BRANCH`] branch and loads it. +/// +/// `update_adj` blocks while downloading (network and disk), so it is called +/// before tokio starts. +fn download_adj() -> Result { + let commit = git::update_adj(None, ADJ_BRANCH).map_err(StartError::Download)?; + + // `update_adj` does not return the folder; it is read from the repository. + let repo = git::open_repo(None).map_err(StartError::Download)?; + let path = repo.workdir().ok_or(StartError::NoWorkdir)?.to_path_buf(); + + let adj = adj::load_from_dir(&path).map_err(|source| StartError::Load { + path: path.clone(), + source, + })?; + info!( + branch = ADJ_BRANCH, + %commit, + path = %path.display(), + boards = adj.pod_data.boards.len(), + "ADJ loaded" + ); + Ok(adj) +} + +/// Where to listen: the backend's IP and the UDP port, as the ADJ gives them. +fn udp_addr(adj: &Adj) -> Result { + let ip = adj + .info + .addresses + .get("backend") + .ok_or(StartError::MissingInAdj("addresses.backend"))?; + let port = adj + .info + .ports + .get("UDP") + .ok_or(StartError::MissingInAdj("ports.UDP"))?; + Ok(SocketAddr::new(*ip, port.0)) +} + +/// Creates every queue, spawns every task, and shuts everything down in order +/// when `event` stops or on Ctrl+C. +async fn serve( + addr: SocketAddr, + index: Arc, + pod_data: Arc, +) -> Result { + let config = event::EventConfig::default(); + let event::Channels { + udp, + tcp, + event: ends, + orders, + problems, + logging, + pipeline, + } = event::channels(&config); + + // Not built yet: TCP, websocket, and modules that report problems. + // Dropping their ends closes those queues, and event stops watching them. + drop((tcp, orders, problems)); + + let udp_task = spawn_udp( + UdpConfig { + addr, + recv_buffer: RECV_BUFFER, + boards: pod_data.boards_by_ip(), + }, + index.clone(), + udp, + ) + .map_err(StartError::Bind)?; + info!(%addr, "listening on UDP (Ctrl+C to stop)"); + + let logging_task = tokio::spawn(stand_in_logging(logging, pod_data.clone())); + let pipeline_task = tokio::spawn(stand_in_pipeline(pipeline, pod_data.clone())); + let mut event_task = event::spawn(config, ends, pod_data, index, None); + + let (stop, by_ctrl_c) = tokio::select! { + stop = &mut event_task => (stop, false), + signal = tokio::signal::ctrl_c() => { + signal.map_err(StartError::CtrlC)?; + info!("Ctrl+C, stopping"); + // Stopping UDP closes its queues: event passes on what is left + // and stops with `Stop::NetGone`. + udp_task.abort(); + (event_task.await, true) + } + }; + udp_task.abort(); + + // event is done, so logging's and pipeline's queues are closed: they + // finish what they have and end on their own. + let finished = tokio::time::timeout(SHUTDOWN_GRACE, async { + let _ = logging_task.await; + let _ = pipeline_task.await; + }) + .await; + if finished.is_err() { + warn!(grace = ?SHUTDOWN_GRACE, "logging and pipeline did not finish in time"); + } + + match stop.map_err(StartError::Event)? { + Stop::Fatal(problem) => { + info!(reason = %problem.text, "stopped after a fatal error"); + Ok(ExitCode::FAILURE) + } + Stop::NetGone if by_ctrl_c => { + info!("stopped"); + Ok(ExitCode::SUCCESS) + } + Stop::NetGone => { + error!("UDP stopped on its own"); + Ok(ExitCode::FAILURE) + } + } +} + +/// Stands in for `logging`: counts what it would record, per board, and +/// writes a summary every second. +async fn stand_in_logging(mut queue: mpsc::Receiver, pod_data: Arc) { + let mut summary = tokio::time::interval(SUMMARY_EVERY); + summary.set_missed_tick_behavior(MissedTickBehavior::Delay); + let mut counts: HashMap = HashMap::new(); + + loop { + tokio::select! { + // The summary first, or under load it would never get its turn. + biased; + _ = summary.tick() => log_summary(&mut counts, &pod_data), + message = queue.recv() => match message { + None => break, + Some(ToLogging::Received(notification)) => { + count_and_trace(¬ification, &mut counts, &pod_data); + } + Some(ToLogging::OrderSent { at, board, order }) => { + let to = order_target(board, &pod_data); + info!(to, id = ?order.id, at = %clock(at), "order sent"); + } + }, + } + } + log_summary(&mut counts, &pod_data); +} + +/// Stands in for `pipeline`: writes to the log what the front would show. +async fn stand_in_pipeline(mut queue: mpsc::Receiver, pod_data: Arc) { + let mut received: u64 = 0; + while let Some(message) = queue.recv().await { + match message { + // The front would get counts, cycle times and averages; here + // packets are only counted, to check that nothing went missing. + ToPipeline::Received(notification) => { + received += 1; + let board = name(&pod_data, notification.board); + match notification.event { + Event::Connected => info!(board, "front: board connected"), + Event::Disconnected => warn!(board, "front: board disconnected"), + Event::Received(_) => {} + } + } + ToPipeline::Problem(problem) => { + let board = problem.board.map(|board| name(&pod_data, board)); + match problem.kind { + ProblemKind::Fatal => { + error!(board = ?board, text = %problem.text, "front: fatal error"); + } + ProblemKind::Shown => { + warn!(board = ?board, text = %problem.text, "front: problem") + } + // event only traces these: they never reach pipeline. + ProblemKind::Silent => {} + } + } + // The front shows both as a message from the backend. + ToPipeline::OrderSent { at, board, order } => { + let to = order_target(board, &pod_data); + info!(to, id = ?order.id, at = %clock(at), "front: order sent"); + } + ToPipeline::OrderFailed { at, order, reason } => { + warn!(id = ?order.id, %reason, at = %clock(at), "front: order not sent"); + } + } + } + info!(notifications = received, "pipeline stand-in finished"); +} + +/// Who an order went to: its board, or every board for the fault. +fn order_target(board: Option, pod_data: &PodData) -> String { + match board { + Some(board) => name(pod_data, board), + None => "every board".to_string(), + } +} + +/// The board's name as the ADJ declares it, or its id if it does not. +fn name(pod_data: &PodData, board: BoardId) -> String { + pod_data + .board_name(board) + .map_or_else(|| format!("{board:?}"), str::to_owned) +} + +/// `at` as seconds since the Unix epoch, with milliseconds, for the log. +fn clock(at: SystemTime) -> String { + match at.duration_since(SystemTime::UNIX_EPOCH) { + Ok(since) => format!("{}.{:03}", since.as_secs(), since.subsec_millis()), + Err(_) => "before 1970".to_string(), + } +} + +/// Counts the notification for the summary and, with `RUST_LOG=debug`, +/// writes it. +fn count_and_trace( + notification: &Notification, + counts: &mut HashMap, + pod_data: &PodData, +) { + *counts.entry(notification.board).or_insert(0) += 1; + + // `debug!`'s fields are only computed when debug is enabled. + match ¬ification.event { + Event::Received(Packet::Data(packet)) => debug!( + board = %name(pod_data, notification.board), + id = ?packet.id, + values = ?packet.values, + "packet" + ), + other => debug!( + board = %name(pod_data, notification.board), + event = ?other, + "notification" + ), + } +} + +/// Writes how many packets arrived from each board since the last summary. +/// Writes nothing if none did. +fn log_summary(counts: &mut HashMap, pod_data: &PodData) { + let total: u64 = counts.values().sum(); + if total == 0 { + return; + } + let mut per_board: Vec = counts + .iter() + .map(|(&board, count)| format!("{}={count}", name(pod_data, board))) + .collect(); + per_board.sort(); + info!(total, boards = %per_board.join(" "), "packets in the last second"); + counts.clear(); } diff --git a/backend/readme-demo.md b/backend/readme-demo.md index 050e911ac..644b186e6 100644 --- a/backend/readme-demo.md +++ b/backend/readme-demo.md @@ -1,22 +1,39 @@ -# Demo: core → station + tracing +# Demo: UDP → event → logging y pipeline + +`crates/station/src/main.rs` junta, por ahora, las piezas que ya existen: + +1. `core::git::update_adj` descarga el ADJ de la rama `adjv3-software`. +2. `core::adj::load_from_dir` lo carga. +3. Con él se construye el `core::protocol::Index`. +4. `core::net::udp::spawn_udp` abre el puerto UDP del ADJ: + `addresses["backend"]` y `ports["UDP"]` de `general_info.json`. +5. `station::event` (ver [`crates/station/src/event/README.md`](crates/station/src/event/README.md)) + crea todas las colas, aplica las reglas de errores y reparte lo que llega + a dos sustitutos de `logging` y `pipeline`, que todavía no existen: el de + logging cuenta los paquetes por placa y escribe un resumen por segundo; el + de pipeline escribe en el log lo que vería el front (problemas, órdenes que + no salieron). Desde `software/backend`, con Rust 1.98.0 y Cargo instalados (la primera ejecución descarga las dependencias): ```sh -# Ejecutar: muestra el saludo y el ciclo de vida a nivel INFO. -cargo run -p station -cargo run -p station -- "Hyperloop UPV" - -# Mostrar también DEBUG del módulo, manteniendo INFO en station. -RUST_LOG=info,software_core::hello_world=debug cargo run -p station -- "Lucía" +# Ejecutar: una línea INFO por segundo con los paquetes recibidos por placa. +cargo run -p station --release -# Filtrar todos los eventos de esta demo (no emite errores). -RUST_LOG=error cargo run -p station +# Además, cada paquete con sus valores decodificados. +# (RUST_LOG=debug a secas también saca el detalle de gix durante la descarga.) +RUST_LOG=info,station=debug cargo run -p station --release -# Tests unitarios y ejemplo de documentación ejecutable (doctest). +# Tests unitarios y doctests (incluye los de UDP, con socket real en loopback). cargo test --workspace +# Prueba de carga de UDP (25 Mbit/s en paquetes de 76 bytes), ignorada por defecto. +cargo test -p software-core --features net --release manual_udp_load -- --ignored --nocapture + +# Prueba de rendimiento de event (un millón de avisos), ignorada por defecto. +cargo test -p station --release manual_event -- --ignored --nocapture + # Generar documentación HTML de la API. cargo doc --workspace --no-deps @@ -25,17 +42,26 @@ cargo fmt --all -- --check cargo clippy --workspace --all-targets -- -D warnings ``` -Abre `target/doc/software_core/hello_world/index.html` para ver la API. +Cómo se comporta: + +- **Un error fatal lo para** y sale con código 1: un datagrama que no se + puede decodificar o perder el socket. El error lleva el nombre de la placa, + sacado de la IP de quien lo mandó. +- **Un fault que mande una placa** (paquete id 0, que UDP reconoce sin mirar + el ADJ) **no lo para**: se muestra el primero de cada placa. Reenviarlo al + resto necesita TCP, que todavía no está, así que solo queda en la traza. +- **Ctrl+C** lo para limpio y sale con código 0. +- Para probarlo en local hace falta algo que mande paquetes a la dirección + del ADJ (`127.0.0.9:50400` en `adjv3-software`), como un simulador de + placas. -- `crates/core/src/hello_world.rs`: `greet(&str) -> String`, con rustdoc, -- `crates/core/src/lib.rs`: exporta el módulo público. -- `crates/station/src/main.rs`: inicializa el subscriber una sola vez y llama a `greet`. -- `#[tracing::instrument]` crea el span `hello_world`; los eventos incluyen - el destinatario y campos estructurados como `greeting` o `used_default`. - `INFO` muestra el saludo; `DEBUG` permite inspeccionar la elección del destinatario. -- Core solo emite eventos: sin subscriber, devuelve igualmente el saludo. - Los tests comprueban ese resultado sin configurar logging global. +Ojo: el ADJ va a la carpeta por defecto de `core::git` +(`~/.cache/hyperloop-control-station/adj` en Linux), la misma que usa el +backend de Go, y cada ejecución con conexión la sustituye por +`adjv3-software`. -Esta demo termina tras saludar; todavía no arranca servidores ni carga TOML. -Usa los comandos Cargo de arriba: los scripts `pnpm dev` están preparados para -la futura configuración del backend, que esta demo no interpreta. +`crates/core/src/hello_world.rs` sigue en core como ejemplo de cómo se +escribe un módulo (docs, trazas, tests, doctest), pero `station` ya no lo +usa. Esta demo todavía no arranca TCP, websocket ni HTTP, ni carga TOML: los scripts +`pnpm dev` están preparados para la futura configuración del backend, que +esta demo no interpreta. From 5b507ddd7f8a0e1132eaa61d1664a4013c849081 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Tue, 1 Dec 2026 20:32:07 +0100 Subject: [PATCH 12/14] docs(backend): keep the Spanish demo docs out of this PR --- backend/crates/station/README.md | 8 ---- backend/readme-demo.md | 70 ++++++++++---------------------- 2 files changed, 22 insertions(+), 56 deletions(-) diff --git a/backend/crates/station/README.md b/backend/crates/station/README.md index aefa4aca6..00e8661df 100644 --- a/backend/crates/station/README.md +++ b/backend/crates/station/README.md @@ -15,11 +15,3 @@ cargo run -p station -- --config ./dev-config.toml *(Pendiente: crear `dev-config.toml` y `config.toml`, portados de `backend_old/cmd/`.)* -Mientras tanto, `src/main.rs` descarga el ADJ, escucha en el puerto UDP y -pasa lo que llega por `event` a dos sustitutos de `logging` y `pipeline`: -`cargo run -p station --release`. Ver -[`../../readme-demo.md`](../../readme-demo.md). - -`event`, la comunicación entre los módulos de station, está documentado en -[`src/event/README.md`](src/event/README.md). - diff --git a/backend/readme-demo.md b/backend/readme-demo.md index 644b186e6..050e911ac 100644 --- a/backend/readme-demo.md +++ b/backend/readme-demo.md @@ -1,38 +1,21 @@ -# Demo: UDP → event → logging y pipeline - -`crates/station/src/main.rs` junta, por ahora, las piezas que ya existen: - -1. `core::git::update_adj` descarga el ADJ de la rama `adjv3-software`. -2. `core::adj::load_from_dir` lo carga. -3. Con él se construye el `core::protocol::Index`. -4. `core::net::udp::spawn_udp` abre el puerto UDP del ADJ: - `addresses["backend"]` y `ports["UDP"]` de `general_info.json`. -5. `station::event` (ver [`crates/station/src/event/README.md`](crates/station/src/event/README.md)) - crea todas las colas, aplica las reglas de errores y reparte lo que llega - a dos sustitutos de `logging` y `pipeline`, que todavía no existen: el de - logging cuenta los paquetes por placa y escribe un resumen por segundo; el - de pipeline escribe en el log lo que vería el front (problemas, órdenes que - no salieron). +# Demo: core → station + tracing Desde `software/backend`, con Rust 1.98.0 y Cargo instalados (la primera ejecución descarga las dependencias): ```sh -# Ejecutar: una línea INFO por segundo con los paquetes recibidos por placa. -cargo run -p station --release - -# Además, cada paquete con sus valores decodificados. -# (RUST_LOG=debug a secas también saca el detalle de gix durante la descarga.) -RUST_LOG=info,station=debug cargo run -p station --release +# Ejecutar: muestra el saludo y el ciclo de vida a nivel INFO. +cargo run -p station +cargo run -p station -- "Hyperloop UPV" -# Tests unitarios y doctests (incluye los de UDP, con socket real en loopback). -cargo test --workspace +# Mostrar también DEBUG del módulo, manteniendo INFO en station. +RUST_LOG=info,software_core::hello_world=debug cargo run -p station -- "Lucía" -# Prueba de carga de UDP (25 Mbit/s en paquetes de 76 bytes), ignorada por defecto. -cargo test -p software-core --features net --release manual_udp_load -- --ignored --nocapture +# Filtrar todos los eventos de esta demo (no emite errores). +RUST_LOG=error cargo run -p station -# Prueba de rendimiento de event (un millón de avisos), ignorada por defecto. -cargo test -p station --release manual_event -- --ignored --nocapture +# Tests unitarios y ejemplo de documentación ejecutable (doctest). +cargo test --workspace # Generar documentación HTML de la API. cargo doc --workspace --no-deps @@ -42,26 +25,17 @@ cargo fmt --all -- --check cargo clippy --workspace --all-targets -- -D warnings ``` -Cómo se comporta: - -- **Un error fatal lo para** y sale con código 1: un datagrama que no se - puede decodificar o perder el socket. El error lleva el nombre de la placa, - sacado de la IP de quien lo mandó. -- **Un fault que mande una placa** (paquete id 0, que UDP reconoce sin mirar - el ADJ) **no lo para**: se muestra el primero de cada placa. Reenviarlo al - resto necesita TCP, que todavía no está, así que solo queda en la traza. -- **Ctrl+C** lo para limpio y sale con código 0. -- Para probarlo en local hace falta algo que mande paquetes a la dirección - del ADJ (`127.0.0.9:50400` en `adjv3-software`), como un simulador de - placas. +Abre `target/doc/software_core/hello_world/index.html` para ver la API. -Ojo: el ADJ va a la carpeta por defecto de `core::git` -(`~/.cache/hyperloop-control-station/adj` en Linux), la misma que usa el -backend de Go, y cada ejecución con conexión la sustituye por -`adjv3-software`. +- `crates/core/src/hello_world.rs`: `greet(&str) -> String`, con rustdoc, +- `crates/core/src/lib.rs`: exporta el módulo público. +- `crates/station/src/main.rs`: inicializa el subscriber una sola vez y llama a `greet`. +- `#[tracing::instrument]` crea el span `hello_world`; los eventos incluyen + el destinatario y campos estructurados como `greeting` o `used_default`. + `INFO` muestra el saludo; `DEBUG` permite inspeccionar la elección del destinatario. +- Core solo emite eventos: sin subscriber, devuelve igualmente el saludo. + Los tests comprueban ese resultado sin configurar logging global. -`crates/core/src/hello_world.rs` sigue en core como ejemplo de cómo se -escribe un módulo (docs, trazas, tests, doctest), pero `station` ya no lo -usa. Esta demo todavía no arranca TCP, websocket ni HTTP, ni carga TOML: los scripts -`pnpm dev` están preparados para la futura configuración del backend, que -esta demo no interpreta. +Esta demo termina tras saludar; todavía no arranca servidores ni carga TOML. +Usa los comandos Cargo de arriba: los scripts `pnpm dev` están preparados para +la futura configuración del backend, que esta demo no interpreta. From 381ae81bb7c28aaa3ee2a13064ab18f9d9a80d0e Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Tue, 1 Dec 2026 20:38:58 +0100 Subject: [PATCH 13/14] refactor(backend, station): declare station's modules in lib.rs, keep main.rs as the wiring --- backend/crates/station/src/lib.rs | 12 ++++++++++++ backend/crates/station/src/main.rs | 4 +--- 2 files changed, 13 insertions(+), 3 deletions(-) create mode 100644 backend/crates/station/src/lib.rs diff --git a/backend/crates/station/src/lib.rs b/backend/crates/station/src/lib.rs new file mode 100644 index 000000000..9eb696501 --- /dev/null +++ b/backend/crates/station/src/lib.rs @@ -0,0 +1,12 @@ +//! The station backend's modules. +//! +//! Every module lives here, so that each one compiles and is tested on its +//! own while it is being built, whether or not `main` wires it in yet. +//! `main.rs` only starts them and connects them. +//! +//! - [`event`]: the communication between the modules (see +//! `src/event/README.md`). +//! - [`http`]: the HTTP API (ADJ catalogs and the WebSocket upgrade). + +pub mod event; +pub mod http; diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index 911ea49b4..bf39e02bd 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -26,8 +26,6 @@ //! backend uses: whatever was there is replaced by the [`ADJ_BRANCH`] branch. //! Offline, whatever is in that folder is used, whichever branch it is. -mod event; - use std::collections::HashMap; use std::net::SocketAddr; use std::path::PathBuf; @@ -47,7 +45,7 @@ use tokio::time::MissedTickBehavior; use tracing::{debug, error, info, warn}; use tracing_subscriber::EnvFilter; -use event::{ProblemKind, Stop, ToLogging, ToPipeline}; +use station::event::{self, ProblemKind, Stop, ToLogging, ToPipeline}; /// Branch of the ADJ repository that is downloaded. const ADJ_BRANCH: &str = "adjv3-software"; From d89de542640160e4664102692dadc3a0a4642522 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Tue, 1 Dec 2026 20:46:04 +0100 Subject: [PATCH 14/14] docs(backend, udp): explain what Lookups resolves and where its IP map comes from --- backend/crates/core/src/net/udp.rs | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/backend/crates/core/src/net/udp.rs b/backend/crates/core/src/net/udp.rs index a4c719387..87eabcbb3 100644 --- a/backend/crates/core/src/net/udp.rs +++ b/backend/crates/core/src/net/udp.rs @@ -292,17 +292,38 @@ async fn receive_telemetry( /// raises a fault itself (`SendFault`). const FAULT_ID: [u8; 2] = 0u16.to_le_bytes(); -/// What the receive loop looks things up in, both read-only. +/// 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 address to its board, for errors: see [`UdpConfig::boards`]. + /// A sender's IP to its board, for the datagrams that have no id. boards: &'a HashMap, } impl Lookups<'_> { - /// The board `from` belongs to, if any. + /// 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() }