Skip to content

[Event] Backend/event - #683

Merged
JavierRibaldelRio merged 9 commits into
backend/netfrom
backend/event
Dec 1, 2026
Merged

JavierRibaldelRio merged 9 commits into
backend/netfrom
backend/event

Conversation

@JavierRibaldelRio

@JavierRibaldelRio JavierRibaldelRio commented Dec 1, 2026 •

Copy link
Copy Markdown
Member

(Includes UDP from NET)

What event is

station::event is how station's modules talk to each other. It is the single consumer of core::net's queues:

  • It hands everything the boards send to logging (disk) and pipeline (front).
  • It writes the front's orders and the fault to TCP.
  • It decides what every error means: ignore it, show it, or stop the backend.

The full design (queues, error table, shutdown, contract) is in backend/crates/station/src/event/README.md. This description is the short version, plus what each module has to do to plug into it.

How it works

event is three tasks:

TOWARDS THE FRONT
  net::udp  ─① errors / ④ data──────────┐
  net::tcp  ─① errors / ③ prot., msg.───┼──► ROUTING LOOP ─⑤─► logging  (disk)
  station   ─② problems──────────────────┘    errors first,  ─⑥─► pipeline (front)
                                              then TCP,
                                              then UDP

TOWARDS THE BOARDS
  front → websocket ─⑦─► ORDERS WORKER ──► TCP: the order to its board
                               │ order id 0
                               ▼
  routing loop ─────⑧──► FAULT WORKER  ──► TCP: the fault to every board
# Queue From → to Type
① net errors (one per transport) net::udp, net::tcp → routing loop ErrorReport
② problems any station module → routing loop Problem
③ TCP notifications net::tcp → routing loop Notification
④ UDP notifications net::udp → routing loop Notification
⑤ to logging routing loop, workers → logging ToLogging
⑥ to pipeline routing loop, workers → pipeline ToPipeline
⑦ orders websocket → orders worker OrderPacket
⑧ fault requests (private) routing loop, orders worker → fault worker FaultRequest
  • Routing loop (router.rs). One select! with a fixed order: errors, problems, TCP, UDP.
    • Every notification goes to logging and pipeline as one shared copy (Arc<Notification>).
    • Every error goes through policy.rs.
    • It never writes to a socket, so it never waits on one.
  • Orders worker (orders.rs). Takes the front's orders one at a time, writes each one to TCP and waits for the result.
    • Written: OrderSent goes to logging and pipeline.
    • Not written: OrderFailed goes to pipeline, with the reason.
    • Order id 0 is the fault: it is handed to the fault worker.
  • Fault worker (fault.rs). Sends the fault (order id 0) to every board, once per request, and reports which boards it did not reach.

Principles

  1. Each module is its own task, and modules only talk through bounded queues. event::channels() creates every queue in one call. There are circles (event → logging → event, event → TCP → event), and creating everything first removes the "who exists first" problem. event owns the types of every queue, so logging and pipeline depend on event, never the other way round.
  2. Nothing decoded is ever dropped. When a queue is full, whoever sends to it waits. The backpressure reaches the socket, so the kernel buffer is the only place anything can be lost, and only before it is decoded.
  3. Fixed priority: errors, then TCP, then UDP. An error or a protection never waits behind thousands of telemetry packets. TCP carries little traffic, so reading it first does not starve UDP.
  4. Nothing that waits on a socket runs in the routing loop. That is why the workers exist.
  5. event never looks inside the data. logging picks the measurements it stores and pipeline computes what the front shows. event only routes.
  6. Each error is traced once, by the module that detects it. event applies one of three procedures:
    1. Silent: trace only.
    2. Shown: sent to the front.
    3. Fatal: fault, shown, safe shutdown.
  7. The fault comes first. The rules give 200 ms from a fault to the order on the wire.
    • A board in fault: it sends packet id 0, a protection the ADJ declares with severity Fault, or a message of level Fault/Panic. If propagate_fault is on (the default), the fault is sent to every board each time one arrives.
    • The front's fault: order id 0. It follows the normal order flow: sent to every board, and the front is told whether it went out.
    • A fatal error: the fault is requested before anything else, then the problem is shown, the data already queued is passed on, and the backend stops.

How each module plugs in

main

let channels = event::channels(&config);

spawn_udp(udp_config, index.clone(), channels.udp)?;                 // ① ④
// net::tcp takes channels.tcp                                          ① ③
let event = event::spawn(config, channels.event, pod_data, index, tcp); // tcp: Option<Arc<dyn TcpLink>>
// logging takes channels.logging                                       ⑤
// pipeline takes channels.pipeline                                     ⑥
// websocket takes channels.orders                                      ⑦
// every station module that reports problems gets a clone of channels.problems  ②
  • main keeps no copy of a Reporter: a Reporter left alive keeps its queues open, and the routing loop never ends.
  • If TCP is not started, drop channels.tcp.
  • event's task ends with a Stop: Fatal(problem) exits with code 1; NetGone exits with 0 after Ctrl+C and with 1 otherwise.

net (udp and tcp): the Reporter, not the Sinks

net only ever sees the sending side: one Reporter per transport (channels.udp, channels.tcp), cloned once per task (the UDP loop, each TCP connection). The receiving side (Sinks, with notifications and errors) belongs to event: it travels inside channels.event and only the routing loop reads it. net never touches a Sinks.

  • reporter.notify(board, event).await for everything that happens: Event::Connected, Event::Disconnected, Event::Received(packet). It stamps the time (at) itself; nothing else may stamp it by hand.
  • reporter.report(error).await for everything that goes wrong. The identity goes inside the error variant (board, address).
  • Waiting is intended. If the queue is full, notify waits: never drop, never try_send.
  • Err(Closed) means event is gone: stop the task.

