diff --git a/backend/crates/station/README.md b/backend/crates/station/README.md index e0faef483..f73390e3b 100644 --- a/backend/crates/station/README.md +++ b/backend/crates/station/README.md @@ -4,16 +4,26 @@ El backend de la Control Station de Hyperloop UPV: escucha a las placas del pod, decodifica sus paquetes, los reenvía a los frontends y guarda un registro en disco. Construido sobre [`software-core`](../core/README.md). -La librería ([`lib.rs`](src/lib.rs)) expone los módulos [HTTP](src/http/README.md) -y [WebSocket](src/websocket/README.md) como `station::http` y -`station::websocket`. +La librería ([`lib.rs`](src/lib.rs)) expone los módulos de station: + +- [`event`](src/event/README.md): la comunicación entre los módulos. +- [`pipeline`](src/pipeline/README.md): convierte lo que reparte `event` en lo + que muestra el front. +- [`payload`](src/payload/README.md): los mensajes que viajan por el + WebSocket. +- [`websocket`](src/websocket/README.md): el broker y las conexiones con los + frontends. +- [`http`](src/http/README.md): la API HTTP (catálogos del ADJ y el upgrade a + WebSocket). ## Ejecutar la demo ```sh -cargo run -p station -- "Hyperloop UPV" +cargo run -p station --release ``` -El binario ([`main.rs`](src/main.rs)) ejecuta la [demo de saludo](../../readme-demo.md). -El arranque del backend y la carga de la configuración quedan pendientes. - +El binario ([`main.rs`](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`. Ver [`../../readme-demo.md`](../../readme-demo.md). El arranque +completo del backend (TCP, WebSocket y HTTP) y la carga de la configuración +quedan pendientes. diff --git a/backend/crates/station/src/event.rs b/backend/crates/station/src/event.rs index e8cdf82cf..0b8c26449 100644 --- a/backend/crates/station/src/event.rs +++ b/backend/crates/station/src/event.rs @@ -79,8 +79,13 @@ pub struct EventConfig { pub udp_queue: usize, /// Slots in ⑤ (to `logging`). pub logging_queue: usize, - /// Slots in ⑥ (to `pipeline`). + /// Slots in ⑥ (to `pipeline`: everything but telemetry). Little traffic, + /// and nothing on it may be lost: when it is full, the routing loop waits. pub pipeline_queue: usize, + /// Slots in ⑨ (telemetry to `pipeline`). When it is full, the routing + /// loop drops the front's copy instead of waiting (`logging` still gets + /// it), so a slow front never slows down the backend. + pub pipeline_data_queue: usize, /// Slots in ⑦ (orders from the front). pub orders_queue: usize, /// Send the fault a board sends to every other board as well. @@ -98,7 +103,8 @@ impl Default for EventConfig { tcp_queue: 1024, udp_queue: 8192, logging_queue: 8192, - pipeline_queue: 8192, + pipeline_queue: 1024, + pipeline_data_queue: 8192, orders_queue: 32, propagate_fault: true, fault_timeout: Duration::from_secs(2), @@ -166,11 +172,13 @@ pub enum ToLogging { }, } -/// What `pipeline` receives (⑥). +/// What `pipeline` receives on ⑥: everything but telemetry, which goes on ⑨ +/// ([`Channels::pipeline_data`]). #[derive(Debug)] pub enum ToPipeline { - /// A notification, TCP or UDP, as soon as it arrives. `logging` gets the - /// same copy. + /// A notification that is not a data packet (connected, disconnected, a + /// protection, a message), as soon as it arrives. `logging` gets the same + /// copy. Received(Arc), /// Something the operator is told, shown on the front as a message from /// the backend: as information, a warning or a fatal error, by its kind. @@ -231,15 +239,19 @@ pub struct Channels { pub notices: mpsc::Sender, /// ⑤, for `logging`. pub logging: mpsc::Receiver, - /// ⑥, for `pipeline`. + /// ⑥, for `pipeline`: everything but telemetry. pub pipeline: mpsc::Receiver, + /// ⑨, for `pipeline`: telemetry only, every notification a + /// `Packet::Data`, the same copy `logging` gets. The routing loop drops + /// the front's copy when it is full. + pub pipeline_data: mpsc::Receiver>, } /// `event`'s own ends of the queues: the reading side of ① ② ③ ④ ⑦ and the -/// writing side of ⑤ ⑥. Only [`spawn`] opens it. +/// writing side of ⑤ ⑥ ⑨. Only [`spawn`] opens it. #[derive(Debug)] pub struct EventEnds { - /// ① ② ③ ④ ⑤ ⑥: for the routing loop. + /// ① ② ③ ④ ⑤ ⑥ ⑨: for the routing loop. router: RouterEnds, /// ⑦: for the orders worker. orders: mpsc::Receiver, @@ -263,6 +275,7 @@ pub fn channels(config: &EventConfig) -> Channels { 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)); + let (pipeline_data_tx, pipeline_data_rx) = mpsc::channel(config.pipeline_data_queue.max(1)); Channels { udp, @@ -274,6 +287,7 @@ pub fn channels(config: &EventConfig) -> Channels { notices: notices_rx, logging: logging_tx, pipeline: pipeline_tx, + pipeline_data: pipeline_data_tx, tcp_capacity, udp_capacity, }, @@ -283,6 +297,7 @@ pub fn channels(config: &EventConfig) -> Channels { notices: notices_tx, logging: logging_rx, pipeline: pipeline_rx, + pipeline_data: pipeline_data_rx, } } @@ -296,7 +311,7 @@ pub fn channels(config: &EventConfig) -> Channels { /// 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` +/// been stopped too: by then every sender of ⑤ ⑥ ⑨ is gone, so `logging` /// and `pipeline` finish what they have queued and end on their own. pub fn spawn( config: EventConfig, @@ -354,7 +369,7 @@ async fn run( let router = Router::new(config, pod_data, index, ends, fault_tx); // Runs until it has to stop. It takes the router by value, so its ends of - // ⑤ ⑥ ⑧ are dropped when it returns. + // ⑤ ⑥ ⑧ ⑨ are dropped when it returns (⑨ has no other sender). let stop = router.route().await; // The workers would never end on their own (⑦ and ⑧ stay open), and their diff --git a/backend/crates/station/src/event/README.md b/backend/crates/station/src/event/README.md index c03d0e54d..3621fb13f 100644 --- a/backend/crates/station/src/event/README.md +++ b/backend/crates/station/src/event/README.md @@ -39,7 +39,7 @@ the boards. │ net::udp │ ─④ UDP notif.──► │ event: routing loop │ │ logging │ → disk └────────────┘ │ │ └──────────┘ ┌─ task ─────┐ ─① errors──────► │ reads in this order: │ - │ net::tcp │ ─③ TCP notif.──► │ 1. ① ② errors │ ─⑥─► ┌─ task ───┐ + │ net::tcp │ ─③ TCP notif.──► │ 1. ① ② errors │ ─⑥⑨► ┌─ task ───┐ └────────────┘ │ 2. ③ TCP notifications │ │ pipeline │ → websocket → front any station ─② notices─────► │ 3. ④ UDP notifications │ └──────────┘ module └────────────┬─────────────┘ @@ -101,7 +101,9 @@ Why it is built like this: - **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. + yet, which has not been decoded yet. `net` works the same way. The one + exception is the front's copy of telemetry (⑨): see + [Towards the front](#towards-the-front). - **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 @@ -131,9 +133,10 @@ event/ | ③ | TCP notifications | `net::tcp` → routing loop | `Notification` (protections, messages, connected/disconnected) | | ④ | UDP notifications | `net::udp` → routing loop | `Notification` (data) | | ⑤ | to logging | routing loop, both workers → `logging` | `ToLogging` | -| ⑥ | to pipeline | routing loop, both workers → `pipeline` | `ToPipeline` | +| ⑥ | to pipeline | routing loop, both workers → `pipeline` | `ToPipeline` (everything but telemetry) | | ⑦ | orders | `websocket` → orders worker | `OrderPacket` (id 0 = fault) | | ⑧ | fault requests | routing loop, orders worker → fault worker | `FaultRequest` | +| ⑨ | telemetry to pipeline | routing loop → `pipeline` | `Arc` (data packets only) | **The routing loop reads ① to ④ in that order: errors, then TCP, then UDP.** @@ -160,7 +163,7 @@ spawn_udp(udp_config, index.clone(), channels.udp)?; // ① ④ // the TCP client takes channels.tcp ① ③ let event = event::spawn(config, channels.event, pod_data, index, tcp); // Arc, Arc, Option> logging::spawn(channels.logging, ...); // ⑤ -pipeline::spawn(channels.pipeline, broker_client, ...); // ⑥ +pipeline::spawn(config, channels.pipeline, channels.pipeline_data, broker_client, ...); // ⑥ ⑨ OrderForwarder::new(index, channels.orders); // ⑦ (websocket) // channels.notices is cloned for every station module that reports errors or news ② ``` @@ -187,8 +190,8 @@ Why one place, instead of each module creating its own input queue: | What arrives | `logging` | `pipeline` | fault worker | |---|---|---|---| -| TCP notification (③) | yes | yes | — | -| UDP notification (④) | yes | yes | — | +| Notification that is not a data packet (③: connected, disconnected, protections, messages) | yes | yes, on ⑥ | — | +| Data packet (④, telemetry) | yes | yes, on ⑨; dropped if ⑨ is full | — | | Notice 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, every time, if `propagate_fault` is on | @@ -196,7 +199,8 @@ Why one place, instead of each module creating its own input queue: **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, +same copy to both `logging` and `pipeline`: to `pipeline` on ⑨ if it is a data +packet, on ⑥ otherwise. 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 @@ -204,9 +208,21 @@ 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). +reaches the disk, the same rule `net` follows, and nothing but telemetry is +lost on its way to the front. 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), and ⑥ carries little +traffic. + +**When ⑨ is full, `event` drops the front's copy of that data packet; it does +not wait.** A full ⑨ means the front is behind, and the front only shows +averages over 100 ms windows: losing some of its samples is better than +slowing down the routing loop, and with it the disk and the reading of `net`. +`logging` already has its copy, so nothing is lost from the record. The routing +loop traces when it starts dropping and, once ⑨ has room again, how many it +dropped; it keeps no timer and allocates nothing per packet for it. Telemetry +on its own queue also means a protection or a message on ⑥ never waits behind +it. ## Towards the boards @@ -219,7 +235,7 @@ is expected to keep up with the incoming rate (about 15–25 Mbit/s). 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 + backend (`backend/message`), 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 @@ -281,7 +297,7 @@ since nothing went wrong; it only shares the queue (②) and the way to the fron | 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** | | `Notice` from a station module (②) | whatever that module reports | what the module says: **1** (`Silent`), **2** (`Warning`) or **3** (`Fatal`); an `Info` is not an error and is only shown | -| `logging` or `pipeline` stops (⑤ or ⑥ closed) | nothing is recorded, or nothing is shown | **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 @@ -338,7 +354,7 @@ queues close, and the routing loop passes on whatever was left and ends with **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 +2. When `event` ends, ⑤ ⑥ ⑨ 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 @@ -358,7 +374,7 @@ pub struct Channels { /// 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. + /// ⑤ ⑥ ⑨), for `spawn`. Opaque. pub event: EventEnds, /// ⑦, for websocket's OrderForwarder. pub orders: mpsc::Sender, @@ -366,14 +382,16 @@ pub struct Channels { pub notices: mpsc::Sender, /// ⑤, for logging. pub logging: mpsc::Receiver, - /// ⑥, for pipeline. + /// ⑥, for pipeline: everything but telemetry. pub pipeline: mpsc::Receiver, + /// ⑨, for pipeline: data packets only, the same copy logging gets. + pub pipeline_data: 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. +/// too, so that ⑤ ⑥ ⑨ close behind it. pub fn spawn( config: EventConfig, ends: EventEnds, @@ -400,7 +418,8 @@ pub enum ToLogging { } pub enum ToPipeline { - /// A notification, the same copy logging gets. + /// A notification that is not a data packet (those go on ⑨), the same + /// copy logging gets. Received(Arc), Notice(Notice), /// An order the front sent that went out, as in `ToLogging`. @@ -449,7 +468,8 @@ pub struct EventConfig { pub tcp_queue: usize, // ③ (1,024) pub udp_queue: usize, // ④ (8,192) pub logging_queue: usize, // ⑤ (8,192) - pub pipeline_queue: usize, // ⑥ (8,192) + pub pipeline_queue: usize, // ⑥ (1,024) + pub pipeline_data_queue: usize, // ⑨ (8,192); when full, the front's copy is dropped pub orders_queue: usize, // ⑦ (32) 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) @@ -479,7 +499,8 @@ loop, select! in fixed order (closed queues are no longer watched): forward(notification): shared = Arc::new(notification) ⑤.send(Received(shared.clone())).await // on failure: fatal - ⑥.send(Received(shared)).await // on failure: fatal + data packet? ⑨.try_send(shared) // full: drop the front's copy; closed: fatal + otherwise ⑥.send(Received(shared)).await // on failure: fatal ``` ## Performance @@ -498,7 +519,7 @@ 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 +Measured with `manual_event_throughput` (see [Tests](#tests)): about 1,000,000 notifications a second through `event`, over 20 times the requirement. ## Contract with the other modules @@ -526,13 +547,15 @@ notifications a second through `event`, over 20 times the requirement. selection, records the orders that went out, and reports on ② its own failures (e.g. the disk, as a `Fatal` notice) and its news (an `Info`, e.g. recording started). -- **`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 `Notice`, and an order that went out or failed - (`OrderSent`, `OrderFailed`), into a message from the backend - (`message/update`). A notice keeps its kind there: `Info` as info, `Warning` - as warning, `Fatal` as fault. It waits instead of dropping and does not decide anything - about errors. +- **`pipeline`** reads ⑥ and ⑨, ⑥ first, and turns them into what the front + shows: telemetry (⑨) into per-packet updates (counts, cycle time, averages); + any other notification into protection, message or connection updates; a + `Notice`, and an order that went out or failed (`OrderSent`, `OrderFailed`), + into a message from the backend (`backend/message`). A notice keeps its kind + there: `Info` as info, `Warning` as warning, `Fatal` as fault. It drops + nothing itself (when it falls behind, `event` drops the front's copy of + telemetry on ⑨), it ends once both queues are closed, and it does not decide + anything about errors. ## Implementation notes @@ -550,7 +573,9 @@ notifications a second through `event`, over 20 times the requirement. - `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 copy, the + `TcpLink`, no sockets. Covers the order of priority, the shared copy, + telemetry on ⑨ and everything else on ⑥, a full ⑨ dropping the front's copy + without slowing anything down, a closed ⑨ meaning `pipeline` is gone, the fatal stop (and that what was queued before the error still gets through), 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 @@ -559,9 +584,10 @@ notifications a second through `event`, over 20 times the requirement. 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 950,000 a - second, over 20 times the requirement. + a million notifications through a `Reporter` into `event` and readers that + only count, and checks that `logging` got every one (`pipeline` may get + fewer, if ⑨ filled up). On a development machine, in release: about + 1,000,000 a second, over 20 times the requirement. ```sh cargo test -p station --release manual_event -- --ignored --nocapture diff --git a/backend/crates/station/src/event/manual_tests.rs b/backend/crates/station/src/event/manual_tests.rs index 9314ee5d1..7b7e4eab7 100644 --- a/backend/crates/station/src/event/manual_tests.rs +++ b/backend/crates/station/src/event/manual_tests.rs @@ -31,6 +31,7 @@ async fn manual_event_throughput() -> Result<(), Box> { notices, mut logging, mut pipeline, + mut pipeline_data, } = channels(&config); drop((tcp, orders, notices)); let event = spawn(config, event, Arc::default(), Arc::default(), None); @@ -44,12 +45,12 @@ async fn manual_event_throughput() -> Result<(), Box> { } count }); + // Data goes on ⑨; nothing else is sent here, but ⑥ must stay open. + let _events = tokio::spawn(async move { while pipeline.recv().await.is_some() {} }); let shown = tokio::spawn(async move { let mut count = 0; - while let Some(message) = pipeline.recv().await { - if let ToPipeline::Received(_) = message { - count += 1; - } + while pipeline_data.recv().await.is_some() { + count += 1; } count }); @@ -76,13 +77,16 @@ async fn manual_event_throughput() -> Result<(), Box> { 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 + ({:.1}x the required {REQUIRED_PER_SECOND:.0}/s); pipeline got {shown} \ + ({} dropped from the front)", + per_second / REQUIRED_PER_SECOND, + NOTIFICATIONS - shown ); assert!(matches!(stop, Stop::NetGone)); assert_eq!(logged, NOTIFICATIONS, "logging got every notification"); - assert_eq!(shown, NOTIFICATIONS, "pipeline got every notification"); + // The front's copy may be dropped when ⑨ is full; never more than sent. + assert!(shown <= NOTIFICATIONS); assert!(per_second > REQUIRED_PER_SECOND); Ok(()) } diff --git a/backend/crates/station/src/event/router.rs b/backend/crates/station/src/event/router.rs index 76028cbd6..0dc1f769d 100644 --- a/backend/crates/station/src/event/router.rs +++ b/backend/crates/station/src/event/router.rs @@ -1,7 +1,8 @@ //! The routing loop: everything towards the front. //! //! Reads ① ② ③ ④ in fixed order (errors, notices, TCP, UDP), hands every -//! notification to `logging` and `pipeline` (⑤ ⑥), decides what each error +//! notification to `logging` and `pipeline` (⑤, and ⑥ or ⑨ for telemetry), +//! 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. @@ -10,12 +11,13 @@ 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::model::{Packet, PodData}; +use software_core::net::{ErrorReport, Event, Notification, Sinks}; use software_core::protocol::Index; +use tokio::sync::mpsc::error::TrySendError; use tokio::sync::{mpsc, oneshot}; use tokio::time::Instant; -use tracing::{debug, error, warn}; +use tracing::{debug, error, info, warn}; use super::fault::FaultRequest; use super::policy::{self, Action}; @@ -24,7 +26,7 @@ use super::{ }; /// The routing loop's ends of the queues: the reading side of ① ② ③ ④ and -/// the writing side of ⑤ ⑥. +/// the writing side of ⑤ ⑥ ⑨. #[derive(Debug)] pub(super) struct RouterEnds { /// ① and ④: UDP's errors and notifications. @@ -35,8 +37,10 @@ pub(super) struct RouterEnds { pub(super) notices: mpsc::Receiver, /// ⑤: to `logging`. The workers get clones. pub(super) logging: mpsc::Sender, - /// ⑥: to `pipeline`. The workers get clones. + /// ⑥: to `pipeline`, everything but telemetry. The workers get clones. pub(super) pipeline: mpsc::Sender, + /// ⑨: telemetry to `pipeline`. Only the routing loop has it. + pub(super) pipeline_data: 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. @@ -114,12 +118,15 @@ pub(super) struct Router { notices: mpsc::Receiver, logging: mpsc::Sender, pipeline: mpsc::Sender, + pipeline_data: mpsc::Sender>, fault: mpsc::Sender, open: Open, tcp_capacity: usize, udp_capacity: usize, /// The addresses whose fault has already been shown. faults_shown: HashSet, + /// Data packets whose front copy was dropped since ⑨ last had room. + dropped_data: u64, } impl Router { @@ -142,18 +149,20 @@ impl Router { notices: ends.notices, logging: ends.logging, pipeline: ends.pipeline, + pipeline_data: ends.pipeline_data, fault, open: Open::default(), tcp_capacity: ends.tcp_capacity, udp_capacity: ends.udp_capacity, faults_shown: HashSet::new(), + dropped_data: 0, } } /// 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. + /// ⑧ ⑨ 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. @@ -232,23 +241,59 @@ impl Router { } } - /// Sends a notification to both consumers, as one shared copy. - async fn forward(&self, notification: Notification) -> Result<(), Consumer> { + /// Sends a notification to both consumers, as one shared copy: to + /// `logging` always, waiting for room; to `pipeline` on ⑨ if it is + /// telemetry, on ⑥ otherwise. + async fn forward(&mut self, notification: Notification) -> Result<(), Consumer> { let shared = Arc::new(notification); - // Sent to logging + // Logging first, so it has its copy whatever happens to the front's. self.logging .send(ToLogging::Received(shared.clone())) .await .map_err(|_| Consumer::Logging)?; - // Send to pipeline, + if matches!(shared.event, Event::Received(Packet::Data(_))) { + return self.forward_data(shared); + } self.pipeline .send(ToPipeline::Received(shared)) .await .map_err(|_| Consumer::Pipeline) } + /// Hands a data packet to `pipeline` on ⑨ without ever waiting: when ⑨ + /// is full the front is behind, and its copy is dropped (`logging` + /// already has it) instead of slowing down everything upstream. + /// + /// Traces only when it starts dropping and when ⑨ has room again, with + /// how many were dropped: no timer and no allocation per packet. + fn forward_data(&mut self, shared: Arc) -> Result<(), Consumer> { + match self.pipeline_data.try_send(shared) { + Ok(()) => { + if self.dropped_data > 0 { + info!( + dropped = self.dropped_data, + "pipeline caught up: the front gets telemetry again" + ); + self.dropped_data = 0; + } + Ok(()) + } + Err(TrySendError::Full(_)) => { + if self.dropped_data == 0 { + warn!( + "pipeline is behind: dropping the front's copy of telemetry \ + (logging still gets it)" + ); + } + self.dropped_data = self.dropped_data.saturating_add(1); + Ok(()) + } + Err(TrySendError::Closed(_)) => 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> { // diff --git a/backend/crates/station/src/event/tests.rs b/backend/crates/station/src/event/tests.rs index 5cec5a0cf..ad5e0bf17 100644 --- a/backend/crates/station/src/event/tests.rs +++ b/backend/crates/station/src/event/tests.rs @@ -161,6 +161,23 @@ async fn shown( Ok(notifications) } +/// The next `n` data packets on ⑨, the telemetry queue to `pipeline`. +async fn shown_data( + pipeline_data: &mut mpsc::Receiver>, + n: usize, +) -> Result>, Box> { + let mut notifications = Vec::with_capacity(n); + for _ in 0..n { + let notification = next(pipeline_data).await?; + assert!( + matches!(notification.event, Event::Received(Packet::Data(_))), + "only data packets go on ⑨" + ); + notifications.push(notification); + } + Ok(notifications) +} + /// The next `n` notifications on `logging`, failing on anything else. async fn logged( logging: &mut mpsc::Receiver, @@ -186,7 +203,7 @@ async fn each_notification_reaches_logging_and_pipeline_as_the_same_copy() -> Te let _event = spawn(config, channels.event, pod_data(), index(), None); let logged = logged(&mut channels.logging, 3).await?; - let shown = shown(&mut channels.pipeline, 3).await?; + let shown = shown_data(&mut channels.pipeline_data, 3).await?; for (logged, shown) in logged.iter().zip(&shown) { assert!(Arc::ptr_eq(logged, shown), "one copy, shared"); } @@ -213,10 +230,11 @@ async fn errors_come_first_then_tcp_then_udp() -> TestResult { }; assert!(matches!(tcp.event, Event::Connected)); - let ToPipeline::Received(udp) = next(&mut channels.pipeline).await? else { - unreachable!("then the UDP notification"); - }; - assert!(matches!(udp.event, Event::Received(Packet::Data(_)))); + // Logging keeps the order across transports; pipeline gets the data on ⑨. + let logged = logged(&mut channels.logging, 2).await?; + assert!(matches!(logged[0].event, Event::Connected)); + assert!(matches!(logged[1].event, Event::Received(Packet::Data(_)))); + shown_data(&mut channels.pipeline_data, 1).await?; Ok(()) } @@ -237,7 +255,7 @@ async fn a_fatal_error_passes_on_what_was_queued_and_stops() -> TestResult { assert!(notice.text.starts_with("HVSCU: "), "{}", notice.text); // The data that arrived before the error still gets through, to both. - shown(&mut channels.pipeline, 2).await?; + shown_data(&mut channels.pipeline_data, 2).await?; logged(&mut channels.logging, 2).await?; let Stop::Fatal(stopped_by) = stops(event).await? else { @@ -259,7 +277,7 @@ async fn a_board_fault_is_shown_once_per_board_and_sent_to_every_board_each_time } 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?; + channels.tcp.notify(HVSCU, Event::Connected).await?; let ToPipeline::Notice(first) = next(&mut channels.pipeline).await? else { unreachable!("HVSCU's first fault is shown"); @@ -377,6 +395,7 @@ async fn closed_queues_do_not_hide_the_others() -> TestResult { notices, mut logging, pipeline: _pipeline, + pipeline_data: _pipeline_data, } = channels(&config); drop((tcp, orders, notices)); let _event = spawn(config, event, pod_data(), index(), None); @@ -591,6 +610,7 @@ async fn when_logging_stops_event_stops_and_tells_pipeline() -> TestResult { notices: _notices, logging, mut pipeline, + pipeline_data: _pipeline_data, } = channels(&config); drop(logging); let event = spawn(config, event, pod_data(), index(), None); @@ -619,6 +639,7 @@ async fn when_net_closes_what_was_left_is_passed_on_and_event_stops() -> TestRes notices: _notices, mut logging, pipeline: _pipeline, + pipeline_data: _pipeline_data, } = channels(&config); udp.notify(HVSCU, data()).await?; udp.notify(HVSCU, data()).await?; @@ -660,3 +681,87 @@ async fn a_fault_that_never_goes_out_does_not_block_the_stop() -> TestResult { ); Ok(()) } + +#[tokio::test] +async fn data_goes_to_its_own_queue_and_everything_else_to_pipeline() -> TestResult { + let config = EventConfig::default(); + let mut channels = channels(&config); + channels.tcp.notify(HVSCU, Event::Connected).await?; + channels + .tcp + .notify(HVSCU, policy::protection_triggered(2)) + .await?; + channels.udp.notify(HVSCU, data()).await?; + let _event = spawn(config, channels.event, pod_data(), index(), None); + + let shown = shown(&mut channels.pipeline, 2).await?; + assert!(matches!(shown[0].event, Event::Connected)); + assert!(matches!( + shown[1].event, + Event::Received(Packet::Protection(_)) + )); + shown_data(&mut channels.pipeline_data, 1).await?; + + sleep(Duration::from_millis(50)).await; + assert!(channels.pipeline.try_recv().is_err(), "nothing else on ⑥"); + assert!( + channels.pipeline_data.try_recv().is_err(), + "nothing else on ⑨" + ); + Ok(()) +} + +#[tokio::test] +async fn a_full_data_queue_drops_the_front_copy_without_stopping_event() -> TestResult { + let config = EventConfig { + pipeline_data_queue: 2, + ..EventConfig::default() + }; + let mut channels = channels(&config); + let event = spawn(config, channels.event, pod_data(), index(), None); + + // ⑨ is never read meanwhile: pipeline is behind. + for _ in 0..5 { + channels.udp.notify(HVSCU, data()).await?; + } + channels.tcp.notify(HVSCU, Event::Connected).await?; + + // Logging gets everything, and event keeps routing: what comes after + // the data still reaches pipeline on ⑥. + logged(&mut channels.logging, 6).await?; + let shown = shown(&mut channels.pipeline, 1).await?; + assert!(matches!(shown[0].event, Event::Connected)); + + // ⑨ holds what fit; the front's copy of the rest was dropped. + shown_data(&mut channels.pipeline_data, 2).await?; + assert!(channels.pipeline_data.try_recv().is_err()); + assert!( + !event.is_finished(), + "a slow front does not stop the backend" + ); + Ok(()) +} + +#[tokio::test] +async fn closing_the_data_queue_means_pipeline_is_gone() -> TestResult { + let config = EventConfig::default(); + let Channels { + udp, + tcp: _tcp, + event, + orders: _orders, + notices: _notices, + logging: _logging, + pipeline: _pipeline, + pipeline_data, + } = channels(&config); + drop(pipeline_data); + let event = spawn(config, event, pod_data(), index(), None); + + udp.notify(HVSCU, data()).await?; + let Stop::Fatal(notice) = stops(event).await? else { + unreachable!("losing pipeline is fatal"); + }; + assert!(notice.text.contains("pipeline"), "{}", notice.text); + Ok(()) +} diff --git a/backend/crates/station/src/lib.rs b/backend/crates/station/src/lib.rs index 20d297fb6..46ea1e5e1 100644 --- a/backend/crates/station/src/lib.rs +++ b/backend/crates/station/src/lib.rs @@ -7,9 +7,14 @@ //! - [`event`]: the communication between the modules (see //! `src/event/README.md`). //! - [`http`]: the HTTP API (ADJ catalogs and the WebSocket upgrade). +//! - [`payload`]: the messages that travel over the WebSocket. +//! - [`pipeline`]: turns what `event` routes into what the front shows (see +//! `src/pipeline/README.md`). +//! - [`websocket`]: the broker and the connections with the frontends. pub mod event; pub mod http; +pub mod payload; +pub mod pipeline; mod vehicle; pub mod websocket; -pub mod payload; diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index ab048ae59..ebeb949f1 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -1,12 +1,13 @@ //! 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: +//! between UDP and two stand-ins: `logging` does not exist yet, and +//! [`station::pipeline`] needs the `websocket` broker, which is not started +//! yet either: //! //! - 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: -//! notices and failed orders. +//! - the **pipeline stand-in** counts the telemetry it gets and writes to the +//! log what the front would show: board connections, notices and orders. //! //! There is no TCP and no websocket yet: their queues are closed at start. //! @@ -163,6 +164,7 @@ async fn serve( notices, logging, pipeline, + pipeline_data, } = event::channels(&config); // Not built yet: TCP, websocket, and modules that report notices. @@ -182,7 +184,7 @@ async fn serve( 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 pipeline_task = tokio::spawn(stand_in_pipeline(pipeline, pipeline_data, pod_data.clone())); let mut event_task = event::spawn(config, ends, pod_data, index, None); let (stop, by_ctrl_c) = tokio::select! { @@ -253,12 +255,36 @@ async fn stand_in_logging(mut queue: mpsc::Receiver, pod_data: Arc, pod_data: Arc) { - let mut received: u64 = 0; - while let Some(message) = queue.recv().await { +/// +/// Reads ⑥ (everything but telemetry) before ⑨ (telemetry), like `pipeline`, +/// until `event` has closed both. +async fn stand_in_pipeline( + mut queue: mpsc::Receiver, + mut data: mpsc::Receiver>, + pod_data: Arc, +) { + let (mut received, mut data_received): (u64, u64) = (0, 0); + let (mut queue_open, mut data_open) = (true, true); + while queue_open || data_open { + let message = tokio::select! { + biased; + message = queue.recv(), if queue_open => message, + notification = data.recv(), if data_open => { + // The front would get counts, cycle times and averages; here + // packets are only counted. When this falls behind, event + // drops the front's copy: the count may be lower than logging's. + match notification { + Some(_) => data_received += 1, + None => data_open = false, + } + continue; + } + }; + let Some(message) = message else { + queue_open = false; + continue; + }; 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); @@ -294,7 +320,11 @@ async fn stand_in_pipeline(mut queue: mpsc::Receiver, pod_data: Arc< } } } - info!(notifications = received, "pipeline stand-in finished"); + info!( + notifications = received, + data = data_received, + "pipeline stand-in finished" + ); } /// Who an order went to: its board, or every board for the fault. diff --git a/backend/crates/station/src/pipeline.rs b/backend/crates/station/src/pipeline.rs new file mode 100644 index 000000000..ec8823187 --- /dev/null +++ b/backend/crates/station/src/pipeline.rs @@ -0,0 +1,314 @@ +//! Transforms what `event` routes to the front into frontend WebSocket +//! payloads and publishes them through +//! [`crate::websocket::broker::BrokerClient`]. +//! +//! It reads two queues: ⑥ ([`crate::event::ToPipeline`]: everything but +//! telemetry) and ⑨ (telemetry only, `Packet::Data` notifications). +//! +//! # Contract +//! +//! - **Immediate events.** Board connections, protections and board messages +//! are published as soon as they arrive. Notices and order outcomes are +//! published as messages from the backend itself (`backend/message`). +//! - **100 ms data aggregation.** `Packet::Data` frames are accumulated per +//! packet ID in memory (cumulative `count`, mean `cycle_time` over the +//! window, and per-measurement `last` + window `average`) and flushed to +//! `podData/update` on a fixed interval. +//! - **Events before telemetry.** ⑥ is always read before ⑨, so a protection +//! or a message never waits behind telemetry. +//! - **Saturation is `event`'s.** When ⑨ is full because `pipeline` is behind, +//! `event` drops the front's copy of telemetry instead of waiting; `pipeline` +//! itself drops nothing and awaits broker capacity. +//! - **Clean shutdown.** Once `event` has closed both queues, any pending +//! telemetry is flushed to the broker before the task exits. +//! +//! # Not handled here +//! +//! - Frontend-to-backend topics (`order/send`, `logger/enable`, +//! `logger/variables`, `connection/heartbeat`) are consumed by `websocket`, +//! which also detects a lost frontend and reports it to `event` itself. +//! - `logger/response` is published directly by `logging`. +//! - `order/stateOrders` has no corresponding packet variant in +//! `software_core::model::Packet` yet. + +mod accumulator; +mod message; +mod timestamp; + +#[cfg(test)] +mod tests; + +use std::collections::HashMap; +use std::sync::Arc; +use std::time::Duration; + +use crate::event::ToPipeline; +use crate::payload::{ + Connection, ConnectionUpdate, DataPacketUpdate, DataUpdate, ProtectionUpdate, +}; +use crate::websocket::broker::BrokerClient; +use accumulator::DataAccumulator; +use software_core::model::{AdjId, BoardId, Packet, PodData}; +use software_core::net::{Event, Notification}; +use software_core::protocol::Index; +use tokio::sync::mpsc; +use tokio::task::JoinHandle; +use tokio::time::{Instant, MissedTickBehavior, interval_at}; +use tracing::{error, warn}; + +/// Configuration for the pipeline task. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Config { + /// How often accumulated `Data` telemetry is flushed to the broker. + pub data_flush_interval: Duration, +} + +impl Default for Config { + fn default() -> Self { + Self { + data_flush_interval: Duration::from_millis(100), + } + } +} + +/// Spawns the pipeline task consuming `rx` (⑥) and `data_rx` (⑨), both from +/// `event`, and publishing payloads to `broker`. +/// +/// The task exits cleanly once both queues close and pending telemetry is +/// flushed, or immediately if `broker` has already shut down. +pub fn spawn( + config: Config, + rx: mpsc::Receiver, + data_rx: mpsc::Receiver>, + broker: BrokerClient, + pod_data: Arc, + index: Arc, +) -> JoinHandle<()> { + tokio::spawn(run_loop(config, rx, data_rx, broker, pod_data, index)) +} + +/// Runs the main pipeline loop, interleaving periodic 100 ms telemetry +/// flushes, incoming [`ToPipeline`] items and incoming telemetry. +async fn run_loop( + config: Config, + mut rx: mpsc::Receiver, + mut data_rx: mpsc::Receiver>, + broker: BrokerClient, + pod_data: Arc, + index: Arc, +) { + // `tokio::time::interval_at` panics on a zero duration; clamp to at least 1 ms. + let period = config.data_flush_interval.max(Duration::from_millis(1)); + // Start the first tick after one full period rather than immediately at t = 0. + let mut tick = interval_at(Instant::now() + period, period); + // Skip missed ticks instead of firing a burst of catch-up flushes after a stall. + tick.set_missed_tick_behavior(MissedTickBehavior::Skip); + + let mut accumulator = DataAccumulator::default(); + + // Track connection state for every board declared in the ADJ (all start disconnected). + let mut board_connections: HashMap = + pod_data.boards.keys().map(|&id| (id, false)).collect(); + + // Publish initial `false` states so the frontend immediately sees all boards. + if !board_connections.is_empty() + && !publish_or_log( + broker + .publish_connections(connection_snapshot(&board_connections, &pod_data)) + .await, + ) + { + return; + } + + // Holds the latest snapshot per packet ID because `Broker::publish_data` replaces the whole map. + let mut latest_data: HashMap = HashMap::new(); + + // A closed queue answers "closed" instantly, every time, so it is no + // longer polled: in a `biased;` select it would win every round. + let mut events_open = true; + let mut data_open = true; + + while events_open || data_open { + // `biased;` polls branches in top-to-bottom order instead of randomly: + // the flush tick first, so sustained traffic cannot starve flushes; + // then events, so they never wait behind telemetry. + tokio::select! { + biased; + // 1. Periodic 100 ms telemetry flush. + _ = tick.tick() => { + if !flush_data(&broker, &index, &mut accumulator, &mut latest_data).await { + return; + } + } + // 2. Everything but telemetry (⑥). + item = rx.recv(), if events_open => { + let Some(item) = item else { + events_open = false; + continue; + }; + if !handle_item( + item, + &broker, + &pod_data, + &index, + &mut accumulator, + &mut board_connections, + ) + .await + { + return; + } + } + // 3. Telemetry (⑨): recording it never waits. + notification = data_rx.recv(), if data_open => { + let Some(notification) = notification else { + data_open = false; + continue; + }; + if let Event::Received(Packet::Data(data)) = ¬ification.event { + accumulator.record(data, notification.at, &index); + } + } + } + } + + // `event` has closed both queues: publish what is left and stop. + let _ = flush_data(&broker, &index, &mut accumulator, &mut latest_data).await; +} + +/// Handles a single [`ToPipeline`] item. Returns `false` if the broker closed. +async fn handle_item( + item: ToPipeline, + broker: &BrokerClient, + pod_data: &PodData, + index: &Index, + accumulator: &mut DataAccumulator, + board_connections: &mut HashMap, +) -> bool { + match item { + ToPipeline::Received(notification) => { + handle_notification( + ¬ification, + broker, + pod_data, + index, + accumulator, + board_connections, + ) + .await + } + ToPipeline::Notice(notice) => match message::from_notice(notice, pod_data) { + Some(message) => publish_or_log(broker.publish_backend_message(message).await), + None => true, + }, + ToPipeline::OrderSent { at, board, order } => { + let message = message::from_order_sent(at, board, &order, pod_data, index); + publish_or_log(broker.publish_backend_message(message).await) + } + ToPipeline::OrderFailed { at, order, reason } => { + let message = message::from_order_failed(at, &order, &reason, pod_data, index); + publish_or_log(broker.publish_backend_message(message).await) + } + } +} + +/// Maps a wire-level [`Notification`] that arrived on ⑥ (connection +/// transition or decoded packet) to its WebSocket topic. +/// +/// Returns `false` if publishing fails because the broker closed. +async fn handle_notification( + notification: &Notification, + broker: &BrokerClient, + pod_data: &PodData, + index: &Index, + accumulator: &mut DataAccumulator, + board_connections: &mut HashMap, +) -> bool { + match ¬ification.event { + Event::Connected | Event::Disconnected => { + let is_connected = matches!(notification.event, Event::Connected); + if board_connections.insert(notification.board, is_connected) == Some(is_connected) { + return true; + } + let snapshot = connection_snapshot(board_connections, pod_data); + publish_or_log(broker.publish_connections(snapshot).await) + } + // `event` sends telemetry on ⑨; recorded all the same if it ever + // arrives here. + Event::Received(Packet::Data(data)) => { + accumulator.record(data, notification.at, index); + true + } + Event::Received(Packet::Protection(protection)) => { + let update = ProtectionUpdate { + id: protection.id, + value: protection.value.clone(), + timestamp: timestamp::from_short(notification.at, protection.timestamp), + }; + publish_or_log(broker.publish_protection(update).await) + } + Event::Received(Packet::Message(msg)) => { + let update = message::from_board_message( + notification.board, + notification.at, + msg, + pod_data, + index, + ); + publish_or_log(broker.publish_message(update).await) + } + Event::Received(Packet::Order(order)) => { + warn!(id = order.id.0, "ignoring unexpected inbound order packet"); + true + } + } +} + +/// Drains all telemetry packets updated during the current window and +/// publishes each [`crate::payload::DataPacketUpdate`] to the broker. +/// +/// Stops early and returns `false` if the broker has closed. +async fn flush_data( + broker: &BrokerClient, + index: &Index, + accumulator: &mut DataAccumulator, + latest_data: &mut HashMap, +) -> bool { + let updates = accumulator.drain_updates(index); + if updates.is_empty() { + return true; + } + for update in updates { + latest_data.insert(update.id, update); + } + publish_or_log(broker.publish_data(DataUpdate(latest_data.clone())).await) +} + +/// Converts a broker publish result into a loop-continuation flag (`true` to +/// keep running, `false` to exit), logging an error when the broker closes. +fn publish_or_log(result: Result<(), crate::websocket::broker::Error>) -> bool { + match result { + Ok(()) => true, + Err(err) => { + error!(%err, "websocket broker closed, stopping pipeline"); + false + } + } +} + +/// Builds the full `connection/update` snapshot from `board_connections`. +fn connection_snapshot( + board_connections: &HashMap, + pod_data: &PodData, +) -> ConnectionUpdate { + ConnectionUpdate( + board_connections + .iter() + .map(|(&id, &is_connected)| { + let name = message::board_name(pod_data, id); + (name.clone(), Connection { name, is_connected }) + }) + .collect(), + ) +} diff --git a/backend/crates/station/src/pipeline/README.md b/backend/crates/station/src/pipeline/README.md new file mode 100644 index 000000000..503f82391 --- /dev/null +++ b/backend/crates/station/src/pipeline/README.md @@ -0,0 +1,168 @@ +# Pipeline (`station::pipeline`) + +Transforms what `event` routes to the front into frontend WebSocket payloads +(`station::payload`) and publishes them through +[`crate::websocket::broker::BrokerClient`]. It reads two queues from `event`: +⑥ ([`crate::event::ToPipeline`]: everything but telemetry) and ⑨ (telemetry +only: `Arc`, every one a `Packet::Data`). + +`event` routes decoded packets and backend outcomes without inspecting their +contents. `pipeline` is the stage that turns them into the exact shapes the +frontend expects: it publishes discrete events immediately, tracks per-board +connection state, and aggregates high-rate UDP telemetry into 100 ms windows. + +## Overview + +```text + event ─⑥ ToPipeline──────────► pipeline + ├── immediate ──► BrokerClient + │ ├── connection/update + │ ├── protection/update + │ ├── message/update (board messages) + │ └── backend/message (notices, order outcomes) + event ─⑨ Arc───► └── 100 ms tick ─► BrokerClient + (data packets only) └── podData/update +``` + +## Files + +```text +pipeline.rs # module root: Config, spawn, biased select! loop, routing +pipeline/ +├── accumulator.rs # 100 ms telemetry windowing (count, cycle_time, last, average) +├── message.rs # message/update and backend/message builders +├── timestamp.rs # SystemTime / ShortTimestamp -> UTC MessageTimestamp +├── tests.rs # unit tests against a real Broker (no sockets) +└── README.md +``` + +## Input-to-Topic Mapping + +| Input | Condition / inner event | Topic | Broker method | Delivery | +| --- | --- | --- | --- | --- | +| `ToPipeline::Received` | `Event::Connected` / `Event::Disconnected` | `connection/update` | `publish_connections`, on change | Immediate | +| ⑨ telemetry | `Event::Received(Packet::Data(_))` | `podData/update` | `publish_data` | 100 ms window | +| `ToPipeline::Received` | `Event::Received(Packet::Protection(_))` | `protection/update` | `publish_protection` | Immediate | +| `ToPipeline::Received` | `Event::Received(Packet::Message(_))` | `message/update` | `publish_message` | Immediate | +| `ToPipeline::Received` | `Event::Received(Packet::Order(_))` | — | Ignored (traced as a warning) | — | +| `ToPipeline::Notice` | `Info` → `info`, `Warning` → `warning`, `Fatal` → `fault` | `backend/message` | `publish_backend_message` | Immediate | +| `ToPipeline::Notice` | `Silent` | — | Ignored | — | +| `ToPipeline::OrderSent` | Confirmed TCP write → `info` | `backend/message` | `publish_backend_message` | Immediate | +| `ToPipeline::OrderFailed` | Failed write → `warning` | `backend/message` | `publish_backend_message` | Immediate | + +### Not handled by `pipeline` + +- **Frontend-to-backend topics** (`order/send`, `logger/enable`, + `logger/variables`, `connection/heartbeat`) are handled by `websocket`. +- **Frontend liveness** is `websocket`'s: it tracks the heartbeats and reports + a lost frontend to `event` itself. +- **`logger/response`** is published by `logging`. +- **`order/stateOrders`** is not produced: `software_core::model::Packet` has + no state-orders packet variant. + +## Board Connections (`pipeline.rs`) + +`pipeline` keeps a `HashMap` seeded at startup with every board +declared in `PodData::boards`, all disconnected. + +- On startup, the full map is published to `connection/update` so the frontend + sees every board at once. +- `Event::Connected` and `Event::Disconnected` update the map, and the full map + is published again only when a board's state actually changes. + +## 100 ms Data Aggregation (`accumulator.rs`) + +High-frequency telemetry (`Packet::Data`) is accumulated per packet ID and +flushed every `Config::data_flush_interval` (default `100 ms`). + +- **Per packet:** + - `count`: packets received under that `AdjId` since startup. + - `cycleTime`: mean interval between receptions, in nanoseconds, over the + packets received in the current window (the previous reception time + carries over from one window to the next). +- **Per measurement**, keyed by its numeric ADJ `id` (as `payload` defines it): + - Numeric measurements carry `{ "last": f64, "average": f64 }`: the latest + sample and the arithmetic mean over the window. + - Boolean and enum measurements carry their latest value. +- **Snapshot:** the broker replaces the whole `podData/update` map on every + publication, so `pipeline` keeps the latest update of every packet and + publishes all of them on each flush. A packet with no frames in a window + keeps its previous values; a window with no frames at all publishes nothing. + +## Messages & Timestamps (`message.rs`, `timestamp.rs`) + +- **Board messages** (`message/update`): `kind` and `name` are the level the + ADJ assigns to the message id (`name` is its ADJ name, such as `"warning"`), + `origin` is the packet's `origin` (where on the board it was produced) and + `payload` its text. +- **Backend messages** (`backend/message`): a notice keeps its board, or + `null` when it concerns no single board. Order outcomes name the order as + the ADJ does (`"Order Start sent"`, `"Order Start not sent: "`), on + the order's board; the fault (order id 0) concerns every board, so its board + is `null`. +- **Board names** come from `PodData::board_name`, falling back to the board's + id, as in `event`. +- **Timestamps** are UTC calendar times. Backend messages take them from the + moment the backend produced them. Board messages and protections combine the + reception date with the board's `ShortTimestamp` time of day. + +## Loop Priority, Contract & Shutdown + +- **Biased `select!` priority:** `run_loop` polls, in this order, the 100 ms + flush tick, ⑥ and ⑨. Sustained telemetry cannot starve flushes, and a + protection or a message never waits behind telemetry. +- **Saturation is `event`'s.** `pipeline` drops nothing: recording a data + packet never waits, and publishing awaits `BrokerClient` capacity. When + `pipeline` falls behind and ⑨ fills up, `event` drops the front's copy of + telemetry instead of waiting (`logging` still gets it), so a slow front + never slows down the backend. `count` is then the packets `pipeline` + received, not every packet the board sent. +- **No error policy.** Classifying errors and sending the fault belong to + `event`; `pipeline` only shows what it receives. +- **Clean shutdown.** + - A closed queue is no longer polled. Once `event` has closed both ⑥ and ⑨, + `pipeline` flushes any pending telemetry and exits, dropping its + `BrokerClient`. + - If `BrokerClient` returns `Error::BrokerClosed`, `pipeline` traces the + error and exits immediately; `event` then sees ⑥ and ⑨ closed. + +## Usage + +```rust +use station::pipeline::{self, Config}; + +let pipeline_handle = pipeline::spawn( + Config::default(), + channels.pipeline, // ⑥ + channels.pipeline_data, // ⑨ + broker_client, + pod_data, + index, +); +``` + +## Tests + +Unit tests in `pipeline/tests.rs` wire `pipeline::spawn` to a real `Broker` +(no sockets), on an ADJ fixture with two boards, and check: + +- immediate forwarding of board connections, protections and board messages, + with `origin`/`name` as in `payload/example/message.json`; +- every board published as disconnected at startup, and the connection map + published again only when a board's state changes; +- notices of every kind and both order outcomes on `backend/message`, and + nothing the backend produces on `message/update`; +- 100 ms windowing for `Packet::Data` (cumulative `count`, mean `cycleTime`, + window `average`, `last`, and flush on shutdown); +- the whole `podData/update` map on every flush (a packet with no frames + keeps its values), and nothing published for an empty window; +- telemetry still read after ⑥ closes, and the task ending, with a final + flush, only once both queues are closed; +- the task ending as soon as the broker is gone, which closes ⑥ and ⑨; +- the accumulator's defensive paths: packets the ADJ does not declare as + `Data`, a clock that steps back, and values missing or of another kind; +- UTC calendar conversion on epoch and leap-day timestamps. + +```sh +cargo test -p station pipeline +``` diff --git a/backend/crates/station/src/pipeline/accumulator.rs b/backend/crates/station/src/pipeline/accumulator.rs new file mode 100644 index 000000000..a02d56f65 --- /dev/null +++ b/backend/crates/station/src/pipeline/accumulator.rs @@ -0,0 +1,213 @@ +use std::collections::HashMap; +use std::time::SystemTime; + +use crate::payload::{DataPacketUpdate, MeasurementUpdate}; +use software_core::model::{AdjId, DataPacket, PacketType, Value}; +use software_core::protocol::Index; +use tracing::debug; + +/// Accumulates `Data` packets per packet ID across each flush window. +#[derive(Debug, Default)] +pub(super) struct DataAccumulator { + packets: HashMap, +} + +#[derive(Debug)] +struct PacketWindow { + /// Total packets received for this ID since startup. + count: u64, + /// Arrival timestamp of the previous packet (persists across flush windows). + last_at: Option, + /// Last computed mean cycle time in nanoseconds. + last_cycle_time_ns: u64, + /// Sum of inter-arrival deltas (ns) within the current window. + cycle_sum_ns: u128, + /// Number of inter-arrival deltas recorded within the current window. + cycle_samples: u64, + /// Positional measurement accumulators matching `PacketType::Data`. + measurements: Vec>, + /// Whether at least one packet arrived since the last flush. + dirty: bool, +} + +#[derive(Debug)] +enum MeasurementAccumulator { + Numeric { last: f64, sum: f64, samples: u64 }, + Boolean(bool), + Enum(String), +} + +impl MeasurementAccumulator { + /// Initializes an accumulator from the first decoded [`Value`] observed in + /// the current flush window. + fn from_value(value: &Value) -> Self { + match value { + Value::Number(v) => Self::Numeric { + last: *v, + sum: *v, + samples: 1, + }, + Value::Bool(b) => Self::Boolean(*b), + Value::Enum(s) => Self::Enum(s.clone()), + } + } + + /// Folds a newly received [`Value`] into this measurement's window state, + /// updating the running sum/sample count for numbers or replacing the + /// latest value for booleans and enums. + fn update(&mut self, value: &Value) { + match (self, value) { + (Self::Numeric { last, sum, samples }, Value::Number(v)) => { + *last = *v; + *sum += *v; + *samples += 1; + } + (Self::Boolean(last), Value::Bool(b)) => { + *last = *b; + } + (Self::Enum(last), Value::Enum(s)) => { + // `clone_from` reuses `last`'s existing heap buffer when the + // variant changes, avoiding a fresh String allocation. + if last != s { + last.clone_from(s); + } + } + (slot, other) => { + // Defensive fallback if a measurement's runtime variant ever + // disagrees with the previous sample in the same slot. + *slot = Self::from_value(other); + } + } + } + + /// Finalizes the window accumulator into the serialized + /// [`MeasurementUpdate`] payload, computing the arithmetic mean for + /// numeric measurements. + fn into_update(self) -> MeasurementUpdate { + match self { + Self::Numeric { last, sum, samples } => MeasurementUpdate::Numeric { + last, + average: sum / (samples as f64), + }, + Self::Boolean(b) => MeasurementUpdate::Boolean(b), + Self::Enum(s) => MeasurementUpdate::Enum(s), + } + } +} + +impl DataAccumulator { + /// Records one incoming [`DataPacket`] into its per-ID window, updating + /// cumulative packet count, inter-arrival timing, and per-measurement stats. + /// + /// The checks below cannot fail for a packet `protocol` decoded with the + /// same [`Index`]; they trace at `debug` so that, if they ever did, they + /// would not flood the log at telemetry rate. + pub(super) fn record(&mut self, packet: &DataPacket, at: SystemTime, index: &Index) { + let Some(def) = index.packet(packet.id) else { + debug!(id = packet.id.0, "unknown data packet id in index"); + return; + }; + let PacketType::Data(defs) = &def.packet_type else { + debug!( + id = packet.id.0, + "packet id in DataPacket does not map to PacketType::Data" + ); + return; + }; + + if packet.values.len() != defs.len() { + debug!( + id = packet.id.0, + expected = defs.len(), + actual = packet.values.len(), + "data packet value count mismatch" + ); + } + + // Lazily initialize the packet's window on first arrival. Mapping over + // `0..defs.len()` avoids requiring `Clone` on `MeasurementAccumulator`. + let window = self + .packets + .entry(packet.id) + .or_insert_with(|| PacketWindow { + count: 0, + last_at: None, + last_cycle_time_ns: 0, + cycle_sum_ns: 0, + cycle_samples: 0, + measurements: (0..defs.len()).map(|_| None).collect(), + dirty: false, + }); + + window.count = window.count.saturating_add(1); + // Rust 2024 let-chain: only accumulate cycle time when a previous + // timestamp exists and the system clock did not step backwards. + if let Some(prev) = window.last_at + && let Ok(delta) = at.duration_since(prev) + { + window.cycle_sum_ns = window.cycle_sum_ns.saturating_add(delta.as_nanos()); + window.cycle_samples = window.cycle_samples.saturating_add(1); + } + window.last_at = Some(at); + + // Match positional wire values to their positional slots; `zip` stops + // safely at the shorter slice if a count mismatch occurred. + for (slot, value) in window.measurements.iter_mut().zip(packet.values.iter()) { + match slot { + Some(acc) => acc.update(value), + None => *slot = Some(MeasurementAccumulator::from_value(value)), + } + } + + window.dirty = true; + } + + /// Builds [`DataPacketUpdate`] payloads for every packet ID that received + /// at least one frame since the last flush, resetting per-window accumulators + /// while preserving cumulative `count` and `last_at`. + pub(super) fn drain_updates(&mut self, index: &Index) -> Vec { + let mut updates = Vec::new(); + + for (&id, window) in &mut self.packets { + if !window.dirty { + continue; + } + window.dirty = false; + + // Average inter-arrival deltas in u128 (matching `Duration::as_nanos`) + // and clamp to `u64::MAX` on overflow instead of truncating with `as`. + if window.cycle_samples > 0 { + let avg_ns = window.cycle_sum_ns / u128::from(window.cycle_samples); + window.last_cycle_time_ns = u64::try_from(avg_ns).unwrap_or(u64::MAX); + window.cycle_sum_ns = 0; + window.cycle_samples = 0; + } + + let Some(def) = index.packet(id) else { + continue; + }; + let PacketType::Data(defs) = &def.packet_type else { + continue; + }; + + // `slot.take()` moves the accumulator out and resets the slot to + // `None` in one step, preparing it cleanly for the next 100 ms window. + let mut measurement_updates: HashMap = + HashMap::with_capacity(defs.len()); + for (measurement_def, slot) in defs.iter().zip(window.measurements.iter_mut()) { + if let Some(acc) = slot.take() { + measurement_updates.insert(measurement_def.id, acc.into_update()); + } + } + + updates.push(DataPacketUpdate { + id, + count: window.count, + cycle_time: window.last_cycle_time_ns, + measurement_updates, + }); + } + + updates + } +} diff --git a/backend/crates/station/src/pipeline/message.rs b/backend/crates/station/src/pipeline/message.rs new file mode 100644 index 000000000..5e514117a --- /dev/null +++ b/backend/crates/station/src/pipeline/message.rs @@ -0,0 +1,130 @@ +use std::time::SystemTime; + +use super::timestamp; +use crate::event::{Notice, NoticeKind}; +use crate::payload::{BackendMessage, MessageUpdate}; +use software_core::model::{ + AdjId, BoardId, MessageLevel, MessagePacket, OrderPacket, PacketType, PodData, +}; +use software_core::protocol::Index; +use tracing::warn; + +/// Order id 0: the fault, sent to every board. +const FAULT_ID: AdjId = AdjId(0); + +/// The board's name as the ADJ declares it, or its id if the ADJ does not +/// declare it (the same fallback `event` uses). +pub(super) fn board_name(pod_data: &PodData, board: BoardId) -> String { + pod_data + .board_name(board) + .map_or_else(|| format!("{board:?}"), str::to_owned) +} + +/// The order's name as the ADJ declares it, or its numeric id if the ADJ +/// does not declare it. +fn order_name(index: &Index, order: AdjId) -> String { + index + .packet(order) + .map_or_else(|| order.0.to_string(), |def| def.name.clone()) +} + +/// Converts a board's free-text [`MessagePacket`] into a `message/update` +/// payload, resolving its level from the ADJ [`Index`]. +pub(super) fn from_board_message( + board: BoardId, + at: SystemTime, + message: &MessagePacket, + pod_data: &PodData, + index: &Index, +) -> MessageUpdate { + let kind = match index.packet(message.id).map(|def| &def.packet_type) { + Some(PacketType::Message(level)) => *level, + Some(_) => { + warn!( + id = message.id.0, + "message packet id does not map to PacketType::Message" + ); + MessageLevel::Info + } + None => { + warn!(id = message.id.0, "unknown message packet id in index"); + MessageLevel::Info + } + }; + + MessageUpdate { + kind, + payload: message.message.clone(), + board: board_name(pod_data, board), + origin: message.origin.clone(), + name: kind.name().to_owned(), + timestamp: timestamp::from_short(at, message.timestamp), + } +} + +/// Converts a [`Notice`] into a `backend/message` payload, keeping its kind: +/// `Info` as info, `Warning` as warning, `Fatal` as fault. Returns `None` for +/// [`NoticeKind::Silent`], which is never shown on the front. +pub(super) fn from_notice(notice: Notice, pod_data: &PodData) -> Option { + let kind = match notice.kind { + NoticeKind::Info => MessageLevel::Info, + NoticeKind::Warning => MessageLevel::Warning, + NoticeKind::Fatal => MessageLevel::Fault, + NoticeKind::Silent => return None, + }; + + Some(BackendMessage::new( + kind, + notice.board.map(|board| board_name(pod_data, board)), + notice.text, + timestamp::from_system_time(notice.at), + )) +} + +/// Builds the informational `backend/message` confirming that TCP wrote an +/// order. `board` is `None` for the fault, which goes to every board. +pub(super) fn from_order_sent( + at: SystemTime, + board: Option, + order: &OrderPacket, + pod_data: &PodData, + index: &Index, +) -> BackendMessage { + let name = order_name(index, order.id); + let text = match board { + Some(_) => format!("Order {name} sent"), + None => format!("Order {name} sent to every board"), + }; + + BackendMessage::new( + MessageLevel::Info, + board.map(|board| board_name(pod_data, board)), + text, + timestamp::from_system_time(at), + ) +} + +/// Builds the warning `backend/message` explaining why an order did not go +/// out. The board is the one the ADJ assigns to the order; none for the fault. +pub(super) fn from_order_failed( + at: SystemTime, + order: &OrderPacket, + reason: &str, + pod_data: &PodData, + index: &Index, +) -> BackendMessage { + let board = if order.id == FAULT_ID { + None + } else { + index + .packet(order.id) + .map(|def| board_name(pod_data, def.board)) + }; + + BackendMessage::new( + MessageLevel::Warning, + board, + format!("Order {} not sent: {reason}", order_name(index, order.id)), + timestamp::from_system_time(at), + ) +} diff --git a/backend/crates/station/src/pipeline/tests.rs b/backend/crates/station/src/pipeline/tests.rs new file mode 100644 index 000000000..15d4a9b73 --- /dev/null +++ b/backend/crates/station/src/pipeline/tests.rs @@ -0,0 +1,771 @@ +use std::collections::HashMap; +use std::net::IpAddr; +use std::sync::Arc; +use std::time::{Duration, UNIX_EPOCH}; + +use software_core::model::{ + AdjId, Board, BoardId, DataPacket, MacAddress, Measurement, MeasurementKind, MessageLevel, + MessagePacket, NumericKind, OrderPacket, Packet, PacketDef, PacketType, PodData, + ProtectionPacket, ShortTimestamp, Value, +}; +use software_core::net::{Event, Notification}; +use software_core::protocol::Index; +use tokio::sync::mpsc; +use tokio::time::{advance, timeout}; + +use super::accumulator::DataAccumulator; +use super::{Config, spawn, timestamp}; +use crate::event::{Notice, NoticeKind, ToPipeline}; +use crate::payload::{ConnectionUpdate, MeasurementUpdate, MessageTimestamp, ProtectionUpdate}; +use crate::websocket::broker::Broker; + +/// Builds a minimal ADJ fixture with two boards: +/// +/// - `PCU` (ID 5): a 3-measurement `Data` packet (ID 551), an `Order` packet +/// (ID 1001) and a `Warning` message definition (ID 10); +/// - `BCU` (ID 6): a 1-measurement `Data` packet (ID 661). +fn sample_fixture() -> (Arc, Arc) { + let voltage_a = Measurement { + id: AdjId(3001), + alias: "voltage_battery_a".to_string(), + name: "Voltage Battery A".to_string(), + display_units: "V".to_string(), + kind: MeasurementKind::Numeric { + wire_type: NumericKind::F32, + }, + protections: vec![], + }; + let active = Measurement { + id: AdjId(3002), + alias: "is_active".to_string(), + name: "Is Active".to_string(), + display_units: String::new(), + kind: MeasurementKind::Boolean, + protections: vec![], + }; + let state = Measurement { + id: AdjId(3003), + alias: "state".to_string(), + name: "State".to_string(), + display_units: String::new(), + kind: MeasurementKind::Enum { + options: vec!["Idle".to_string(), "Fault".to_string()], + }, + protections: vec![], + }; + + let data_def = PacketDef { + id: AdjId(551), + board: BoardId(5), + name: "Batteries Voltage".to_string(), + packet_type: PacketType::Data(vec![voltage_a, active, state]), + }; + let order_def = PacketDef { + id: AdjId(1001), + board: BoardId(5), + name: "Start".to_string(), + packet_type: PacketType::Order(vec![]), + }; + let msg_def = PacketDef { + id: AdjId(10), + board: BoardId(0), + name: "warning".to_string(), + packet_type: PacketType::Message(MessageLevel::Warning), + }; + + let pcu = Board { + id: BoardId(5), + name: "PCU".to_string(), + ip: IpAddr::from([192, 168, 0, 5]), + mac: MacAddress([0; 6]), + packets: HashMap::from([ + (data_def.id, data_def), + (order_def.id, order_def), + (msg_def.id, msg_def), + ]), + }; + + let current = Measurement { + id: AdjId(3101), + alias: "current".to_string(), + name: "Current".to_string(), + display_units: "A".to_string(), + kind: MeasurementKind::Numeric { + wire_type: NumericKind::F32, + }, + protections: vec![], + }; + let current_def = PacketDef { + id: AdjId(661), + board: BoardId(6), + name: "Current".to_string(), + packet_type: PacketType::Data(vec![current]), + }; + let bcu = Board { + id: BoardId(6), + name: "BCU".to_string(), + ip: IpAddr::from([192, 168, 0, 6]), + mac: MacAddress([0; 6]), + packets: HashMap::from([(current_def.id, current_def)]), + }; + + let pod_data = Arc::new(PodData { + boards: HashMap::from([(pcu.id, pcu), (bcu.id, bcu)]), + }); + let index = Arc::new(Index::new(&pod_data, None)); + (pod_data, index) +} + +/// Verifies that every non-telemetry `ToPipeline` variant is transformed and +/// forwarded to its corresponding broker topic immediately. +#[tokio::test] +async fn forwards_connections_protections_and_board_messages_immediately() +-> Result<(), Box> { + let (pod_data, index) = sample_fixture(); + let (broker, client) = Broker::new(); + let sub = client.subscriber(); + let mut conn_sub = sub.subscribe_connections(); + let mut msg_sub = sub.subscribe_messages()?; + let mut prot_sub = sub.subscribe_protections()?; + let mut backend_sub = sub.subscribe_backend_messages()?; + let broker_task = tokio::spawn(broker.run()); + + let (tx, rx) = mpsc::channel(32); + let (data_tx, data_rx) = mpsc::channel(32); + let pipe_task = spawn(Config::default(), rx, data_rx, client, pod_data, index); + + // 1. Connection update + tx.send(ToPipeline::Received(Arc::new(Notification { + board: BoardId(5), + at: UNIX_EPOCH + Duration::from_secs(1_700_000_000), + event: Event::Connected, + }))) + .await?; + timeout(Duration::from_secs(1), conn_sub.changed()).await??; + assert!(conn_sub.borrow_and_update().0["PCU"].is_connected); + + // 2. Protection event + // Compound ADJv3 protection ID: high 3 bits = protection slot (1), low 13 bits = measurement ID (3001). + let protection = ProtectionPacket { + id: AdjId((1 << 13) | 3001), + timestamp: ShortTimestamp { + hour: 12, + minute: 34, + second: 56, + subsecond: 7, + }, + value: Value::Number(48.5), + }; + let protection_update = ProtectionUpdate { + id: AdjId((1 << 13) | 3001), + timestamp: MessageTimestamp { + second: 56, + minute: 34, + hour: 12, + day: 14, + month: 11, + year: 2023, + }, + value: Value::Number(48.5), + }; + tx.send(ToPipeline::Received(Arc::new(Notification { + board: BoardId(5), + at: UNIX_EPOCH + Duration::from_secs(1_700_000_001), + event: Event::Received(Packet::Protection(protection.clone())), + }))) + .await?; + let got_prot = timeout(Duration::from_secs(1), prot_sub.recv()).await??; + assert_eq!(got_prot, protection_update); + + // 3. Board message + tx.send(ToPipeline::Received(Arc::new(Notification { + board: BoardId(5), + at: UNIX_EPOCH + Duration::from_secs(1_700_000_002), + event: Event::Received(Packet::Message(MessagePacket { + id: AdjId(10), + timestamp: ShortTimestamp { + hour: 1, + minute: 2, + second: 3, + subsecond: 4, + }, + origin: "pcu.c".to_string(), + message: "temp high".to_string(), + })), + }))) + .await?; + // As `payload/example/message.json`: `origin` is where on the board it was + // produced, `name` the ADJ name of its level. + let got_msg = timeout(Duration::from_secs(1), msg_sub.recv()).await??; + assert_eq!(got_msg.kind, MessageLevel::Warning); + assert_eq!(got_msg.board, "PCU"); + assert_eq!(got_msg.origin, "pcu.c"); + assert_eq!(got_msg.name, "warning"); + assert_eq!(got_msg.payload, "temp high"); + assert_eq!(got_msg.timestamp.hour, 1); + + drop((tx, data_tx)); + timeout(Duration::from_secs(1), pipe_task).await??; + timeout(Duration::from_secs(1), broker_task).await??; + // Board messages never go on `backend/message`. + assert!(backend_sub.try_recv().is_err()); + Ok(()) +} + +/// Verifies that notices and order outcomes are published as messages from +/// the backend itself (`backend/message`), never on `message/update`. +#[tokio::test] +async fn publishes_notices_and_order_outcomes_as_backend_messages() +-> Result<(), Box> { + let (pod_data, index) = sample_fixture(); + let (broker, client) = Broker::new(); + let sub = client.subscriber(); + let mut msg_sub = sub.subscribe_messages()?; + let mut backend_sub = sub.subscribe_backend_messages()?; + let broker_task = tokio::spawn(broker.run()); + + let (tx, rx) = mpsc::channel(32); + let (data_tx, data_rx) = mpsc::channel(32); + let pipe_task = spawn(Config::default(), rx, data_rx, client, pod_data, index); + let at = UNIX_EPOCH + Duration::from_secs(1_700_000_000); + + // 1. Notices keep their kind; a silent one is never published. + for (kind, board, text) in [ + (NoticeKind::Silent, None, "only traced"), + (NoticeKind::Info, None, "recording started"), + (NoticeKind::Warning, Some(BoardId(5)), "PCU: write failed"), + (NoticeKind::Fatal, Some(BoardId(5)), "PCU: decode failed"), + ] { + tx.send(ToPipeline::Notice(Notice { + at, + board, + kind, + text: text.to_string(), + })) + .await?; + } + for (level, board, text) in [ + (MessageLevel::Info, None, "recording started"), + (MessageLevel::Warning, Some("PCU"), "PCU: write failed"), + (MessageLevel::Fault, Some("PCU"), "PCU: decode failed"), + ] { + let got = timeout(Duration::from_secs(1), backend_sub.recv()).await??; + assert_eq!(got.kind, level); + assert_eq!(got.board.as_deref(), board); + assert_eq!(got.text, text); + } + + // 2. Order outcomes name the order as the ADJ does; the fault (id 0, + // not declared in this fixture) concerns no single board. + tx.send(ToPipeline::OrderSent { + at, + board: Some(BoardId(5)), + order: OrderPacket::new(AdjId(1001), vec![]), + }) + .await?; + tx.send(ToPipeline::OrderSent { + at, + board: None, + order: OrderPacket::new(AdjId(0), vec![]), + }) + .await?; + tx.send(ToPipeline::OrderFailed { + at, + order: OrderPacket::new(AdjId(1001), vec![]), + reason: "PCU is not connected".to_string(), + }) + .await?; + tx.send(ToPipeline::OrderFailed { + at, + order: OrderPacket::new(AdjId(0), vec![]), + reason: "TCP not available".to_string(), + }) + .await?; + for (level, board, text) in [ + (MessageLevel::Info, Some("PCU"), "Order Start sent"), + (MessageLevel::Info, None, "Order 0 sent to every board"), + ( + MessageLevel::Warning, + Some("PCU"), + "Order Start not sent: PCU is not connected", + ), + ( + MessageLevel::Warning, + None, + "Order 0 not sent: TCP not available", + ), + ] { + let got = timeout(Duration::from_secs(1), backend_sub.recv()).await??; + assert_eq!(got.kind, level); + assert_eq!(got.board.as_deref(), board); + assert_eq!(got.text, text); + } + + drop((tx, data_tx)); + timeout(Duration::from_secs(1), pipe_task).await??; + timeout(Duration::from_secs(1), broker_task).await??; + // Nothing the backend produces goes on `message/update`. + assert!(msg_sub.try_recv().is_err()); + Ok(()) +} + +/// Verifies 100 ms telemetry windowing (cumulative count, mean cycle time, +/// per-measurement last and average) and final flush when the input channel closes. +/// +/// `start_paused = true` freezes Tokio's virtual clock so 100 ms intervals run +/// deterministically and instantaneously via `tokio::time::advance`. +#[tokio::test(start_paused = true)] +async fn batches_data_every_100ms_with_window_average_last_and_cycle_time() +-> Result<(), Box> { + let (pod_data, index) = sample_fixture(); + let (broker, client) = Broker::new(); + let mut data_sub = client.subscriber().subscribe_data(); + let broker_task = tokio::spawn(broker.run()); + + let (tx, rx) = mpsc::channel(32); + let (data_tx, data_rx) = mpsc::channel(32); + let pipe_task = spawn(Config::default(), rx, data_rx, client, pod_data, index); + tokio::task::yield_now().await; + + let t0 = UNIX_EPOCH + Duration::from_secs(1_700_000_000); + let samples = [ + (t0, 10.0, false, "Idle"), + (t0 + Duration::from_millis(20), 20.0, true, "Idle"), + (t0 + Duration::from_millis(50), 30.0, true, "Fault"), + ]; + + for (at, voltage, active, state) in samples { + data_tx + .send(Arc::new(Notification { + board: BoardId(5), + at, + event: Event::Received(Packet::Data(DataPacket::new( + AdjId(551), + vec![ + Value::Number(voltage), + Value::Bool(active), + Value::Enum(state.to_string()), + ], + ))), + })) + .await?; + } + tokio::task::yield_now().await; + + // Advance once to trigger pipeline's 100 ms flush into the broker and + // yield twice so both tasks process the queued update. The second advance + // only fires an empty window, which publishes nothing. + advance(Duration::from_millis(100)).await; + tokio::task::yield_now().await; + tokio::task::yield_now().await; + advance(Duration::from_millis(100)).await; + timeout(Duration::from_millis(10), data_sub.changed()).await??; + + let first = data_sub.borrow_and_update().0[&AdjId(551)].clone(); + assert_eq!(first.count, 3); + // Deltas were 20 ms and 30 ms -> average 25 ms = 25_000_000 ns. + assert_eq!(first.cycle_time, 25_000_000); + assert_eq!( + first.measurement_updates[&AdjId(3001)], + MeasurementUpdate::Numeric { + last: 30.0, + average: 20.0, + } + ); + assert_eq!( + first.measurement_updates[&AdjId(3002)], + MeasurementUpdate::Boolean(true) + ); + assert_eq!( + first.measurement_updates[&AdjId(3003)], + MeasurementUpdate::Enum("Fault".to_string()) + ); + + // Next window resets the measurement average while preserving cumulative count. + data_tx + .send(data_notification(t0 + Duration::from_millis(150), 50.0)) + .await?; + + // Closing both queues flushes remaining data immediately and stops both tasks cleanly. + drop((tx, data_tx)); + timeout(Duration::from_secs(1), pipe_task).await??; + timeout(Duration::from_secs(1), broker_task).await??; + + let second = data_sub.borrow_and_update().0[&AdjId(551)].clone(); + assert_eq!(second.count, 4); + assert_eq!(second.cycle_time, 100_000_000); + assert_eq!( + second.measurement_updates[&AdjId(3001)], + MeasurementUpdate::Numeric { + last: 50.0, + average: 50.0, + } + ); + Ok(()) +} + +/// Verifies `timestamp::from_system_time` on boundary dates (Unix epoch and +/// a Gregorian leap day, whose milliseconds are dropped). +#[test] +fn utc_calendar_conversion_handles_epoch_and_leap_day() { + let epoch = timestamp::from_system_time(UNIX_EPOCH); + assert_eq!( + epoch, + MessageTimestamp { + second: 0, + minute: 0, + hour: 0, + day: 1, + month: 1, + year: 1970, + } + ); + + // 2024-02-29 13:45:09.250 UTC = 1_709_214_309 s + 250 ms + let leap = timestamp::from_system_time( + UNIX_EPOCH + Duration::from_secs(1_709_214_309) + Duration::from_millis(250), + ); + assert_eq!( + leap, + MessageTimestamp { + second: 9, + minute: 45, + hour: 13, + day: 29, + month: 2, + year: 2024, + } + ); +} + +/// Verifies that `pipeline` keeps reading telemetry (⑨) after ⑥ closes, and +/// only stops, with a final flush, once both queues are closed. +#[tokio::test] +async fn stops_only_once_both_queues_close_and_flushes_what_is_left() +-> Result<(), Box> { + let (pod_data, index) = sample_fixture(); + let (broker, client) = Broker::new(); + let data_sub = client.subscriber().subscribe_data(); + let broker_task = tokio::spawn(broker.run()); + + let (tx, rx) = mpsc::channel(32); + let (data_tx, data_rx) = mpsc::channel(32); + let pipe_task = spawn(Config::default(), rx, data_rx, client, pod_data, index); + + // ⑥ closes first: telemetry still has to get through. + drop(tx); + data_tx + .send(data_notification( + UNIX_EPOCH + Duration::from_secs(1_700_000_000), + 7.0, + )) + .await?; + tokio::task::yield_now().await; + assert!(!pipe_task.is_finished(), "⑨ is still open"); + + drop(data_tx); + timeout(Duration::from_secs(1), pipe_task).await??; + timeout(Duration::from_secs(1), broker_task).await??; + + let packet = data_sub.borrow().0[&AdjId(551)].clone(); + assert_eq!(packet.count, 1); + assert_eq!( + packet.measurement_updates[&AdjId(3001)], + MeasurementUpdate::Numeric { + last: 7.0, + average: 7.0, + } + ); + Ok(()) +} + +/// Verifies that every flush publishes the whole `podData/update` map, since +/// the broker replaces it on every publication: a packet with no frames in a +/// window keeps its last values, and a window with no frames at all +/// publishes nothing. +/// +/// With the clock paused, Tokio moves it to the next timer as soon as every +/// task is idle, so each flush follows on its own once the frames are read. +#[tokio::test(start_paused = true)] +async fn every_flush_publishes_every_packet_and_an_empty_window_nothing() +-> Result<(), Box> { + let (pod_data, index) = sample_fixture(); + let (broker, client) = Broker::new(); + let mut data_sub = client.subscriber().subscribe_data(); + let broker_task = tokio::spawn(broker.run()); + + let (tx, rx) = mpsc::channel(32); + let (data_tx, data_rx) = mpsc::channel(32); + let pipe_task = spawn(Config::default(), rx, data_rx, client, pod_data, index); + let t0 = UNIX_EPOCH + Duration::from_secs(1_700_000_000); + + // 1st window: both packets. + data_tx.send(data_notification(t0, 10.0)).await?; + data_tx.send(bcu_notification(t0, 1.0)).await?; + timeout(Duration::from_secs(1), data_sub.changed()).await??; + let first = data_sub.borrow_and_update().clone(); + assert_eq!(first.0.len(), 2); + assert_eq!(first.0[&AdjId(661)].count, 1); + + // 2nd window: only BCU's packet. PCU's stays in the map as it was. + data_tx + .send(bcu_notification(t0 + Duration::from_millis(100), 2.0)) + .await?; + timeout(Duration::from_secs(1), data_sub.changed()).await??; + let second = data_sub.borrow_and_update().clone(); + assert_eq!(second.0.len(), 2); + assert_eq!(second.0[&AdjId(551)], first.0[&AdjId(551)]); + assert_eq!(second.0[&AdjId(661)].count, 2); + assert_eq!(second.0[&AdjId(661)].cycle_time, 100_000_000); + assert_eq!( + second.0[&AdjId(661)].measurement_updates[&AdjId(3101)], + MeasurementUpdate::Numeric { + last: 2.0, + average: 2.0, + } + ); + + // No frames: three more ticks go by without a publication. + assert!( + timeout(Duration::from_millis(350), data_sub.changed()) + .await + .is_err(), + "an empty window published" + ); + + drop((tx, data_tx)); + timeout(Duration::from_secs(1), pipe_task).await??; + timeout(Duration::from_secs(1), broker_task).await??; + Ok(()) +} + +/// Verifies that every board the ADJ declares is published as disconnected +/// at startup, and that the map is published again only when a board's state +/// actually changes. +#[tokio::test] +async fn publishes_every_board_at_startup_and_connections_only_on_change() +-> Result<(), Box> { + let (pod_data, index) = sample_fixture(); + let (broker, client) = Broker::new(); + let sub = client.subscriber(); + let mut conn_sub = sub.subscribe_connections(); + let mut prot_sub = sub.subscribe_protections()?; + let broker_task = tokio::spawn(broker.run()); + + let (tx, rx) = mpsc::channel(32); + let (data_tx, data_rx) = mpsc::channel(32); + let pipe_task = spawn(Config::default(), rx, data_rx, client, pod_data, index); + + // At startup: every board, all disconnected. + timeout(Duration::from_secs(1), conn_sub.changed()).await??; + let update = conn_sub.borrow_and_update().clone(); + assert_eq!(connected(&update), [("BCU", false), ("PCU", false)]); + + tx.send(connection(BoardId(5), Event::Connected)).await?; + timeout(Duration::from_secs(1), conn_sub.changed()).await??; + let update = conn_sub.borrow_and_update().clone(); + assert_eq!(connected(&update), [("BCU", false), ("PCU", true)]); + + // The same state again publishes nothing. The protection behind it goes + // through the same queues, so once it arrives the repeated `Connected` + // has been handled. + tx.send(connection(BoardId(5), Event::Connected)).await?; + tx.send(ToPipeline::Received(Arc::new(Notification { + board: BoardId(5), + at: UNIX_EPOCH, + event: Event::Received(Packet::Protection(ProtectionPacket { + id: AdjId((1 << 13) | 3001), + timestamp: ShortTimestamp { + hour: 0, + minute: 0, + second: 0, + subsecond: 0, + }, + value: Value::Number(48.5), + })), + }))) + .await?; + timeout(Duration::from_secs(1), prot_sub.recv()).await??; + assert!(!conn_sub.has_changed()?, "a repeated state was published"); + + tx.send(connection(BoardId(5), Event::Disconnected)).await?; + timeout(Duration::from_secs(1), conn_sub.changed()).await??; + let update = conn_sub.borrow_and_update().clone(); + assert_eq!(connected(&update), [("BCU", false), ("PCU", false)]); + + drop((tx, data_tx)); + timeout(Duration::from_secs(1), pipe_task).await??; + timeout(Duration::from_secs(1), broker_task).await??; + Ok(()) +} + +/// Verifies that `pipeline` stops as soon as the broker is gone, without +/// waiting for `event` to close its queues, so that `event` sees ⑥ and ⑨ +/// closed. +#[tokio::test] +async fn stops_when_the_broker_is_gone_and_closes_both_queues() +-> Result<(), Box> { + let (pod_data, index) = sample_fixture(); + let (broker, client) = Broker::new(); + let mut conn_sub = client.subscriber().subscribe_connections(); + let broker_task = tokio::spawn(broker.run()); + + let (tx, rx) = mpsc::channel(32); + let (data_tx, data_rx) = mpsc::channel(32); + let pipe_task = spawn(Config::default(), rx, data_rx, client, pod_data, index); + timeout(Duration::from_secs(1), conn_sub.changed()).await??; + + // The broker goes away while pipeline is running. + broker_task.abort(); + assert!(broker_task.await.is_err_and(|err| err.is_cancelled())); + + // The next publication fails: pipeline stops with ⑥ and ⑨ still open. + tx.send(connection(BoardId(5), Event::Connected)).await?; + timeout(Duration::from_secs(1), pipe_task).await??; + assert!(tx.is_closed()); + assert!(data_tx.is_closed()); + Ok(()) +} + +/// Verifies that the accumulator ignores a packet the ADJ does not declare as +/// `Data` (an unknown id, or an order's id) instead of failing. +#[test] +fn accumulator_ignores_packets_the_adj_does_not_declare_as_data() { + let (_, index) = sample_fixture(); + let mut accumulator = DataAccumulator::default(); + for id in [AdjId(9999), AdjId(1001)] { + accumulator.record( + &DataPacket::new(id, vec![Value::Number(1.0)]), + UNIX_EPOCH, + &index, + ); + } + assert!(accumulator.drain_updates(&index).is_empty()); +} + +/// Verifies that a reception earlier than the previous one (the system clock +/// stepped back) adds no interval to `cycleTime`, and that the next interval +/// is measured from it. +#[test] +fn accumulator_skips_the_interval_when_the_clock_goes_back() { + let (_, index) = sample_fixture(); + let mut accumulator = DataAccumulator::default(); + let t0 = UNIX_EPOCH + Duration::from_secs(1_700_000_000); + for at in [ + t0, + t0 - Duration::from_millis(10), + t0 + Duration::from_millis(20), + ] { + accumulator.record(&bcu_packet(1.0), at, &index); + } + + let updates = accumulator.drain_updates(&index); + assert_eq!(updates.len(), 1); + assert_eq!(updates[0].count, 3); + // Only the last interval counts: from -10 ms to +20 ms. + assert_eq!(updates[0].cycle_time, 30_000_000); +} + +/// Verifies that a packet with fewer values than the ADJ declares is still +/// counted and its values recorded, and that a measurement whose value comes +/// in another kind takes the new kind. +#[test] +fn accumulator_records_what_it_can_from_a_malformed_packet() { + let (_, index) = sample_fixture(); + let mut accumulator = DataAccumulator::default(); + let t0 = UNIX_EPOCH + Duration::from_secs(1_700_000_000); + accumulator.record( + &DataPacket::new( + AdjId(551), + vec![ + Value::Number(10.0), + Value::Bool(true), + Value::Enum("Idle".to_string()), + ], + ), + t0, + &index, + ); + // 551 declares three measurements: this one brings two, the second one + // a number instead of a boolean. + accumulator.record( + &DataPacket::new(AdjId(551), vec![Value::Number(20.0), Value::Number(1.0)]), + t0 + Duration::from_millis(10), + &index, + ); + + let updates = accumulator.drain_updates(&index); + assert_eq!(updates.len(), 1); + let update = &updates[0].measurement_updates; + assert_eq!(updates[0].count, 2); + assert_eq!( + update[&AdjId(3001)], + MeasurementUpdate::Numeric { + last: 20.0, + average: 15.0, + } + ); + assert_eq!( + update[&AdjId(3002)], + MeasurementUpdate::Numeric { + last: 1.0, + average: 1.0, + } + ); + assert_eq!( + update[&AdjId(3003)], + MeasurementUpdate::Enum("Idle".to_string()) + ); +} + +/// A telemetry notification for packet 551 of the fixture, as `event` sends +/// it on ⑨. +fn data_notification(at: std::time::SystemTime, voltage: f64) -> Arc { + Arc::new(Notification { + board: BoardId(5), + at, + event: Event::Received(Packet::Data(DataPacket::new( + AdjId(551), + vec![ + Value::Number(voltage), + Value::Bool(true), + Value::Enum("Idle".to_string()), + ], + ))), + }) +} + +/// Packet 661 of the fixture (BCU's only measurement). +fn bcu_packet(current: f64) -> DataPacket { + DataPacket::new(AdjId(661), vec![Value::Number(current)]) +} + +/// A telemetry notification for packet 661 of the fixture, as `event` sends +/// it on ⑨. +fn bcu_notification(at: std::time::SystemTime, current: f64) -> Arc { + Arc::new(Notification { + board: BoardId(6), + at, + event: Event::Received(Packet::Data(bcu_packet(current))), + }) +} + +/// A board connecting or disconnecting, as `event` sends it on ⑥. +fn connection(board: BoardId, event: Event) -> ToPipeline { + ToPipeline::Received(Arc::new(Notification { + board, + at: UNIX_EPOCH, + event, + })) +} + +/// The connection map as `(board, connected)` pairs, sorted by board name. +fn connected(update: &ConnectionUpdate) -> Vec<(&str, bool)> { + let mut boards: Vec<(&str, bool)> = update + .0 + .values() + .map(|board| (board.name.as_str(), board.is_connected)) + .collect(); + boards.sort_unstable(); + boards +} diff --git a/backend/crates/station/src/pipeline/timestamp.rs b/backend/crates/station/src/pipeline/timestamp.rs new file mode 100644 index 000000000..3292dc35f --- /dev/null +++ b/backend/crates/station/src/pipeline/timestamp.rs @@ -0,0 +1,68 @@ +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use crate::payload::MessageTimestamp; +use software_core::model::ShortTimestamp; + +/// Converts a [`SystemTime`] into a UTC [`MessageTimestamp`]. +pub(super) fn from_system_time(at: SystemTime) -> MessageTimestamp { + // Clamp timestamps before 1970-01-01 to the Unix epoch rather than panicking. + let dur = at.duration_since(UNIX_EPOCH).unwrap_or(Duration::ZERO); + let total_secs = dur.as_secs(); + // 86,400 seconds per UTC day (POSIX/Unix time ignores leap seconds). + let days = i64::try_from(total_secs / 86_400).unwrap_or(0); + let secs_of_day = total_secs % 86_400; + + let (year, month, day) = civil_from_days(days); + // Use fallible `try_from` instead of `as` casts to avoid silent truncation. + let hour = u8::try_from(secs_of_day / 3_600).unwrap_or(0); + let minute = u8::try_from((secs_of_day % 3_600) / 60).unwrap_or(0); + let second = u8::try_from(secs_of_day % 60).unwrap_or(0); + + MessageTimestamp { + second, + minute, + hour, + day, + month, + year, + } +} + +/// Combines the reception calendar date from `received_at` with the board's +/// [`ShortTimestamp`] time of day and raw subsecond byte. +pub(super) fn from_short(received_at: SystemTime, short: ShortTimestamp) -> MessageTimestamp { + let date = from_system_time(received_at); + MessageTimestamp { + second: short.second, + minute: short.minute, + hour: short.hour, + day: date.day, + month: date.month, + year: date.year, + } +} + +/// Converts days since 1970-01-01 (UTC) to `(year, month, day)` using +/// Howard Hinnant's civil calendar algorithm. +fn civil_from_days(days_since_epoch: i64) -> (u16, u8, u8) { + // Shift epoch from 1970-01-01 to 0000-03-01 so leap day (Feb 29) falls at + // the very end of the year, simplifying leap-year arithmetic. + let z = days_since_epoch + 719_468; + // Split into 400-year Gregorian eras (exactly 146,097 days each). + let era = if z >= 0 { z } else { z - 146_096 } / 146_097; + let doe = u64::try_from(z - era * 146_097).unwrap_or(0); // day of era [0, 146096] + let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; // year of era [0, 399] + let y = i64::try_from(yoe).unwrap_or(0) + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // day of year from Mar 1 [0, 365] + let mp = (5 * doy + 2) / 153; // shifted month index [0, 11] (Mar = 0 .. Feb = 11) + let d = doy - (153 * mp + 2) / 5 + 1; // day of month [1, 31] + let m = if mp < 10 { mp + 3 } else { mp - 9 }; // calendar month [1, 12] + // Months Jan and Feb belong to the following calendar year relative to the Mar 1 base. + let year = y + i64::from(m <= 2); + + ( + u16::try_from(year).unwrap_or(0), + u8::try_from(m).unwrap_or(1), + u8::try_from(d).unwrap_or(1), + ) +} diff --git a/backend/crates/station/src/vehicle.rs b/backend/crates/station/src/vehicle.rs index e69de29bb..8b1378917 100644 --- a/backend/crates/station/src/vehicle.rs +++ b/backend/crates/station/src/vehicle.rs @@ -0,0 +1 @@ + diff --git a/backend/readme-demo.md b/backend/readme-demo.md index 050e911ac..b4a8452f5 100644 --- a/backend/readme-demo.md +++ b/backend/readme-demo.md @@ -1,22 +1,41 @@ -# 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: `logging` todavía no existe, y `station::pipeline` (ver + [`crates/station/src/pipeline/README.md`](crates/station/src/pipeline/README.md)) + necesita el broker de `websocket`, que la demo no arranca. El de logging + cuenta los paquetes por placa y escribe un resumen por segundo; el de + pipeline cuenta la telemetría que le llega y escribe en el log lo que vería + el front (conexiones, notices y órdenes). 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 +44,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.