Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
c6679ce
wip: net
JavierRibaldelRio Oct 18, 2026
7b98b80
wip(backend, net): upload cargo.toml
JavierRibaldelRio Oct 18, 2026
7f1ad44
Feat(backend, net, udp):
Nov 8, 2026
ba36fea
Feat(backend, net, udp): Amended implementation to ditch the use of a…
GaziH Nov 17, 2026
85be313
Merge origin/new-backend into backend/net-udp
JavierRibaldelRio Nov 25, 2026
c11853c
refactor(backend, udp)
JavierRibaldelRio Nov 25, 2026
0c586d7
chore: update CI to test all features
JavierRibaldelRio Nov 25, 2026
cba2da9
Merge pull request #673 from Hyperloop-UPV/backend/net-udp
JavierRibaldelRio Nov 25, 2026
a1faca9
wip: event
JavierRibaldelRio Nov 25, 2026
7c5bc2b
feat(backend, model): relaction functions
JavierRibaldelRio Dec 1, 2026
bba52df
feat(backend, udp): obtain board on errors
JavierRibaldelRio Dec 1, 2026
7689c91
refactor(backend, event): incoporate fault
JavierRibaldelRio Dec 1, 2026
edaf45e
Merge branch 'backend/net' into backend/event
JavierRibaldelRio Dec 1, 2026
6c0ea2b
feat(backend, station): run UDP through event in main, with stand-ins…
JavierRibaldelRio Dec 1, 2026
5b507dd
docs(backend): keep the Spanish demo docs out of this PR
JavierRibaldelRio Dec 1, 2026
381ae81
refactor(backend, station): declare station's modules in lib.rs, keep…
JavierRibaldelRio Dec 1, 2026
d89de54
docs(backend, udp): explain what Lookups resolves and where its IP ma…
JavierRibaldelRio Dec 1, 2026
99a31ba
Merge pull request #683 from Hyperloop-UPV/backend/event
JavierRibaldelRio Dec 1, 2026
656b191
Merge branch 'new-backend' into backend/net
JavierRibaldelRio Dec 5, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions .github/workflows/rust-tests.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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 }}
1 change: 1 addition & 0 deletions backend/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 11 additions & 3 deletions backend/crates/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ repository.workspace = true
default = []
# NTP server
ntp = ["dep:tokio", "dep:ntp_usg-server", "dep:tracing-subscriber"]
# TCP/UDP transport (pulls in tokio)
net = ["dep:tokio"]
# TCP/UDP transport (pulls in tokio and socket2 for SO_RCVBUF)
net = ["dep:tokio", "dep:socket2"]
# ADJ download through git
git = ["dep:tempfile", "dep:dirs", "dep:gix"]
# Packet sniffing through pcap (dependency added when the module is written)
Expand All @@ -40,7 +40,15 @@ serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
tracing.workspace = true
tokio = { workspace = true, optional = true, features = ["macros", "rt-multi-thread"] }
# `io-util` is what `net` needs on top of the workspace's own list
# (`net`, `sync`, `time`...): `AsyncReadExt`/`AsyncWriteExt`, i.e. reading
# a TCP stream into a buffer at all.
tokio = { workspace = true, optional = true, features = [
"macros",
"rt-multi-thread",
"io-util",
] }
socket2 = { version = "0.6", optional = true }
tracing-subscriber = { workspace = true, optional = true , features = ["env-filter", "fmt"]}
tracing-appender = { workspace = true, optional = true }
gix = { version = "0.87.1", optional = true, features = ["blocking-http-transport-reqwest-rust-tls", "blocking-network-client", "worktree-mutation"] }
Expand Down
7 changes: 6 additions & 1 deletion backend/crates/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
pub mod hello_world;

/// # Git module
/// Handles updates and changes within the ADJ.
/// Handles updates and changes within the ADJ.
/// Checks the ADJ Github repository and
#[cfg(feature = "git")]
pub mod git;
Expand All @@ -26,6 +26,11 @@ pub mod adj;
/// [`protocol::tcp`], [`protocol::udp`].
pub mod protocol;

/// Owns the real tokio sockets and reports what arrives on them, calling
/// into [`protocol`] to decode. See [`net::tcp`], [`net::udp`].
#[cfg(feature = "net")]
pub mod net;