How event reads each error:

Error Procedure
UdpError::Decode, UdpError::Recv fatal
UdpError::Fault { from, board } (packet id 0, recognised before decoding) board fault: first one per board shown, fault sent to every board each time
tcp::Error::Decode fatal
tcp::Error::Connect silent (the Disconnected notification already tells the front)
tcp::Error::Write shown

Specifics:

  • net::udp resolves the board of an error from the sender's IP: UdpConfig::boards, built with PodData::boards_by_ip() (included in this PR).
  • net::tcp additionally:
    • recognises packet id 0 as a fault before decoding, like UDP (this needs a tcp::Error::Fault variant, which policy::classify will map to board fault);
    • does not report reconnection failures, only traces them;
    • is handed to event as a TcpLink, directly or through a thin adapter:
      • send(order) returns the board once the order is written, and fails right away if the board is not connected;
      • send_fault() returns the boards it did not reach.

logging

It receives channels.logging, an mpsc::Receiver<ToLogging> (⑤):

pub enum ToLogging {
    Received(Arc<Notification>),   // everything the boards send; pipeline gets the same copy
    OrderSent { at, board, order }, // an order TCP confirmed it wrote; board = None for the fault
}
  • A Notification carries board, at (the full date, taken when the bytes came off the socket) and event. Protections and messages also carry the board's own clock (ShortTimestamp, a time of day with no date).
  • Keep reading. If logging falls behind, event waits, and so does net behind it.
  • Choosing which measurements to store is logging's job. event sends everything.
  • Report your own failures on channels.problems as a Problem. Use ProblemKind::Fatal for anything that stops recording (for instance the disk), and event::full_message(&err) for the text with all its causes.
  • When recv() returns None, event has stopped: write what is left, flush and end. That is the shutdown signal.
  • Dropping the receiver early is fatal for event ("logging stopped: nothing is being recorded").

pipeline

It receives channels.pipeline, an mpsc::Receiver<ToPipeline> (⑥):

Variant What to do with it
Received(Arc<Notification>) Per-packet updates (counts, cycle time, averages), protection and message updates
Problem(Problem) A message from the backend (message/update). kind says whether it is Shown or Fatal
OrderSent { at, board, order } message/update: the order went out (board = None for the fault)
OrderFailed { at, order, reason } message/update: the order did not go out, and why
  • Same rules as logging: keep reading, never drop, and end when recv() returns None.
  • pipeline does not decide anything about errors: that has already been decided.
  • Dropping the receiver early is fatal for event.

websocket (orders)

It receives channels.orders, an mpsc::Sender<OrderPacket> (⑦):

  • Validate each order against the ADJ (the id exists and the values fit its fields), then orders.send(order).await.
  • The fault is just another order: id 0, declared in the ADJ, sent the same way.
  • The result does not come back to websocket: it reaches the front through pipeline (OrderSent/OrderFailed turned into message/update).
  • The logger requests (logger/enable, variable selection) go to logging directly, not through event.
  • If send fails, event is gone.

Any other station module

Clone channels.problems (②) and send a Problem, for example Problem::now(ProblemKind::Shown, board, text).

Also in this PR

  • core::model: PodData::board_name and PodData::boards_by_ip.
  • core::net::udp: UdpError::Decode and UdpError::Fault carry the board (Option<BoardId>), resolved through UdpConfig::boards.
  • station/src/main.rs: downloads the ADJ, listens on UDP and runs everything through event, with stand-ins for logging and pipeline.
  • station/src/lib.rs: station's modules are declared there, so 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 and connects them. http (feat(backend, http): add HTTP API for ADJ catalogs and WebSocket upgrade support #676) was not declared anywhere, so it was not compiled: it is now, with its tests (clippy has three needless_borrows_for_generic_args warnings in http/server.rs tests).

Not wired yet

Testing

  • cargo test -p software-core --all-features and cargo test -p station, the same as CI. 31 tests in event cover:
    • the order of priority and the shared copy;
    • the fatal stop, and that the data queued before the error still gets through;
    • board faults: packet id 0 shown once per board; faults, Fault protections and Fault/Panic messages sent to every board each time; warnings only forwarded;
    • orders with and without TCP, and the front's fault;
    • a consumer that stops, net closing, and a fault that never finishes sending.
  • cargo test -p station --release manual_event -- --ignored --nocapture: about 1,000,000 notifications a second through event, 24 times the 41,000/s required.

@GaziH
GaziH requested review from GaziH and pminmic December 1, 2026 18:58

@pminmic pminmic 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.

Just minor changes, but it's very well done.

Comment thread backend/readme-demo.md Resolved
Comment thread backend/crates/station/README.md Resolved
Comment thread backend/crates/station/src/event.rs Resolved
Comment thread backend/crates/core/src/net/udp.rs Resolved

@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.

Really good stuff, just do what was commented on and should be good!

Comment thread backend/crates/station/src/main.rs Resolved
Comment thread backend/crates/station/src/event.rs Resolved
@JavierRibaldelRio
JavierRibaldelRio merged commit 99a31ba into backend/net Dec 1, 2026
2 checks passed
@JavierRibaldelRio
JavierRibaldelRio deleted the backend/event branch December 1, 2026 19:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants