Skip to content

feat(backend, net::tcp): implement per-board TCP clients with reconnection, keep-alive and fault broadcast - #672

Open
pminmic wants to merge 93 commits into
backend/netfrom
backend/net-tcp
Open

pminmic wants to merge 93 commits into
backend/netfrom
backend/net-tcp

Conversation

@pminmic

@pminmic pminmic commented Nov 5, 2026 •

Copy link
Copy Markdown

Summary

  • Implement per-board TCP clients with independent reconnection supervisors and capped exponential backoff.
  • Add ADJ-based order routing, validation and bounded queues.
  • Handle incoming frame reassembly, packet decoding and lifecycle/error reporting.
  • Serialize orders, configurable keep-alive and prioritized fault requests through one writer per connection.
  • Implement concurrent fault broadcasts with bounded deadlines and per-board write confirmation.
  • Document transport guarantees and provide ignored manual probes.

Validation

Automated tests and local loopback checks pass, but end-to-end validation against board firmware is still pending.

Please review propagate_fault() carefully, particularly whether its behavior matches the firmware's expectations. Its current success result confirms only the TCP write, not firmware receipt or execution.

Pending

  • Hash exchange and validation with boards.

JavierRibaldelRio and others added 30 commits September 29, 2026 09:34
- Header and empty state use the team mark (outreach/main/logo_icon.svg)
  through a TeamLogo component that crops the SVG's empty canvas.
- Header wraps on narrow screens: title + theme toggle, then a full-width
  row of load controls; single row from lg.
- Tab bar scrolls by itself instead of widening the page; board stats wrap;
  the Sockets table keeps a min width and scrolls inside its container.
- New "Count bytes as" switch in the Throughput scenario panel, replacing
  the preamble/inter-frame gap checkbox.
- Wireshark mode counts the frame length a capture on the backend shows:
  no preamble, gap or FCS; received frames padded (60 B min), sent frames
  unpadded (keep-alive 56 B, ACK 54 B).
- Flow breakdowns, table headers and the help sheet follow the mode; the
  help adds a "Matching Wireshark" section.
Native number spinners ignored the theme and overlapped right-aligned values. StepperInput hides them and draws themed up/down buttons (±1, never below 0); arrow keys still step the value.
[ADJ Viewer]: enhancements & throughtput calculator
[ADJ Viewer] throughput calculator enhancements
[Testing View] feat(testing-view): new colour theme Twight
feat(competition-view): terminal-style message log, font-size control and mock backend

@GaziH GaziH left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks great overall, waiting on Javier's requested changes to be implemented.

@JavierRibaldelRio
JavierRibaldelRio changed the base branch from new-backend to backend/net December 1, 2026 19:48
@JavierRibaldelRio

Copy link
Copy Markdown
Member

I just change the PR base to be merge into backend/net (instead of new-backend)

}
// Defer even definite decode errors until the undecodable suffix exceeds the limit.
Err(error) if pending.len() > MAX_FRAME_LEN => Err(error),
Err(_) => Ok(None),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: one unknown frame stalls the board's whole TCP stream.

next_frame defers even errors that more bytes can never fix (for example UnknownId) until more than 374 bytes are buffered. Until then, every later protection, message and 00 00 fault from that board waits behind the bad frame. On a quiet link that wait can last forever. When the Decode error finally fires, the session closes and drops the valid frames buffered behind it. And if the board closes the connection while bytes are still deferred, the error comes out as a non-fatal TcpError::Read (EOF) instead of Decode.

Scenario: a board sends a frame whose ID is not in the Index. Example: add_state_order (5) or blcu_ack (4). Go decoded both, but the Index only holds board packets plus the four message severities. The board then sends a fault-level protection and a 00 00 fault. Neither is published until 375 bytes have piled up. At that point the session is torn down with Decode, and the protection and fault are thrown away.

Fix: fail straight away on decode errors that more input cannot resolve (UnknownId, WrongPacketType, invalid UTF-8, ...). Defer only errors that mean the input is incomplete (EOF).

};
// Close and unregister before collecting a terminal write failure.
drop(registration);
if let Some(source) = writer.take_unreported_failure() {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: a fatal decode error can be lost here.

session::run returns any write failure the supervisor still owes a report for, and that replaces the reader's own result. If the reader ends with Err(TcpError::Decode) while a keep-alive (or fault) write is parked inside write_all, select! drops that write. Its FrameGuard::drop records Supervisor(Interrupted), and this line then returns a non-fatal TcpError::Write in place of the Decode. The same swap turns a normal PeerClosed or ConsumerClosed into a reported Write error.

Scenario: a board stops reading, so its send buffer fills and the 50 ms keep-alive blocks part-way through a frame. The same board then sends more than 374 undecodable bytes. The supervisor reports TcpError::Write (classified Action::Show) instead of Decode (Action::Fatal), so the application never faults the pod for the ADJ/firmware mismatch.

Fix: if result is Err, keep that error and report the write failure alongside it (or log it). Only substitute the write failure when the reader ended with Ok(..).

}
let result = tokio::select! {
biased;
() = writer.closed() => Ok(SessionEnd::PeerClosed),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: a failed outgoing write throws away incoming data that has already arrived.

When an order write times out or fails part-way through a frame, fail(Caller) closes the writer. This biased branch then wins and drops the reader. Complete frames still sitting in pending (for example, waiting for room on the notification channel) are discarded, along with anything in the kernel receive buffer, which goes with the zero-linger RST. The supervisor also logs this as PeerClosed, even though the local side ended it.

Scenario: a busy board stops reading for more than 2 s while it is sending protections. An order's write_all times out after writing part of the frame. The session ends as PeerClosed, and the protections already received are never reported to the operator.

Fix: on a local write failure, stop writing but let the reader publish what it already holds (or drain for a short deadline) before tearing the session down. Also give this case its own SessionEnd instead of PeerClosed.

bytes: &[u8],
budget: Duration,
) -> Result<(), SendError> {
let deadline = Instant::now() + budget;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: a large write_timeout panics, and the release profile's panic = "abort" turns that into a process abort.

Instant::now() + budget overflows for durations such as Duration::MAX. The same unchecked addition appears in BoardClients::broadcast_fault (started + self.write_timeout, board_clients.rs:100) and in run_keep_alive (keep_alive.rs:33). By contrast, connect_timeout and the backoff go through tokio's timeout/sleep, which saturate.

Scenario: a consumer sets TcpConfig { write_timeout: Duration::MAX, .. } to mean "no limit". The first send(), broadcast_fault() or heartbeat then panics with "overflow when adding duration to instant".

Fix: use checked_add and fall back to a far-future deadline, or reject oversized values when the TcpConfig is built.

tracing::debug!(board = ?link.board, addr = %link.addr, "Attempting TCP connection");
match connect_once(link, connect_timeout).await {
Ok(stream) => {
backoff.reset();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): a peer that accepts the connection and then drops it straight away is retried at the initial interval forever.

The backoff is reset on every successful connect, so a session that ends immediately is always followed by the initial 100 ms wait, and the backoff never grows.

Scenario: a board whose TCP server accepts and then closes at once. Causes include its only client slot being taken by another client, the board being in its bootloader, or the board sending frames that never decode. The supervisor then emits a Connected/Disconnected pair about ten times per second per board, flooding the consumers.

Fix: reset the backoff only once a session has stayed up for some minimum time (or after its first decoded frame).

Comment on lines +208 to +210
/// Deterministic partial-write and control scheduling fixtures.
pub(super) mod writes {
//! Scripted writes exercise partial-frame failures without relying on OS buffers.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): this file makes cargo clippy --all-targets --all-features -- -D warnings fail.

The writes module has both an outer /// doc and an inner //! doc, which trips clippy::mixed_attributes_style (error: item has both inner and outer attributes). The repo-root CLAUDE.md lists cargo clippy --workspace --all-targets -- -D warnings and says "Lints are strict on purpose".

Suggested change
/// Deterministic partial-write and control scheduling fixtures.
pub(super) mod writes {
//! Scripted writes exercise partial-frame failures without relying on OS buffers.
/// Deterministic partial-write and control scheduling fixtures.
///
/// Scripted writes exercise partial-frame failures without relying on OS buffers.
pub(super) mod writes {

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

TCP Module

4 participants