// Utils module
pub(crate) mod utils;
/// Everything a recording needs on disk: writing CSV, text and JSON
Expand Down
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);
}
}
45 changes: 45 additions & 0 deletions backend/crates/core/src/net.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
//! Real sockets, on top of tokio (feature `net`).
//!
//! Two submodules do the actual I/O: [`crate::net::tcp`], a client that
//! keeps one task per board and recovers frames out of a byte stream,
//! and [`crate::net::udp`], a single shared receive-only socket. This module opens nothing. It defines only what
//! both of them need to agree on: [`crate::net::Event`] (what happened on
//! a link, carried by a [`crate::net::Notification`]) and
//! [`crate::net::Reporter`] (the two sinks they report through — one for
//! notifications, one for errors).
//!
//! Everything that reaches a [`crate::net::Reporter`] has already been
//! decoded by [`crate::protocol`], which this module layers on top of:
//! `protocol` turns bytes into packets and never touches a socket, `net`
//! owns the socket and calls into it. A sniffer or a simulator can use
//! `protocol` on its own, against a capture, without any of this.
//!
//! # Identity
//!
//! Everything that travels down the notification channel carries its
//! board: [`crate::net::Notification`] holds a
//! [`crate::model::BoardId`] next to the timestamp, whatever the event
//! is. No consumer ever has to go and look up whose packet it just got.
//!
//! It is never a second source of truth, though — it is resolved from
//! what the ADJ already says, once, here. A TCP task was spawned for one
//! board and knows it without asking; [`crate::net::udp`] resolves it
//! from the decoded packet's id through [`crate::protocol::Index`] (every
//! [`crate::model::PacketDef`] carries its `board`), which is one
//! `HashMap` lookup per datagram instead of one per consumer downstream.
//!
//! A board id is all the identity there is: one connection per board, and
//! one shared socket for UDP, so nothing needs telling apart beyond it.
//!
//! Addresses are for the operator, not for the domain types: they show
//! up interpolated in each submodule's error messages (`tcp::Error`,
//! `udp::UdpError`), which is where somebody actually reads them.

mod error;
mod report;

pub mod tcp;
pub mod udp;

pub use error::Error;
pub use report::{Closed, ErrorReport, Event, Notification, Reporter, Sinks};
184 changes: 184 additions & 0 deletions backend/crates/core/src/net/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
# `net` — Real Sockets (feature `net`)

Owns the actual tokio sockets. `protocol` turns bytes into packets and never
touches a socket; `net` owns the socket and calls into `protocol`. Nothing above
`net` (WebSocket, disk, aggregation) is known here.

Two submodules do the I/O, and **this directory's shared part opens nothing**:

```
net/
├── net.rs # module root: docs and re-exports
├── report.rs # Event, Notification, ErrorReport, Reporter — what is reported
├── error.rs # Error — aggregates tcp::Error / udp::UdpError, nothing else
├── tcp.rs # the TCP client (not written yet: error type + contract)
├── udp.rs # the shared UDP socket
└── udp/ # its tests: tests.rs, test_support.rs, manual_tests.rs (load probe)
```

## The shared part

### Identity: the board travels with everything

Every notification carries its board, whatever the event:

```rust
Notification { board: BoardId, at: SystemTime, event: Event }
```

It is never a second source of truth, though — it is resolved from what the ADJ
already says, once, inside `net`. A TCP task was spawned for one board and knows
it without asking; `udp` resolves it from the decoded packet's id through `Index`
(every `PacketDef` carries its `board`), which is one `HashMap` lookup per
datagram instead of one per consumer downstream.

And the board is all the identity there is: one connection per board, one shared
socket for UDP, so nothing needs telling apart beyond it.

Addresses are for the operator, not for the domain types: they show up
interpolated in `tcp::Error`/`udp::UdpError` messages, which is where somebody
actually reads them.

### `Event` and `Notification` — what happened, and when

```rust
enum Event {
Connected, // TCP only
Disconnected, // TCP only
Received(model::Packet),
}
```

`Event::Received` leans on the existing `model::Packet` umbrella
(`Data | Order | Protection | Message`) rather than repeating that split with one
variant per packet type. Its `Order` variant is never produced while receiving —
it is there for an eventual "the order really did go out on the wire" report,
which only `net` can make.

`board` and `at` sit in the envelope rather than inside the variants so that
**everything** that travels down the channel carries them, and so a notification
**cannot be built without a timestamp**. `Reporter::notify` is the only thing that
stamps it. That
matters: a queue adds delay under load, so a date taken when the record is
*written* would be wrong by exactly that delay, precisely when the data matters
most. It is also the only full date a record can have — the board clock on
protections and messages (`ShortTimestamp`) is a time of day with no date.

### `Reporter` — the two sinks

```rust
let (reporter, sinks) = Reporter::channels(notifications, errors);

reporter.notify(board, event).await?; // notification channel
reporter.report(tcp_or_udp_error).await?; // error channel
```

Cloneable, and meant to be cloned: one copy per TCP connection task, one for the
UDP loop, all feeding the same two channels.

Two channels, not one, because the rules differ. **A notification is never
dropped**: `notify` waits when the channel is full, so the backpressure reaches
the read loop and the kernel's receive buffer becomes the only place anything can
be lost — and whatever is lost there is lost *before* being decoded, so
"everything decoded gets through" stays literally true. An error is rare enough
that it can afford to queue behind telemetry.

`ErrorReport` carries **no board**, unlike a notification: the identity of what
failed lives inside the `Error` variant, which is the only place that always has
it. A datagram that fails to decode has no id to resolve a board from — it is not
in the ADJ, so there is no `PacketDef` to ask — so `udp::UdpError::Decode` holds the
address it came from and the board that address belongs to, if it belongs to one
(`UdpConfig::boards`). `UdpError::Fault` carries the same two.

### `Error` — aggregation only

`net::Error` adds no identity and no message of its own; both variants are
`#[error(transparent)]`, so `to_string()` is the submodule's own message with its
identity already interpolated, and `source()` still reaches the original
`io::Error` or `DecodeError`. Each submodule owns its error type and puts the
board or address **inside the variant** — the Go backend lost exactly
that when an error crossed its channel. `is_fatal()`, if needed, belongs to each
submodule's own error: nobody outside knows which of its variants are fatal.

## The contract for the two submodules

| | `tcp` | `udp` |
|---|---|---|
| Entry point | `spawn(Config, Arc<Index>, Reporter) -> Handles` | `spawn_udp(UdpConfig, Arc<Index>, Reporter) -> Result<JoinHandle<()>, UdpError>` (binds first) |
| Inputs | its `Config` (boards, timeouts, backoff, keep-alive) | its `UdpConfig` (bind address, `SO_RCVBUF`, IP → board) |
| Role | client only; one connection per board, one task each | one shared socket, receive-only, one task |
| Framing | buffer + `&mut Cursor` + advance by `cursor.position()`; bail out past 374 bytes | none — `recv_from` delivers a whole datagram into a reused 64 KiB buffer |
| Writing | yes (orders, keep-alive); a single writer task per connection | no |
| On a decode error | report it; **fatal**, and close/reopen the connection (the stream cannot be resynchronised) | report it; **fatal**, and keep receiving |
| `Connected`/`Disconnected` | per board | never |
| Fault | writes it: `Handles::propagate_fault()`, id 0 to every board | cannot write; a received id 0 is reported as `UdpError::Fault`, before decoding |

Both take the same two things besides their own `Config`: an `Arc<Index>` — the
only part of the ADJ `net` needs, owned by `station` and read-only here — and a
`Reporter`. Neither reads a config file, and neither reads the ADJ itself: the
addresses `tcp` connects to are resolved by `station` and arrive in `Config`,
which is also what lets a test point it at a fake peer.

`net` never decides to fault the pod, but `tcp` is what can write one: `station`
reads `is_fatal()` and calls `Handles::propagate_fault()`, which puts the order
with id 0 into every board's writer channel (the Go backend's `SendFault`). A
*received* packet with id 0 is the same action requested by a board, and
`station` answers it the same way. In `udp` it arrives on the error channel as
`UdpError::Fault { from, board }`: recognised by its id alone, before decoding, without
looking at the ADJ.

Three rules both follow:

1. The timestamp comes from `Reporter`, never by hand.
2. Decode and report, nothing else — no disk, no WebSocket, no aggregation.
3. What to do about an error is decided locally; only the report goes up.

### What "fatal" means

`tcp::Error::is_fatal`/`udp::UdpError::is_fatal` are about the **pod**: they say
the pod has to be sent to fault. They are a hint, not a decision — what happens
next (the fault, closing the connections, shutting the backend down safely) is
decided by whoever consumes the error channel (`station`). Nothing in `net` ever
calls `std::process::exit`.

On either transport, a decode failure is fatal, and this is a deliberate
departure from Go. Nothing corrupts a frame or a datagram in flight (both
transports checksum, TCP retransmits, and the pod's network does not fragment), so
something that will not decode means the loaded ADJ does not describe what the
firmware is sending — which reconnecting cannot fix. A failed connect or write is
*not* fatal: that is what the backoff is for.

Two more are fatal in `udp`: losing the socket (`UdpError::Recv`), which is every
board's telemetry gone at once, and a fault sent by a board (`UdpError::Fault`,
packet id 0), which is a board asking for exactly that.

`net` never raises the fault itself — neither transport does. It logs, it reports,
and `is_fatal()` is the classification whoever consumes the error channel acts on.
That is deliberate: a mismatched ADJ fails on every frame that follows, thousands
a second, so the fault has to be broadcast **once**, and the guard for that lives
in one place instead of one per transport.

## Why TCP needs a buffer and UDP does not

TCP is a byte stream and preserves no write boundaries, so one read can deliver
half a frame or two frames glued together — both are normal, and the glued case is
the frequent one. Our frames carry no length prefix: a protection's length is
fixed but derivable only from the ADJ (`2 + 4 + 2 + the watched measurement's wire
width`), and a message ends at the second NUL byte of its two variable-length
strings. So a frame's end is never known in advance, only deduced by parsing it —
which is why the loop tries, and retries with more bytes when it fails.

The Go backend never faced this because it read straight off the connection, where
a blocking read simply waits mid-frame. That state has to live somewhere: in Go it
lived in the blocked goroutine's stack, and here it lives in an explicit buffer —
which is also what lets `protocol` stay synchronous and socket-free, reusable by a
sniffer against a capture.

UDP has none of it: the kernel hands over a whole datagram or nothing.

## Open questions

- Who raises the fault on `is_fatal()`, and where its "only once" guard lives.
Not in `net`: both transports only report.
- Whether an order's write is reported back as
`Event::Received(Packet::Order(..))`, or `station` just assumes it went out.
Loading
Loading