Skip to content
55 changes: 55 additions & 0 deletions backend/crates/core/src/model/board.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,27 @@ pub struct PodData {
pub boards: HashMap<BoardId, Board>,
}

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<IpAddr, BoardId> {
self.boards
.values()
.map(|board| (board.ip, board.id))
.collect()
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -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);
}
}
11 changes: 6 additions & 5 deletions backend/crates/core/src/net/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -104,7 +105,7 @@ submodule's own error: nobody outside knows which of its variants are fatal.
| | `tcp` | `udp` |
|---|---|---|
| Entry point | `spawn(Config, Arc<Index>, Reporter) -> Handles` | `spawn_udp(UdpConfig, Arc<Index>, Reporter) -> Result<JoinHandle<()>, 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 |
Expand All @@ -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:
Expand Down
14 changes: 8 additions & 6 deletions backend/crates/core/src/net/report.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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]
Expand Down
125 changes: 99 additions & 26 deletions backend/crates/core/src/net/udp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand All @@ -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`.
Expand Down Expand Up @@ -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<IpAddr, BoardId>,
}

/// Binds the shared socket and spawns the receive loop.
Expand All @@ -160,13 +175,13 @@ pub fn spawn_udp(
adj: Arc<Index>,
reporter: Reporter,
) -> Result<JoinHandle<()>, 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<tokio::net::UdpSocket, UdpError> {
fn bind_telemetry_socket(config: &UdpConfig) -> Result<tokio::net::UdpSocket, UdpError> {
// 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,
Expand Down Expand Up @@ -236,15 +251,24 @@ fn bind_telemetry_socket(config: UdpConfig) -> Result<tokio::net::UdpSocket, Udp
}

/// Main UDP loop: reads datagrams into a reusable 64 KiB buffer, decodes in-place, and reports.
async fn receive_telemetry(socket: tokio::net::UdpSocket, adj: Arc<Index>, reporter: Reporter) {
async fn receive_telemetry(
socket: tokio::net::UdpSocket,
adj: Arc<Index>,
boards: HashMap<IpAddr, BoardId>,
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 !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;
}
Expand All @@ -268,33 +292,79 @@ async fn receive_telemetry(socket: tokio::net::UdpSocket, adj: Arc<Index>, repor
/// raises a fault itself (`SendFault`).
const FAULT_ID: [u8; 2] = 0u16.to_le_bytes();

/// Decodes a single datagram slice against `adj` and forwards the result or error to `reporter`.
/// The two read-only tables the receive loop resolves a datagram against,
/// bundled so that [`decode_and_report`] takes one argument for both.
///
/// They answer the same question, "which board is this from?", for two
/// kinds of datagram:
///
/// - **One that decodes** carries an id, and the [`Index`] leads from the id
/// to its [`crate::model::PacketDef`], which names its board.
/// - **One that never gets an id**, a fault (packet id 0) or a datagram that
/// fails to decode, only has the sender's address. `boards` leads from
/// that address to its board, so that its error can still name the board
/// ([`UdpError::Fault`], [`UdpError::Decode`]).
///
/// `boards` is the ADJ's own data, not a second definition of it: it is
/// built once from [`crate::model::PodData`] with
/// [`crate::model::PodData::boards_by_ip`], and comes in through
/// [`UdpConfig::boards`]. It is not in the [`Index`] because the index knows
/// nothing about addresses on purpose (see its docs), and it is not looked up
/// in `PodData` directly so that UDP gets only what it uses, not the whole
/// pod.
#[derive(Debug, Clone, Copy)]
struct Lookups<'a> {
/// A decoded id to its definition, and through it to its board.
adj: &'a Index,
/// A sender's IP to its board, for the datagrams that have no id.
boards: &'a HashMap<IpAddr, BoardId>,
}

impl Lookups<'_> {
/// The board `from` belongs to, or `None` if its IP is no board's. Only
/// the IP counts: a board is identified by its address, not by the port
/// it sends from.
fn board_at(&self, from: SocketAddr) -> Option<BoardId> {
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();
}
};
Expand All @@ -305,7 +375,7 @@ async fn decode_and_report(
// run; it is handled rather than unwrapped because the decode lives
// in another module. One extra `HashMap` lookup per datagram is not
// worth changing `protocol`'s API to avoid.
let Some(packet_def) = adj.packet(packet.id) else {
let Some(packet_def) = lookups.adj.packet(packet.id) else {
warn!(id = ?packet.id, "decoded packet id not in index");
return true;
};
Expand Down Expand Up @@ -370,11 +440,11 @@ impl TraceRateLimit {
/// Something that went wrong on the shared UDP socket, or that a board
/// says went wrong ([`UdpError::Fault`]).
///
/// No [`crate::model::BoardId`] in any variant, on purpose: the socket
/// belongs to no board, and a datagram that fails to decode may not
/// resolve to one at all — [`UdpError::Decode`] and [`UdpError::Fault`]
/// carry the address the datagram came from, which is the only identity
/// that always exists.
/// [`UdpError::Decode`] and [`UdpError::Fault`] concern one datagram, so
/// they carry the address it came from, the only identity that always
/// exists, and the board that address belongs to, when it belongs to one
/// (see [`UdpConfig::boards`]). [`UdpError::Bind`] and [`UdpError::Recv`]
/// concern the socket, which belongs to no board.
#[derive(Debug, thiserror::Error)]
pub enum UdpError {
/// The socket could not be bound, so no telemetry will arrive at all.
Expand All @@ -400,9 +470,10 @@ pub enum UdpError {
/// [`UdpError::is_fatal`].
#[error("could not decode a datagram from {from}")]
Decode {
/// Where the datagram came from — there may be no board to
/// attribute it to.
/// Where the datagram came from.
from: SocketAddr,
/// The board `from` belongs to; `None` if it belongs to none.
board: Option<BoardId>,
/// What [`crate::protocol`] said about it.
#[source]
source: DecodeError,
Expand All @@ -413,9 +484,11 @@ pub enum UdpError {
/// arrived fine — but the pod telling the backend it is in trouble.
#[error("the board at {from} signalled a fault (packet id 0)")]
Fault {
/// Where the fault came from: the board's address, since a fault
/// carries nothing else that says which board sent it.
/// Where the fault came from. A fault carries nothing else that
/// says which board sent it.
from: SocketAddr,
/// The board `from` belongs to; `None` if it belongs to none.
board: Option<BoardId>,
},
}

Expand Down
8 changes: 7 additions & 1 deletion backend/crates/core/src/net/udp/manual_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading