From 8d8193408fe961fba8889fa3c70f697d9398d86e Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Tue, 24 Nov 2026 21:08:44 +0100 Subject: [PATCH 01/17] Feat(backend, pipeline): Add pipeline module so Javier can have a look --- backend/crates/core/src/lib.rs | 1 + backend/crates/core/src/pipeline/mod.rs | 1 + backend/crates/core/src/pipeline/pipeline.rs | 286 +++++++++++++++++++ 3 files changed, 288 insertions(+) create mode 100644 backend/crates/core/src/pipeline/mod.rs create mode 100644 backend/crates/core/src/pipeline/pipeline.rs diff --git a/backend/crates/core/src/lib.rs b/backend/crates/core/src/lib.rs index 573dd787e..92ce900f4 100644 --- a/backend/crates/core/src/lib.rs +++ b/backend/crates/core/src/lib.rs @@ -23,3 +23,4 @@ pub mod protocol; /// into [`protocol`] to decode. See [`net::tcp`], [`net::udp`]. #[cfg(feature = "net")] pub mod net; +pub mod pipeline; diff --git a/backend/crates/core/src/pipeline/mod.rs b/backend/crates/core/src/pipeline/mod.rs new file mode 100644 index 000000000..e979cae3b --- /dev/null +++ b/backend/crates/core/src/pipeline/mod.rs @@ -0,0 +1 @@ +pub mod pipeline; \ No newline at end of file diff --git a/backend/crates/core/src/pipeline/pipeline.rs b/backend/crates/core/src/pipeline/pipeline.rs new file mode 100644 index 000000000..a8c92f0f7 --- /dev/null +++ b/backend/crates/core/src/pipeline/pipeline.rs @@ -0,0 +1,286 @@ +//! Central routing and fan-out stage between `net` and downstream consumers. +//! +//! # What this module is +//! +//! The single consumer of [`crate::net::Sinks`]. Everything that comes off the +//! wire (UDP telemetry, TCP orders/messages, connection transitions, and +//! transport errors) enters here once and is distributed to whoever needs it: +//! live observers (WebSocket/frontend, protection checks), optional disk +//! recording, and the pod fault supervisor. +//! +//! # Entry point +//! +//! [`spawn`], taking [`Config`], [`crate::net::Sinks`], and an optional +//! recorder channel. Returns a [`Pipeline`] handle exposing live telemetry +//! subscriptions, the single-shot fault receiver, and the task's `JoinHandle`. +//! +//! # Contract +//! +//! - **Never backpressure `net`.** Both `sinks.notifications` and +//! `sinks.errors` are drained continuously in a single `tokio::select!` loop. +//! A slow frontend or stalled disk writer must never block UDP/TCP ingestion: +//! live consumers use a [`tokio::sync::broadcast`] channel (lagging receivers +//! skip old frames), and optional disk recording uses non-blocking `try_send`. +//! - **Single "fault once" guard.** Transport modules (`net::udp`, `net::tcp`) +//! report every error and keep running without acting on it. This module +//! checks [`NetError::is_fatal`] and emits **at most one** fault trigger on +//! [`Pipeline::faults`] so `station` sends the pod to fault once—even if a +//! mismatched ADJ produces thousands of decode errors per second. +//! - **Stay alive after fault.** Faulting is about the **pod**, not this +//! process. After emitting a fault trigger, the loop keeps routing packets +//! and draining errors so operators can inspect telemetry and logs. +//! - **Zero-copy fan-out.** Each [`Notification`] is wrapped in an `Arc` once +//! and shared across all subscribers rather than cloned per consumer. +//! - **Clean shutdown.** Disables closed `select!` branches to avoid busy +//! spinning and exits once both upstream `net` channels have closed. + +use crate::net::{Error as NetError, Notification, Sinks}; +use std::sync::Arc; +use tokio::sync::mpsc::error::TrySendError; +use tokio::sync::{broadcast, mpsc}; +use tokio::task::JoinHandle; +use tracing::{error, warn}; + +/// Sizing parameters for the pipeline's internal channels. +/// +/// Resolved by `station` before spawning; this module reads no config files. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Config { + /// Capacity of the live [`broadcast`] channel shared by subscribers + /// (WebSocket server, state aggregator, protections). + /// + /// A subscriber falling more than this many notifications behind receives + /// `RecvError::Lagged` and jumps to the latest frame instead of stalling + /// the network receive loops. + pub broadcast_capacity: usize, +} + +impl Default for Config { + fn default() -> Self { + Self { + broadcast_capacity: 1024, + } + } +} + +/// Handle to a running pipeline task. +pub struct Pipeline { + telemetry_tx: broadcast::Sender>, + /// Fires at most once when the first fatal transport error arrives. + /// + /// `station` listens here to command the pod into fault state. + pub faults: mpsc::Receiver, + /// Handle to the background routing task. + pub handle: JoinHandle<()>, +} + +impl Pipeline { + /// Subscribes a new live consumer (e.g. WebSocket broadcaster or state + /// cache) to every [`Notification`] flowing through the pipeline. + pub fn subscribe(&self) -> broadcast::Receiver> { + self.telemetry_tx.subscribe() + } +} + +/// Spawns the pipeline routing task. +/// +/// `recorder` is optional: pass `Some(tx)` when disk recording is enabled, or +/// `None` in lightweight demos/tests. Recording uses `try_send` so a full disk +/// buffer drops frames with a warning rather than stalling `net`. +/// +/// TODO(review): Confirm whether protections (ADJv3 range/limit checks) should +/// run inline in `handle_notification` before fan-out, or as a separate task +/// calling `pipeline.subscribe()`. +pub fn spawn( + config: Config, + sinks: Sinks, + recorder: Option>>, +) -> Pipeline { + let (telemetry_tx, _) = broadcast::channel(config.broadcast_capacity); + // Capacity 1 is enough: the fault-once guard sends at most one fatal error. + let (fault_tx, fault_rx) = mpsc::channel(1); + + let handle = tokio::spawn(run_loop(sinks, telemetry_tx.clone(), fault_tx, recorder)); + + Pipeline { + telemetry_tx, + faults: fault_rx, + handle, + } +} + +/// Main routing loop: drains both `net` channels until upstream closes. +async fn run_loop( + mut sinks: Sinks, + telemetry_tx: broadcast::Sender>, + fault_tx: mpsc::Sender, + mut recorder: Option>>, +) { + let mut faulted = false; + let mut notifications_open = true; + let mut errors_open = true; + + while notifications_open || errors_open { + tokio::select! { + res = sinks.notifications.recv(), if notifications_open => { + match res { + Some(notification) => { + handle_notification(notification, &telemetry_tx, &mut recorder); + } + None => notifications_open = false, + } + } + res = sinks.errors.recv(), if errors_open => { + match res { + Some(err) => { + handle_error(err, &mut faulted, &fault_tx); + } + None => errors_open = false, + } + } + } + } +} + +/// Fans a single notification out to live subscribers and the optional recorder. +fn handle_notification( + notification: Notification, + telemetry_tx: &broadcast::Sender>, + recorder: &mut Option>>, +) { + let shared = Arc::new(notification); + + // TODO(review): If state aggregation / rate throttling for the frontend + // belongs inside `pipeline` rather than downstream, hook it in here. + + // Broadcast returns Err only when there are zero active subscribers, which + // is expected during startup or headless runs. + let _ = telemetry_tx.send(Arc::clone(&shared)); + + if let Some(tx) = recorder.as_ref() { + match tx.try_send(shared) { + Ok(()) => {} + Err(TrySendError::Full(_)) => { + // TODO(review): Consider rate-limiting this warning or tracking + // a dropped-frame counter if high-rate telemetry overflows disk. + warn!("recorder channel full, dropping notification to avoid stalling net"); + } + Err(TrySendError::Closed(_)) => { + warn!("recorder channel closed, disabling recording sink"); + *recorder = None; + } + } + } +} + +/// Evaluates a transport error against the fault-once guard. +fn handle_error(err: NetError, faulted: &mut bool, fault_tx: &mpsc::Sender) { + if !err.is_fatal() { + warn!(%err, "non-fatal network error"); + return; + } + + if *faulted { + // Already triggered a pod fault; keep draining silently so `sinks.errors` + // never fills up and deadlocks the transport tasks. + return; + } + + *faulted = true; + error!(%err, "fatal network error — triggering pod fault"); + + if let Err(send_err) = fault_tx.try_send(err) { + error!(%send_err, "could not deliver fault trigger to supervisor"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::{AdjId, BoardId, DataOrderPacket, Packet}; + use crate::net::{udp, Event, Reporter}; + use crate::protocol::DecodeError; + use std::net::{IpAddr, SocketAddr}; + + fn sample_notification() -> (BoardId, Event) { + let packet = DataOrderPacket::new(AdjId(551), vec![]); + (BoardId(5), Event::Received(Packet::Data(packet))) + } + + fn fatal_udp_error() -> udp::Error { + udp::Error::Decode { + from: SocketAddr::new(IpAddr::from([192, 168, 1, 3]), 50400), + source: DecodeError::UnknownId(AdjId(9999)), + } + } + + #[tokio::test] + async fn fans_out_notifications_to_multiple_subscribers_and_recorder() { + let (reporter, sinks) = Reporter::channels(16, 16); + let (rec_tx, mut rec_rx) = mpsc::channel(16); + + let pipeline = spawn(Config::default(), sinks, Some(rec_tx)); + let mut sub_a = pipeline.subscribe(); + let mut sub_b = pipeline.subscribe(); + + let (board, event) = sample_notification(); + reporter.notify(board, event).await.unwrap(); + + let a = sub_a.recv().await.unwrap(); + let b = sub_b.recv().await.unwrap(); + let rec = rec_rx.recv().await.unwrap(); + + assert_eq!(a.board, BoardId(5)); + assert_eq!(b.board, BoardId(5)); + assert_eq!(rec.board, BoardId(5)); + + drop(reporter); + pipeline.handle.await.unwrap(); + } + + #[tokio::test] + async fn fatal_errors_trigger_fault_only_once_and_keep_draining() { + let (reporter, sinks) = Reporter::channels(16, 4); + let mut pipeline = spawn(Config::default(), sinks, None); + let mut sub = pipeline.subscribe(); + + // Flood more fatal errors than the error channel capacity (4) to verify + // the pipeline keeps draining without deadlocking. + for _ in 0..20 { + reporter.report(fatal_udp_error()).await.unwrap(); + } + + // Exactly one fault trigger should be emitted. + let first_fault = pipeline.faults.recv().await; + assert!(first_fault.is_some()); + + // Telemetry must still flow after faulting. + let (board, event) = sample_notification(); + reporter.notify(board, event).await.unwrap(); + let received = sub.recv().await.unwrap(); + assert_eq!(received.board, BoardId(5)); + + drop(reporter); + pipeline.handle.await.unwrap(); + + // No second fault trigger was queued. + assert!(pipeline.faults.try_recv().is_err()); + } + + #[tokio::test] + async fn full_recorder_does_not_block_live_subscribers() { + let (reporter, sinks) = Reporter::channels(16, 16); + // Recorder with capacity 1 that nobody reads from. + let (rec_tx, _rec_rx) = mpsc::channel(1); + + let pipeline = spawn(Config::default(), sinks, Some(rec_tx)); + let mut sub = pipeline.subscribe(); + + for _ in 0..5 { + let (board, event) = sample_notification(); + reporter.notify(board, event).await.unwrap(); + } + + for _ in 0..5 { + let msg = sub.recv().await.unwrap(); + assert_eq!(msg \ No newline at end of file From 95640427d1cb17d75e8af01c548f6e1e8de94b98 Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Tue, 24 Nov 2026 21:09:30 +0100 Subject: [PATCH 02/17] Feat(backend, pipeline): added missing lines. --- backend/crates/core/src/pipeline/pipeline.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/backend/crates/core/src/pipeline/pipeline.rs b/backend/crates/core/src/pipeline/pipeline.rs index a8c92f0f7..2c68a6a47 100644 --- a/backend/crates/core/src/pipeline/pipeline.rs +++ b/backend/crates/core/src/pipeline/pipeline.rs @@ -283,4 +283,10 @@ mod tests { for _ in 0..5 { let msg = sub.recv().await.unwrap(); - assert_eq!(msg \ No newline at end of file + assert_eq!(msg.board, BoardId(5)); + } + + drop(reporter); + pipeline.handle.await.unwrap(); + } +} \ No newline at end of file From da342fd08fd2893c9a25cd12e263bfe5c06dfa4b Mon Sep 17 00:00:00 2001 From: GaziH Date: Tue, 1 Dec 2026 19:16:34 +0100 Subject: [PATCH 03/17] Feat(backend, pipeline): move pipeline to station and publish WS payloads" -m "- Move pipeline from software-core into station (crates/station/src/pipeline.rs) - Map ToPipeline variants (connections, protections, board messages, problems, order outcomes) to payload types and publish immediately via BrokerClient - Aggregate Packet::Data telemetry per packet ID over 100 ms windows (cumulative count, mean cycle_time, per-measurement last and window average) and flush on shutdown - Re-export MeasurementUpdate, MessageKind, MessagePayload, and MessageTimestamp from station::payload - Expose event and pipeline from station::lib so station modules share crate-level imports - Add unit tests for immediate event forwarding, 100 ms data windowing, and UTC calendar timestamp conversion --- backend/crates/core/src/pipeline/pipeline.rs | 292 ------ .../{core => station}/src/pipeline/mod.rs | 0 .../crates/station/src/pipeline/pipeline.rs | 888 ++++++++++++++++++ 3 files changed, 888 insertions(+), 292 deletions(-) delete mode 100644 backend/crates/core/src/pipeline/pipeline.rs rename backend/crates/{core => station}/src/pipeline/mod.rs (100%) create mode 100644 backend/crates/station/src/pipeline/pipeline.rs diff --git a/backend/crates/core/src/pipeline/pipeline.rs b/backend/crates/core/src/pipeline/pipeline.rs deleted file mode 100644 index 2c68a6a47..000000000 --- a/backend/crates/core/src/pipeline/pipeline.rs +++ /dev/null @@ -1,292 +0,0 @@ -//! Central routing and fan-out stage between `net` and downstream consumers. -//! -//! # What this module is -//! -//! The single consumer of [`crate::net::Sinks`]. Everything that comes off the -//! wire (UDP telemetry, TCP orders/messages, connection transitions, and -//! transport errors) enters here once and is distributed to whoever needs it: -//! live observers (WebSocket/frontend, protection checks), optional disk -//! recording, and the pod fault supervisor. -//! -//! # Entry point -//! -//! [`spawn`], taking [`Config`], [`crate::net::Sinks`], and an optional -//! recorder channel. Returns a [`Pipeline`] handle exposing live telemetry -//! subscriptions, the single-shot fault receiver, and the task's `JoinHandle`. -//! -//! # Contract -//! -//! - **Never backpressure `net`.** Both `sinks.notifications` and -//! `sinks.errors` are drained continuously in a single `tokio::select!` loop. -//! A slow frontend or stalled disk writer must never block UDP/TCP ingestion: -//! live consumers use a [`tokio::sync::broadcast`] channel (lagging receivers -//! skip old frames), and optional disk recording uses non-blocking `try_send`. -//! - **Single "fault once" guard.** Transport modules (`net::udp`, `net::tcp`) -//! report every error and keep running without acting on it. This module -//! checks [`NetError::is_fatal`] and emits **at most one** fault trigger on -//! [`Pipeline::faults`] so `station` sends the pod to fault once—even if a -//! mismatched ADJ produces thousands of decode errors per second. -//! - **Stay alive after fault.** Faulting is about the **pod**, not this -//! process. After emitting a fault trigger, the loop keeps routing packets -//! and draining errors so operators can inspect telemetry and logs. -//! - **Zero-copy fan-out.** Each [`Notification`] is wrapped in an `Arc` once -//! and shared across all subscribers rather than cloned per consumer. -//! - **Clean shutdown.** Disables closed `select!` branches to avoid busy -//! spinning and exits once both upstream `net` channels have closed. - -use crate::net::{Error as NetError, Notification, Sinks}; -use std::sync::Arc; -use tokio::sync::mpsc::error::TrySendError; -use tokio::sync::{broadcast, mpsc}; -use tokio::task::JoinHandle; -use tracing::{error, warn}; - -/// Sizing parameters for the pipeline's internal channels. -/// -/// Resolved by `station` before spawning; this module reads no config files. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Config { - /// Capacity of the live [`broadcast`] channel shared by subscribers - /// (WebSocket server, state aggregator, protections). - /// - /// A subscriber falling more than this many notifications behind receives - /// `RecvError::Lagged` and jumps to the latest frame instead of stalling - /// the network receive loops. - pub broadcast_capacity: usize, -} - -impl Default for Config { - fn default() -> Self { - Self { - broadcast_capacity: 1024, - } - } -} - -/// Handle to a running pipeline task. -pub struct Pipeline { - telemetry_tx: broadcast::Sender>, - /// Fires at most once when the first fatal transport error arrives. - /// - /// `station` listens here to command the pod into fault state. - pub faults: mpsc::Receiver, - /// Handle to the background routing task. - pub handle: JoinHandle<()>, -} - -impl Pipeline { - /// Subscribes a new live consumer (e.g. WebSocket broadcaster or state - /// cache) to every [`Notification`] flowing through the pipeline. - pub fn subscribe(&self) -> broadcast::Receiver> { - self.telemetry_tx.subscribe() - } -} - -/// Spawns the pipeline routing task. -/// -/// `recorder` is optional: pass `Some(tx)` when disk recording is enabled, or -/// `None` in lightweight demos/tests. Recording uses `try_send` so a full disk -/// buffer drops frames with a warning rather than stalling `net`. -/// -/// TODO(review): Confirm whether protections (ADJv3 range/limit checks) should -/// run inline in `handle_notification` before fan-out, or as a separate task -/// calling `pipeline.subscribe()`. -pub fn spawn( - config: Config, - sinks: Sinks, - recorder: Option>>, -) -> Pipeline { - let (telemetry_tx, _) = broadcast::channel(config.broadcast_capacity); - // Capacity 1 is enough: the fault-once guard sends at most one fatal error. - let (fault_tx, fault_rx) = mpsc::channel(1); - - let handle = tokio::spawn(run_loop(sinks, telemetry_tx.clone(), fault_tx, recorder)); - - Pipeline { - telemetry_tx, - faults: fault_rx, - handle, - } -} - -/// Main routing loop: drains both `net` channels until upstream closes. -async fn run_loop( - mut sinks: Sinks, - telemetry_tx: broadcast::Sender>, - fault_tx: mpsc::Sender, - mut recorder: Option>>, -) { - let mut faulted = false; - let mut notifications_open = true; - let mut errors_open = true; - - while notifications_open || errors_open { - tokio::select! { - res = sinks.notifications.recv(), if notifications_open => { - match res { - Some(notification) => { - handle_notification(notification, &telemetry_tx, &mut recorder); - } - None => notifications_open = false, - } - } - res = sinks.errors.recv(), if errors_open => { - match res { - Some(err) => { - handle_error(err, &mut faulted, &fault_tx); - } - None => errors_open = false, - } - } - } - } -} - -/// Fans a single notification out to live subscribers and the optional recorder. -fn handle_notification( - notification: Notification, - telemetry_tx: &broadcast::Sender>, - recorder: &mut Option>>, -) { - let shared = Arc::new(notification); - - // TODO(review): If state aggregation / rate throttling for the frontend - // belongs inside `pipeline` rather than downstream, hook it in here. - - // Broadcast returns Err only when there are zero active subscribers, which - // is expected during startup or headless runs. - let _ = telemetry_tx.send(Arc::clone(&shared)); - - if let Some(tx) = recorder.as_ref() { - match tx.try_send(shared) { - Ok(()) => {} - Err(TrySendError::Full(_)) => { - // TODO(review): Consider rate-limiting this warning or tracking - // a dropped-frame counter if high-rate telemetry overflows disk. - warn!("recorder channel full, dropping notification to avoid stalling net"); - } - Err(TrySendError::Closed(_)) => { - warn!("recorder channel closed, disabling recording sink"); - *recorder = None; - } - } - } -} - -/// Evaluates a transport error against the fault-once guard. -fn handle_error(err: NetError, faulted: &mut bool, fault_tx: &mpsc::Sender) { - if !err.is_fatal() { - warn!(%err, "non-fatal network error"); - return; - } - - if *faulted { - // Already triggered a pod fault; keep draining silently so `sinks.errors` - // never fills up and deadlocks the transport tasks. - return; - } - - *faulted = true; - error!(%err, "fatal network error — triggering pod fault"); - - if let Err(send_err) = fault_tx.try_send(err) { - error!(%send_err, "could not deliver fault trigger to supervisor"); - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::model::{AdjId, BoardId, DataOrderPacket, Packet}; - use crate::net::{udp, Event, Reporter}; - use crate::protocol::DecodeError; - use std::net::{IpAddr, SocketAddr}; - - fn sample_notification() -> (BoardId, Event) { - let packet = DataOrderPacket::new(AdjId(551), vec![]); - (BoardId(5), Event::Received(Packet::Data(packet))) - } - - fn fatal_udp_error() -> udp::Error { - udp::Error::Decode { - from: SocketAddr::new(IpAddr::from([192, 168, 1, 3]), 50400), - source: DecodeError::UnknownId(AdjId(9999)), - } - } - - #[tokio::test] - async fn fans_out_notifications_to_multiple_subscribers_and_recorder() { - let (reporter, sinks) = Reporter::channels(16, 16); - let (rec_tx, mut rec_rx) = mpsc::channel(16); - - let pipeline = spawn(Config::default(), sinks, Some(rec_tx)); - let mut sub_a = pipeline.subscribe(); - let mut sub_b = pipeline.subscribe(); - - let (board, event) = sample_notification(); - reporter.notify(board, event).await.unwrap(); - - let a = sub_a.recv().await.unwrap(); - let b = sub_b.recv().await.unwrap(); - let rec = rec_rx.recv().await.unwrap(); - - assert_eq!(a.board, BoardId(5)); - assert_eq!(b.board, BoardId(5)); - assert_eq!(rec.board, BoardId(5)); - - drop(reporter); - pipeline.handle.await.unwrap(); - } - - #[tokio::test] - async fn fatal_errors_trigger_fault_only_once_and_keep_draining() { - let (reporter, sinks) = Reporter::channels(16, 4); - let mut pipeline = spawn(Config::default(), sinks, None); - let mut sub = pipeline.subscribe(); - - // Flood more fatal errors than the error channel capacity (4) to verify - // the pipeline keeps draining without deadlocking. - for _ in 0..20 { - reporter.report(fatal_udp_error()).await.unwrap(); - } - - // Exactly one fault trigger should be emitted. - let first_fault = pipeline.faults.recv().await; - assert!(first_fault.is_some()); - - // Telemetry must still flow after faulting. - let (board, event) = sample_notification(); - reporter.notify(board, event).await.unwrap(); - let received = sub.recv().await.unwrap(); - assert_eq!(received.board, BoardId(5)); - - drop(reporter); - pipeline.handle.await.unwrap(); - - // No second fault trigger was queued. - assert!(pipeline.faults.try_recv().is_err()); - } - - #[tokio::test] - async fn full_recorder_does_not_block_live_subscribers() { - let (reporter, sinks) = Reporter::channels(16, 16); - // Recorder with capacity 1 that nobody reads from. - let (rec_tx, _rec_rx) = mpsc::channel(1); - - let pipeline = spawn(Config::default(), sinks, Some(rec_tx)); - let mut sub = pipeline.subscribe(); - - for _ in 0..5 { - let (board, event) = sample_notification(); - reporter.notify(board, event).await.unwrap(); - } - - for _ in 0..5 { - let msg = sub.recv().await.unwrap(); - assert_eq!(msg.board, BoardId(5)); - } - - drop(reporter); - pipeline.handle.await.unwrap(); - } -} \ No newline at end of file diff --git a/backend/crates/core/src/pipeline/mod.rs b/backend/crates/station/src/pipeline/mod.rs similarity index 100% rename from backend/crates/core/src/pipeline/mod.rs rename to backend/crates/station/src/pipeline/mod.rs diff --git a/backend/crates/station/src/pipeline/pipeline.rs b/backend/crates/station/src/pipeline/pipeline.rs new file mode 100644 index 000000000..8270f442e --- /dev/null +++ b/backend/crates/station/src/pipeline/pipeline.rs @@ -0,0 +1,888 @@ +//! Transforms [`crate::event::ToPipeline`] items into frontend WebSocket payloads +//! and publishes them through [`crate::websocket::broker::BrokerClient`]. +//! +//! # Contract +//! +//! - **Immediate events.** Connections, protections, board messages, backend +//! problems, and order outcomes are converted and published immediately. +//! - **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. Idle packets are not republished. +//! - **Wait, don't drop.** Reads continuously from `channels.pipeline` and +//! awaits broker capacity instead of dropping decoded events. +//! - **Clean shutdown.** When `event` closes the input channel (`None`), any +//! pending telemetry is flushed to the broker before the task exits. +//! - **No error policy.** `event` already decides what is silent, shown, or +//! fatal; `pipeline` only formats and publishes. +//! +//! # Topics not handled here +//! +//! - Frontend-to-backend topics (`order/send`, `logger/enable`, +//! `logger/variables`, `connection/heartbeat`) are consumed by `websocket`. +//! - `logger/response` is published directly by `logging`. +//! - `order/stateOrders` has no corresponding packet variant in +//! `software_core::model::Packet` yet. + +use std::collections::HashMap; +use std::sync::Arc; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use crate::event::{Problem, ProblemKind, ToPipeline}; +use crate::payload::{ + Connection, DataPacketUpdate, MeasurementUpdate, MessageKind, MessagePayload, + MessageTimestamp, MessageUpdate, ProtectionUpdate, +}; +use crate::websocket::broker::BrokerClient; +use software_core::model::{ + AdjId, BoardId, DataPacket, MessagePacket, OrderPacket, Packet, PacketType, PodData, + ShortTimestamp, Value, +}; +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 publishing to `broker`. +/// +/// The task exits cleanly once `rx` closes and pending telemetry is flushed, +/// or immediately if `broker` has already shut down. +pub fn spawn( + config: Config, + rx: mpsc::Receiver, + broker: BrokerClient, + pod_data: Arc, + index: Arc, +) -> JoinHandle<()> { + tokio::spawn(run_loop(config, rx, broker, pod_data, index)) +} + +async fn run_loop( + config: Config, + mut rx: mpsc::Receiver, + broker: BrokerClient, + pod_data: Arc, + index: Arc, +) { + let period = config.data_flush_interval.max(Duration::from_millis(1)); + let mut tick = interval_at(Instant::now() + period, period); + tick.set_missed_tick_behavior(MissedTickBehavior::Skip); + + let mut accumulator = DataAccumulator::default(); + + loop { + // Poll the 100 ms flush tick first so sustained high-rate UDP traffic + // can never starve telemetry publication. + tokio::select! { + biased; + _ = tick.tick() => { + if !flush_data(&broker, &index, &mut accumulator).await { + return; + } + } + item = rx.recv() => { + match item { + Some(msg) => { + if !handle_item(msg, &broker, &pod_data, &index, &mut accumulator).await { + return; + } + } + None => { + let _ = flush_data(&broker, &index, &mut accumulator).await; + return; + } + } + } + } + } +} + +/// 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, +) -> bool { + match item { + ToPipeline::Received(notification) => { + handle_notification(¬ification, broker, pod_data, index, accumulator).await + } + ToPipeline::Problem(problem) => handle_problem(problem, broker, pod_data).await, + ToPipeline::OrderSent { at, board, order } => { + handle_order_sent(at, board, order, broker, pod_data).await + } + ToPipeline::OrderFailed { at, order, reason } => { + handle_order_failed(at, order, reason, broker, pod_data, index).await + } + } +} + +async fn handle_notification( + notification: &Notification, + broker: &BrokerClient, + pod_data: &PodData, + index: &Index, + accumulator: &mut DataAccumulator, +) -> bool { + match ¬ification.event { + Event::Connected => { + let update = Connection { + name: board_name(pod_data, notification.board), + is_connected: true, + }; + publish_or_log(broker.publish_connection(update).await) + } + Event::Disconnected => { + let update = Connection { + name: board_name(pod_data, notification.board), + is_connected: false, + }; + publish_or_log(broker.publish_connection(update).await) + } + Event::Received(Packet::Data(data)) => { + accumulator.record(data, notification.at, index); + true + } + Event::Received(Packet::Protection(protection)) => { + let update = ProtectionUpdate::from(protection.clone()); + publish_or_log(broker.publish_protection(update).await) + } + Event::Received(Packet::Message(message)) => { + let update = build_board_message(notification.board, notification.at, message, 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 + } + } +} + +async fn handle_problem(problem: Problem, broker: &BrokerClient, pod_data: &PodData) -> bool { + let kind = match problem.kind { + ProblemKind::Shown => MessageKind::Warning, + ProblemKind::Fatal => MessageKind::Fault, + ProblemKind::Silent => return true, + }; + + let board = problem + .board + .map_or_else(|| "backend".to_string(), |id| board_name(pod_data, id)); + + let update = MessageUpdate { + kind, + payload: MessagePayload::Text(problem.text), + board, + name: "backend".to_string(), + timestamp: timestamp_from_system_time(problem.at), + }; + + publish_or_log(broker.publish_message(update).await) +} + +async fn handle_order_sent( + at: SystemTime, + board: Option, + order: OrderPacket, + broker: &BrokerClient, + pod_data: &PodData, +) -> bool { + let board_label = board.map_or_else(|| "all".to_string(), |id| board_name(pod_data, id)); + + let update = MessageUpdate { + kind: MessageKind::Info, + payload: MessagePayload::Text(format!("Order {} sent", order.id.0)), + board: board_label, + name: order.id.0.to_string(), + timestamp: timestamp_from_system_time(at), + }; + + publish_or_log(broker.publish_message(update).await) +} + +async fn handle_order_failed( + at: SystemTime, + order: OrderPacket, + reason: String, + broker: &BrokerClient, + pod_data: &PodData, + index: &Index, +) -> bool { + let board_label = if order.id == AdjId(0) { + "all".to_string() + } else if let Some(def) = index.packet(order.id) { + board_name(pod_data, def.board) + } else { + "backend".to_string() + }; + + let update = MessageUpdate { + kind: MessageKind::Warning, + payload: MessagePayload::Text(reason), + board: board_label, + name: order.id.0.to_string(), + timestamp: timestamp_from_system_time(at), + }; + + publish_or_log(broker.publish_message(update).await) +} + +fn build_board_message( + board: BoardId, + at: SystemTime, + message: &MessagePacket, + pod_data: &PodData, + index: &Index, +) -> MessageUpdate { + let kind = match index.packet(message.id) { + Some(def) => match def.packet_type { + PacketType::Message(level) => MessageKind::from(level), + _ => { + warn!(id = message.id.0, "message packet id does not map to PacketType::Message"); + MessageKind::Info + } + }, + None => { + warn!(id = message.id.0, "unknown message packet id in index"); + MessageKind::Info + } + }; + + let name = if message.origin.is_empty() { + message.id.0.to_string() + } else { + message.origin.clone() + }; + + MessageUpdate { + kind, + payload: MessagePayload::Text(message.message.clone()), + board: board_name(pod_data, board), + name, + timestamp: timestamp_from_short(at, message.timestamp), + } +} + +async fn flush_data( + broker: &BrokerClient, + index: &Index, + accumulator: &mut DataAccumulator, +) -> bool { + for update in accumulator.drain_updates(index) { + if !publish_or_log(broker.publish_data(update).await) { + return false; + } + } + true +} + +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 + } + } +} + +fn board_name(pod_data: &PodData, board: BoardId) -> String { + pod_data + .boards + .get(&board) + .map_or_else(|| format!("board-{}", board.0), |b| b.name.clone()) +} + +// --------------------------------------------------------------------------- +// 100 ms Telemetry Accumulator +// --------------------------------------------------------------------------- + +#[derive(Debug, Default)] +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 { + 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()), + } + } + + 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)) => { + if last != s { + last.clone_from(s); + } + } + (slot, other) => { + *slot = Self::from_value(other); + } + } + } + + 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 { + fn record(&mut self, packet: &DataPacket, at: SystemTime, index: &Index) { + let Some(def) = index.packet(packet.id) else { + warn!(id = packet.id.0, "unknown data packet id in index"); + return; + }; + let PacketType::Data(defs) = &def.packet_type else { + warn!(id = packet.id.0, "packet id in DataPacket does not map to PacketType::Data"); + return; + }; + + if packet.values.len() != defs.len() { + warn!( + id = packet.id.0, + expected = defs.len(), + actual = packet.values.len(), + "data packet value count mismatch" + ); + } + + 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); + 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); + + 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; + } + + 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; + + 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; + }; + + let mut measurement_updates = 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.alias.clone(), acc.into_update()); + } + } + + updates.push(DataPacketUpdate { + id, + // Raw wire bytes are not carried by `Notification`; left empty. + hex_value: String::new(), + count: window.count, + cycle_time: window.last_cycle_time_ns, + measurement_updates, + }); + } + + updates + } +} + +// --------------------------------------------------------------------------- +// UTC Calendar Timestamp Conversion (zero external dependencies) +// --------------------------------------------------------------------------- + +/// Converts a [`SystemTime`] into a UTC [`MessageTimestamp`]. +fn timestamp_from_system_time(at: SystemTime) -> MessageTimestamp { + let dur = at.duration_since(UNIX_EPOCH).unwrap_or(Duration::ZERO); + let total_secs = dur.as_secs(); + 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); + 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); + let counter = u16::try_from(dur.subsec_millis()).unwrap_or(0); + + MessageTimestamp { + counter, + 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. +fn timestamp_from_short(received_at: SystemTime, short: ShortTimestamp) -> MessageTimestamp { + let date = timestamp_from_system_time(received_at); + MessageTimestamp { + counter: u16::from(short.subsecond), + 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) { + let z = days_since_epoch + 719_468; + let era = if z >= 0 { z } else { z - 146_096 } / 146_097; + let doe = u64::try_from(z - era * 146_097).unwrap_or(0); + let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; + let y = i64::try_from(yoe).unwrap_or(0) + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + 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), + ) +} + +#[cfg(test)] +mod tests { + use std::net::IpAddr; + + use software_core::model::{ + Board, MacAddress, Measurement, MeasurementKind, MessageLevel, NumericKind, PacketDef, + ProtectionPacket, + }; + use tokio::time::{advance, timeout}; + + use super::*; + use crate::websocket::broker::Broker; + + 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 pod_data = Arc::new(PodData { + boards: HashMap::from([(pcu.id, pcu)]), + }); + let index = Arc::new(Index::new(&pod_data, None)); + (pod_data, index) + } + + #[tokio::test] + async fn forwards_connections_protections_messages_problems_and_orders_immediately() + -> Result<(), Box> { + let (pod_data, index) = sample_fixture(); + let (broker, client) = Broker::new(); + let mut conn_sub = client.subscribe_connections(); + let mut msg_sub = client.subscribe_messages()?; + let mut prot_sub = client.subscribe_protections()?; + let broker_task = tokio::spawn(broker.run()); + + let (tx, rx) = mpsc::channel(32); + let pipe_task = spawn(Config::default(), 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()["PCU"].is_connected); + + // 2. Protection event + let protection = ProtectionPacket { + id: AdjId((1 << 13) | 3001), + timestamp: ShortTimestamp { + hour: 12, + minute: 34, + second: 56, + subsecond: 7, + }, + 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, ProtectionUpdate::from(protection)); + + // 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?; + let got_msg = timeout(Duration::from_secs(1), msg_sub.recv()).await??; + assert_eq!(got_msg.kind, MessageKind::Warning); + assert_eq!(got_msg.board, "PCU"); + assert_eq!(got_msg.name, "pcu.c"); + assert_eq!(got_msg.payload, MessagePayload::Text("temp high".to_string())); + assert_eq!(got_msg.timestamp.hour, 1); + assert_eq!(got_msg.timestamp.counter, 4); + + // 4. Problem (Fatal -> Fault) + tx.send(ToPipeline::Problem(Problem { + at: UNIX_EPOCH + Duration::from_secs(1_700_000_003), + board: Some(BoardId(5)), + kind: ProblemKind::Fatal, + text: "decode failed".to_string(), + })) + .await?; + let got_problem = timeout(Duration::from_secs(1), msg_sub.recv()).await??; + assert_eq!(got_problem.kind, MessageKind::Fault); + assert_eq!(got_problem.board, "PCU"); + assert_eq!( + got_problem.payload, + MessagePayload::Text("decode failed".to_string()) + ); + + // 5. OrderSent & OrderFailed + tx.send(ToPipeline::OrderSent { + at: UNIX_EPOCH + Duration::from_secs(1_700_000_004), + board: Some(BoardId(5)), + order: OrderPacket::new(AdjId(1001), vec![]), + }) + .await?; + let got_sent = timeout(Duration::from_secs(1), msg_sub.recv()).await??; + assert_eq!(got_sent.kind, MessageKind::Info); + assert_eq!(got_sent.name, "1001"); + assert_eq!(got_sent.board, "PCU"); + + tx.send(ToPipeline::OrderFailed { + at: UNIX_EPOCH + Duration::from_secs(1_700_000_005), + order: OrderPacket::new(AdjId(1001), vec![]), + reason: "board disconnected".to_string(), + }) + .await?; + let got_failed = timeout(Duration::from_secs(1), msg_sub.recv()).await??; + assert_eq!(got_failed.kind, MessageKind::Warning); + assert_eq!(got_failed.name, "1001"); + assert_eq!( + got_failed.payload, + MessagePayload::Text("board disconnected".to_string()) + ); + + drop(tx); + timeout(Duration::from_secs(1), pipe_task).await??; + timeout(Duration::from_secs(1), broker_task).await??; + Ok(()) + } + + #[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.subscribe_data(); + let broker_task = tokio::spawn(broker.run()); + + let (tx, rx) = mpsc::channel(32); + let pipe_task = spawn(Config::default(), 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 { + tx.send(ToPipeline::Received(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; + + // First 100 ms tick flushes pipeline -> broker; next 100 ms tick flushes broker -> watch. + advance(Duration::from_millis(100)).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()[&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["voltage_battery_a"], + MeasurementUpdate::Numeric { + last: 30.0, + average: 20.0, + } + ); + assert_eq!( + first.measurement_updates["is_active"], + MeasurementUpdate::Boolean(true) + ); + assert_eq!( + first.measurement_updates["state"], + MeasurementUpdate::Enum("Fault".to_string()) + ); + + // Next window resets the measurement average while preserving cumulative count. + tx.send(ToPipeline::Received(Arc::new(Notification { + board: BoardId(5), + at: t0 + Duration::from_millis(150), + event: Event::Received(Packet::Data(DataPacket::new( + AdjId(551), + vec![ + Value::Number(50.0), + Value::Bool(false), + Value::Enum("Idle".to_string()), + ], + ))), + }))) + .await?; + + // Dropping `tx` flushes remaining data immediately and stops both tasks cleanly. + drop(tx); + timeout(Duration::from_secs(1), pipe_task).await??; + timeout(Duration::from_secs(1), broker_task).await??; + + let second = data_sub.borrow_and_update()[&551].clone(); + assert_eq!(second.count, 4); + assert_eq!(second.cycle_time, 100_000_000); + assert_eq!( + second.measurement_updates["voltage_battery_a"], + MeasurementUpdate::Numeric { + last: 50.0, + average: 50.0, + } + ); + Ok(()) + } + + #[test] + fn utc_calendar_conversion_handles_epoch_and_leap_day() { + let epoch = timestamp_from_system_time(UNIX_EPOCH); + assert_eq!( + epoch, + MessageTimestamp { + counter: 0, + 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 { + counter: 250, + second: 9, + minute: 45, + hour: 13, + day: 29, + month: 2, + year: 2024, + } + ); + } +} \ No newline at end of file From 4b67a0dcc8bbd9fbc1f12caa938085a8b36f76e8 Mon Sep 17 00:00:00 2001 From: GaziH Date: Tue, 1 Dec 2026 19:28:32 +0100 Subject: [PATCH 04/17] Feat(backend, pipeline): Refactored pipeline to be split up in similiar format as rest of station. Created README --- backend/crates/station/src/lib.rs | 6 +- backend/crates/station/src/main.rs | 2 +- backend/crates/station/src/payload.rs | 4 +- backend/crates/station/src/pipeline.rs | 208 ++++ backend/crates/station/src/pipeline/README.md | 134 +++ .../station/src/pipeline/accumulator.rs | 191 ++++ .../crates/station/src/pipeline/message.rs | 115 +++ backend/crates/station/src/pipeline/mod.rs | 1 - .../crates/station/src/pipeline/pipeline.rs | 888 ------------------ backend/crates/station/src/pipeline/tests.rs | 335 +++++++ .../crates/station/src/pipeline/timestamp.rs | 64 ++ 11 files changed, 1055 insertions(+), 893 deletions(-) create mode 100644 backend/crates/station/src/pipeline.rs create mode 100644 backend/crates/station/src/pipeline/README.md create mode 100644 backend/crates/station/src/pipeline/accumulator.rs create mode 100644 backend/crates/station/src/pipeline/message.rs delete mode 100644 backend/crates/station/src/pipeline/mod.rs delete mode 100644 backend/crates/station/src/pipeline/pipeline.rs create mode 100644 backend/crates/station/src/pipeline/tests.rs create mode 100644 backend/crates/station/src/pipeline/timestamp.rs diff --git a/backend/crates/station/src/lib.rs b/backend/crates/station/src/lib.rs index b7e482da0..3c53fc30c 100644 --- a/backend/crates/station/src/lib.rs +++ b/backend/crates/station/src/lib.rs @@ -1,4 +1,8 @@ pub mod http; mod vehicle; pub mod websocket; -pub mod payload; \ No newline at end of file +pub mod payload; + +pub mod pipeline; + +pub mod event; \ No newline at end of file diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index 911ea49b4..6da759f7f 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -26,7 +26,7 @@ //! backend uses: whatever was there is replaced by the [`ADJ_BRANCH`] branch. //! Offline, whatever is in that folder is used, whichever branch it is. -mod event; +use station::event; use std::collections::HashMap; use std::net::SocketAddr; diff --git a/backend/crates/station/src/payload.rs b/backend/crates/station/src/payload.rs index a2f6d5069..edcb33277 100644 --- a/backend/crates/station/src/payload.rs +++ b/backend/crates/station/src/payload.rs @@ -12,8 +12,8 @@ mod protection; mod serialize; pub use connection::{Connection, ConnectionUpdate}; -pub use data::{DataPacketUpdate, DataUpdate}; -pub use message::{MessageUpdate}; +pub use data::{DataPacketUpdate, DataUpdate, MeasurementUpdate}; +pub use message::{MessageKind, MessagePayload, MessageTimestamp, MessageUpdate}; pub use order::{OrderField, OrderSend, StateOrdersUpdate}; pub use protection::{ProtectionPayload, ProtectionUpdate}; diff --git a/backend/crates/station/src/pipeline.rs b/backend/crates/station/src/pipeline.rs new file mode 100644 index 000000000..29ff104bc --- /dev/null +++ b/backend/crates/station/src/pipeline.rs @@ -0,0 +1,208 @@ +//! Transforms [`crate::event::ToPipeline`] items into frontend WebSocket payloads +//! and publishes them through [`crate::websocket::broker::BrokerClient`]. +//! +//! # Contract +//! +//! - **Immediate events.** Connections, protections, board messages, backend +//! problems, and order outcomes are converted and published immediately. +//! - **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. Idle packets are not republished. +//! - **Wait, don't drop.** Reads continuously from `channels.pipeline` and +//! awaits broker capacity instead of dropping decoded events. +//! - **Clean shutdown.** When `event` closes the input channel (`None`), any +//! pending telemetry is flushed to the broker before the task exits. +//! - **No error policy.** `event` already decides what is silent, shown, or +//! fatal; `pipeline` only formats and publishes. +//! +//! # Topics not handled here +//! +//! - Frontend-to-backend topics (`order/send`, `logger/enable`, +//! `logger/variables`, `connection/heartbeat`) are consumed by `websocket`. +//! - `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::sync::Arc; +use std::time::Duration; + +use accumulator::DataAccumulator; +use crate::event::ToPipeline; +use crate::payload::{Connection, ProtectionUpdate}; +use crate::websocket::broker::BrokerClient; +use software_core::model::{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 publishing to `broker`. +/// +/// The task exits cleanly once `rx` closes and pending telemetry is flushed, +/// or immediately if `broker` has already shut down. +pub fn spawn( + config: Config, + rx: mpsc::Receiver, + broker: BrokerClient, + pod_data: Arc, + index: Arc, +) -> JoinHandle<()> { + tokio::spawn(run_loop(config, rx, broker, pod_data, index)) +} + +async fn run_loop( + config: Config, + mut rx: mpsc::Receiver, + broker: BrokerClient, + pod_data: Arc, + index: Arc, +) { + let period = config.data_flush_interval.max(Duration::from_millis(1)); + let mut tick = interval_at(Instant::now() + period, period); + tick.set_missed_tick_behavior(MissedTickBehavior::Skip); + + let mut accumulator = DataAccumulator::default(); + + loop { + // Poll the 100 ms flush tick first so sustained high-rate UDP traffic + // can never starve telemetry publication. + tokio::select! { + biased; + _ = tick.tick() => { + if !flush_data(&broker, &index, &mut accumulator).await { + return; + } + } + item = rx.recv() => { + match item { + Some(msg) => { + if !handle_item(msg, &broker, &pod_data, &index, &mut accumulator).await { + return; + } + } + None => { + let _ = flush_data(&broker, &index, &mut accumulator).await; + return; + } + } + } + } + } +} + +/// 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, +) -> bool { + match item { + ToPipeline::Received(notification) => { + handle_notification(¬ification, broker, pod_data, index, accumulator).await + } + ToPipeline::Problem(problem) => match message::from_problem(problem, pod_data) { + Some(update) => publish_or_log(broker.publish_message(update).await), + None => true, + }, + ToPipeline::OrderSent { at, board, order } => { + let update = message::from_order_sent(at, board, order, pod_data); + publish_or_log(broker.publish_message(update).await) + } + ToPipeline::OrderFailed { at, order, reason } => { + let update = message::from_order_failed(at, order, reason, pod_data, index); + publish_or_log(broker.publish_message(update).await) + } + } +} + +async fn handle_notification( + notification: &Notification, + broker: &BrokerClient, + pod_data: &PodData, + index: &Index, + accumulator: &mut DataAccumulator, +) -> bool { + match ¬ification.event { + Event::Connected => { + let update = Connection { + name: message::board_name(pod_data, notification.board), + is_connected: true, + }; + publish_or_log(broker.publish_connection(update).await) + } + Event::Disconnected => { + let update = Connection { + name: message::board_name(pod_data, notification.board), + is_connected: false, + }; + publish_or_log(broker.publish_connection(update).await) + } + Event::Received(Packet::Data(data)) => { + accumulator.record(data, notification.at, index); + true + } + Event::Received(Packet::Protection(protection)) => { + let update = ProtectionUpdate::from(protection.clone()); + 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 + } + } +} + +async fn flush_data( + broker: &BrokerClient, + index: &Index, + accumulator: &mut DataAccumulator, +) -> bool { + for update in accumulator.drain_updates(index) { + if !publish_or_log(broker.publish_data(update).await) { + return false; + } + } + true +} + +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 + } + } +} \ No newline at end of file diff --git a/backend/crates/station/src/pipeline/README.md b/backend/crates/station/src/pipeline/README.md new file mode 100644 index 000000000..ee1ee5f57 --- /dev/null +++ b/backend/crates/station/src/pipeline/README.md @@ -0,0 +1,134 @@ +# Pipeline (`station::pipeline`) + +Transforms [`crate::event::ToPipeline`] items into frontend WebSocket payloads +(`station::payload`) and publishes them through [`crate::websocket::broker::BrokerClient`]. + +`event` routes decoded packets and backend outcomes without inspecting their +contents. `pipeline` is the stage that turns those domain events into the exact +shapes the frontend expects: publishing discrete events immediately and +aggregating high-rate UDP telemetry into 100 ms windows. + +## Overview + +```text + event ──(channels.pipeline: ToPipeline)──► pipeline + ├── immediate ──► BrokerClient + │ ├── connection/update + │ ├── protection/update + │ └── message/update + └── 100 ms tick ─► BrokerClient + └── podData/update +``` + +## Files + +```text +pipeline.rs # module root: Config, spawn, select! loop, routing +pipeline/ +├── accumulator.rs # 100 ms telemetry windowing (count, cycle_time, last, average) +├── message.rs # MessageUpdate builders (board messages, problems, order outcomes) +├── timestamp.rs # SystemTime / ShortTimestamp -> UTC MessageTimestamp +├── tests.rs # unit tests against a real Broker +└── README.md +``` + +## Input-to-Topic Mapping + +| `ToPipeline` variant | Condition / inner event | Target topic | `BrokerClient` method | Delivery | +| --- | --- | --- | --- | --- | +| `Received(Notification)` | `Event::Connected` / `Event::Disconnected` | `connection/update` | `publish_connection` | Immediate | +| `Received(Notification)` | `Event::Received(Packet::Data(_))` | `podData/update` | `publish_data` | 100 ms window | +| `Received(Notification)` | `Event::Received(Packet::Protection(_))` | `protection/update` | `publish_protection` | Immediate | +| `Received(Notification)` | `Event::Received(Packet::Message(_))` | `message/update` | `publish_message` | Immediate | +| `Received(Notification)` | `Event::Received(Packet::Order(_))` | — | Ignored (logged as warning) | — | +| `Problem(Problem)` | `ProblemKind::Shown` → `warning` | `message/update` | `publish_message` | Immediate | +| `Problem(Problem)` | `ProblemKind::Fatal` → `fault` | `message/update` | `publish_message` | Immediate | +| `Problem(Problem)` | `ProblemKind::Silent` | — | Ignored | — | +| `OrderSent` | Confirmed TCP write → `info` | `message/update` | `publish_message` | Immediate | +| `OrderFailed` | Failed TCP write → `warning` | `message/update` | `publish_message` | Immediate | + +### Topics not handled by `pipeline` + +- **Frontend-to-backend topics** (`order/send`, `logger/enable`, + `logger/variables`, `connection/heartbeat`) are handled directly by `websocket`. +- **`logger/response`** is published directly by `logging`. +- **`order/stateOrders`** is not produced yet because `software_core::model::Packet` + has no state-orders packet variant. + +## 100 ms Data Aggregation (`accumulator.rs`) + +High-frequency telemetry (`Packet::Data`) is accumulated in place per packet ID +and flushed every `Config::data_flush_interval` (default `100 ms`). + +- **Per-packet statistics:** + - `count`: cumulative number of packets received for that `AdjId` since startup. + - `cycleTime`: mean inter-arrival interval in nanoseconds across packets + received in the current window (`last_at` persists across window boundaries). + - `hexValue`: left empty (`""`), as `Notification` carries decoded `Value`s + rather than raw UDP bytes. +- **Per-measurement updates** (keyed by each measurement's ADJ `alias`): + - Numeric measurements emit `{ "last": f64, "average": f64 }`, where `last` is + the most recent sample and `average` is the arithmetic mean over the window. + - Boolean and enum measurements emit their latest value directly. +- **Idle packets** (no frames received during a window) are skipped on flush; the + WebSocket broker retains their previous snapshot. +- **Starvation protection:** the main `tokio::select!` uses `biased;` with the + flush timer polled first so sustained UDP rates cannot delay telemetry flushes. + +## Messages & Timestamps (`message.rs`, `timestamp.rs`) + +- **Board names** are resolved from `PodData::boards` (falling back to + `"board-"`). Backend-wide problems use `"backend"`, and broadcast fault + orders (`board = None` or `AdjId(0)`) use `"all"`. +- **Order notices** use the numeric order ID as `name` (`order.id.0.to_string()`), + matching the legacy frontend convention. +- **UTC calendar conversion** uses a zero-dependency civil-date calculation from + `SystemTime`: + - Backend-generated messages (`Problem`, `OrderSent`, `OrderFailed`) populate + `timestamp` from `at`, with `counter` set to milliseconds (`0–999`). + - Board messages (`Packet::Message`) combine the reception calendar date from + `Notification::at` with the board's `ShortTimestamp` (`hour`, `minute`, + `second`) and store its raw `subsecond` byte in `counter`. + +## Contract & Shutdown + +- **Wait, don't drop.** `pipeline` reads continuously from `channels.pipeline` + and awaits `BrokerClient` capacity rather than dropping decoded events. +- **No error policy.** Error classification and fault propagation belong solely + to `event`. +- **Clean shutdown.** + - When `event` closes `channels.pipeline` (`recv()` returns `None`), `pipeline` + flushes any dirty telemetry in the accumulator to the broker and exits. + - If `BrokerClient` returns `Error::BrokerClosed`, `pipeline` logs the error + and exits immediately. + +## Usage + +```rust +use station::pipeline::{self, Config}; + +let pipeline_handle = pipeline::spawn( + Config::default(), + channels.pipeline, + broker_client, + pod_data, + index, +); +``` + +## Tests + +Unit tests in `pipeline/tests.rs` wire `pipeline::spawn` to a real `Broker` +instance (no sockets required) and verify: + +- Immediate forwarding of connections, protections, board messages, problems, + and order outcomes (`OrderSent` / `OrderFailed`). +- 100 ms windowing for `Packet::Data` (cumulative `count`, mean `cycleTime`, + window `average`, `last`, and flush-on-shutdown). +- UTC calendar conversion on epoch and leap-day timestamps. + +Run them with: + +```sh +cargo test -p station pipeline +``` \ No newline at end of file diff --git a/backend/crates/station/src/pipeline/accumulator.rs b/backend/crates/station/src/pipeline/accumulator.rs new file mode 100644 index 000000000..e6d2a0a72 --- /dev/null +++ b/backend/crates/station/src/pipeline/accumulator.rs @@ -0,0 +1,191 @@ +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::warn; + +/// 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 { + 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()), + } + } + + 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)) => { + if last != s { + last.clone_from(s); + } + } + (slot, other) => { + *slot = Self::from_value(other); + } + } + } + + 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 { + pub(super) fn record(&mut self, packet: &DataPacket, at: SystemTime, index: &Index) { + let Some(def) = index.packet(packet.id) else { + warn!(id = packet.id.0, "unknown data packet id in index"); + return; + }; + let PacketType::Data(defs) = &def.packet_type else { + warn!( + id = packet.id.0, + "packet id in DataPacket does not map to PacketType::Data" + ); + return; + }; + + if packet.values.len() != defs.len() { + warn!( + id = packet.id.0, + expected = defs.len(), + actual = packet.values.len(), + "data packet value count mismatch" + ); + } + + 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); + 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); + + 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; + } + + 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; + + 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; + }; + + let mut measurement_updates = 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.alias.clone(), acc.into_update()); + } + } + + updates.push(DataPacketUpdate { + id, + // Raw wire bytes are not carried by `Notification`; left empty. + hex_value: String::new(), + count: window.count, + cycle_time: window.last_cycle_time_ns, + measurement_updates, + }); + } + + updates + } +} \ No newline at end of file diff --git a/backend/crates/station/src/pipeline/message.rs b/backend/crates/station/src/pipeline/message.rs new file mode 100644 index 000000000..a5a408ccd --- /dev/null +++ b/backend/crates/station/src/pipeline/message.rs @@ -0,0 +1,115 @@ +use std::time::SystemTime; + +use super::timestamp; +use crate::event::{Problem, ProblemKind}; +use crate::payload::{MessageKind, MessagePayload, MessageUpdate}; +use software_core::model::{AdjId, BoardId, MessagePacket, OrderPacket, PacketType, PodData}; +use software_core::protocol::Index; +use tracing::warn; + +pub(super) fn board_name(pod_data: &PodData, board: BoardId) -> String { + pod_data + .boards + .get(&board) + .map_or_else(|| format!("board-{}", board.0), |b| b.name.clone()) +} + +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) { + Some(def) => match def.packet_type { + PacketType::Message(level) => MessageKind::from(level), + _ => { + warn!( + id = message.id.0, + "message packet id does not map to PacketType::Message" + ); + MessageKind::Info + } + }, + None => { + warn!(id = message.id.0, "unknown message packet id in index"); + MessageKind::Info + } + }; + + let name = if message.origin.is_empty() { + message.id.0.to_string() + } else { + message.origin.clone() + }; + + MessageUpdate { + kind, + payload: MessagePayload::Text(message.message.clone()), + board: board_name(pod_data, board), + name, + timestamp: timestamp::from_short(at, message.timestamp), + } +} + +pub(super) fn from_problem(problem: Problem, pod_data: &PodData) -> Option { + let kind = match problem.kind { + ProblemKind::Shown => MessageKind::Warning, + ProblemKind::Fatal => MessageKind::Fault, + ProblemKind::Silent => return None, + }; + + let board = problem + .board + .map_or_else(|| "backend".to_string(), |id| board_name(pod_data, id)); + + Some(MessageUpdate { + kind, + payload: MessagePayload::Text(problem.text), + board, + name: "backend".to_string(), + timestamp: timestamp::from_system_time(problem.at), + }) +} + +pub(super) fn from_order_sent( + at: SystemTime, + board: Option, + order: OrderPacket, + pod_data: &PodData, +) -> MessageUpdate { + let board_label = board.map_or_else(|| "all".to_string(), |id| board_name(pod_data, id)); + + MessageUpdate { + kind: MessageKind::Info, + payload: MessagePayload::Text(format!("Order {} sent", order.id.0)), + board: board_label, + name: order.id.0.to_string(), + timestamp: timestamp::from_system_time(at), + } +} + +pub(super) fn from_order_failed( + at: SystemTime, + order: OrderPacket, + reason: String, + pod_data: &PodData, + index: &Index, +) -> MessageUpdate { + let board_label = if order.id == AdjId(0) { + "all".to_string() + } else if let Some(def) = index.packet(order.id) { + board_name(pod_data, def.board) + } else { + "backend".to_string() + }; + + MessageUpdate { + kind: MessageKind::Warning, + payload: MessagePayload::Text(reason), + board: board_label, + name: order.id.0.to_string(), + timestamp: timestamp::from_system_time(at), + } +} \ No newline at end of file diff --git a/backend/crates/station/src/pipeline/mod.rs b/backend/crates/station/src/pipeline/mod.rs deleted file mode 100644 index e979cae3b..000000000 --- a/backend/crates/station/src/pipeline/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod pipeline; \ No newline at end of file diff --git a/backend/crates/station/src/pipeline/pipeline.rs b/backend/crates/station/src/pipeline/pipeline.rs deleted file mode 100644 index 8270f442e..000000000 --- a/backend/crates/station/src/pipeline/pipeline.rs +++ /dev/null @@ -1,888 +0,0 @@ -//! Transforms [`crate::event::ToPipeline`] items into frontend WebSocket payloads -//! and publishes them through [`crate::websocket::broker::BrokerClient`]. -//! -//! # Contract -//! -//! - **Immediate events.** Connections, protections, board messages, backend -//! problems, and order outcomes are converted and published immediately. -//! - **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. Idle packets are not republished. -//! - **Wait, don't drop.** Reads continuously from `channels.pipeline` and -//! awaits broker capacity instead of dropping decoded events. -//! - **Clean shutdown.** When `event` closes the input channel (`None`), any -//! pending telemetry is flushed to the broker before the task exits. -//! - **No error policy.** `event` already decides what is silent, shown, or -//! fatal; `pipeline` only formats and publishes. -//! -//! # Topics not handled here -//! -//! - Frontend-to-backend topics (`order/send`, `logger/enable`, -//! `logger/variables`, `connection/heartbeat`) are consumed by `websocket`. -//! - `logger/response` is published directly by `logging`. -//! - `order/stateOrders` has no corresponding packet variant in -//! `software_core::model::Packet` yet. - -use std::collections::HashMap; -use std::sync::Arc; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; - -use crate::event::{Problem, ProblemKind, ToPipeline}; -use crate::payload::{ - Connection, DataPacketUpdate, MeasurementUpdate, MessageKind, MessagePayload, - MessageTimestamp, MessageUpdate, ProtectionUpdate, -}; -use crate::websocket::broker::BrokerClient; -use software_core::model::{ - AdjId, BoardId, DataPacket, MessagePacket, OrderPacket, Packet, PacketType, PodData, - ShortTimestamp, Value, -}; -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 publishing to `broker`. -/// -/// The task exits cleanly once `rx` closes and pending telemetry is flushed, -/// or immediately if `broker` has already shut down. -pub fn spawn( - config: Config, - rx: mpsc::Receiver, - broker: BrokerClient, - pod_data: Arc, - index: Arc, -) -> JoinHandle<()> { - tokio::spawn(run_loop(config, rx, broker, pod_data, index)) -} - -async fn run_loop( - config: Config, - mut rx: mpsc::Receiver, - broker: BrokerClient, - pod_data: Arc, - index: Arc, -) { - let period = config.data_flush_interval.max(Duration::from_millis(1)); - let mut tick = interval_at(Instant::now() + period, period); - tick.set_missed_tick_behavior(MissedTickBehavior::Skip); - - let mut accumulator = DataAccumulator::default(); - - loop { - // Poll the 100 ms flush tick first so sustained high-rate UDP traffic - // can never starve telemetry publication. - tokio::select! { - biased; - _ = tick.tick() => { - if !flush_data(&broker, &index, &mut accumulator).await { - return; - } - } - item = rx.recv() => { - match item { - Some(msg) => { - if !handle_item(msg, &broker, &pod_data, &index, &mut accumulator).await { - return; - } - } - None => { - let _ = flush_data(&broker, &index, &mut accumulator).await; - return; - } - } - } - } - } -} - -/// 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, -) -> bool { - match item { - ToPipeline::Received(notification) => { - handle_notification(¬ification, broker, pod_data, index, accumulator).await - } - ToPipeline::Problem(problem) => handle_problem(problem, broker, pod_data).await, - ToPipeline::OrderSent { at, board, order } => { - handle_order_sent(at, board, order, broker, pod_data).await - } - ToPipeline::OrderFailed { at, order, reason } => { - handle_order_failed(at, order, reason, broker, pod_data, index).await - } - } -} - -async fn handle_notification( - notification: &Notification, - broker: &BrokerClient, - pod_data: &PodData, - index: &Index, - accumulator: &mut DataAccumulator, -) -> bool { - match ¬ification.event { - Event::Connected => { - let update = Connection { - name: board_name(pod_data, notification.board), - is_connected: true, - }; - publish_or_log(broker.publish_connection(update).await) - } - Event::Disconnected => { - let update = Connection { - name: board_name(pod_data, notification.board), - is_connected: false, - }; - publish_or_log(broker.publish_connection(update).await) - } - Event::Received(Packet::Data(data)) => { - accumulator.record(data, notification.at, index); - true - } - Event::Received(Packet::Protection(protection)) => { - let update = ProtectionUpdate::from(protection.clone()); - publish_or_log(broker.publish_protection(update).await) - } - Event::Received(Packet::Message(message)) => { - let update = build_board_message(notification.board, notification.at, message, 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 - } - } -} - -async fn handle_problem(problem: Problem, broker: &BrokerClient, pod_data: &PodData) -> bool { - let kind = match problem.kind { - ProblemKind::Shown => MessageKind::Warning, - ProblemKind::Fatal => MessageKind::Fault, - ProblemKind::Silent => return true, - }; - - let board = problem - .board - .map_or_else(|| "backend".to_string(), |id| board_name(pod_data, id)); - - let update = MessageUpdate { - kind, - payload: MessagePayload::Text(problem.text), - board, - name: "backend".to_string(), - timestamp: timestamp_from_system_time(problem.at), - }; - - publish_or_log(broker.publish_message(update).await) -} - -async fn handle_order_sent( - at: SystemTime, - board: Option, - order: OrderPacket, - broker: &BrokerClient, - pod_data: &PodData, -) -> bool { - let board_label = board.map_or_else(|| "all".to_string(), |id| board_name(pod_data, id)); - - let update = MessageUpdate { - kind: MessageKind::Info, - payload: MessagePayload::Text(format!("Order {} sent", order.id.0)), - board: board_label, - name: order.id.0.to_string(), - timestamp: timestamp_from_system_time(at), - }; - - publish_or_log(broker.publish_message(update).await) -} - -async fn handle_order_failed( - at: SystemTime, - order: OrderPacket, - reason: String, - broker: &BrokerClient, - pod_data: &PodData, - index: &Index, -) -> bool { - let board_label = if order.id == AdjId(0) { - "all".to_string() - } else if let Some(def) = index.packet(order.id) { - board_name(pod_data, def.board) - } else { - "backend".to_string() - }; - - let update = MessageUpdate { - kind: MessageKind::Warning, - payload: MessagePayload::Text(reason), - board: board_label, - name: order.id.0.to_string(), - timestamp: timestamp_from_system_time(at), - }; - - publish_or_log(broker.publish_message(update).await) -} - -fn build_board_message( - board: BoardId, - at: SystemTime, - message: &MessagePacket, - pod_data: &PodData, - index: &Index, -) -> MessageUpdate { - let kind = match index.packet(message.id) { - Some(def) => match def.packet_type { - PacketType::Message(level) => MessageKind::from(level), - _ => { - warn!(id = message.id.0, "message packet id does not map to PacketType::Message"); - MessageKind::Info - } - }, - None => { - warn!(id = message.id.0, "unknown message packet id in index"); - MessageKind::Info - } - }; - - let name = if message.origin.is_empty() { - message.id.0.to_string() - } else { - message.origin.clone() - }; - - MessageUpdate { - kind, - payload: MessagePayload::Text(message.message.clone()), - board: board_name(pod_data, board), - name, - timestamp: timestamp_from_short(at, message.timestamp), - } -} - -async fn flush_data( - broker: &BrokerClient, - index: &Index, - accumulator: &mut DataAccumulator, -) -> bool { - for update in accumulator.drain_updates(index) { - if !publish_or_log(broker.publish_data(update).await) { - return false; - } - } - true -} - -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 - } - } -} - -fn board_name(pod_data: &PodData, board: BoardId) -> String { - pod_data - .boards - .get(&board) - .map_or_else(|| format!("board-{}", board.0), |b| b.name.clone()) -} - -// --------------------------------------------------------------------------- -// 100 ms Telemetry Accumulator -// --------------------------------------------------------------------------- - -#[derive(Debug, Default)] -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 { - 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()), - } - } - - 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)) => { - if last != s { - last.clone_from(s); - } - } - (slot, other) => { - *slot = Self::from_value(other); - } - } - } - - 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 { - fn record(&mut self, packet: &DataPacket, at: SystemTime, index: &Index) { - let Some(def) = index.packet(packet.id) else { - warn!(id = packet.id.0, "unknown data packet id in index"); - return; - }; - let PacketType::Data(defs) = &def.packet_type else { - warn!(id = packet.id.0, "packet id in DataPacket does not map to PacketType::Data"); - return; - }; - - if packet.values.len() != defs.len() { - warn!( - id = packet.id.0, - expected = defs.len(), - actual = packet.values.len(), - "data packet value count mismatch" - ); - } - - 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); - 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); - - 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; - } - - 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; - - 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; - }; - - let mut measurement_updates = 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.alias.clone(), acc.into_update()); - } - } - - updates.push(DataPacketUpdate { - id, - // Raw wire bytes are not carried by `Notification`; left empty. - hex_value: String::new(), - count: window.count, - cycle_time: window.last_cycle_time_ns, - measurement_updates, - }); - } - - updates - } -} - -// --------------------------------------------------------------------------- -// UTC Calendar Timestamp Conversion (zero external dependencies) -// --------------------------------------------------------------------------- - -/// Converts a [`SystemTime`] into a UTC [`MessageTimestamp`]. -fn timestamp_from_system_time(at: SystemTime) -> MessageTimestamp { - let dur = at.duration_since(UNIX_EPOCH).unwrap_or(Duration::ZERO); - let total_secs = dur.as_secs(); - 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); - 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); - let counter = u16::try_from(dur.subsec_millis()).unwrap_or(0); - - MessageTimestamp { - counter, - 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. -fn timestamp_from_short(received_at: SystemTime, short: ShortTimestamp) -> MessageTimestamp { - let date = timestamp_from_system_time(received_at); - MessageTimestamp { - counter: u16::from(short.subsecond), - 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) { - let z = days_since_epoch + 719_468; - let era = if z >= 0 { z } else { z - 146_096 } / 146_097; - let doe = u64::try_from(z - era * 146_097).unwrap_or(0); - let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; - let y = i64::try_from(yoe).unwrap_or(0) + era * 400; - let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); - let mp = (5 * doy + 2) / 153; - let d = doy - (153 * mp + 2) / 5 + 1; - let m = if mp < 10 { mp + 3 } else { mp - 9 }; - 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), - ) -} - -#[cfg(test)] -mod tests { - use std::net::IpAddr; - - use software_core::model::{ - Board, MacAddress, Measurement, MeasurementKind, MessageLevel, NumericKind, PacketDef, - ProtectionPacket, - }; - use tokio::time::{advance, timeout}; - - use super::*; - use crate::websocket::broker::Broker; - - 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 pod_data = Arc::new(PodData { - boards: HashMap::from([(pcu.id, pcu)]), - }); - let index = Arc::new(Index::new(&pod_data, None)); - (pod_data, index) - } - - #[tokio::test] - async fn forwards_connections_protections_messages_problems_and_orders_immediately() - -> Result<(), Box> { - let (pod_data, index) = sample_fixture(); - let (broker, client) = Broker::new(); - let mut conn_sub = client.subscribe_connections(); - let mut msg_sub = client.subscribe_messages()?; - let mut prot_sub = client.subscribe_protections()?; - let broker_task = tokio::spawn(broker.run()); - - let (tx, rx) = mpsc::channel(32); - let pipe_task = spawn(Config::default(), 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()["PCU"].is_connected); - - // 2. Protection event - let protection = ProtectionPacket { - id: AdjId((1 << 13) | 3001), - timestamp: ShortTimestamp { - hour: 12, - minute: 34, - second: 56, - subsecond: 7, - }, - 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, ProtectionUpdate::from(protection)); - - // 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?; - let got_msg = timeout(Duration::from_secs(1), msg_sub.recv()).await??; - assert_eq!(got_msg.kind, MessageKind::Warning); - assert_eq!(got_msg.board, "PCU"); - assert_eq!(got_msg.name, "pcu.c"); - assert_eq!(got_msg.payload, MessagePayload::Text("temp high".to_string())); - assert_eq!(got_msg.timestamp.hour, 1); - assert_eq!(got_msg.timestamp.counter, 4); - - // 4. Problem (Fatal -> Fault) - tx.send(ToPipeline::Problem(Problem { - at: UNIX_EPOCH + Duration::from_secs(1_700_000_003), - board: Some(BoardId(5)), - kind: ProblemKind::Fatal, - text: "decode failed".to_string(), - })) - .await?; - let got_problem = timeout(Duration::from_secs(1), msg_sub.recv()).await??; - assert_eq!(got_problem.kind, MessageKind::Fault); - assert_eq!(got_problem.board, "PCU"); - assert_eq!( - got_problem.payload, - MessagePayload::Text("decode failed".to_string()) - ); - - // 5. OrderSent & OrderFailed - tx.send(ToPipeline::OrderSent { - at: UNIX_EPOCH + Duration::from_secs(1_700_000_004), - board: Some(BoardId(5)), - order: OrderPacket::new(AdjId(1001), vec![]), - }) - .await?; - let got_sent = timeout(Duration::from_secs(1), msg_sub.recv()).await??; - assert_eq!(got_sent.kind, MessageKind::Info); - assert_eq!(got_sent.name, "1001"); - assert_eq!(got_sent.board, "PCU"); - - tx.send(ToPipeline::OrderFailed { - at: UNIX_EPOCH + Duration::from_secs(1_700_000_005), - order: OrderPacket::new(AdjId(1001), vec![]), - reason: "board disconnected".to_string(), - }) - .await?; - let got_failed = timeout(Duration::from_secs(1), msg_sub.recv()).await??; - assert_eq!(got_failed.kind, MessageKind::Warning); - assert_eq!(got_failed.name, "1001"); - assert_eq!( - got_failed.payload, - MessagePayload::Text("board disconnected".to_string()) - ); - - drop(tx); - timeout(Duration::from_secs(1), pipe_task).await??; - timeout(Duration::from_secs(1), broker_task).await??; - Ok(()) - } - - #[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.subscribe_data(); - let broker_task = tokio::spawn(broker.run()); - - let (tx, rx) = mpsc::channel(32); - let pipe_task = spawn(Config::default(), 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 { - tx.send(ToPipeline::Received(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; - - // First 100 ms tick flushes pipeline -> broker; next 100 ms tick flushes broker -> watch. - advance(Duration::from_millis(100)).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()[&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["voltage_battery_a"], - MeasurementUpdate::Numeric { - last: 30.0, - average: 20.0, - } - ); - assert_eq!( - first.measurement_updates["is_active"], - MeasurementUpdate::Boolean(true) - ); - assert_eq!( - first.measurement_updates["state"], - MeasurementUpdate::Enum("Fault".to_string()) - ); - - // Next window resets the measurement average while preserving cumulative count. - tx.send(ToPipeline::Received(Arc::new(Notification { - board: BoardId(5), - at: t0 + Duration::from_millis(150), - event: Event::Received(Packet::Data(DataPacket::new( - AdjId(551), - vec![ - Value::Number(50.0), - Value::Bool(false), - Value::Enum("Idle".to_string()), - ], - ))), - }))) - .await?; - - // Dropping `tx` flushes remaining data immediately and stops both tasks cleanly. - drop(tx); - timeout(Duration::from_secs(1), pipe_task).await??; - timeout(Duration::from_secs(1), broker_task).await??; - - let second = data_sub.borrow_and_update()[&551].clone(); - assert_eq!(second.count, 4); - assert_eq!(second.cycle_time, 100_000_000); - assert_eq!( - second.measurement_updates["voltage_battery_a"], - MeasurementUpdate::Numeric { - last: 50.0, - average: 50.0, - } - ); - Ok(()) - } - - #[test] - fn utc_calendar_conversion_handles_epoch_and_leap_day() { - let epoch = timestamp_from_system_time(UNIX_EPOCH); - assert_eq!( - epoch, - MessageTimestamp { - counter: 0, - 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 { - counter: 250, - second: 9, - minute: 45, - hour: 13, - day: 29, - month: 2, - year: 2024, - } - ); - } -} \ No newline at end of file diff --git a/backend/crates/station/src/pipeline/tests.rs b/backend/crates/station/src/pipeline/tests.rs new file mode 100644 index 000000000..30c3f074e --- /dev/null +++ b/backend/crates/station/src/pipeline/tests.rs @@ -0,0 +1,335 @@ +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::{Config, spawn, timestamp}; +use crate::event::{Problem, ProblemKind, ToPipeline}; +use crate::payload::{ + MeasurementUpdate, MessageKind, MessagePayload, MessageTimestamp, ProtectionUpdate, +}; +use crate::websocket::broker::Broker; + +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 pod_data = Arc::new(PodData { + boards: HashMap::from([(pcu.id, pcu)]), + }); + let index = Arc::new(Index::new(&pod_data, None)); + (pod_data, index) +} + +#[tokio::test] +async fn forwards_connections_protections_messages_problems_and_orders_immediately() + -> Result<(), Box> { + let (pod_data, index) = sample_fixture(); + let (broker, client) = Broker::new(); + let mut conn_sub = client.subscribe_connections(); + let mut msg_sub = client.subscribe_messages()?; + let mut prot_sub = client.subscribe_protections()?; + let broker_task = tokio::spawn(broker.run()); + + let (tx, rx) = mpsc::channel(32); + let pipe_task = spawn(Config::default(), 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()["PCU"].is_connected); + + // 2. Protection event + let protection = ProtectionPacket { + id: AdjId((1 << 13) | 3001), + timestamp: ShortTimestamp { + hour: 12, + minute: 34, + second: 56, + subsecond: 7, + }, + 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, ProtectionUpdate::from(protection)); + + // 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?; + let got_msg = timeout(Duration::from_secs(1), msg_sub.recv()).await??; + assert_eq!(got_msg.kind, MessageKind::Warning); + assert_eq!(got_msg.board, "PCU"); + assert_eq!(got_msg.name, "pcu.c"); + assert_eq!(got_msg.payload, MessagePayload::Text("temp high".to_string())); + assert_eq!(got_msg.timestamp.hour, 1); + assert_eq!(got_msg.timestamp.counter, 4); + + // 4. Problem (Fatal -> Fault) + tx.send(ToPipeline::Problem(Problem { + at: UNIX_EPOCH + Duration::from_secs(1_700_000_003), + board: Some(BoardId(5)), + kind: ProblemKind::Fatal, + text: "decode failed".to_string(), + })) + .await?; + let got_problem = timeout(Duration::from_secs(1), msg_sub.recv()).await??; + assert_eq!(got_problem.kind, MessageKind::Fault); + assert_eq!(got_problem.board, "PCU"); + assert_eq!( + got_problem.payload, + MessagePayload::Text("decode failed".to_string()) + ); + + // 5. OrderSent & OrderFailed + tx.send(ToPipeline::OrderSent { + at: UNIX_EPOCH + Duration::from_secs(1_700_000_004), + board: Some(BoardId(5)), + order: OrderPacket::new(AdjId(1001), vec![]), + }) + .await?; + let got_sent = timeout(Duration::from_secs(1), msg_sub.recv()).await??; + assert_eq!(got_sent.kind, MessageKind::Info); + assert_eq!(got_sent.name, "1001"); + assert_eq!(got_sent.board, "PCU"); + + tx.send(ToPipeline::OrderFailed { + at: UNIX_EPOCH + Duration::from_secs(1_700_000_005), + order: OrderPacket::new(AdjId(1001), vec![]), + reason: "board disconnected".to_string(), + }) + .await?; + let got_failed = timeout(Duration::from_secs(1), msg_sub.recv()).await??; + assert_eq!(got_failed.kind, MessageKind::Warning); + assert_eq!(got_failed.name, "1001"); + assert_eq!( + got_failed.payload, + MessagePayload::Text("board disconnected".to_string()) + ); + + drop(tx); + timeout(Duration::from_secs(1), pipe_task).await??; + timeout(Duration::from_secs(1), broker_task).await??; + Ok(()) +} + +#[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.subscribe_data(); + let broker_task = tokio::spawn(broker.run()); + + let (tx, rx) = mpsc::channel(32); + let pipe_task = spawn(Config::default(), 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 { + tx.send(ToPipeline::Received(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; + + // First 100 ms tick flushes pipeline -> broker; next 100 ms tick flushes broker -> watch. + 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()[&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["voltage_battery_a"], + MeasurementUpdate::Numeric { + last: 30.0, + average: 20.0, + } + ); + assert_eq!( + first.measurement_updates["is_active"], + MeasurementUpdate::Boolean(true) + ); + assert_eq!( + first.measurement_updates["state"], + MeasurementUpdate::Enum("Fault".to_string()) + ); + + // Next window resets the measurement average while preserving cumulative count. + tx.send(ToPipeline::Received(Arc::new(Notification { + board: BoardId(5), + at: t0 + Duration::from_millis(150), + event: Event::Received(Packet::Data(DataPacket::new( + AdjId(551), + vec![ + Value::Number(50.0), + Value::Bool(false), + Value::Enum("Idle".to_string()), + ], + ))), + }))) + .await?; + + // Dropping `tx` flushes remaining data immediately and stops both tasks cleanly. + drop(tx); + timeout(Duration::from_secs(1), pipe_task).await??; + timeout(Duration::from_secs(1), broker_task).await??; + + let second = data_sub.borrow_and_update()[&551].clone(); + assert_eq!(second.count, 4); + assert_eq!(second.cycle_time, 100_000_000); + assert_eq!( + second.measurement_updates["voltage_battery_a"], + MeasurementUpdate::Numeric { + last: 50.0, + average: 50.0, + } + ); + Ok(()) +} + +#[test] +fn utc_calendar_conversion_handles_epoch_and_leap_day() { + let epoch = timestamp::from_system_time(UNIX_EPOCH); + assert_eq!( + epoch, + MessageTimestamp { + counter: 0, + 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 { + counter: 250, + second: 9, + minute: 45, + hour: 13, + day: 29, + month: 2, + year: 2024, + } + ); +} \ No newline at end of file diff --git a/backend/crates/station/src/pipeline/timestamp.rs b/backend/crates/station/src/pipeline/timestamp.rs new file mode 100644 index 000000000..de8dab49c --- /dev/null +++ b/backend/crates/station/src/pipeline/timestamp.rs @@ -0,0 +1,64 @@ +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 { + let dur = at.duration_since(UNIX_EPOCH).unwrap_or(Duration::ZERO); + let total_secs = dur.as_secs(); + 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); + 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); + let counter = u16::try_from(dur.subsec_millis()).unwrap_or(0); + + MessageTimestamp { + counter, + 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 { + counter: u16::from(short.subsecond), + 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) { + let z = days_since_epoch + 719_468; + let era = if z >= 0 { z } else { z - 146_096 } / 146_097; + let doe = u64::try_from(z - era * 146_097).unwrap_or(0); + let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; + let y = i64::try_from(yoe).unwrap_or(0) + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + 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), + ) +} \ No newline at end of file From 33d7fbd188c2a3164eb0f91c655aca90124e7d76 Mon Sep 17 00:00:00 2001 From: GaziH Date: Tue, 1 Dec 2026 20:11:28 +0100 Subject: [PATCH 05/17] Feat(backend, pipeline): Made in line comments where necessary. --- backend/crates/station/src/pipeline.rs | 25 +++++++++++-- .../station/src/pipeline/accumulator.rs | 36 +++++++++++++++++-- .../crates/station/src/pipeline/message.rs | 14 ++++++++ .../crates/station/src/pipeline/timestamp.rs | 4 +++ 4 files changed, 74 insertions(+), 5 deletions(-) diff --git a/backend/crates/station/src/pipeline.rs b/backend/crates/station/src/pipeline.rs index 29ff104bc..c94b2b805 100644 --- a/backend/crates/station/src/pipeline.rs +++ b/backend/crates/station/src/pipeline.rs @@ -75,6 +75,11 @@ pub fn spawn( tokio::spawn(run_loop(config, rx, broker, pod_data, index)) } +/// Runs the main pipeline event loop, interleaving incoming `ToPipeline` +/// events with periodic flushes of accumulated telemetry. +/// +/// Exits cleanly once `rx` closes (after a final telemetry flush) or +/// immediately if the WebSocket broker shuts down. async fn run_loop( config: Config, mut rx: mpsc::Receiver, @@ -82,15 +87,19 @@ async fn run_loop( 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); + // If the runtime stalls, skip missed ticks instead of firing a burst of catch-up flushes. tick.set_missed_tick_behavior(MissedTickBehavior::Skip); let mut accumulator = DataAccumulator::default(); loop { - // Poll the 100 ms flush tick first so sustained high-rate UDP traffic - // can never starve telemetry publication. + // `biased;` polls branches in top-to-bottom order instead of randomly. + // Checking the flush tick first guarantees sustained high-rate UDP traffic + // cannot starve the 100 ms telemetry publication. tokio::select! { biased; _ = tick.tick() => { @@ -106,6 +115,8 @@ async fn run_loop( } } None => { + // Upstream (`event`) closed: perform a best-effort flush of any + // buffered telemetry before exiting. let _ = flush_data(&broker, &index, &mut accumulator).await; return; } @@ -142,6 +153,10 @@ async fn handle_item( } } +/// Maps a wire-level [`Notification`] (connection state change or decoded +/// packet) to its corresponding WebSocket topic or telemetry accumulator. +/// +/// Returns `false` if publishing fails because the broker closed. async fn handle_notification( notification: &Notification, broker: &BrokerClient, @@ -184,6 +199,10 @@ async fn handle_notification( } } +/// 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, @@ -197,6 +216,8 @@ async fn flush_data( true } +/// 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, diff --git a/backend/crates/station/src/pipeline/accumulator.rs b/backend/crates/station/src/pipeline/accumulator.rs index e6d2a0a72..1e694f60d 100644 --- a/backend/crates/station/src/pipeline/accumulator.rs +++ b/backend/crates/station/src/pipeline/accumulator.rs @@ -38,6 +38,9 @@ enum MeasurementAccumulator { } 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 { @@ -50,10 +53,13 @@ impl MeasurementAccumulator { } } + /// 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 { + Self::Numeric { // If Numeric, update last, add to sum and 1 sample to calculate rolling average last, sum, samples, @@ -64,10 +70,11 @@ impl MeasurementAccumulator { *sum += *v; *samples += 1; } - (Self::Boolean(last), Value::Bool(b)) => { + (Self::Boolean(last), Value::Bool(b)) => //If Bool just change last variable + { *last = *b; } - (Self::Enum(last), Value::Enum(s)) => { + (Self::Enum(last), Value::Enum(s)) => { //If Enum just change value if different if last != s { last.clone_from(s); } @@ -78,6 +85,9 @@ impl MeasurementAccumulator { } } + /// Finalizes the window accumulator into the serialized + /// [`MeasurementUpdate`] payload, computes rolling average + /// for numeric measurements. fn into_update(self) -> MeasurementUpdate { match self { Self::Numeric { @@ -95,6 +105,9 @@ impl MeasurementAccumulator { } impl DataAccumulator { + + /// Records one incoming [`DataPacket`] into its per-ID window, updating + /// cumulative packet count, inter-arrival timing, and per-measurement stats. pub(super) fn record(&mut self, packet: &DataPacket, at: SystemTime, index: &Index) { let Some(def) = index.packet(packet.id) else { warn!(id = packet.id.0, "unknown data packet id in index"); @@ -117,6 +130,9 @@ impl DataAccumulator { ); } + // Lazily initialize the packet's window on first arrival. Using a map + // over `0..defs.len()` avoids requiring `Clone` on `MeasurementAccumulator` + // (which `vec![None; defs.len()]` would need). let window = self.packets.entry(packet.id).or_insert_with(|| PacketWindow { count: 0, last_at: None, @@ -127,7 +143,11 @@ impl DataAccumulator { 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 + // (`duration_since` returns `Err` on backwards clock jumps). if let Some(prev) = window.last_at && let Ok(delta) = at.duration_since(prev) { @@ -136,6 +156,8 @@ impl DataAccumulator { } 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), @@ -146,6 +168,9 @@ impl DataAccumulator { 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(); @@ -155,6 +180,8 @@ impl DataAccumulator { } 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); @@ -170,6 +197,9 @@ impl DataAccumulator { }; let mut measurement_updates = HashMap::with_capacity(defs.len()); + + // `slot.take()` moves the accumulator out and resets the slot to + // `None` in one step, preparing it cleanly for the next 100 ms window. for (measurement_def, slot) in defs.iter().zip(window.measurements.iter_mut()) { if let Some(acc) = slot.take() { measurement_updates.insert(measurement_def.alias.clone(), acc.into_update()); diff --git a/backend/crates/station/src/pipeline/message.rs b/backend/crates/station/src/pipeline/message.rs index a5a408ccd..aa1e937b2 100644 --- a/backend/crates/station/src/pipeline/message.rs +++ b/backend/crates/station/src/pipeline/message.rs @@ -7,13 +7,20 @@ use software_core::model::{AdjId, BoardId, MessagePacket, OrderPacket, PacketTyp use software_core::protocol::Index; use tracing::warn; +/// Looks up a board's human-readable name from [`PodData`], falling back to +/// `"board-"` if the ID is absent. pub(super) fn board_name(pod_data: &PodData, board: BoardId) -> String { + + // `map_or_else` evaluates the fallback closure lazily so `"board-"` is + // only allocated when the lookup misses. pod_data .boards .get(&board) .map_or_else(|| format!("board-{}", board.0), |b| b.name.clone()) } +/// Converts a board's free-text [`MessagePacket`] into a frontend +/// [`MessageUpdate`], resolving severity from the ADJ [`Index`]. pub(super) fn from_board_message( board: BoardId, at: SystemTime, @@ -53,6 +60,8 @@ pub(super) fn from_board_message( } } +/// Converts a backend [`Problem`] into a [`MessageUpdate`], returning `None` +/// for [`ProblemKind::Silent`] problems that should not be shown on the front. pub(super) fn from_problem(problem: Problem, pod_data: &PodData) -> Option { let kind = match problem.kind { ProblemKind::Shown => MessageKind::Warning, @@ -73,6 +82,8 @@ pub(super) fn from_problem(problem: Problem, pod_data: &PodData) -> Option, @@ -90,6 +101,8 @@ pub(super) fn from_order_sent( } } +/// Builds a warning [`MessageUpdate`] explaining why an order failed to send. +/// Resolves the target board from the ADJ [`Index`], or `"all"` for fault ID 0. pub(super) fn from_order_failed( at: SystemTime, order: OrderPacket, @@ -97,6 +110,7 @@ pub(super) fn from_order_failed( pod_data: &PodData, index: &Index, ) -> MessageUpdate { + // Order ID 0 is the reserved broadcast fault order targeting every board. let board_label = if order.id == AdjId(0) { "all".to_string() } else if let Some(def) = index.packet(order.id) { diff --git a/backend/crates/station/src/pipeline/timestamp.rs b/backend/crates/station/src/pipeline/timestamp.rs index de8dab49c..e4bd2f42a 100644 --- a/backend/crates/station/src/pipeline/timestamp.rs +++ b/backend/crates/station/src/pipeline/timestamp.rs @@ -5,15 +5,19 @@ 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); + // Backend-originated messages use millisecond subsecond ticks (0–999) as the RTC counter. let counter = u16::try_from(dur.subsec_millis()).unwrap_or(0); MessageTimestamp { From 192cd8dbf23f0da756221ed1eac570c640b9c142 Mon Sep 17 00:00:00 2001 From: GaziH Date: Thu, 3 Dec 2026 17:32:58 +0100 Subject: [PATCH 06/17] Feat(backend, pipeline): Added management of frontend connection. More Comments. --- backend/crates/station/src/pipeline.rs | 109 +++++++++++--- .../station/src/pipeline/accumulator.rs | 29 ++-- .../crates/station/src/pipeline/frontend.rs | 103 +++++++++++++ .../crates/station/src/pipeline/message.rs | 1 - backend/crates/station/src/pipeline/tests.rs | 140 +++++++++++++++++- .../crates/station/src/pipeline/timestamp.rs | 18 ++- 6 files changed, 352 insertions(+), 48 deletions(-) create mode 100644 backend/crates/station/src/pipeline/frontend.rs diff --git a/backend/crates/station/src/pipeline.rs b/backend/crates/station/src/pipeline.rs index c94b2b805..14787ec46 100644 --- a/backend/crates/station/src/pipeline.rs +++ b/backend/crates/station/src/pipeline.rs @@ -1,5 +1,6 @@ -//! Transforms [`crate::event::ToPipeline`] items into frontend WebSocket payloads -//! and publishes them through [`crate::websocket::broker::BrokerClient`]. +//! Transforms [`crate::event::ToPipeline`] items into frontend WebSocket payloads, +//! publishes them through [`crate::websocket::broker::BrokerClient`], and monitors +//! the `websocket ↔ front` connection state. //! //! # Contract //! @@ -9,12 +10,14 @@ //! 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. Idle packets are not republished. +//! - **Frontend connection watchdog.** Tracks active frontend sessions reported +//! by `websocket`. Losing the last frontend starts a reconnect grace period +//! (default 3 s); a heartbeat timeout on the last client or expiration of +//! that grace period sends a [`ProblemKind::Fatal`] to `event`. //! - **Wait, don't drop.** Reads continuously from `channels.pipeline` and //! awaits broker capacity instead of dropping decoded events. //! - **Clean shutdown.** When `event` closes the input channel (`None`), any //! pending telemetry is flushed to the broker before the task exits. -//! - **No error policy.** `event` already decides what is silent, shown, or -//! fatal; `pipeline` only formats and publishes. //! //! # Topics not handled here //! @@ -25,25 +28,29 @@ //! `software_core::model::Packet` yet. mod accumulator; +mod frontend; mod message; mod timestamp; #[cfg(test)] mod tests; +pub use frontend::FrontendEvent; + use std::sync::Arc; use std::time::Duration; use accumulator::DataAccumulator; -use crate::event::ToPipeline; +use crate::event::{Problem, ProblemKind, ToPipeline}; use crate::payload::{Connection, ProtectionUpdate}; use crate::websocket::broker::BrokerClient; +use frontend::FrontendWatchdog; use software_core::model::{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 tokio::time::{Instant, MissedTickBehavior, interval_at, sleep_until}; use tracing::{error, warn}; /// Configuration for the pipeline task. @@ -51,38 +58,53 @@ use tracing::{error, warn}; pub struct Config { /// How often accumulated `Data` telemetry is flushed to the broker. pub data_flush_interval: Duration, + /// Grace period allowed for a frontend client to reconnect after the last + /// active frontend socket closes before reporting a fatal problem to `event`. + pub frontend_disconnect_timeout: Duration, } impl Default for Config { fn default() -> Self { Self { data_flush_interval: Duration::from_millis(100), + frontend_disconnect_timeout: Duration::from_secs(3), } } } -/// Spawns the pipeline task consuming `rx` and publishing to `broker`. +/// Spawns the pipeline task consuming `rx` (`event`) and `frontend_rx` +/// (`websocket`), publishing payloads to `broker`, and reporting frontend +/// disconnects on `problems`. /// /// The task exits cleanly once `rx` closes and pending telemetry is flushed, /// or immediately if `broker` has already shut down. pub fn spawn( config: Config, rx: mpsc::Receiver, + frontend_rx: mpsc::Receiver, + problems: mpsc::Sender, broker: BrokerClient, pod_data: Arc, index: Arc, ) -> JoinHandle<()> { - tokio::spawn(run_loop(config, rx, broker, pod_data, index)) + tokio::spawn(run_loop( + config, + rx, + frontend_rx, + problems, + broker, + pod_data, + index, + )) } -/// Runs the main pipeline event loop, interleaving incoming `ToPipeline` -/// events with periodic flushes of accumulated telemetry. -/// -/// Exits cleanly once `rx` closes (after a final telemetry flush) or -/// immediately if the WebSocket broker shuts down. +/// Runs the main pipeline event loop, interleaving frontend connection checks, +/// periodic 100 ms telemetry flushes, and incoming [`ToPipeline`] events. async fn run_loop( config: Config, mut rx: mpsc::Receiver, + mut frontend_rx: mpsc::Receiver, + problems: mpsc::Sender, broker: BrokerClient, pod_data: Arc, index: Arc, @@ -91,22 +113,53 @@ async fn run_loop( 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); - // If the runtime stalls, skip missed ticks instead of firing a burst of catch-up flushes. + // 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(); + let mut watchdog = FrontendWatchdog::new(config.frontend_disconnect_timeout); + let mut frontend_open = true; loop { + let frontend_deadline = watchdog.deadline(); + // `biased;` polls branches in top-to-bottom order instead of randomly. - // Checking the flush tick first guarantees sustained high-rate UDP traffic - // cannot starve the 100 ms telemetry publication. + // Checking frontend liveness and the 100 ms flush tick first prevents + // sustained high-rate UDP traffic from starving disconnects or flushes. tokio::select! { biased; + // 1. Frontend reconnect grace timer expired (only polled while a deadline is active). + _ = async { + if let Some(deadline) = frontend_deadline { + sleep_until(deadline).await; + } + }, if frontend_deadline.is_some() => { + if let Some(reason) = watchdog.on_timeout() { + report_frontend_fatal(&problems, reason).await; + } + } + // 2. Frontend session lifecycle events forwarded from `websocket`. + fe = frontend_rx.recv(), if frontend_open => { + match fe { + Some(event) => { + if let Some(reason) = watchdog.on_event(event, Instant::now()) { + report_frontend_fatal(&problems, reason).await; + } + } + None => { + // Stop polling once `websocket` drops its sender so a closed + // channel does not win every `biased;` round. + frontend_open = false; + } + } + } + // 3. Periodic 100 ms telemetry flush. _ = tick.tick() => { if !flush_data(&broker, &index, &mut accumulator).await { return; } } + // 4. Incoming routed items from `event`. item = rx.recv() => { match item { Some(msg) => { @@ -138,6 +191,7 @@ async fn handle_item( ToPipeline::Received(notification) => { handle_notification(¬ification, broker, pod_data, index, accumulator).await } + // TODO(websocket-merge): If `websocket` / `payload` splits backend problem onto a dedicated `problem/update` topic. ToPipeline::Problem(problem) => match message::from_problem(problem, pod_data) { Some(update) => publish_or_log(broker.publish_message(update).await), None => true, @@ -153,8 +207,8 @@ async fn handle_item( } } -/// Maps a wire-level [`Notification`] (connection state change or decoded -/// packet) to its corresponding WebSocket topic or telemetry accumulator. +/// Maps a wire-level [`Notification`] (connection transition or decoded packet) +/// to its WebSocket topic or the 100 ms telemetry accumulator. /// /// Returns `false` if publishing fails because the broker closed. async fn handle_notification( @@ -188,8 +242,13 @@ async fn handle_notification( 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); + 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)) => { @@ -199,6 +258,16 @@ async fn handle_notification( } } +/// Reports a fatal frontend-disconnect [`Problem`] to `event` so it propagates +/// the pod fault and performs an ordered shutdown. +async fn report_frontend_fatal(problems: &mpsc::Sender, reason: &'static str) { + error!(reason, "frontend connection lost, reporting fatal problem to event"); + let problem = Problem::now(ProblemKind::Fatal, None, reason); + if problems.send(problem).await.is_err() { + warn!("event problems channel closed before frontend disconnect could be reported"); + } +} + /// Drains all telemetry packets updated during the current window and /// publishes each [`crate::payload::DataPacketUpdate`] to the broker. /// diff --git a/backend/crates/station/src/pipeline/accumulator.rs b/backend/crates/station/src/pipeline/accumulator.rs index 1e694f60d..7aacf82e7 100644 --- a/backend/crates/station/src/pipeline/accumulator.rs +++ b/backend/crates/station/src/pipeline/accumulator.rs @@ -38,7 +38,6 @@ enum MeasurementAccumulator { } impl MeasurementAccumulator { - /// Initializes an accumulator from the first decoded [`Value`] observed in /// the current flush window. fn from_value(value: &Value) -> Self { @@ -59,7 +58,7 @@ impl MeasurementAccumulator { fn update(&mut self, value: &Value) { match (self, value) { ( - Self::Numeric { // If Numeric, update last, add to sum and 1 sample to calculate rolling average + Self::Numeric { last, sum, samples, @@ -70,24 +69,27 @@ impl MeasurementAccumulator { *sum += *v; *samples += 1; } - (Self::Boolean(last), Value::Bool(b)) => //If Bool just change last variable - { + (Self::Boolean(last), Value::Bool(b)) => { *last = *b; } - (Self::Enum(last), Value::Enum(s)) => { //If Enum just change value if different + (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, computes rolling average - /// for numeric measurements. + /// [`MeasurementUpdate`] payload, computing the arithmetic mean for + /// numeric measurements. fn into_update(self) -> MeasurementUpdate { match self { Self::Numeric { @@ -105,7 +107,6 @@ impl MeasurementAccumulator { } impl DataAccumulator { - /// Records one incoming [`DataPacket`] into its per-ID window, updating /// cumulative packet count, inter-arrival timing, and per-measurement stats. pub(super) fn record(&mut self, packet: &DataPacket, at: SystemTime, index: &Index) { @@ -130,9 +131,8 @@ impl DataAccumulator { ); } - // Lazily initialize the packet's window on first arrival. Using a map - // over `0..defs.len()` avoids requiring `Clone` on `MeasurementAccumulator` - // (which `vec![None; defs.len()]` would need). + // 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, @@ -143,11 +143,9 @@ impl DataAccumulator { 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 - // (`duration_since` returns `Err` on backwards clock jumps). + // timestamp exists and the system clock did not step backwards. if let Some(prev) = window.last_at && let Ok(delta) = at.duration_since(prev) { @@ -196,10 +194,9 @@ impl DataAccumulator { continue; }; - let mut measurement_updates = HashMap::with_capacity(defs.len()); - // `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::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.alias.clone(), acc.into_update()); diff --git a/backend/crates/station/src/pipeline/frontend.rs b/backend/crates/station/src/pipeline/frontend.rs new file mode 100644 index 000000000..5fd0709d1 --- /dev/null +++ b/backend/crates/station/src/pipeline/frontend.rs @@ -0,0 +1,103 @@ +//! Tracks the `websocket ↔ front` connection state inside `pipeline`. +//! +//! `websocket` forwards session lifecycle transitions via [`FrontendEvent`], +//! and [`FrontendWatchdog`] decides when the loss of the last frontend client +//! becomes a fatal backend problem. + +use std::time::Duration; + +use tokio::time::Instant; + +/// Frontend session lifecycle events sent by `websocket` to `pipeline`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FrontendEvent { + /// A frontend WebSocket client connected. + Connected, + /// A frontend WebSocket client disconnected normally or dropped its socket. + /// If it was the last active client, the reconnect grace window starts. + Disconnected, + /// A frontend WebSocket client timed out waiting for a heartbeat. + /// If it was the last active client, the heartbeat timeout already + /// satisfies the reconnect period, so it is fatal immediately. + HeartbeatTimeout, +} + +/// Tracks active frontend connections and the post-disconnect reconnect deadline. +#[derive(Debug)] +pub(super) struct FrontendWatchdog { + grace_timeout: Duration, + active_clients: usize, + /// True once at least one frontend has connected (startup with 0 clients is not fatal). + had_client: bool, + /// Active reconnect deadline while waiting for a client to return after dropping to 0. + reconnect_deadline: Option, + /// Ensures a fatal disconnect problem is reported at most once. + reported_fatal: bool, +} + +impl FrontendWatchdog { + /// Creates a watchdog that allows `grace_timeout` for reconnection after + /// the last frontend disconnects normally. + pub(super) fn new(grace_timeout: Duration) -> Self { + Self { + grace_timeout, + active_clients: 0, + had_client: false, + reconnect_deadline: None, + reported_fatal: false, + } + } + + /// Returns the currently armed reconnect deadline, if any. + pub(super) fn deadline(&self) -> Option { + self.reconnect_deadline + } + + /// Processes a [`FrontendEvent`] at `now`. + /// + /// Returns `Some(reason)` when the event triggers an immediate fatal + /// disconnect (e.g. heartbeat timeout on the last client). + pub(super) fn on_event(&mut self, event: FrontendEvent, now: Instant) -> Option<&'static str> { + match event { + FrontendEvent::Connected => { + self.active_clients = self.active_clients.saturating_add(1); + self.had_client = true; + // A returning client cancels any pending reconnect deadline. + self.reconnect_deadline = None; + None + } + FrontendEvent::Disconnected => { + self.active_clients = self.active_clients.saturating_sub(1); + if self.had_client && self.active_clients == 0 && !self.reported_fatal { + if self.grace_timeout.is_zero() { + self.reported_fatal = true; + return Some("all frontend connections lost"); + } + self.reconnect_deadline = Some(now + self.grace_timeout); + } + None + } + FrontendEvent::HeartbeatTimeout => { + self.active_clients = self.active_clients.saturating_sub(1); + if self.had_client && self.active_clients == 0 && !self.reported_fatal { + // The heartbeat timeout already elapsed the disconnect window. + self.reconnect_deadline = None; + self.reported_fatal = true; + return Some("last frontend connection timed out on heartbeat"); + } + None + } + } + } + + /// Fires when [`Self::deadline`] elapses without any client reconnecting. + pub(super) fn on_timeout(&mut self) -> Option<&'static str> { + self.reconnect_deadline = None; + if self.had_client && self.active_clients == 0 && !self.reported_fatal { + self.reported_fatal = true; + Some("all frontend connections lost (reconnect timeout expired)") + } else { + None + } + } +} \ No newline at end of file diff --git a/backend/crates/station/src/pipeline/message.rs b/backend/crates/station/src/pipeline/message.rs index aa1e937b2..5dd77775b 100644 --- a/backend/crates/station/src/pipeline/message.rs +++ b/backend/crates/station/src/pipeline/message.rs @@ -10,7 +10,6 @@ use tracing::warn; /// Looks up a board's human-readable name from [`PodData`], falling back to /// `"board-"` if the ID is absent. pub(super) fn board_name(pod_data: &PodData, board: BoardId) -> String { - // `map_or_else` evaluates the fallback closure lazily so `"board-"` is // only allocated when the lookup misses. pod_data diff --git a/backend/crates/station/src/pipeline/tests.rs b/backend/crates/station/src/pipeline/tests.rs index 30c3f074e..3930a3610 100644 --- a/backend/crates/station/src/pipeline/tests.rs +++ b/backend/crates/station/src/pipeline/tests.rs @@ -13,13 +13,16 @@ use software_core::protocol::Index; use tokio::sync::mpsc; use tokio::time::{advance, timeout}; -use super::{Config, spawn, timestamp}; +use super::{Config, FrontendEvent, spawn, timestamp}; use crate::event::{Problem, ProblemKind, ToPipeline}; use crate::payload::{ MeasurementUpdate, MessageKind, MessagePayload, MessageTimestamp, ProtectionUpdate, }; use crate::websocket::broker::Broker; +/// Builds a minimal ADJ fixture with one board (`PCU`, ID 5) containing a +/// 3-measurement `Data` packet (ID 551), an `Order` packet (ID 1001), and a +/// `Warning` message definition (ID 10). fn sample_fixture() -> (Arc, Arc) { let voltage_a = Measurement { id: AdjId(3001), @@ -88,6 +91,8 @@ fn sample_fixture() -> (Arc, Arc) { (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_messages_problems_and_orders_immediately() -> Result<(), Box> { @@ -99,7 +104,17 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate let broker_task = tokio::spawn(broker.run()); let (tx, rx) = mpsc::channel(32); - let pipe_task = spawn(Config::default(), rx, client, pod_data, index); + let (_fe_tx, fe_rx) = mpsc::channel(16); + let (problems_tx, _problems_rx) = mpsc::channel(16); + let pipe_task = spawn( + Config::default(), + rx, + fe_rx, + problems_tx, + client, + pod_data, + index, + ); // 1. Connection update tx.send(ToPipeline::Received(Arc::new(Notification { @@ -112,6 +127,7 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate assert!(conn_sub.borrow_and_update()["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 { @@ -204,6 +220,11 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate 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> { @@ -213,7 +234,17 @@ async fn batches_data_every_100ms_with_window_average_last_and_cycle_time() let broker_task = tokio::spawn(broker.run()); let (tx, rx) = mpsc::channel(32); - let pipe_task = spawn(Config::default(), rx, client, pod_data, index); + let (_fe_tx, fe_rx) = mpsc::channel(16); + let (problems_tx, _problems_rx) = mpsc::channel(16); + let pipe_task = spawn( + Config::default(), + rx, + fe_rx, + problems_tx, + client, + pod_data, + index, + ); tokio::task::yield_now().await; let t0 = UNIX_EPOCH + Duration::from_secs(1_700_000_000); @@ -240,7 +271,9 @@ async fn batches_data_every_100ms_with_window_average_last_and_cycle_time() } tokio::task::yield_now().await; - // First 100 ms tick flushes pipeline -> broker; next 100 ms tick flushes broker -> watch. + // Advance once to trigger pipeline's 100 ms flush into the broker, yield + // twice so both tasks process the queued update, then advance again to + // trigger the broker's own 100 ms batch flush to `watch` subscribers. advance(Duration::from_millis(100)).await; tokio::task::yield_now().await; tokio::task::yield_now().await; @@ -300,6 +333,105 @@ async fn batches_data_every_100ms_with_window_average_last_and_cycle_time() Ok(()) } +/// Verifies that reconnecting within the 3 s grace window cancels the fatal +/// disconnect, while staying disconnected past 3 s reports `ProblemKind::Fatal`. +#[tokio::test(start_paused = true)] +async fn frontend_disconnect_allows_reconnect_and_reports_fatal_after_grace_period() + -> Result<(), Box> { + let (pod_data, index) = sample_fixture(); + let (broker, client) = Broker::new(); + let broker_task = tokio::spawn(broker.run()); + + let (tx, rx) = mpsc::channel(16); + let (fe_tx, fe_rx) = mpsc::channel(16); + let (problems_tx, mut problems_rx) = mpsc::channel(16); + let pipe_task = spawn( + Config::default(), + rx, + fe_rx, + problems_tx, + client, + pod_data, + index, + ); + tokio::task::yield_now().await; + + // Client connects, disconnects, then reconnects after 2 s (within 3 s grace). + fe_tx.send(FrontendEvent::Connected).await?; + fe_tx.send(FrontendEvent::Disconnected).await?; + advance(Duration::from_secs(2)).await; + fe_tx.send(FrontendEvent::Connected).await?; + advance(Duration::from_secs(5)).await; + assert!( + problems_rx.try_recv().is_err(), + "reconnecting within the grace period must cancel the fatal problem" + ); + + // Client disconnects again and does not return within 3 s. + fe_tx.send(FrontendEvent::Disconnected).await?; + tokio::task::yield_now().await; + advance(Duration::from_millis(2_999)).await; + assert!(problems_rx.try_recv().is_err()); + + advance(Duration::from_millis(1)).await; + let problem = timeout(Duration::from_millis(10), problems_rx.recv()) + .await? + .ok_or("expected fatal problem on reconnect timeout")?; + assert_eq!(problem.kind, ProblemKind::Fatal); + assert_eq!(problem.board, None); + + drop(tx); + timeout(Duration::from_secs(1), pipe_task).await??; + timeout(Duration::from_secs(1), broker_task).await??; + Ok(()) +} + +/// Verifies that a heartbeat timeout on the last active frontend client reports +/// `ProblemKind::Fatal` immediately without waiting for another 3 s grace period. +#[tokio::test(start_paused = true)] +async fn frontend_heartbeat_timeout_on_last_client_is_fatal_immediately() + -> Result<(), Box> { + let (pod_data, index) = sample_fixture(); + let (broker, client) = Broker::new(); + let broker_task = tokio::spawn(broker.run()); + + let (tx, rx) = mpsc::channel(16); + let (fe_tx, fe_rx) = mpsc::channel(16); + let (problems_tx, mut problems_rx) = mpsc::channel(16); + let pipe_task = spawn( + Config::default(), + rx, + fe_rx, + problems_tx, + client, + pod_data, + index, + ); + tokio::task::yield_now().await; + + // Two clients connect; one times out -> still alive because one remains. + fe_tx.send(FrontendEvent::Connected).await?; + fe_tx.send(FrontendEvent::Connected).await?; + fe_tx.send(FrontendEvent::HeartbeatTimeout).await?; + tokio::task::yield_now().await; + assert!(problems_rx.try_recv().is_err()); + + // Last client times out -> immediate fatal without advancing virtual time. + fe_tx.send(FrontendEvent::HeartbeatTimeout).await?; + let problem = timeout(Duration::from_millis(10), problems_rx.recv()) + .await? + .ok_or("expected immediate fatal problem on last heartbeat timeout")?; + assert_eq!(problem.kind, ProblemKind::Fatal); + assert_eq!(problem.board, None); + + drop(tx); + timeout(Duration::from_secs(1), pipe_task).await??; + timeout(Duration::from_secs(1), broker_task).await??; + Ok(()) +} + +/// Verifies `timestamp::from_system_time` on boundary dates (Unix epoch and +/// a Gregorian leap day with millisecond counter). #[test] fn utc_calendar_conversion_handles_epoch_and_leap_day() { let epoch = timestamp::from_system_time(UNIX_EPOCH); diff --git a/backend/crates/station/src/pipeline/timestamp.rs b/backend/crates/station/src/pipeline/timestamp.rs index e4bd2f42a..cc82da4c8 100644 --- a/backend/crates/station/src/pipeline/timestamp.rs +++ b/backend/crates/station/src/pipeline/timestamp.rs @@ -8,7 +8,7 @@ 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). + // 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; @@ -49,15 +49,19 @@ pub(super) fn from_short(received_at: SystemTime, short: ShortTimestamp) -> Mess /// 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); - let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; + 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); - let mp = (5 * doy + 2) / 153; - let d = doy - (153 * mp + 2) / 5 + 1; - let m = if mp < 10 { mp + 3 } else { mp - 9 }; + 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); ( From b0e8847ecc9319d7cc43419e022f29ad5112d296 Mon Sep 17 00:00:00 2001 From: GaziH Date: Thu, 3 Dec 2026 22:14:32 +0100 Subject: [PATCH 07/17] Feat(backend, pipeline): Added /heartbeat management. --- backend/crates/station/src/pipeline.rs | 11 +- .../crates/station/src/pipeline/frontend.rs | 110 ++++++++++-------- backend/crates/station/src/pipeline/tests.rs | 51 +++++--- 3 files changed, 107 insertions(+), 65 deletions(-) diff --git a/backend/crates/station/src/pipeline.rs b/backend/crates/station/src/pipeline.rs index 14787ec46..e9e52961e 100644 --- a/backend/crates/station/src/pipeline.rs +++ b/backend/crates/station/src/pipeline.rs @@ -58,6 +58,9 @@ use tracing::{error, warn}; pub struct Config { /// How often accumulated `Data` telemetry is flushed to the broker. pub data_flush_interval: Duration, + /// Maximum time allowed between `connection/heartbeat` keep-alives for a + /// frontend session before it is considered dead. + pub frontend_heartbeat_timeout: Duration, /// Grace period allowed for a frontend client to reconnect after the last /// active frontend socket closes before reporting a fatal problem to `event`. pub frontend_disconnect_timeout: Duration, @@ -67,6 +70,7 @@ impl Default for Config { fn default() -> Self { Self { data_flush_interval: Duration::from_millis(100), + frontend_heartbeat_timeout: Duration::from_secs(3), frontend_disconnect_timeout: Duration::from_secs(3), } } @@ -117,7 +121,10 @@ async fn run_loop( tick.set_missed_tick_behavior(MissedTickBehavior::Skip); let mut accumulator = DataAccumulator::default(); - let mut watchdog = FrontendWatchdog::new(config.frontend_disconnect_timeout); + let mut watchdog = FrontendWatchdog::new( + config.frontend_heartbeat_timeout, + config.frontend_disconnect_timeout, + ); let mut frontend_open = true; loop { @@ -134,7 +141,7 @@ async fn run_loop( sleep_until(deadline).await; } }, if frontend_deadline.is_some() => { - if let Some(reason) = watchdog.on_timeout() { + if let Some(reason) = watchdog.on_timeout(Instant::now()) { report_frontend_fatal(&problems, reason).await; } } diff --git a/backend/crates/station/src/pipeline/frontend.rs b/backend/crates/station/src/pipeline/frontend.rs index 5fd0709d1..c690b4f98 100644 --- a/backend/crates/station/src/pipeline/frontend.rs +++ b/backend/crates/station/src/pipeline/frontend.rs @@ -1,74 +1,84 @@ -//! Tracks the `websocket ↔ front` connection state inside `pipeline`. +//! Tracks `websocket ↔ front` session liveness and keep-alives (`connection/heartbeat`). //! -//! `websocket` forwards session lifecycle transitions via [`FrontendEvent`], -//! and [`FrontendWatchdog`] decides when the loss of the last frontend client -//! becomes a fatal backend problem. +//! `websocket` forwards session lifecycle transitions and keep-alive signals via +//! [`FrontendEvent`], and [`FrontendWatchdog`] owns both the per-session +//! heartbeat timer and the post-disconnect reconnect grace timer. +use std::collections::HashMap; use std::time::Duration; use tokio::time::Instant; -/// Frontend session lifecycle events sent by `websocket` to `pipeline`. +/// Frontend session events forwarded from `websocket` to `pipeline`. +/// +/// Each active WebSocket connection is identified by a unique session ID (`u64`) +/// so a silently dead tab expires on its own without blocking disconnect detection. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum FrontendEvent { /// A frontend WebSocket client connected. - Connected, - /// A frontend WebSocket client disconnected normally or dropped its socket. - /// If it was the last active client, the reconnect grace window starts. - Disconnected, - /// A frontend WebSocket client timed out waiting for a heartbeat. - /// If it was the last active client, the heartbeat timeout already - /// satisfies the reconnect period, so it is fatal immediately. - HeartbeatTimeout, + Connected(u64), + /// A keep-alive (`connection/heartbeat`) arrived from this frontend session. + Heartbeat(u64), + /// A frontend WebSocket client disconnected. If it was the last live + /// session, the reconnect grace window starts. + Disconnected(u64), } -/// Tracks active frontend connections and the post-disconnect reconnect deadline. +/// Tracks active frontend sessions, their keep-alive deadlines, and the +/// post-disconnect reconnect deadline. #[derive(Debug)] pub(super) struct FrontendWatchdog { + heartbeat_timeout: Duration, grace_timeout: Duration, - active_clients: usize, + /// Active sessions mapped to the instant their keep-alive expires. + sessions: HashMap, /// True once at least one frontend has connected (startup with 0 clients is not fatal). had_client: bool, - /// Active reconnect deadline while waiting for a client to return after dropping to 0. + /// Armed while waiting for a client to reconnect after all sessions closed cleanly. reconnect_deadline: Option, /// Ensures a fatal disconnect problem is reported at most once. reported_fatal: bool, } impl FrontendWatchdog { - /// Creates a watchdog that allows `grace_timeout` for reconnection after - /// the last frontend disconnects normally. - pub(super) fn new(grace_timeout: Duration) -> Self { + /// Creates a watchdog with separate keep-alive and post-disconnect grace timeouts. + pub(super) fn new(heartbeat_timeout: Duration, grace_timeout: Duration) -> Self { Self { + heartbeat_timeout, grace_timeout, - active_clients: 0, + sessions: HashMap::new(), had_client: false, reconnect_deadline: None, reported_fatal: false, } } - /// Returns the currently armed reconnect deadline, if any. + /// Returns the next timer deadline that `run_loop` should wake up for: + /// either the reconnect grace deadline or the earliest session heartbeat expiry. pub(super) fn deadline(&self) -> Option { + if self.reported_fatal { + return None; + } self.reconnect_deadline + .or_else(|| self.sessions.values().copied().min()) } /// Processes a [`FrontendEvent`] at `now`. /// - /// Returns `Some(reason)` when the event triggers an immediate fatal - /// disconnect (e.g. heartbeat timeout on the last client). + /// Returns `Some(reason)` only when a zero-duration grace timeout makes a + /// disconnect fatal immediately. pub(super) fn on_event(&mut self, event: FrontendEvent, now: Instant) -> Option<&'static str> { match event { - FrontendEvent::Connected => { - self.active_clients = self.active_clients.saturating_add(1); + FrontendEvent::Connected(id) | FrontendEvent::Heartbeat(id) => { + self.sessions.insert(id, now + self.heartbeat_timeout); self.had_client = true; - // A returning client cancels any pending reconnect deadline. + // A live or returning client cancels any pending reconnect deadline. self.reconnect_deadline = None; None } - FrontendEvent::Disconnected => { - self.active_clients = self.active_clients.saturating_sub(1); - if self.had_client && self.active_clients == 0 && !self.reported_fatal { + FrontendEvent::Disconnected(id) => { + self.sessions.remove(&id); + if self.had_client && self.sessions.is_empty() && !self.reported_fatal { if self.grace_timeout.is_zero() { self.reported_fatal = true; return Some("all frontend connections lost"); @@ -77,27 +87,35 @@ impl FrontendWatchdog { } None } - FrontendEvent::HeartbeatTimeout => { - self.active_clients = self.active_clients.saturating_sub(1); - if self.had_client && self.active_clients == 0 && !self.reported_fatal { - // The heartbeat timeout already elapsed the disconnect window. - self.reconnect_deadline = None; - self.reported_fatal = true; - return Some("last frontend connection timed out on heartbeat"); - } - None - } } } - /// Fires when [`Self::deadline`] elapses without any client reconnecting. - pub(super) fn on_timeout(&mut self) -> Option<&'static str> { - self.reconnect_deadline = None; - if self.had_client && self.active_clients == 0 && !self.reported_fatal { + /// Processes an elapsed timer at `now`, expiring stale heartbeats and + /// checking the reconnect grace deadline. + pub(super) fn on_timeout(&mut self, now: Instant) -> Option<&'static str> { + if self.reported_fatal { + return None; + } + + if let Some(deadline) = self.reconnect_deadline + && now >= deadline + { + self.reconnect_deadline = None; + if self.had_client && self.sessions.is_empty() { + self.reported_fatal = true; + return Some("all frontend connections lost (reconnect timeout expired)"); + } + } + + let before = self.sessions.len(); + self.sessions.retain(|_, expires_at| *expires_at > now); + if before > 0 && self.sessions.is_empty() { + // The heartbeat timeout already elapsed the disconnect window, so + // losing the last live session to a missed keep-alive is fatal immediately. self.reported_fatal = true; - Some("all frontend connections lost (reconnect timeout expired)") - } else { - None + return Some("last frontend connection timed out on heartbeat"); } + + None } } \ No newline at end of file diff --git a/backend/crates/station/src/pipeline/tests.rs b/backend/crates/station/src/pipeline/tests.rs index 3930a3610..e0b3d778d 100644 --- a/backend/crates/station/src/pipeline/tests.rs +++ b/backend/crates/station/src/pipeline/tests.rs @@ -356,19 +356,23 @@ async fn frontend_disconnect_allows_reconnect_and_reports_fatal_after_grace_peri ); tokio::task::yield_now().await; - // Client connects, disconnects, then reconnects after 2 s (within 3 s grace). - fe_tx.send(FrontendEvent::Connected).await?; - fe_tx.send(FrontendEvent::Disconnected).await?; + // Session 1 connects, disconnects, then session 2 connects after 2 s (within 3 s grace). + fe_tx.send(FrontendEvent::Connected(1)).await?; + fe_tx.send(FrontendEvent::Disconnected(1)).await?; + tokio::task::yield_now().await; + advance(Duration::from_secs(2)).await; + fe_tx.send(FrontendEvent::Connected(2)).await?; + tokio::task::yield_now().await; + + // Advance 2 s (past session 1's old 3 s grace deadline, before session 2's heartbeat expiry). advance(Duration::from_secs(2)).await; - fe_tx.send(FrontendEvent::Connected).await?; - advance(Duration::from_secs(5)).await; assert!( problems_rx.try_recv().is_err(), "reconnecting within the grace period must cancel the fatal problem" ); - // Client disconnects again and does not return within 3 s. - fe_tx.send(FrontendEvent::Disconnected).await?; + // Session 2 disconnects and does not return within 3 s. + fe_tx.send(FrontendEvent::Disconnected(2)).await?; tokio::task::yield_now().await; advance(Duration::from_millis(2_999)).await; assert!(problems_rx.try_recv().is_err()); @@ -386,10 +390,11 @@ async fn frontend_disconnect_allows_reconnect_and_reports_fatal_after_grace_peri Ok(()) } -/// Verifies that a heartbeat timeout on the last active frontend client reports -/// `ProblemKind::Fatal` immediately without waiting for another 3 s grace period. +/// Verifies that `connection/heartbeat` keep-alives renew a session's 3 s +/// deadline, stale sessions expire independently, and losing the last live +/// session to a heartbeat timeout reports `ProblemKind::Fatal` immediately. #[tokio::test(start_paused = true)] -async fn frontend_heartbeat_timeout_on_last_client_is_fatal_immediately() +async fn frontend_heartbeat_renews_liveness_and_expires_last_session_as_fatal() -> Result<(), Box> { let (pod_data, index) = sample_fixture(); let (broker, client) = Broker::new(); @@ -409,18 +414,30 @@ async fn frontend_heartbeat_timeout_on_last_client_is_fatal_immediately() ); tokio::task::yield_now().await; - // Two clients connect; one times out -> still alive because one remains. - fe_tx.send(FrontendEvent::Connected).await?; - fe_tx.send(FrontendEvent::Connected).await?; - fe_tx.send(FrontendEvent::HeartbeatTimeout).await?; + // Two sessions connect at t = 0 (both expire at t = 3 s). + fe_tx.send(FrontendEvent::Connected(1)).await?; + fe_tx.send(FrontendEvent::Connected(2)).await?; + tokio::task::yield_now().await; + + // At t = 2 s, session 1 sends a keep-alive (now expires at t = 5 s); session 2 goes silent. + advance(Duration::from_secs(2)).await; + fe_tx.send(FrontendEvent::Heartbeat(1)).await?; + tokio::task::yield_now().await; + + // At t = 3 s, session 2 times out, but session 1 is still alive -> not fatal. + advance(Duration::from_secs(1)).await; tokio::task::yield_now().await; assert!(problems_rx.try_recv().is_err()); - // Last client times out -> immediate fatal without advancing virtual time. - fe_tx.send(FrontendEvent::HeartbeatTimeout).await?; + // At t = 4.999 s, session 1 is still within its keep-alive window. + advance(Duration::from_millis(1_999)).await; + assert!(problems_rx.try_recv().is_err()); + + // At t = 5.000 s, session 1 expires -> last live frontend lost, fatal immediately. + advance(Duration::from_millis(1)).await; let problem = timeout(Duration::from_millis(10), problems_rx.recv()) .await? - .ok_or("expected immediate fatal problem on last heartbeat timeout")?; + .ok_or("expected fatal problem when last frontend heartbeat expires")?; assert_eq!(problem.kind, ProblemKind::Fatal); assert_eq!(problem.board, None); From 0099c45ea1f8cc7cce1a42d2d112b7f24e12b102 Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Thu, 3 Dec 2026 23:01:34 +0100 Subject: [PATCH 08/17] Feat(backend, pipeline): Added board connection tracking --- backend/crates/station/src/pipeline.rs | 41 ++++++++++++++++++-------- 1 file changed, 29 insertions(+), 12 deletions(-) diff --git a/backend/crates/station/src/pipeline.rs b/backend/crates/station/src/pipeline.rs index e9e52961e..190faabc7 100644 --- a/backend/crates/station/src/pipeline.rs +++ b/backend/crates/station/src/pipeline.rs @@ -35,6 +35,7 @@ mod timestamp; #[cfg(test)] mod tests; +use std::collections::HashMap; pub use frontend::FrontendEvent; use std::sync::Arc; @@ -45,7 +46,7 @@ use crate::event::{Problem, ProblemKind, ToPipeline}; use crate::payload::{Connection, ProtectionUpdate}; use crate::websocket::broker::BrokerClient; use frontend::FrontendWatchdog; -use software_core::model::{Packet, PodData}; +use software_core::model::{BoardId, Packet, PodData}; use software_core::net::{Event, Notification}; use software_core::protocol::Index; use tokio::sync::mpsc; @@ -127,6 +128,21 @@ async fn run_loop( ); let mut frontend_open = true; + // 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. + for (&id, &is_connected) in &board_connections { + let update = Connection { + name: message::board_name(&pod_data, id), + is_connected, + }; + if !publish_or_log(broker.publish_connection(update).await) { + return; + } + } + loop { let frontend_deadline = watchdog.deadline(); @@ -170,7 +186,7 @@ async fn run_loop( item = rx.recv() => { match item { Some(msg) => { - if !handle_item(msg, &broker, &pod_data, &index, &mut accumulator).await { + if !handle_item(msg, &broker, &pod_data, &index, &mut accumulator, &mut board_connections).await { return; } } @@ -193,10 +209,11 @@ async fn handle_item( 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).await + handle_notification(¬ification, broker, pod_data, index, accumulator, board_connections).await } // TODO(websocket-merge): If `websocket` / `payload` splits backend problem onto a dedicated `problem/update` topic. ToPipeline::Problem(problem) => match message::from_problem(problem, pod_data) { @@ -217,6 +234,7 @@ async fn handle_item( /// Maps a wire-level [`Notification`] (connection transition or decoded packet) /// to its WebSocket topic or the 100 ms telemetry accumulator. /// +/// /// Returns `false` if publishing fails because the broker closed. async fn handle_notification( notification: &Notification, @@ -224,19 +242,18 @@ async fn handle_notification( pod_data: &PodData, index: &Index, accumulator: &mut DataAccumulator, + board_connections: &mut HashMap, ) -> bool { match ¬ification.event { - Event::Connected => { - let update = Connection { - name: message::board_name(pod_data, notification.board), - is_connected: true, - }; - publish_or_log(broker.publish_connection(update).await) - } - Event::Disconnected => { + Event::Connected | Event::Disconnected => { + let is_connected = matches!(notification.event, Event::Connected); + // Only publish when a board's connection state actually changes. + if board_connections.insert(notification.board, is_connected) == Some(is_connected) { + return true; + } let update = Connection { name: message::board_name(pod_data, notification.board), - is_connected: false, + is_connected, }; publish_or_log(broker.publish_connection(update).await) } From 4970360e90e6c0e2333a6354f3b5fbd329b36a6c Mon Sep 17 00:00:00 2001 From: GaziH Date: Fri, 4 Dec 2026 17:08:04 +0100 Subject: [PATCH 09/17] Feat(backend, pipeline): Fixed rust formatting with rustfmt --- backend/crates/station/src/lib.rs | 4 +- backend/crates/station/src/pipeline.rs | 21 +++++++--- .../station/src/pipeline/accumulator.rs | 38 ++++++++----------- .../crates/station/src/pipeline/frontend.rs | 2 +- .../crates/station/src/pipeline/message.rs | 2 +- backend/crates/station/src/pipeline/tests.rs | 31 ++++++++------- .../crates/station/src/pipeline/timestamp.rs | 2 +- backend/crates/station/src/vehicle.rs | 1 + backend/crates/station/src/websocket.rs | 2 +- 9 files changed, 55 insertions(+), 48 deletions(-) diff --git a/backend/crates/station/src/lib.rs b/backend/crates/station/src/lib.rs index 3c53fc30c..a8a0126eb 100644 --- a/backend/crates/station/src/lib.rs +++ b/backend/crates/station/src/lib.rs @@ -1,8 +1,8 @@ pub mod http; +pub mod payload; mod vehicle; pub mod websocket; -pub mod payload; pub mod pipeline; -pub mod event; \ No newline at end of file +pub mod event; diff --git a/backend/crates/station/src/pipeline.rs b/backend/crates/station/src/pipeline.rs index 190faabc7..ab7931c4c 100644 --- a/backend/crates/station/src/pipeline.rs +++ b/backend/crates/station/src/pipeline.rs @@ -35,16 +35,16 @@ mod timestamp; #[cfg(test)] mod tests; -use std::collections::HashMap; pub use frontend::FrontendEvent; +use std::collections::HashMap; use std::sync::Arc; use std::time::Duration; -use accumulator::DataAccumulator; use crate::event::{Problem, ProblemKind, ToPipeline}; use crate::payload::{Connection, ProtectionUpdate}; use crate::websocket::broker::BrokerClient; +use accumulator::DataAccumulator; use frontend::FrontendWatchdog; use software_core::model::{BoardId, Packet, PodData}; use software_core::net::{Event, Notification}; @@ -213,7 +213,15 @@ async fn handle_item( ) -> bool { match item { ToPipeline::Received(notification) => { - handle_notification(¬ification, broker, pod_data, index, accumulator, board_connections).await + handle_notification( + ¬ification, + broker, + pod_data, + index, + accumulator, + board_connections, + ) + .await } // TODO(websocket-merge): If `websocket` / `payload` splits backend problem onto a dedicated `problem/update` topic. ToPipeline::Problem(problem) => match message::from_problem(problem, pod_data) { @@ -285,7 +293,10 @@ async fn handle_notification( /// Reports a fatal frontend-disconnect [`Problem`] to `event` so it propagates /// the pod fault and performs an ordered shutdown. async fn report_frontend_fatal(problems: &mpsc::Sender, reason: &'static str) { - error!(reason, "frontend connection lost, reporting fatal problem to event"); + error!( + reason, + "frontend connection lost, reporting fatal problem to event" + ); let problem = Problem::now(ProblemKind::Fatal, None, reason); if problems.send(problem).await.is_err() { warn!("event problems channel closed before frontend disconnect could be reported"); @@ -319,4 +330,4 @@ fn publish_or_log(result: Result<(), crate::websocket::broker::Error>) -> bool { false } } -} \ No newline at end of file +} diff --git a/backend/crates/station/src/pipeline/accumulator.rs b/backend/crates/station/src/pipeline/accumulator.rs index 7aacf82e7..247d0d157 100644 --- a/backend/crates/station/src/pipeline/accumulator.rs +++ b/backend/crates/station/src/pipeline/accumulator.rs @@ -57,14 +57,7 @@ impl MeasurementAccumulator { /// latest value for booleans and enums. fn update(&mut self, value: &Value) { match (self, value) { - ( - Self::Numeric { - last, - sum, - samples, - }, - Value::Number(v), - ) => { + (Self::Numeric { last, sum, samples }, Value::Number(v)) => { *last = *v; *sum += *v; *samples += 1; @@ -92,11 +85,7 @@ impl MeasurementAccumulator { /// numeric measurements. fn into_update(self) -> MeasurementUpdate { match self { - Self::Numeric { - last, - sum, - samples, - } => MeasurementUpdate::Numeric { + Self::Numeric { last, sum, samples } => MeasurementUpdate::Numeric { last, average: sum / (samples as f64), }, @@ -133,15 +122,18 @@ impl DataAccumulator { // 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, - }); + 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 @@ -215,4 +207,4 @@ impl DataAccumulator { updates } -} \ No newline at end of file +} diff --git a/backend/crates/station/src/pipeline/frontend.rs b/backend/crates/station/src/pipeline/frontend.rs index c690b4f98..d7d33dcf5 100644 --- a/backend/crates/station/src/pipeline/frontend.rs +++ b/backend/crates/station/src/pipeline/frontend.rs @@ -118,4 +118,4 @@ impl FrontendWatchdog { None } -} \ No newline at end of file +} diff --git a/backend/crates/station/src/pipeline/message.rs b/backend/crates/station/src/pipeline/message.rs index 5dd77775b..52ca96dca 100644 --- a/backend/crates/station/src/pipeline/message.rs +++ b/backend/crates/station/src/pipeline/message.rs @@ -125,4 +125,4 @@ pub(super) fn from_order_failed( name: order.id.0.to_string(), timestamp: timestamp::from_system_time(at), } -} \ No newline at end of file +} diff --git a/backend/crates/station/src/pipeline/tests.rs b/backend/crates/station/src/pipeline/tests.rs index e0b3d778d..bbd483339 100644 --- a/backend/crates/station/src/pipeline/tests.rs +++ b/backend/crates/station/src/pipeline/tests.rs @@ -95,7 +95,7 @@ fn sample_fixture() -> (Arc, Arc) { /// forwarded to its corresponding broker topic immediately. #[tokio::test] async fn forwards_connections_protections_messages_problems_and_orders_immediately() - -> Result<(), Box> { +-> Result<(), Box> { let (pod_data, index) = sample_fixture(); let (broker, client) = Broker::new(); let mut conn_sub = client.subscribe_connections(); @@ -122,7 +122,7 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate at: UNIX_EPOCH + Duration::from_secs(1_700_000_000), event: Event::Connected, }))) - .await?; + .await?; timeout(Duration::from_secs(1), conn_sub.changed()).await??; assert!(conn_sub.borrow_and_update()["PCU"].is_connected); @@ -143,7 +143,7 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate at: UNIX_EPOCH + Duration::from_secs(1_700_000_001), event: Event::Received(Packet::Protection(protection.clone())), }))) - .await?; + .await?; let got_prot = timeout(Duration::from_secs(1), prot_sub.recv()).await??; assert_eq!(got_prot, ProtectionUpdate::from(protection)); @@ -163,12 +163,15 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate message: "temp high".to_string(), })), }))) - .await?; + .await?; let got_msg = timeout(Duration::from_secs(1), msg_sub.recv()).await??; assert_eq!(got_msg.kind, MessageKind::Warning); assert_eq!(got_msg.board, "PCU"); assert_eq!(got_msg.name, "pcu.c"); - assert_eq!(got_msg.payload, MessagePayload::Text("temp high".to_string())); + assert_eq!( + got_msg.payload, + MessagePayload::Text("temp high".to_string()) + ); assert_eq!(got_msg.timestamp.hour, 1); assert_eq!(got_msg.timestamp.counter, 4); @@ -179,7 +182,7 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate kind: ProblemKind::Fatal, text: "decode failed".to_string(), })) - .await?; + .await?; let got_problem = timeout(Duration::from_secs(1), msg_sub.recv()).await??; assert_eq!(got_problem.kind, MessageKind::Fault); assert_eq!(got_problem.board, "PCU"); @@ -194,7 +197,7 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate board: Some(BoardId(5)), order: OrderPacket::new(AdjId(1001), vec![]), }) - .await?; + .await?; let got_sent = timeout(Duration::from_secs(1), msg_sub.recv()).await??; assert_eq!(got_sent.kind, MessageKind::Info); assert_eq!(got_sent.name, "1001"); @@ -205,7 +208,7 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate order: OrderPacket::new(AdjId(1001), vec![]), reason: "board disconnected".to_string(), }) - .await?; + .await?; let got_failed = timeout(Duration::from_secs(1), msg_sub.recv()).await??; assert_eq!(got_failed.kind, MessageKind::Warning); assert_eq!(got_failed.name, "1001"); @@ -227,7 +230,7 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate /// 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> { +-> Result<(), Box> { let (pod_data, index) = sample_fixture(); let (broker, client) = Broker::new(); let mut data_sub = client.subscribe_data(); @@ -267,7 +270,7 @@ async fn batches_data_every_100ms_with_window_average_last_and_cycle_time() ], ))), }))) - .await?; + .await?; } tokio::task::yield_now().await; @@ -313,7 +316,7 @@ async fn batches_data_every_100ms_with_window_average_last_and_cycle_time() ], ))), }))) - .await?; + .await?; // Dropping `tx` flushes remaining data immediately and stops both tasks cleanly. drop(tx); @@ -337,7 +340,7 @@ async fn batches_data_every_100ms_with_window_average_last_and_cycle_time() /// disconnect, while staying disconnected past 3 s reports `ProblemKind::Fatal`. #[tokio::test(start_paused = true)] async fn frontend_disconnect_allows_reconnect_and_reports_fatal_after_grace_period() - -> Result<(), Box> { +-> Result<(), Box> { let (pod_data, index) = sample_fixture(); let (broker, client) = Broker::new(); let broker_task = tokio::spawn(broker.run()); @@ -395,7 +398,7 @@ async fn frontend_disconnect_allows_reconnect_and_reports_fatal_after_grace_peri /// session to a heartbeat timeout reports `ProblemKind::Fatal` immediately. #[tokio::test(start_paused = true)] async fn frontend_heartbeat_renews_liveness_and_expires_last_session_as_fatal() - -> Result<(), Box> { +-> Result<(), Box> { let (pod_data, index) = sample_fixture(); let (broker, client) = Broker::new(); let broker_task = tokio::spawn(broker.run()); @@ -481,4 +484,4 @@ fn utc_calendar_conversion_handles_epoch_and_leap_day() { year: 2024, } ); -} \ No newline at end of file +} diff --git a/backend/crates/station/src/pipeline/timestamp.rs b/backend/crates/station/src/pipeline/timestamp.rs index cc82da4c8..912f09226 100644 --- a/backend/crates/station/src/pipeline/timestamp.rs +++ b/backend/crates/station/src/pipeline/timestamp.rs @@ -69,4 +69,4 @@ fn civil_from_days(days_since_epoch: i64) -> (u16, u8, u8) { u8::try_from(m).unwrap_or(1), u8::try_from(d).unwrap_or(1), ) -} \ No newline at end of file +} 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/crates/station/src/websocket.rs b/backend/crates/station/src/websocket.rs index 0b71c4a29..e23fb32d6 100644 --- a/backend/crates/station/src/websocket.rs +++ b/backend/crates/station/src/websocket.rs @@ -5,13 +5,13 @@ use std::time::Duration; +use super::payload::{LoggerEnable, LoggerVariables}; use axum::extract::ws::WebSocket; use serde::{Deserialize, Serialize}; use tokio::{ sync::mpsc, time::{Instant, sleep_until}, }; -use super::payload::{LoggerEnable, LoggerVariables}; use self::broker::BrokerClient; use self::handler::SessionEnd; From b675ae8bbd35810bfc6c00b42ec540c6322f206c Mon Sep 17 00:00:00 2001 From: GaziH Date: Fri, 4 Dec 2026 17:09:37 +0100 Subject: [PATCH 10/17] Feat(backend, pipeline): Updated ReadMe --- backend/crates/station/src/pipeline/README.md | 126 +++++++++++++----- 1 file changed, 94 insertions(+), 32 deletions(-) diff --git a/backend/crates/station/src/pipeline/README.md b/backend/crates/station/src/pipeline/README.md index ee1ee5f57..816937652 100644 --- a/backend/crates/station/src/pipeline/README.md +++ b/backend/crates/station/src/pipeline/README.md @@ -1,60 +1,77 @@ # Pipeline (`station::pipeline`) Transforms [`crate::event::ToPipeline`] items into frontend WebSocket payloads -(`station::payload`) and publishes them through [`crate::websocket::broker::BrokerClient`]. +(`station::payload`), publishes them through +[`crate::websocket::broker::BrokerClient`], and monitors `websocket ↔ front` +session liveness (`connection/heartbeat`). `event` routes decoded packets and backend outcomes without inspecting their contents. `pipeline` is the stage that turns those domain events into the exact -shapes the frontend expects: publishing discrete events immediately and -aggregating high-rate UDP telemetry into 100 ms windows. +shapes the frontend expects: publishing discrete events immediately, tracking +per-board connection state, aggregating high-rate UDP telemetry into 100 ms +windows, and reporting fatal frontend disconnects back to `event`. ## Overview ```text - event ──(channels.pipeline: ToPipeline)──► pipeline - ├── immediate ──► BrokerClient - │ ├── connection/update - │ ├── protection/update - │ └── message/update - └── 100 ms tick ─► BrokerClient - └── podData/update + event ─────(channels.pipeline: ToPipeline)────► pipeline + websocket ─(frontend_rx: FrontendEvent)───────► ├── immediate ──► BrokerClient + │ ├── connection/update + │ ├── protection/update + │ └── message/update + ├── 100 ms tick ─► BrokerClient + │ └── podData/update + └── fatal loss ──► event (channels.problems) ``` ## Files ```text -pipeline.rs # module root: Config, spawn, select! loop, routing +pipeline.rs # module root: Config, spawn, biased select! loop, routing pipeline/ ├── accumulator.rs # 100 ms telemetry windowing (count, cycle_time, last, average) +├── frontend.rs # websocket <-> front keep-alive & reconnect grace watchdog ├── message.rs # MessageUpdate builders (board messages, problems, order outcomes) ├── timestamp.rs # SystemTime / ShortTimestamp -> UTC MessageTimestamp -├── tests.rs # unit tests against a real Broker +├── tests.rs # unit tests against a real Broker (no sockets) └── README.md ``` ## Input-to-Topic Mapping -| `ToPipeline` variant | Condition / inner event | Target topic | `BrokerClient` method | Delivery | +| Input | Condition / inner event | Target | Action / method | Delivery | | --- | --- | --- | --- | --- | -| `Received(Notification)` | `Event::Connected` / `Event::Disconnected` | `connection/update` | `publish_connection` | Immediate | -| `Received(Notification)` | `Event::Received(Packet::Data(_))` | `podData/update` | `publish_data` | 100 ms window | -| `Received(Notification)` | `Event::Received(Packet::Protection(_))` | `protection/update` | `publish_protection` | Immediate | -| `Received(Notification)` | `Event::Received(Packet::Message(_))` | `message/update` | `publish_message` | Immediate | -| `Received(Notification)` | `Event::Received(Packet::Order(_))` | — | Ignored (logged as warning) | — | -| `Problem(Problem)` | `ProblemKind::Shown` → `warning` | `message/update` | `publish_message` | Immediate | -| `Problem(Problem)` | `ProblemKind::Fatal` → `fault` | `message/update` | `publish_message` | Immediate | -| `Problem(Problem)` | `ProblemKind::Silent` | — | Ignored | — | -| `OrderSent` | Confirmed TCP write → `info` | `message/update` | `publish_message` | Immediate | -| `OrderFailed` | Failed TCP write → `warning` | `message/update` | `publish_message` | Immediate | +| `ToPipeline::Received` | `Event::Connected` / `Event::Disconnected` | `connection/update` | Updates `board_connections`; calls `publish_connection` on change | Immediate | +| `ToPipeline::Received` | `Event::Received(Packet::Data(_))` | `podData/update` | Accumulated; `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 (logged as warning) | — | +| `ToPipeline::Problem` | `ProblemKind::Shown` → `warning` | `message/update` | `publish_message` | Immediate | +| `ToPipeline::Problem` | `ProblemKind::Fatal` → `fault` | `message/update` | `publish_message` | Immediate | +| `ToPipeline::Problem` | `ProblemKind::Silent` | — | Ignored | — | +| `ToPipeline::OrderSent` | Confirmed TCP write → `info` | `message/update` | `publish_message` | Immediate | +| `ToPipeline::OrderFailed` | Failed TCP write → `warning` | `message/update` | `publish_message` | Immediate | +| `FrontendEvent` | `Connected(id)` / `Heartbeat(id)` / `Disconnected(id)` | `channels.problems` | Renews/tracks liveness; sends `ProblemKind::Fatal` on fatal loss | Immediate / Timer | ### Topics not handled by `pipeline` -- **Frontend-to-backend topics** (`order/send`, `logger/enable`, - `logger/variables`, `connection/heartbeat`) are handled directly by `websocket`. +- **Frontend-to-backend control topics** (`order/send`, `logger/enable`, + `logger/variables`) are handled directly by `websocket`. - **`logger/response`** is published directly by `logging`. - **`order/stateOrders`** is not produced yet because `software_core::model::Packet` has no state-orders packet variant. +## Board Connections (`pipeline.rs`) + +`pipeline` maintains a `HashMap` seeded at startup with every +board declared in `PodData::boards` set to `false` (disconnected). + +- On startup, all initial `false` states are published to `connection/update` so + the frontend immediately sees the full board list. +- Subsequent `Event::Connected` and `Event::Disconnected` notifications update + the map and only publish to `BrokerClient` when a board's state actually + changes. + ## 100 ms Data Aggregation (`accumulator.rs`) High-frequency telemetry (`Packet::Data`) is accumulated in place per packet ID @@ -72,8 +89,29 @@ and flushed every `Config::data_flush_interval` (default `100 ms`). - Boolean and enum measurements emit their latest value directly. - **Idle packets** (no frames received during a window) are skipped on flush; the WebSocket broker retains their previous snapshot. -- **Starvation protection:** the main `tokio::select!` uses `biased;` with the - flush timer polled first so sustained UDP rates cannot delay telemetry flushes. + +## Frontend Liveness & Keep-Alives (`frontend.rs`) + +`FrontendWatchdog` tracks `websocket ↔ front` session health via `FrontendEvent` +messages keyed by a per-connection session ID (`u64`): + +- **`FrontendEvent::Connected(id)` / `FrontendEvent::Heartbeat(id)`:** registers + or renews session `id`'s keep-alive deadline (`Config::frontend_heartbeat_timeout`, + default `3 s`) and cancels any armed reconnect grace deadline. +- **`FrontendEvent::Disconnected(id)`:** removes session `id`. If it was the + last active session, arms a reconnect grace window + (`Config::frontend_disconnect_timeout`, default `3 s`). +- **Independent session expiry:** if one tab goes silent without closing TCP + while another remains active, only the stale session expires after `3 s`. +- **Fatal reporting:** + - Startup with `0` connected frontends is not fatal; monitoring activates once + at least one frontend connects. + - Losing the last live session to a heartbeat timeout reports + `ProblemKind::Fatal` to `event` (`channels.problems`) immediately (the + heartbeat window already elapsed). + - Failing to reconnect before the post-disconnect grace deadline expires + reports `ProblemKind::Fatal` to `event`. + - Fatal disconnect is reported at most once. ## Messages & Timestamps (`message.rs`, `timestamp.rs`) @@ -90,12 +128,21 @@ and flushed every `Config::data_flush_interval` (default `100 ms`). `Notification::at` with the board's `ShortTimestamp` (`hour`, `minute`, `second`) and store its raw `subsecond` byte in `counter`. -## Contract & Shutdown +## Loop Priority, Contract & Shutdown +- **Biased `select!` priority:** `run_loop` polls branches in fixed order: + 1. Frontend heartbeat / reconnect timer (`sleep_until`) + 2. Incoming `FrontendEvent` messages from `websocket` + 3. 100 ms telemetry flush tick + 4. Incoming `ToPipeline` items from `event` + + Sustained high-rate UDP traffic cannot starve frontend disconnect detection or + telemetry flushes. - **Wait, don't drop.** `pipeline` reads continuously from `channels.pipeline` and awaits `BrokerClient` capacity rather than dropping decoded events. -- **No error policy.** Error classification and fault propagation belong solely - to `event`. +- **No network error policy.** Board/socket error classification and fault + propagation belong solely to `event`; `pipeline` only reports frontend loss as + a `ProblemKind::Fatal`. - **Clean shutdown.** - When `event` closes `channels.pipeline` (`recv()` returns `None`), `pipeline` flushes any dirty telemetry in the accumulator to the broker and exits. @@ -110,21 +157,36 @@ use station::pipeline::{self, Config}; let pipeline_handle = pipeline::spawn( Config::default(), channels.pipeline, + frontend_rx, + channels.problems.clone(), broker_client, pod_data, index, ); ``` +## Pending Integration (after `websocket` merges) + +- Wire `websocket` session transitions (`Connected(id)`, `Disconnected(id)`) and + inbound `connection/heartbeat` messages (`Heartbeat(id)`) into `frontend_rx`, + and remove duplicate liveness timers from `websocket`. +- If `websocket` / `payload` splits backend problems onto a dedicated + `problem/update` topic, switch the `ToPipeline::Problem` arm in `pipeline.rs` + from `publish_message` to `publish_problem`. + ## Tests Unit tests in `pipeline/tests.rs` wire `pipeline::spawn` to a real `Broker` instance (no sockets required) and verify: -- Immediate forwarding of connections, protections, board messages, problems, - and order outcomes (`OrderSent` / `OrderFailed`). +- Immediate forwarding of board connections, protections, board messages, + problems, and order outcomes (`OrderSent` / `OrderFailed`). - 100 ms windowing for `Packet::Data` (cumulative `count`, mean `cycleTime`, window `average`, `last`, and flush-on-shutdown). +- Frontend reconnect grace period cancellation and `ProblemKind::Fatal` emission + on expiry. +- Per-session `connection/heartbeat` renewal, independent stale-session expiry, + and immediate `ProblemKind::Fatal` when the last live frontend times out. - UTC calendar conversion on epoch and leap-day timestamps. Run them with: From 799f13512e250a516293522a81872e15be2fd68f Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Sat, 5 Dec 2026 11:13:13 +0100 Subject: [PATCH 11/17] Feat(backend, pipeline): Fixed merging conflicts --- backend/crates/station/src/pipeline.rs | 70 ++++++++++++------- .../station/src/pipeline/accumulator.rs | 6 +- .../crates/station/src/pipeline/message.rs | 22 +++--- backend/crates/station/src/pipeline/tests.rs | 52 ++++++++------ .../crates/station/src/pipeline/timestamp.rs | 4 -- 5 files changed, 92 insertions(+), 62 deletions(-) diff --git a/backend/crates/station/src/pipeline.rs b/backend/crates/station/src/pipeline.rs index ab7931c4c..3d0deeb94 100644 --- a/backend/crates/station/src/pipeline.rs +++ b/backend/crates/station/src/pipeline.rs @@ -42,11 +42,11 @@ use std::sync::Arc; use std::time::Duration; use crate::event::{Problem, ProblemKind, ToPipeline}; -use crate::payload::{Connection, ProtectionUpdate}; +use crate::payload::{Connection, ProtectionUpdate, ConnectionUpdate, DataPacketUpdate, DataUpdate}; use crate::websocket::broker::BrokerClient; use accumulator::DataAccumulator; use frontend::FrontendWatchdog; -use software_core::model::{BoardId, Packet, PodData}; +use software_core::model::{BoardId, Packet, PodData, AdjId}; use software_core::net::{Event, Notification}; use software_core::protocol::Index; use tokio::sync::mpsc; @@ -133,16 +133,19 @@ async fn run_loop( pod_data.boards.keys().map(|&id| (id, false)).collect(); // Publish initial `false` states so the frontend immediately sees all boards. - for (&id, &is_connected) in &board_connections { - let update = Connection { - name: message::board_name(&pod_data, id), - is_connected, - }; - if !publish_or_log(broker.publish_connection(update).await) { - return; - } + 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(); + loop { let frontend_deadline = watchdog.deadline(); @@ -178,7 +181,7 @@ async fn run_loop( } // 3. Periodic 100 ms telemetry flush. _ = tick.tick() => { - if !flush_data(&broker, &index, &mut accumulator).await { + if !flush_data(&broker, &index, &mut accumulator, &mut latest_data).await { return; } } @@ -193,7 +196,7 @@ async fn run_loop( None => { // Upstream (`event`) closed: perform a best-effort flush of any // buffered telemetry before exiting. - let _ = flush_data(&broker, &index, &mut accumulator).await; + let _ = flush_data(&broker, &index, &mut accumulator, &mut latest_data).await; return; } } @@ -255,22 +258,22 @@ async fn handle_notification( match ¬ification.event { Event::Connected | Event::Disconnected => { let is_connected = matches!(notification.event, Event::Connected); - // Only publish when a board's connection state actually changes. if board_connections.insert(notification.board, is_connected) == Some(is_connected) { return true; } - let update = Connection { - name: message::board_name(pod_data, notification.board), - is_connected, - }; - publish_or_log(broker.publish_connection(update).await) + let snapshot = connection_snapshot(board_connections, pod_data); + publish_or_log(broker.publish_connections(snapshot).await) } Event::Received(Packet::Data(data)) => { accumulator.record(data, notification.at, index); true } Event::Received(Packet::Protection(protection)) => { - let update = ProtectionUpdate::from(protection.clone()); + 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)) => { @@ -311,13 +314,16 @@ async fn flush_data( broker: &BrokerClient, index: &Index, accumulator: &mut DataAccumulator, + latest_data: &mut HashMap, ) -> bool { - for update in accumulator.drain_updates(index) { - if !publish_or_log(broker.publish_data(update).await) { - return false; - } + let updates = accumulator.drain_updates(index); + if updates.is_empty() { + return true; } - 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 @@ -331,3 +337,19 @@ fn publish_or_log(result: Result<(), crate::websocket::broker::Error>) -> bool { } } } + +/// 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/accumulator.rs b/backend/crates/station/src/pipeline/accumulator.rs index 247d0d157..e977eef7e 100644 --- a/backend/crates/station/src/pipeline/accumulator.rs +++ b/backend/crates/station/src/pipeline/accumulator.rs @@ -188,17 +188,15 @@ impl DataAccumulator { // `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::with_capacity(defs.len()); + 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.alias.clone(), acc.into_update()); + measurement_updates.insert(measurement_def.id.clone(), acc.into_update()); } } updates.push(DataPacketUpdate { id, - // Raw wire bytes are not carried by `Notification`; left empty. - hex_value: String::new(), count: window.count, cycle_time: window.last_cycle_time_ns, measurement_updates, diff --git a/backend/crates/station/src/pipeline/message.rs b/backend/crates/station/src/pipeline/message.rs index 52ca96dca..09e7f3676 100644 --- a/backend/crates/station/src/pipeline/message.rs +++ b/backend/crates/station/src/pipeline/message.rs @@ -2,8 +2,8 @@ use std::time::SystemTime; use super::timestamp; use crate::event::{Problem, ProblemKind}; -use crate::payload::{MessageKind, MessagePayload, MessageUpdate}; -use software_core::model::{AdjId, BoardId, MessagePacket, OrderPacket, PacketType, PodData}; +use crate::payload::{MessagePayload, MessageUpdate}; +use software_core::model::{MessageLevel, AdjId, BoardId, MessagePacket, OrderPacket, PacketType, PodData}; use software_core::protocol::Index; use tracing::warn; @@ -29,18 +29,18 @@ pub(super) fn from_board_message( ) -> MessageUpdate { let kind = match index.packet(message.id) { Some(def) => match def.packet_type { - PacketType::Message(level) => MessageKind::from(level), + PacketType::Message(level) => MessageLevel::from(level), _ => { warn!( id = message.id.0, "message packet id does not map to PacketType::Message" ); - MessageKind::Info + MessageLevel::Info } }, None => { warn!(id = message.id.0, "unknown message packet id in index"); - MessageKind::Info + MessageLevel::Info } }; @@ -54,6 +54,7 @@ pub(super) fn from_board_message( kind, payload: MessagePayload::Text(message.message.clone()), board: board_name(pod_data, board), + origin: String::new(), name, timestamp: timestamp::from_short(at, message.timestamp), } @@ -63,8 +64,8 @@ pub(super) fn from_board_message( /// for [`ProblemKind::Silent`] problems that should not be shown on the front. pub(super) fn from_problem(problem: Problem, pod_data: &PodData) -> Option { let kind = match problem.kind { - ProblemKind::Shown => MessageKind::Warning, - ProblemKind::Fatal => MessageKind::Fault, + ProblemKind::Shown => MessageLevel::Warning, + ProblemKind::Fatal => MessageLevel::Fault, ProblemKind::Silent => return None, }; @@ -76,6 +77,7 @@ pub(super) fn from_problem(problem: Problem, pod_data: &PodData) -> Option Result<(), Box> { let (pod_data, index) = sample_fixture(); let (broker, client) = Broker::new(); - let mut conn_sub = client.subscribe_connections(); - let mut msg_sub = client.subscribe_messages()?; - let mut prot_sub = client.subscribe_protections()?; + 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 broker_task = tokio::spawn(broker.run()); let (tx, rx) = mpsc::channel(32); @@ -124,7 +125,7 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate }))) .await?; timeout(Duration::from_secs(1), conn_sub.changed()).await??; - assert!(conn_sub.borrow_and_update()["PCU"].is_connected); + 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). @@ -138,6 +139,18 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate }, 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), @@ -145,7 +158,7 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate }))) .await?; let got_prot = timeout(Duration::from_secs(1), prot_sub.recv()).await??; - assert_eq!(got_prot, ProtectionUpdate::from(protection)); + assert_eq!(got_prot, protection_update); // 3. Board message tx.send(ToPipeline::Received(Arc::new(Notification { @@ -165,7 +178,7 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate }))) .await?; let got_msg = timeout(Duration::from_secs(1), msg_sub.recv()).await??; - assert_eq!(got_msg.kind, MessageKind::Warning); + assert_eq!(got_msg.kind, MessageLevel::Warning); assert_eq!(got_msg.board, "PCU"); assert_eq!(got_msg.name, "pcu.c"); assert_eq!( @@ -173,7 +186,6 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate MessagePayload::Text("temp high".to_string()) ); assert_eq!(got_msg.timestamp.hour, 1); - assert_eq!(got_msg.timestamp.counter, 4); // 4. Problem (Fatal -> Fault) tx.send(ToPipeline::Problem(Problem { @@ -184,7 +196,7 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate })) .await?; let got_problem = timeout(Duration::from_secs(1), msg_sub.recv()).await??; - assert_eq!(got_problem.kind, MessageKind::Fault); + assert_eq!(got_problem.kind, MessageLevel::Fault); assert_eq!(got_problem.board, "PCU"); assert_eq!( got_problem.payload, @@ -199,7 +211,7 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate }) .await?; let got_sent = timeout(Duration::from_secs(1), msg_sub.recv()).await??; - assert_eq!(got_sent.kind, MessageKind::Info); + assert_eq!(got_sent.kind, MessageLevel::Info); assert_eq!(got_sent.name, "1001"); assert_eq!(got_sent.board, "PCU"); @@ -210,7 +222,7 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate }) .await?; let got_failed = timeout(Duration::from_secs(1), msg_sub.recv()).await??; - assert_eq!(got_failed.kind, MessageKind::Warning); + assert_eq!(got_failed.kind, MessageLevel::Warning); assert_eq!(got_failed.name, "1001"); assert_eq!( got_failed.payload, @@ -233,7 +245,7 @@ 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.subscribe_data(); + let mut data_sub = client.subscriber().subscribe_data(); let broker_task = tokio::spawn(broker.run()); let (tx, rx) = mpsc::channel(32); @@ -283,23 +295,23 @@ async fn batches_data_every_100ms_with_window_average_last_and_cycle_time() advance(Duration::from_millis(100)).await; timeout(Duration::from_millis(10), data_sub.changed()).await??; - let first = data_sub.borrow_and_update()[&551].clone(); + 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["voltage_battery_a"], + first.measurement_updates[&AdjId(3001)], MeasurementUpdate::Numeric { last: 30.0, average: 20.0, } ); assert_eq!( - first.measurement_updates["is_active"], + first.measurement_updates[&AdjId(3002)], MeasurementUpdate::Boolean(true) ); assert_eq!( - first.measurement_updates["state"], + first.measurement_updates[&AdjId(3003)], MeasurementUpdate::Enum("Fault".to_string()) ); @@ -323,11 +335,11 @@ async fn batches_data_every_100ms_with_window_average_last_and_cycle_time() timeout(Duration::from_secs(1), pipe_task).await??; timeout(Duration::from_secs(1), broker_task).await??; - let second = data_sub.borrow_and_update()[&551].clone(); + 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["voltage_battery_a"], + second.measurement_updates[&AdjId(3001)], MeasurementUpdate::Numeric { last: 50.0, average: 50.0, @@ -458,7 +470,6 @@ fn utc_calendar_conversion_handles_epoch_and_leap_day() { assert_eq!( epoch, MessageTimestamp { - counter: 0, second: 0, minute: 0, hour: 0, @@ -475,7 +486,6 @@ fn utc_calendar_conversion_handles_epoch_and_leap_day() { assert_eq!( leap, MessageTimestamp { - counter: 250, second: 9, minute: 45, hour: 13, diff --git a/backend/crates/station/src/pipeline/timestamp.rs b/backend/crates/station/src/pipeline/timestamp.rs index 912f09226..3292dc35f 100644 --- a/backend/crates/station/src/pipeline/timestamp.rs +++ b/backend/crates/station/src/pipeline/timestamp.rs @@ -17,11 +17,8 @@ pub(super) fn from_system_time(at: SystemTime) -> MessageTimestamp { 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); - // Backend-originated messages use millisecond subsecond ticks (0–999) as the RTC counter. - let counter = u16::try_from(dur.subsec_millis()).unwrap_or(0); MessageTimestamp { - counter, second, minute, hour, @@ -36,7 +33,6 @@ pub(super) fn from_system_time(at: SystemTime) -> MessageTimestamp { pub(super) fn from_short(received_at: SystemTime, short: ShortTimestamp) -> MessageTimestamp { let date = from_system_time(received_at); MessageTimestamp { - counter: u16::from(short.subsecond), second: short.second, minute: short.minute, hour: short.hour, From 9e7e13aa18428d8f78bb50c83ca9c7a7d94e3b48 Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Sat, 5 Dec 2026 11:36:40 +0100 Subject: [PATCH 12/17] Feat(backend, pipeline): Upload of test used. --- .../station/src/examples/podDataTest.rs | 519 ++++++++++++++++++ 1 file changed, 519 insertions(+) create mode 100644 backend/crates/station/src/examples/podDataTest.rs diff --git a/backend/crates/station/src/examples/podDataTest.rs b/backend/crates/station/src/examples/podDataTest.rs new file mode 100644 index 000000000..2ab9d056c --- /dev/null +++ b/backend/crates/station/src/examples/podDataTest.rs @@ -0,0 +1,519 @@ +//! Temporary test harness: runs `UDP + synthetic board traffic -> event -> pipeline -> Broker`. +//! Remember to revert with `git checkout -- crates/station/src/main.rs` before committing. + +use std::collections::HashMap; +use std::net::SocketAddr; +use std::path::PathBuf; +use std::process::ExitCode; +use std::sync::Arc; +use std::time::{Duration, SystemTime}; + +use software_core::adj::{self, Adj, LoadError}; +use software_core::git::{self, GitError}; +use software_core::model::{ + AdjId, BoardId, DataPacket, MeasurementKind, OrderPacket, Packet, PacketType, PodData, + ProtectionPacket, ShortTimestamp, Value, +}; +use software_core::net::udp::{UdpConfig, UdpError, spawn_udp}; +use software_core::net::{Event, Notification}; +use software_core::protocol::Index; +use tokio::sync::{broadcast, mpsc}; +use tokio::task::JoinError; +use tokio::time::MissedTickBehavior; +use tracing::{debug, error, info, warn}; +use tracing_subscriber::EnvFilter; + +use station::event::{self, Problem, ProblemKind, Stop, ToLogging, ToPipeline}; +use station::pipeline::{self, Config as PipelineConfig, FrontendEvent}; +use station::websocket::broker::{Broker, Subscriber}; + +const ADJ_BRANCH: &str = "adjv3-software"; +const RECV_BUFFER: usize = 2 * 1024 * 1024; +const SUMMARY_EVERY: Duration = Duration::from_secs(1); +const SHUTDOWN_GRACE: Duration = Duration::from_secs(5); + +#[derive(Debug, thiserror::Error)] +enum StartError { + #[error("could not get the ADJ (branch {ADJ_BRANCH})")] + Download(#[source] GitError), + #[error("the downloaded ADJ has no working directory")] + NoWorkdir, + #[error("could not load the ADJ from {path}")] + Load { + path: PathBuf, + #[source] + source: LoadError, + }, + #[error("the ADJ's general_info.json has no `{0}`")] + MissingInAdj(&'static str), + #[error("could not start tokio")] + Runtime(#[source] std::io::Error), + #[error("could not listen for Ctrl+C")] + CtrlC(#[source] std::io::Error), + #[error("could not open the UDP port")] + Bind(#[source] UdpError), + #[error("the event task failed")] + Event(#[source] JoinError), +} + +fn main() -> ExitCode { + let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); + tracing_subscriber::fmt().with_env_filter(filter).init(); + + match run() { + Ok(code) => code, + Err(error) => { + error!(error = %event::full_message(&error), "stopping"); + ExitCode::FAILURE + } + } +} + +fn run() -> Result { + let adj = download_adj()?; + let addr = udp_addr(&adj)?; + let index = Arc::new(Index::new(&adj.pod_data, Some(&adj.info.message_levels))); + let pod_data = Arc::new(adj.pod_data); + + let runtime = tokio::runtime::Runtime::new().map_err(StartError::Runtime)?; + runtime.block_on(serve(addr, index, pod_data)) +} + +fn download_adj() -> Result { + let commit = git::update_adj(None, ADJ_BRANCH).map_err(StartError::Download)?; + let repo = git::open_repo(None).map_err(StartError::Download)?; + let path = repo.workdir().ok_or(StartError::NoWorkdir)?.to_path_buf(); + + let adj = adj::load_from_dir(&path).map_err(|source| StartError::Load { + path: path.clone(), + source, + })?; + info!( + branch = ADJ_BRANCH, + %commit, + path = %path.display(), + boards = adj.pod_data.boards.len(), + "ADJ loaded" + ); + Ok(adj) +} + +fn udp_addr(adj: &Adj) -> Result { + let ip = adj + .info + .addresses + .get("backend") + .ok_or(StartError::MissingInAdj("addresses.backend"))?; + let port = adj + .info + .ports + .get("UDP") + .ok_or(StartError::MissingInAdj("ports.UDP"))?; + Ok(SocketAddr::new(*ip, port.0)) +} + +async fn serve( + addr: SocketAddr, + index: Arc, + pod_data: Arc, +) -> Result { + let config = event::EventConfig::default(); + let event::Channels { + udp, + tcp, + event: ends, + orders, + problems, + logging, + pipeline: event_pipeline_rx, + } = event::channels(&config); + + drop(tcp); + + let udp_task = spawn_udp( + UdpConfig { + addr, + recv_buffer: RECV_BUFFER, + boards: pod_data.boards_by_ip(), + }, + index.clone(), + udp, + ) + .map_err(StartError::Bind)?; + info!(%addr, "listening on UDP (Ctrl+C to stop)"); + + // Real websocket Broker + console monitor acting as the frontend subscriber. + let (broker, broker_client) = Broker::new(); + let subscriber = broker_client.subscriber(); + let broker_task = tokio::spawn(broker.run()); + let monitor_task = tokio::spawn(monitor_broker(subscriber)); + + // Merge real `event -> pipeline` output with our synthetic board events. + let (pipe_tx, pipe_rx) = mpsc::channel::(128); + let bridge_tx = pipe_tx.clone(); + let bridge_task = tokio::spawn(async move { + let mut rx = event_pipeline_rx; + while let Some(item) = rx.recv().await { + if bridge_tx.send(item).await.is_err() { + break; + } + } + }); + + let (frontend_tx, frontend_rx) = mpsc::channel::(16); + + let logging_task = tokio::spawn(stand_in_logging(logging, pod_data.clone())); + let pipeline_task = pipeline::spawn( + PipelineConfig::default(), + pipe_rx, + frontend_rx, + problems.clone(), + broker_client, + pod_data.clone(), + index.clone(), + ); + let mut event_task = event::spawn(config, ends, pod_data.clone(), index, None); + + // Inject synthetic events using the real ADJ definitions. + let sim_task = tokio::spawn(simulate_traffic( + pod_data, + pipe_tx, + orders, + problems, + frontend_tx, + )); + + let (stop, by_ctrl_c) = tokio::select! { + stop = &mut event_task => (stop, false), + signal = tokio::signal::ctrl_c() => { + signal.map_err(StartError::CtrlC)?; + info!("Ctrl+C, stopping"); + udp_task.abort(); + sim_task.abort(); + (event_task.await, true) + } + }; + udp_task.abort(); + sim_task.abort(); + + let finished = tokio::time::timeout(SHUTDOWN_GRACE, async { + let _ = bridge_task.await; + let _ = logging_task.await; + let _ = pipeline_task.await; + let _ = broker_task.await; + let _ = monitor_task.await; + }) + .await; + if finished.is_err() { + warn!(grace = ?SHUTDOWN_GRACE, "tasks did not finish in time"); + } + + match stop.map_err(StartError::Event)? { + Stop::Fatal(problem) => { + info!(reason = %problem.text, "stopped after a fatal error"); + Ok(ExitCode::FAILURE) + } + Stop::NetGone if by_ctrl_c => { + info!("stopped"); + Ok(ExitCode::SUCCESS) + } + Stop::NetGone => { + error!("UDP stopped on its own"); + Ok(ExitCode::FAILURE) + } + } +} + +/// Feeds a short sequence of realistic ADJ events through `event` and `pipeline`. +async fn simulate_traffic( + pod_data: Arc, + pipe_tx: mpsc::Sender, + orders: mpsc::Sender, + problems: mpsc::Sender, + frontend_tx: mpsc::Sender, +) { + // Pick the first board that declares at least one Data packet in the loaded ADJ. + let Some((board_id, data_id, first_meas_id)) = pod_data.boards.values().find_map(|board| { + board + .packets + .values() + .find_map(|def| match &def.packet_type { + PacketType::Data(defs) if !defs.is_empty() => { + Some((board.id, def.id, defs[0].id)) + } + _ => None, + }) + }) else { + warn!("no Data packets found in ADJ to simulate"); + return; + }; + + let order_id = pod_data + .boards + .values() + .find_map(|board| { + board + .packets + .values() + .find_map(|def| match &def.packet_type { + PacketType::Order(_) => Some(def.id), + _ => None, + }) + }) + .unwrap_or(AdjId(1001)); + + info!( + board = %name(&pod_data, board_id), + data_packet = data_id.0, + order_packet = order_id.0, + "starting synthetic scenario" + ); + + // 1. Frontend connects. + let _ = frontend_tx.send(FrontendEvent::Connected(1)).await; + tokio::time::sleep(Duration::from_millis(200)).await; + + // 2. Board connects -> `connection/update`. + let _ = pipe_tx + .send(ToPipeline::Received(Arc::new(Notification { + board: board_id, + at: SystemTime::now(), + event: Event::Connected, + }))) + .await; + + // 3. Burst of 16 Data packets (1 every 25 ms -> ~4 aggregated 100 ms `podData/update` flushes). + for step in 1_u32..=16 { + let values = match pod_data + .boards + .get(&board_id) + .and_then(|b| b.packets.get(&data_id)) + .map(|def| &def.packet_type) + { + Some(PacketType::Data(defs)) => defs + .iter() + .map(|m| match &m.kind { + MeasurementKind::Numeric { .. } => Value::Number(f64::from(step) * 10.0), + MeasurementKind::Boolean => Value::Bool(step % 2 == 0), + MeasurementKind::Enum { options } => { + let idx = (step as usize) % options.len().max(1); + Value::Enum(options.get(idx).cloned().unwrap_or_default()) + } + }) + .collect(), + _ => Vec::new(), + }; + + let _ = pipe_tx + .send(ToPipeline::Received(Arc::new(Notification { + board: board_id, + at: SystemTime::now(), + event: Event::Received(Packet::Data(DataPacket::new(data_id, values))), + }))) + .await; + + tokio::time::sleep(Duration::from_millis(25)).await; + } + + // 4. Protection packet -> `protection/update`. + let _ = pipe_tx + .send(ToPipeline::Received(Arc::new(Notification { + board: board_id, + at: SystemTime::now(), + event: Event::Received(Packet::Protection(ProtectionPacket { + id: AdjId((1 << 13) | (first_meas_id.0 & 0x1FFF)), + timestamp: ShortTimestamp { + hour: 12, + minute: 30, + second: 45, + subsecond: 0, + }, + value: Value::Number(99.5), + })), + }))) + .await; + tokio::time::sleep(Duration::from_millis(200)).await; + + // 5. Real `event` round-trip: Problem & OrderPacket go through `event -> pipeline -> Broker`. + let _ = problems + .send(Problem::now( + ProblemKind::Shown, + Some(board_id), + "simulated warning through event", + )) + .await; + let _ = orders.send(OrderPacket::new(order_id, vec![])).await; + tokio::time::sleep(Duration::from_millis(200)).await; + + // 6. Board disconnects -> `connection/update`. + let _ = pipe_tx + .send(ToPipeline::Received(Arc::new(Notification { + board: board_id, + at: SystemTime::now(), + event: Event::Disconnected, + }))) + .await; + + info!("synthetic scenario complete — keeping frontend heartbeat alive (press Ctrl+C to stop)"); + + // 7. Keep frontend alive. Comment out this loop to test the 3 s fatal watchdog! + let mut hb = tokio::time::interval(Duration::from_secs(1)); + loop { + hb.tick().await; + if frontend_tx.send(FrontendEvent::Heartbeat(1)).await.is_err() { + break; + } + } +} + +/// Logs every topic published through `websocket::Broker` by `pipeline`. +async fn monitor_broker(sub: Subscriber) { + let mut conn_sub = sub.subscribe_connections(); + let mut data_sub = sub.subscribe_data(); + let msg_sub = sub.subscribe_messages(); + let prot_sub = sub.subscribe_protections(); + let backend_sub = sub.subscribe_backend_messages(); + + let connections = async move { + while conn_sub.changed().await.is_ok() { + let snap = conn_sub.borrow_and_update(); + info!(boards = ?snap.0, "broker -> connection/update"); + } + }; + + let data = async move { + while data_sub.changed().await.is_ok() { + let snap = data_sub.borrow_and_update(); + for pkt in snap.0.values() { + info!( + id = pkt.id.0, + count = pkt.count, + cycle_time_ns = pkt.cycle_time, + measurements = ?pkt.measurement_updates, + "broker -> podData/update" + ); + } + } + }; + + let messages = async move { + let Ok(mut rx) = msg_sub else { return }; + loop { + match rx.recv().await { + Ok(msg) => info!(?msg, "broker -> message/update"), + Err(broadcast::error::RecvError::Lagged(n)) => { + warn!(skipped = n, "message/update lagged"); + } + Err(broadcast::error::RecvError::Closed) => break, + } + } + }; + + let protections = async move { + let Ok(mut rx) = prot_sub else { return }; + loop { + match rx.recv().await { + Ok(prot) => info!(?prot, "broker -> protection/update"), + Err(broadcast::error::RecvError::Lagged(n)) => { + warn!(skipped = n, "protection/update lagged"); + } + Err(broadcast::error::RecvError::Closed) => break, + } + } + }; + + let backend_messages = async move { + let Ok(mut rx) = backend_sub else { return }; + loop { + match rx.recv().await { + Ok(msg) => info!(?msg, "broker -> backend/message"), + Err(broadcast::error::RecvError::Lagged(n)) => { + warn!(skipped = n, "backend/message lagged"); + } + Err(broadcast::error::RecvError::Closed) => break, + } + } + }; + + tokio::join!(connections, data, messages, protections, backend_messages); +} + +async fn stand_in_logging(mut queue: mpsc::Receiver, pod_data: Arc) { + let mut summary = tokio::time::interval(SUMMARY_EVERY); + summary.set_missed_tick_behavior(MissedTickBehavior::Delay); + let mut counts: HashMap = HashMap::new(); + + loop { + tokio::select! { + biased; + _ = summary.tick() => log_summary(&mut counts, &pod_data), + message = queue.recv() => match message { + None => break, + Some(ToLogging::Received(notification)) => { + count_and_trace(¬ification, &mut counts, &pod_data); + } + Some(ToLogging::OrderSent { at, board, order }) => { + let to = order_target(board, &pod_data); + info!(to, id = ?order.id, at = %clock(at), "order sent"); + } + }, + } + } + log_summary(&mut counts, &pod_data); +} + +fn order_target(board: Option, pod_data: &PodData) -> String { + match board { + Some(board) => name(pod_data, board), + None => "every board".to_string(), + } +} + +fn name(pod_data: &PodData, board: BoardId) -> String { + pod_data + .board_name(board) + .map_or_else(|| format!("{board:?}"), str::to_owned) +} + +fn clock(at: SystemTime) -> String { + match at.duration_since(SystemTime::UNIX_EPOCH) { + Ok(since) => format!("{}.{:03}", since.as_secs(), since.subsec_millis()), + Err(_) => "before 1970".to_string(), + } +} + +fn count_and_trace( + notification: &Notification, + counts: &mut HashMap, + pod_data: &PodData, +) { + *counts.entry(notification.board).or_insert(0) += 1; + + match ¬ification.event { + Event::Received(Packet::Data(packet)) => debug!( + board = %name(pod_data, notification.board), + id = ?packet.id, + values = ?packet.values, + "packet" + ), + other => debug!( + board = %name(pod_data, notification.board), + event = ?other, + "notification" + ), + } +} + +fn log_summary(counts: &mut HashMap, pod_data: &PodData) { + let total: u64 = counts.values().sum(); + if total == 0 { + return; + } + let mut per_board: Vec = counts + .iter() + .map(|(&board, count)| format!("{}={count}", name(pod_data, board))) + .collect(); + per_board.sort(); + info!(total, boards = %per_board.join(" "), "packets in the last second"); + counts.clear(); +} \ No newline at end of file From e45473965f182e5ed3ea255f5839e7c2ff49c235 Mon Sep 17 00:00:00 2001 From: Gazi Al Saad Halawani Date: Sat, 5 Dec 2026 14:31:05 +0100 Subject: [PATCH 13/17] Feat(backend, pipeline): Added pipeline saturation management. --- backend/crates/station/src/pipeline.rs | 102 +++++++++++++++++-- backend/crates/station/src/pipeline/tests.rs | 95 +++++++++++++++++ 2 files changed, 191 insertions(+), 6 deletions(-) diff --git a/backend/crates/station/src/pipeline.rs b/backend/crates/station/src/pipeline.rs index 3d0deeb94..ce5665cb7 100644 --- a/backend/crates/station/src/pipeline.rs +++ b/backend/crates/station/src/pipeline.rs @@ -52,7 +52,7 @@ use software_core::protocol::Index; use tokio::sync::mpsc; use tokio::task::JoinHandle; use tokio::time::{Instant, MissedTickBehavior, interval_at, sleep_until}; -use tracing::{error, warn}; +use tracing::{error, info, warn}; /// Configuration for the pipeline task. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -65,6 +65,10 @@ pub struct Config { /// Grace period allowed for a frontend client to reconnect after the last /// active frontend socket closes before reporting a fatal problem to `event`. pub frontend_disconnect_timeout: Duration, + /// Queue fill percentage (1–100) at which `pipeline` pauses UDP `Data` updates. + pub saturation_high_percent: u8, + /// Queue fill percentage (0–100) at or below which `pipeline` resumes UDP `Data` updates. + pub saturation_low_percent: u8, } impl Default for Config { @@ -73,6 +77,8 @@ impl Default for Config { data_flush_interval: Duration::from_millis(100), frontend_heartbeat_timeout: Duration::from_secs(3), frontend_disconnect_timeout: Duration::from_secs(3), + saturation_high_percent: 80, + saturation_low_percent: 25, } } } @@ -126,6 +132,11 @@ async fn run_loop( config.frontend_heartbeat_timeout, config.frontend_disconnect_timeout, ); + let mut saturation = SaturationState::new( + rx.max_capacity(), + config.saturation_high_percent, + config.saturation_low_percent, + ); let mut frontend_open = true; // Track connection state for every board declared in the ADJ (all start disconnected). @@ -179,9 +190,11 @@ async fn run_loop( } } } - // 3. Periodic 100 ms telemetry flush. + // 3. Periodic 100 ms telemetry flush (skipped while saturated). _ = tick.tick() => { - if !flush_data(&broker, &index, &mut accumulator, &mut latest_data).await { + if !saturation.is_saturated() + && !flush_data(&broker, &index, &mut accumulator, &mut latest_data).await + { return; } } @@ -189,13 +202,25 @@ async fn run_loop( item = rx.recv() => { match item { Some(msg) => { - if !handle_item(msg, &broker, &pod_data, &index, &mut accumulator, &mut board_connections).await { + saturation.observe(rx.len()); + if saturation.is_saturated() && is_udp_data(&msg) { + saturation.record_drop(); + continue; + } + if !handle_item( + msg, + &broker, + &pod_data, + &index, + &mut accumulator, + &mut board_connections, + ) + .await + { return; } } None => { - // Upstream (`event`) closed: perform a best-effort flush of any - // buffered telemetry before exiting. let _ = flush_data(&broker, &index, &mut accumulator, &mut latest_data).await; return; } @@ -353,3 +378,68 @@ fn connection_snapshot( .collect(), ) } + +/// Returns `true` for high-rate UDP telemetry frames that can be shed while saturated. +fn is_udp_data(item: &ToPipeline) -> bool { + matches!( + item, + ToPipeline::Received(notification) + if matches!(notification.event, Event::Received(Packet::Data(_))) + ) +} + +/// Tracks channel-backlog saturation with hysteresis so `pipeline` pauses UDP +/// `Data` updates under heavy load without dropping discrete events. +struct SaturationState { + high_water: usize, + low_water: usize, + saturated: bool, + dropped_data: u64, +} + +impl SaturationState { + fn new(capacity: usize, high_percent: u8, low_percent: u8) -> Self { + let high_pct = usize::from(high_percent.clamp(1, 100)); + let low_pct = usize::from(low_percent.min(high_percent)); + let high_water = (capacity * high_pct).div_ceil(100).max(1); + let low_water = ((capacity * low_pct) / 100).min(high_water.saturating_sub(1)); + Self { + high_water, + low_water, + saturated: false, + dropped_data: 0, + } + } + + fn is_saturated(&self) -> bool { + self.saturated + } + + /// Updates saturation state using `queued_after_recv` (items still waiting + /// in `rx` immediately after popping one item). + fn observe(&mut self, queued_after_recv: usize) { + let depth = queued_after_recv.saturating_add(1); + if !self.saturated && depth >= self.high_water { + self.saturated = true; + self.dropped_data = 0; + warn!( + queued = depth, + high_water = self.high_water, + "pipeline saturated; pausing UDP data updates" + ); + } else if self.saturated && queued_after_recv <= self.low_water { + self.saturated = false; + info!( + queued = queued_after_recv, + low_water = self.low_water, + dropped_data = self.dropped_data, + "pipeline unsaturated; resuming UDP data updates" + ); + self.dropped_data = 0; + } + } + + fn record_drop(&mut self) { + self.dropped_data = self.dropped_data.saturating_add(1); + } +} diff --git a/backend/crates/station/src/pipeline/tests.rs b/backend/crates/station/src/pipeline/tests.rs index 08e57bdab..dc0146bc3 100644 --- a/backend/crates/station/src/pipeline/tests.rs +++ b/backend/crates/station/src/pipeline/tests.rs @@ -495,3 +495,98 @@ fn utc_calendar_conversion_handles_epoch_and_leap_day() { } ); } + +/// Verifies that `pipeline` sheds UDP `Packet::Data` updates when `channels.pipeline` +/// saturates (while still forwarding discrete events like `OrderSent`), and resumes +/// processing `Packet::Data` once the backlog drops below the low-water mark. +#[tokio::test(start_paused = true)] +async fn pauses_udp_data_when_saturated_and_resumes_when_unsaturated() + -> Result<(), Box> { + let (pod_data, index) = sample_fixture(); + let (broker, client) = Broker::new(); + let sub = client.subscriber(); + let mut data_sub = sub.subscribe_data(); + let mut msg_sub = sub.subscribe_messages()?; + let broker_task = tokio::spawn(broker.run()); + + // Capacity 16 -> default high_water = 13 (80%), low_water = 4 (25%). + let (tx, rx) = mpsc::channel(16); + let (_fe_tx, fe_rx) = mpsc::channel(16); + let (problems_tx, _problems_rx) = mpsc::channel(16); + let pipe_task = spawn( + Config::default(), + rx, + fe_rx, + problems_tx, + client, + pod_data, + index, + ); + + let t0 = UNIX_EPOCH + Duration::from_secs(1_700_000_000); + let send_data = |step: u32| ToPipeline::Received(Arc::new(Notification { + board: BoardId(5), + at: t0 + Duration::from_millis(u64::from(step) * 5), + event: Event::Received(Packet::Data(DataPacket::new( + AdjId(551), + vec![ + Value::Number(f64::from(step)), + Value::Bool(true), + Value::Enum("Idle".to_string()), + ], + ))), + })); + + // Enqueue 14 items before `pipe_task` runs (>= high_water 13): + // 7 Data frames -> 1 OrderSent -> 6 Data frames. + for step in 1..=7 { + tx.send(send_data(step)).await?; + } + tx.send(ToPipeline::OrderSent { + at: t0 + Duration::from_millis(40), + board: Some(BoardId(5)), + order: OrderPacket::new(AdjId(1001), vec![]), + }) + .await?; + for step in 8..=13 { + tx.send(send_data(step)).await?; + } + + // OrderSent must still be forwarded immediately while saturated. + let got_sent = timeout(Duration::from_secs(1), msg_sub.recv()).await??; + assert_eq!(got_sent.name, "1001"); + + // Flush the 100 ms window: frames 1..=8 were dropped while saturated, + // and frames 9..=13 were processed after the queue drained to <= 4. + 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, 5); + assert_eq!( + first.measurement_updates[&AdjId(3001)], + MeasurementUpdate::Numeric { + last: 13.0, + average: 11.0, + } + ); + + // Queue is now empty (unsaturated): next UDP Data frame is processed normally. + tx.send(send_data(99)).await?; + tokio::task::yield_now().await; + advance(Duration::from_millis(100)).await; + timeout(Duration::from_millis(10), data_sub.changed()).await??; + let second = data_sub.borrow_and_update().0[&AdjId(551)].clone(); + assert_eq!(second.count, 6); + assert_eq!( + second.measurement_updates[&AdjId(3001)], + MeasurementUpdate::Numeric { + last: 99.0, + average: 99.0, + } + ); + + drop(tx); + timeout(Duration::from_secs(1), pipe_task).await??; + timeout(Duration::from_secs(1), broker_task).await??; + Ok(()) +} From ac9b5cd7908f1db81bf27bb8e1f6d40074f76e78 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sat, 5 Dec 2026 18:29:26 +0100 Subject: [PATCH 14/17] fix --- backend/crates/station/src/event/README.md | 4 +- .../station/src/examples/podDataTest.rs | 519 ------------------ backend/crates/station/src/pipeline.rs | 138 ++--- backend/crates/station/src/pipeline/README.md | 214 +++----- .../station/src/pipeline/accumulator.rs | 17 +- .../crates/station/src/pipeline/frontend.rs | 121 ---- .../crates/station/src/pipeline/message.rs | 162 +++--- backend/crates/station/src/pipeline/tests.rs | 335 +++++------ 8 files changed, 335 insertions(+), 1175 deletions(-) delete mode 100644 backend/crates/station/src/examples/podDataTest.rs delete mode 100644 backend/crates/station/src/pipeline/frontend.rs diff --git a/backend/crates/station/src/event/README.md b/backend/crates/station/src/event/README.md index c03d0e54d..1aad27c93 100644 --- a/backend/crates/station/src/event/README.md +++ b/backend/crates/station/src/event/README.md @@ -219,7 +219,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 @@ -530,7 +530,7 @@ notifications a second through `event`, over 20 times the requirement. 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` + (`backend/message`). 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. diff --git a/backend/crates/station/src/examples/podDataTest.rs b/backend/crates/station/src/examples/podDataTest.rs deleted file mode 100644 index 2ab9d056c..000000000 --- a/backend/crates/station/src/examples/podDataTest.rs +++ /dev/null @@ -1,519 +0,0 @@ -//! Temporary test harness: runs `UDP + synthetic board traffic -> event -> pipeline -> Broker`. -//! Remember to revert with `git checkout -- crates/station/src/main.rs` before committing. - -use std::collections::HashMap; -use std::net::SocketAddr; -use std::path::PathBuf; -use std::process::ExitCode; -use std::sync::Arc; -use std::time::{Duration, SystemTime}; - -use software_core::adj::{self, Adj, LoadError}; -use software_core::git::{self, GitError}; -use software_core::model::{ - AdjId, BoardId, DataPacket, MeasurementKind, OrderPacket, Packet, PacketType, PodData, - ProtectionPacket, ShortTimestamp, Value, -}; -use software_core::net::udp::{UdpConfig, UdpError, spawn_udp}; -use software_core::net::{Event, Notification}; -use software_core::protocol::Index; -use tokio::sync::{broadcast, mpsc}; -use tokio::task::JoinError; -use tokio::time::MissedTickBehavior; -use tracing::{debug, error, info, warn}; -use tracing_subscriber::EnvFilter; - -use station::event::{self, Problem, ProblemKind, Stop, ToLogging, ToPipeline}; -use station::pipeline::{self, Config as PipelineConfig, FrontendEvent}; -use station::websocket::broker::{Broker, Subscriber}; - -const ADJ_BRANCH: &str = "adjv3-software"; -const RECV_BUFFER: usize = 2 * 1024 * 1024; -const SUMMARY_EVERY: Duration = Duration::from_secs(1); -const SHUTDOWN_GRACE: Duration = Duration::from_secs(5); - -#[derive(Debug, thiserror::Error)] -enum StartError { - #[error("could not get the ADJ (branch {ADJ_BRANCH})")] - Download(#[source] GitError), - #[error("the downloaded ADJ has no working directory")] - NoWorkdir, - #[error("could not load the ADJ from {path}")] - Load { - path: PathBuf, - #[source] - source: LoadError, - }, - #[error("the ADJ's general_info.json has no `{0}`")] - MissingInAdj(&'static str), - #[error("could not start tokio")] - Runtime(#[source] std::io::Error), - #[error("could not listen for Ctrl+C")] - CtrlC(#[source] std::io::Error), - #[error("could not open the UDP port")] - Bind(#[source] UdpError), - #[error("the event task failed")] - Event(#[source] JoinError), -} - -fn main() -> ExitCode { - let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); - tracing_subscriber::fmt().with_env_filter(filter).init(); - - match run() { - Ok(code) => code, - Err(error) => { - error!(error = %event::full_message(&error), "stopping"); - ExitCode::FAILURE - } - } -} - -fn run() -> Result { - let adj = download_adj()?; - let addr = udp_addr(&adj)?; - let index = Arc::new(Index::new(&adj.pod_data, Some(&adj.info.message_levels))); - let pod_data = Arc::new(adj.pod_data); - - let runtime = tokio::runtime::Runtime::new().map_err(StartError::Runtime)?; - runtime.block_on(serve(addr, index, pod_data)) -} - -fn download_adj() -> Result { - let commit = git::update_adj(None, ADJ_BRANCH).map_err(StartError::Download)?; - let repo = git::open_repo(None).map_err(StartError::Download)?; - let path = repo.workdir().ok_or(StartError::NoWorkdir)?.to_path_buf(); - - let adj = adj::load_from_dir(&path).map_err(|source| StartError::Load { - path: path.clone(), - source, - })?; - info!( - branch = ADJ_BRANCH, - %commit, - path = %path.display(), - boards = adj.pod_data.boards.len(), - "ADJ loaded" - ); - Ok(adj) -} - -fn udp_addr(adj: &Adj) -> Result { - let ip = adj - .info - .addresses - .get("backend") - .ok_or(StartError::MissingInAdj("addresses.backend"))?; - let port = adj - .info - .ports - .get("UDP") - .ok_or(StartError::MissingInAdj("ports.UDP"))?; - Ok(SocketAddr::new(*ip, port.0)) -} - -async fn serve( - addr: SocketAddr, - index: Arc, - pod_data: Arc, -) -> Result { - let config = event::EventConfig::default(); - let event::Channels { - udp, - tcp, - event: ends, - orders, - problems, - logging, - pipeline: event_pipeline_rx, - } = event::channels(&config); - - drop(tcp); - - let udp_task = spawn_udp( - UdpConfig { - addr, - recv_buffer: RECV_BUFFER, - boards: pod_data.boards_by_ip(), - }, - index.clone(), - udp, - ) - .map_err(StartError::Bind)?; - info!(%addr, "listening on UDP (Ctrl+C to stop)"); - - // Real websocket Broker + console monitor acting as the frontend subscriber. - let (broker, broker_client) = Broker::new(); - let subscriber = broker_client.subscriber(); - let broker_task = tokio::spawn(broker.run()); - let monitor_task = tokio::spawn(monitor_broker(subscriber)); - - // Merge real `event -> pipeline` output with our synthetic board events. - let (pipe_tx, pipe_rx) = mpsc::channel::(128); - let bridge_tx = pipe_tx.clone(); - let bridge_task = tokio::spawn(async move { - let mut rx = event_pipeline_rx; - while let Some(item) = rx.recv().await { - if bridge_tx.send(item).await.is_err() { - break; - } - } - }); - - let (frontend_tx, frontend_rx) = mpsc::channel::(16); - - let logging_task = tokio::spawn(stand_in_logging(logging, pod_data.clone())); - let pipeline_task = pipeline::spawn( - PipelineConfig::default(), - pipe_rx, - frontend_rx, - problems.clone(), - broker_client, - pod_data.clone(), - index.clone(), - ); - let mut event_task = event::spawn(config, ends, pod_data.clone(), index, None); - - // Inject synthetic events using the real ADJ definitions. - let sim_task = tokio::spawn(simulate_traffic( - pod_data, - pipe_tx, - orders, - problems, - frontend_tx, - )); - - let (stop, by_ctrl_c) = tokio::select! { - stop = &mut event_task => (stop, false), - signal = tokio::signal::ctrl_c() => { - signal.map_err(StartError::CtrlC)?; - info!("Ctrl+C, stopping"); - udp_task.abort(); - sim_task.abort(); - (event_task.await, true) - } - }; - udp_task.abort(); - sim_task.abort(); - - let finished = tokio::time::timeout(SHUTDOWN_GRACE, async { - let _ = bridge_task.await; - let _ = logging_task.await; - let _ = pipeline_task.await; - let _ = broker_task.await; - let _ = monitor_task.await; - }) - .await; - if finished.is_err() { - warn!(grace = ?SHUTDOWN_GRACE, "tasks did not finish in time"); - } - - match stop.map_err(StartError::Event)? { - Stop::Fatal(problem) => { - info!(reason = %problem.text, "stopped after a fatal error"); - Ok(ExitCode::FAILURE) - } - Stop::NetGone if by_ctrl_c => { - info!("stopped"); - Ok(ExitCode::SUCCESS) - } - Stop::NetGone => { - error!("UDP stopped on its own"); - Ok(ExitCode::FAILURE) - } - } -} - -/// Feeds a short sequence of realistic ADJ events through `event` and `pipeline`. -async fn simulate_traffic( - pod_data: Arc, - pipe_tx: mpsc::Sender, - orders: mpsc::Sender, - problems: mpsc::Sender, - frontend_tx: mpsc::Sender, -) { - // Pick the first board that declares at least one Data packet in the loaded ADJ. - let Some((board_id, data_id, first_meas_id)) = pod_data.boards.values().find_map(|board| { - board - .packets - .values() - .find_map(|def| match &def.packet_type { - PacketType::Data(defs) if !defs.is_empty() => { - Some((board.id, def.id, defs[0].id)) - } - _ => None, - }) - }) else { - warn!("no Data packets found in ADJ to simulate"); - return; - }; - - let order_id = pod_data - .boards - .values() - .find_map(|board| { - board - .packets - .values() - .find_map(|def| match &def.packet_type { - PacketType::Order(_) => Some(def.id), - _ => None, - }) - }) - .unwrap_or(AdjId(1001)); - - info!( - board = %name(&pod_data, board_id), - data_packet = data_id.0, - order_packet = order_id.0, - "starting synthetic scenario" - ); - - // 1. Frontend connects. - let _ = frontend_tx.send(FrontendEvent::Connected(1)).await; - tokio::time::sleep(Duration::from_millis(200)).await; - - // 2. Board connects -> `connection/update`. - let _ = pipe_tx - .send(ToPipeline::Received(Arc::new(Notification { - board: board_id, - at: SystemTime::now(), - event: Event::Connected, - }))) - .await; - - // 3. Burst of 16 Data packets (1 every 25 ms -> ~4 aggregated 100 ms `podData/update` flushes). - for step in 1_u32..=16 { - let values = match pod_data - .boards - .get(&board_id) - .and_then(|b| b.packets.get(&data_id)) - .map(|def| &def.packet_type) - { - Some(PacketType::Data(defs)) => defs - .iter() - .map(|m| match &m.kind { - MeasurementKind::Numeric { .. } => Value::Number(f64::from(step) * 10.0), - MeasurementKind::Boolean => Value::Bool(step % 2 == 0), - MeasurementKind::Enum { options } => { - let idx = (step as usize) % options.len().max(1); - Value::Enum(options.get(idx).cloned().unwrap_or_default()) - } - }) - .collect(), - _ => Vec::new(), - }; - - let _ = pipe_tx - .send(ToPipeline::Received(Arc::new(Notification { - board: board_id, - at: SystemTime::now(), - event: Event::Received(Packet::Data(DataPacket::new(data_id, values))), - }))) - .await; - - tokio::time::sleep(Duration::from_millis(25)).await; - } - - // 4. Protection packet -> `protection/update`. - let _ = pipe_tx - .send(ToPipeline::Received(Arc::new(Notification { - board: board_id, - at: SystemTime::now(), - event: Event::Received(Packet::Protection(ProtectionPacket { - id: AdjId((1 << 13) | (first_meas_id.0 & 0x1FFF)), - timestamp: ShortTimestamp { - hour: 12, - minute: 30, - second: 45, - subsecond: 0, - }, - value: Value::Number(99.5), - })), - }))) - .await; - tokio::time::sleep(Duration::from_millis(200)).await; - - // 5. Real `event` round-trip: Problem & OrderPacket go through `event -> pipeline -> Broker`. - let _ = problems - .send(Problem::now( - ProblemKind::Shown, - Some(board_id), - "simulated warning through event", - )) - .await; - let _ = orders.send(OrderPacket::new(order_id, vec![])).await; - tokio::time::sleep(Duration::from_millis(200)).await; - - // 6. Board disconnects -> `connection/update`. - let _ = pipe_tx - .send(ToPipeline::Received(Arc::new(Notification { - board: board_id, - at: SystemTime::now(), - event: Event::Disconnected, - }))) - .await; - - info!("synthetic scenario complete — keeping frontend heartbeat alive (press Ctrl+C to stop)"); - - // 7. Keep frontend alive. Comment out this loop to test the 3 s fatal watchdog! - let mut hb = tokio::time::interval(Duration::from_secs(1)); - loop { - hb.tick().await; - if frontend_tx.send(FrontendEvent::Heartbeat(1)).await.is_err() { - break; - } - } -} - -/// Logs every topic published through `websocket::Broker` by `pipeline`. -async fn monitor_broker(sub: Subscriber) { - let mut conn_sub = sub.subscribe_connections(); - let mut data_sub = sub.subscribe_data(); - let msg_sub = sub.subscribe_messages(); - let prot_sub = sub.subscribe_protections(); - let backend_sub = sub.subscribe_backend_messages(); - - let connections = async move { - while conn_sub.changed().await.is_ok() { - let snap = conn_sub.borrow_and_update(); - info!(boards = ?snap.0, "broker -> connection/update"); - } - }; - - let data = async move { - while data_sub.changed().await.is_ok() { - let snap = data_sub.borrow_and_update(); - for pkt in snap.0.values() { - info!( - id = pkt.id.0, - count = pkt.count, - cycle_time_ns = pkt.cycle_time, - measurements = ?pkt.measurement_updates, - "broker -> podData/update" - ); - } - } - }; - - let messages = async move { - let Ok(mut rx) = msg_sub else { return }; - loop { - match rx.recv().await { - Ok(msg) => info!(?msg, "broker -> message/update"), - Err(broadcast::error::RecvError::Lagged(n)) => { - warn!(skipped = n, "message/update lagged"); - } - Err(broadcast::error::RecvError::Closed) => break, - } - } - }; - - let protections = async move { - let Ok(mut rx) = prot_sub else { return }; - loop { - match rx.recv().await { - Ok(prot) => info!(?prot, "broker -> protection/update"), - Err(broadcast::error::RecvError::Lagged(n)) => { - warn!(skipped = n, "protection/update lagged"); - } - Err(broadcast::error::RecvError::Closed) => break, - } - } - }; - - let backend_messages = async move { - let Ok(mut rx) = backend_sub else { return }; - loop { - match rx.recv().await { - Ok(msg) => info!(?msg, "broker -> backend/message"), - Err(broadcast::error::RecvError::Lagged(n)) => { - warn!(skipped = n, "backend/message lagged"); - } - Err(broadcast::error::RecvError::Closed) => break, - } - } - }; - - tokio::join!(connections, data, messages, protections, backend_messages); -} - -async fn stand_in_logging(mut queue: mpsc::Receiver, pod_data: Arc) { - let mut summary = tokio::time::interval(SUMMARY_EVERY); - summary.set_missed_tick_behavior(MissedTickBehavior::Delay); - let mut counts: HashMap = HashMap::new(); - - loop { - tokio::select! { - biased; - _ = summary.tick() => log_summary(&mut counts, &pod_data), - message = queue.recv() => match message { - None => break, - Some(ToLogging::Received(notification)) => { - count_and_trace(¬ification, &mut counts, &pod_data); - } - Some(ToLogging::OrderSent { at, board, order }) => { - let to = order_target(board, &pod_data); - info!(to, id = ?order.id, at = %clock(at), "order sent"); - } - }, - } - } - log_summary(&mut counts, &pod_data); -} - -fn order_target(board: Option, pod_data: &PodData) -> String { - match board { - Some(board) => name(pod_data, board), - None => "every board".to_string(), - } -} - -fn name(pod_data: &PodData, board: BoardId) -> String { - pod_data - .board_name(board) - .map_or_else(|| format!("{board:?}"), str::to_owned) -} - -fn clock(at: SystemTime) -> String { - match at.duration_since(SystemTime::UNIX_EPOCH) { - Ok(since) => format!("{}.{:03}", since.as_secs(), since.subsec_millis()), - Err(_) => "before 1970".to_string(), - } -} - -fn count_and_trace( - notification: &Notification, - counts: &mut HashMap, - pod_data: &PodData, -) { - *counts.entry(notification.board).or_insert(0) += 1; - - match ¬ification.event { - Event::Received(Packet::Data(packet)) => debug!( - board = %name(pod_data, notification.board), - id = ?packet.id, - values = ?packet.values, - "packet" - ), - other => debug!( - board = %name(pod_data, notification.board), - event = ?other, - "notification" - ), - } -} - -fn log_summary(counts: &mut HashMap, pod_data: &PodData) { - let total: u64 = counts.values().sum(); - if total == 0 { - return; - } - let mut per_board: Vec = counts - .iter() - .map(|(&board, count)| format!("{}={count}", name(pod_data, board))) - .collect(); - per_board.sort(); - info!(total, boards = %per_board.join(" "), "packets in the last second"); - counts.clear(); -} \ No newline at end of file diff --git a/backend/crates/station/src/pipeline.rs b/backend/crates/station/src/pipeline.rs index ce5665cb7..1a46d086a 100644 --- a/backend/crates/station/src/pipeline.rs +++ b/backend/crates/station/src/pipeline.rs @@ -1,57 +1,52 @@ -//! Transforms [`crate::event::ToPipeline`] items into frontend WebSocket payloads, -//! publishes them through [`crate::websocket::broker::BrokerClient`], and monitors -//! the `websocket ↔ front` connection state. +//! Transforms [`crate::event::ToPipeline`] items into frontend WebSocket payloads +//! and publishes them through [`crate::websocket::broker::BrokerClient`]. //! //! # Contract //! -//! - **Immediate events.** Connections, protections, board messages, backend -//! problems, and order outcomes are converted and published immediately. +//! - **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. Idle packets are not republished. -//! - **Frontend connection watchdog.** Tracks active frontend sessions reported -//! by `websocket`. Losing the last frontend starts a reconnect grace period -//! (default 3 s); a heartbeat timeout on the last client or expiration of -//! that grace period sends a [`ProblemKind::Fatal`] to `event`. //! - **Wait, don't drop.** Reads continuously from `channels.pipeline` and //! awaits broker capacity instead of dropping decoded events. //! - **Clean shutdown.** When `event` closes the input channel (`None`), any //! pending telemetry is flushed to the broker before the task exits. //! -//! # Topics not handled here +//! # Not handled here //! //! - Frontend-to-backend topics (`order/send`, `logger/enable`, -//! `logger/variables`, `connection/heartbeat`) are consumed by `websocket`. +//! `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 frontend; mod message; mod timestamp; #[cfg(test)] mod tests; -pub use frontend::FrontendEvent; use std::collections::HashMap; - use std::sync::Arc; use std::time::Duration; -use crate::event::{Problem, ProblemKind, ToPipeline}; -use crate::payload::{Connection, ProtectionUpdate, ConnectionUpdate, DataPacketUpdate, DataUpdate}; +use crate::event::ToPipeline; +use crate::payload::{ + Connection, ConnectionUpdate, DataPacketUpdate, DataUpdate, ProtectionUpdate, +}; use crate::websocket::broker::BrokerClient; use accumulator::DataAccumulator; -use frontend::FrontendWatchdog; -use software_core::model::{BoardId, Packet, PodData, AdjId}; +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, sleep_until}; +use tokio::time::{Instant, MissedTickBehavior, interval_at}; use tracing::{error, info, warn}; /// Configuration for the pipeline task. @@ -59,12 +54,6 @@ use tracing::{error, info, warn}; pub struct Config { /// How often accumulated `Data` telemetry is flushed to the broker. pub data_flush_interval: Duration, - /// Maximum time allowed between `connection/heartbeat` keep-alives for a - /// frontend session before it is considered dead. - pub frontend_heartbeat_timeout: Duration, - /// Grace period allowed for a frontend client to reconnect after the last - /// active frontend socket closes before reporting a fatal problem to `event`. - pub frontend_disconnect_timeout: Duration, /// Queue fill percentage (1–100) at which `pipeline` pauses UDP `Data` updates. pub saturation_high_percent: u8, /// Queue fill percentage (0–100) at or below which `pipeline` resumes UDP `Data` updates. @@ -75,47 +64,32 @@ impl Default for Config { fn default() -> Self { Self { data_flush_interval: Duration::from_millis(100), - frontend_heartbeat_timeout: Duration::from_secs(3), - frontend_disconnect_timeout: Duration::from_secs(3), saturation_high_percent: 80, saturation_low_percent: 25, } } } -/// Spawns the pipeline task consuming `rx` (`event`) and `frontend_rx` -/// (`websocket`), publishing payloads to `broker`, and reporting frontend -/// disconnects on `problems`. +/// Spawns the pipeline task consuming `rx` (`event`) and publishing payloads +/// to `broker`. /// /// The task exits cleanly once `rx` closes and pending telemetry is flushed, /// or immediately if `broker` has already shut down. pub fn spawn( config: Config, rx: mpsc::Receiver, - frontend_rx: mpsc::Receiver, - problems: mpsc::Sender, broker: BrokerClient, pod_data: Arc, index: Arc, ) -> JoinHandle<()> { - tokio::spawn(run_loop( - config, - rx, - frontend_rx, - problems, - broker, - pod_data, - index, - )) + tokio::spawn(run_loop(config, rx, broker, pod_data, index)) } -/// Runs the main pipeline event loop, interleaving frontend connection checks, -/// periodic 100 ms telemetry flushes, and incoming [`ToPipeline`] events. +/// Runs the main pipeline loop, interleaving periodic 100 ms telemetry +/// flushes and incoming [`ToPipeline`] items. async fn run_loop( config: Config, mut rx: mpsc::Receiver, - mut frontend_rx: mpsc::Receiver, - problems: mpsc::Sender, broker: BrokerClient, pod_data: Arc, index: Arc, @@ -128,16 +102,11 @@ async fn run_loop( tick.set_missed_tick_behavior(MissedTickBehavior::Skip); let mut accumulator = DataAccumulator::default(); - let mut watchdog = FrontendWatchdog::new( - config.frontend_heartbeat_timeout, - config.frontend_disconnect_timeout, - ); let mut saturation = SaturationState::new( rx.max_capacity(), config.saturation_high_percent, config.saturation_low_percent, ); - let mut frontend_open = true; // Track connection state for every board declared in the ADJ (all start disconnected). let mut board_connections: HashMap = @@ -146,10 +115,10 @@ async fn run_loop( // 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, - ) + broker + .publish_connections(connection_snapshot(&board_connections, &pod_data)) + .await, + ) { return; } @@ -158,39 +127,12 @@ async fn run_loop( let mut latest_data: HashMap = HashMap::new(); loop { - let frontend_deadline = watchdog.deadline(); - // `biased;` polls branches in top-to-bottom order instead of randomly. - // Checking frontend liveness and the 100 ms flush tick first prevents - // sustained high-rate UDP traffic from starving disconnects or flushes. + // Checking the 100 ms flush tick first prevents sustained high-rate + // UDP traffic from starving flushes. tokio::select! { biased; - // 1. Frontend reconnect grace timer expired (only polled while a deadline is active). - _ = async { - if let Some(deadline) = frontend_deadline { - sleep_until(deadline).await; - } - }, if frontend_deadline.is_some() => { - if let Some(reason) = watchdog.on_timeout(Instant::now()) { - report_frontend_fatal(&problems, reason).await; - } - } - // 2. Frontend session lifecycle events forwarded from `websocket`. - fe = frontend_rx.recv(), if frontend_open => { - match fe { - Some(event) => { - if let Some(reason) = watchdog.on_event(event, Instant::now()) { - report_frontend_fatal(&problems, reason).await; - } - } - None => { - // Stop polling once `websocket` drops its sender so a closed - // channel does not win every `biased;` round. - frontend_open = false; - } - } - } - // 3. Periodic 100 ms telemetry flush (skipped while saturated). + // 1. Periodic 100 ms telemetry flush (skipped while saturated). _ = tick.tick() => { if !saturation.is_saturated() && !flush_data(&broker, &index, &mut accumulator, &mut latest_data).await @@ -198,7 +140,7 @@ async fn run_loop( return; } } - // 4. Incoming routed items from `event`. + // 2. Incoming routed items from `event`. item = rx.recv() => { match item { Some(msg) => { @@ -251,18 +193,17 @@ async fn handle_item( ) .await } - // TODO(websocket-merge): If `websocket` / `payload` splits backend problem onto a dedicated `problem/update` topic. - ToPipeline::Problem(problem) => match message::from_problem(problem, pod_data) { - Some(update) => publish_or_log(broker.publish_message(update).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 update = message::from_order_sent(at, board, order, pod_data); - publish_or_log(broker.publish_message(update).await) + 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 update = message::from_order_failed(at, order, reason, pod_data, index); - publish_or_log(broker.publish_message(update).await) + let message = message::from_order_failed(at, &order, &reason, pod_data, index); + publish_or_log(broker.publish_backend_message(message).await) } } } @@ -318,19 +259,6 @@ async fn handle_notification( } } -/// Reports a fatal frontend-disconnect [`Problem`] to `event` so it propagates -/// the pod fault and performs an ordered shutdown. -async fn report_frontend_fatal(problems: &mpsc::Sender, reason: &'static str) { - error!( - reason, - "frontend connection lost, reporting fatal problem to event" - ); - let problem = Problem::now(ProblemKind::Fatal, None, reason); - if problems.send(problem).await.is_err() { - warn!("event problems channel closed before frontend disconnect could be reported"); - } -} - /// Drains all telemetry packets updated during the current window and /// publishes each [`crate::payload::DataPacketUpdate`] to the broker. /// diff --git a/backend/crates/station/src/pipeline/README.md b/backend/crates/station/src/pipeline/README.md index 816937652..0f7cc45b8 100644 --- a/backend/crates/station/src/pipeline/README.md +++ b/backend/crates/station/src/pipeline/README.md @@ -1,27 +1,25 @@ # Pipeline (`station::pipeline`) Transforms [`crate::event::ToPipeline`] items into frontend WebSocket payloads -(`station::payload`), publishes them through -[`crate::websocket::broker::BrokerClient`], and monitors `websocket ↔ front` -session liveness (`connection/heartbeat`). +(`station::payload`) and publishes them through +[`crate::websocket::broker::BrokerClient`]. `event` routes decoded packets and backend outcomes without inspecting their -contents. `pipeline` is the stage that turns those domain events into the exact -shapes the frontend expects: publishing discrete events immediately, tracking -per-board connection state, aggregating high-rate UDP telemetry into 100 ms -windows, and reporting fatal frontend disconnects back to `event`. +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 ─────(channels.pipeline: ToPipeline)────► pipeline - websocket ─(frontend_rx: FrontendEvent)───────► ├── immediate ──► BrokerClient - │ ├── connection/update - │ ├── protection/update - │ └── message/update - ├── 100 ms tick ─► BrokerClient - │ └── podData/update - └── fatal loss ──► event (channels.problems) + event ─(channels.pipeline: ToPipeline)─► pipeline + ├── immediate ──► BrokerClient + │ ├── connection/update + │ ├── protection/update + │ ├── message/update (board messages) + │ └── backend/message (notices, order outcomes) + └── 100 ms tick ─► BrokerClient + └── podData/update ``` ## Files @@ -30,8 +28,7 @@ windows, and reporting fatal frontend disconnects back to `event`. pipeline.rs # module root: Config, spawn, biased select! loop, routing pipeline/ ├── accumulator.rs # 100 ms telemetry windowing (count, cycle_time, last, average) -├── frontend.rs # websocket <-> front keep-alive & reconnect grace watchdog -├── message.rs # MessageUpdate builders (board messages, problems, order outcomes) +├── 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 @@ -39,115 +36,89 @@ pipeline/ ## Input-to-Topic Mapping -| Input | Condition / inner event | Target | Action / method | Delivery | +| Input | Condition / inner event | Topic | Broker method | Delivery | | --- | --- | --- | --- | --- | -| `ToPipeline::Received` | `Event::Connected` / `Event::Disconnected` | `connection/update` | Updates `board_connections`; calls `publish_connection` on change | Immediate | -| `ToPipeline::Received` | `Event::Received(Packet::Data(_))` | `podData/update` | Accumulated; `publish_data` | 100 ms window | +| `ToPipeline::Received` | `Event::Connected` / `Event::Disconnected` | `connection/update` | `publish_connections`, on change | Immediate | +| `ToPipeline::Received` | `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 (logged as warning) | — | -| `ToPipeline::Problem` | `ProblemKind::Shown` → `warning` | `message/update` | `publish_message` | Immediate | -| `ToPipeline::Problem` | `ProblemKind::Fatal` → `fault` | `message/update` | `publish_message` | Immediate | -| `ToPipeline::Problem` | `ProblemKind::Silent` | — | Ignored | — | -| `ToPipeline::OrderSent` | Confirmed TCP write → `info` | `message/update` | `publish_message` | Immediate | -| `ToPipeline::OrderFailed` | Failed TCP write → `warning` | `message/update` | `publish_message` | Immediate | -| `FrontendEvent` | `Connected(id)` / `Heartbeat(id)` / `Disconnected(id)` | `channels.problems` | Renews/tracks liveness; sends `ProblemKind::Fatal` on fatal loss | Immediate / Timer | - -### Topics not handled by `pipeline` - -- **Frontend-to-backend control topics** (`order/send`, `logger/enable`, - `logger/variables`) are handled directly by `websocket`. -- **`logger/response`** is published directly by `logging`. -- **`order/stateOrders`** is not produced yet because `software_core::model::Packet` - has no state-orders packet variant. +| `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` maintains a `HashMap` seeded at startup with every -board declared in `PodData::boards` set to `false` (disconnected). +`pipeline` keeps a `HashMap` seeded at startup with every board +declared in `PodData::boards`, all disconnected. -- On startup, all initial `false` states are published to `connection/update` so - the frontend immediately sees the full board list. -- Subsequent `Event::Connected` and `Event::Disconnected` notifications update - the map and only publish to `BrokerClient` when a board's state actually - changes. +- 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 in place per packet ID -and flushed every `Config::data_flush_interval` (default `100 ms`). - -- **Per-packet statistics:** - - `count`: cumulative number of packets received for that `AdjId` since startup. - - `cycleTime`: mean inter-arrival interval in nanoseconds across packets - received in the current window (`last_at` persists across window boundaries). - - `hexValue`: left empty (`""`), as `Notification` carries decoded `Value`s - rather than raw UDP bytes. -- **Per-measurement updates** (keyed by each measurement's ADJ `alias`): - - Numeric measurements emit `{ "last": f64, "average": f64 }`, where `last` is - the most recent sample and `average` is the arithmetic mean over the window. - - Boolean and enum measurements emit their latest value directly. -- **Idle packets** (no frames received during a window) are skipped on flush; the - WebSocket broker retains their previous snapshot. - -## Frontend Liveness & Keep-Alives (`frontend.rs`) - -`FrontendWatchdog` tracks `websocket ↔ front` session health via `FrontendEvent` -messages keyed by a per-connection session ID (`u64`): - -- **`FrontendEvent::Connected(id)` / `FrontendEvent::Heartbeat(id)`:** registers - or renews session `id`'s keep-alive deadline (`Config::frontend_heartbeat_timeout`, - default `3 s`) and cancels any armed reconnect grace deadline. -- **`FrontendEvent::Disconnected(id)`:** removes session `id`. If it was the - last active session, arms a reconnect grace window - (`Config::frontend_disconnect_timeout`, default `3 s`). -- **Independent session expiry:** if one tab goes silent without closing TCP - while another remains active, only the stale session expires after `3 s`. -- **Fatal reporting:** - - Startup with `0` connected frontends is not fatal; monitoring activates once - at least one frontend connects. - - Losing the last live session to a heartbeat timeout reports - `ProblemKind::Fatal` to `event` (`channels.problems`) immediately (the - heartbeat window already elapsed). - - Failing to reconnect before the post-disconnect grace deadline expires - reports `ProblemKind::Fatal` to `event`. - - Fatal disconnect is reported at most once. +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 names** are resolved from `PodData::boards` (falling back to - `"board-"`). Backend-wide problems use `"backend"`, and broadcast fault - orders (`board = None` or `AdjId(0)`) use `"all"`. -- **Order notices** use the numeric order ID as `name` (`order.id.0.to_string()`), - matching the legacy frontend convention. -- **UTC calendar conversion** uses a zero-dependency civil-date calculation from - `SystemTime`: - - Backend-generated messages (`Problem`, `OrderSent`, `OrderFailed`) populate - `timestamp` from `at`, with `counter` set to milliseconds (`0–999`). - - Board messages (`Packet::Message`) combine the reception calendar date from - `Notification::at` with the board's `ShortTimestamp` (`hour`, `minute`, - `second`) and store its raw `subsecond` byte in `counter`. +- **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 branches in fixed order: - 1. Frontend heartbeat / reconnect timer (`sleep_until`) - 2. Incoming `FrontendEvent` messages from `websocket` - 3. 100 ms telemetry flush tick - 4. Incoming `ToPipeline` items from `event` - - Sustained high-rate UDP traffic cannot starve frontend disconnect detection or - telemetry flushes. +- **Biased `select!` priority:** `run_loop` polls the 100 ms flush tick before + incoming `ToPipeline` items, so sustained high-rate UDP traffic cannot + starve telemetry flushes. - **Wait, don't drop.** `pipeline` reads continuously from `channels.pipeline` and awaits `BrokerClient` capacity rather than dropping decoded events. -- **No network error policy.** Board/socket error classification and fault - propagation belong solely to `event`; `pipeline` only reports frontend loss as - a `ProblemKind::Fatal`. +- **No error policy.** Classifying errors and sending the fault belong to + `event`; `pipeline` only shows what it receives. - **Clean shutdown.** - - When `event` closes `channels.pipeline` (`recv()` returns `None`), `pipeline` - flushes any dirty telemetry in the accumulator to the broker and exits. - - If `BrokerClient` returns `Error::BrokerClosed`, `pipeline` logs the error - and exits immediately. + - When `event` closes `channels.pipeline` (`recv()` returns `None`), + `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 ⑥ closed. ## Usage @@ -157,40 +128,25 @@ use station::pipeline::{self, Config}; let pipeline_handle = pipeline::spawn( Config::default(), channels.pipeline, - frontend_rx, - channels.problems.clone(), broker_client, pod_data, index, ); ``` -## Pending Integration (after `websocket` merges) - -- Wire `websocket` session transitions (`Connected(id)`, `Disconnected(id)`) and - inbound `connection/heartbeat` messages (`Heartbeat(id)`) into `frontend_rx`, - and remove duplicate liveness timers from `websocket`. -- If `websocket` / `payload` splits backend problems onto a dedicated - `problem/update` topic, switch the `ToPipeline::Problem` arm in `pipeline.rs` - from `publish_message` to `publish_problem`. - ## Tests Unit tests in `pipeline/tests.rs` wire `pipeline::spawn` to a real `Broker` -instance (no sockets required) and verify: +(no sockets) and check: -- Immediate forwarding of board connections, protections, board messages, - problems, and order outcomes (`OrderSent` / `OrderFailed`). +- immediate forwarding of board connections, protections and board messages, + with `origin`/`name` as in `payload/example/message.json`; +- 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). -- Frontend reconnect grace period cancellation and `ProblemKind::Fatal` emission - on expiry. -- Per-session `connection/heartbeat` renewal, independent stale-session expiry, - and immediate `ProblemKind::Fatal` when the last live frontend times out. + window `average`, `last`, and flush on shutdown); - UTC calendar conversion on epoch and leap-day timestamps. -Run them with: - ```sh cargo test -p station pipeline -``` \ No newline at end of file +``` diff --git a/backend/crates/station/src/pipeline/accumulator.rs b/backend/crates/station/src/pipeline/accumulator.rs index e977eef7e..a02d56f65 100644 --- a/backend/crates/station/src/pipeline/accumulator.rs +++ b/backend/crates/station/src/pipeline/accumulator.rs @@ -4,7 +4,7 @@ use std::time::SystemTime; use crate::payload::{DataPacketUpdate, MeasurementUpdate}; use software_core::model::{AdjId, DataPacket, PacketType, Value}; use software_core::protocol::Index; -use tracing::warn; +use tracing::debug; /// Accumulates `Data` packets per packet ID across each flush window. #[derive(Debug, Default)] @@ -98,13 +98,17 @@ impl MeasurementAccumulator { 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 { - warn!(id = packet.id.0, "unknown data packet id in index"); + debug!(id = packet.id.0, "unknown data packet id in index"); return; }; let PacketType::Data(defs) = &def.packet_type else { - warn!( + debug!( id = packet.id.0, "packet id in DataPacket does not map to PacketType::Data" ); @@ -112,7 +116,7 @@ impl DataAccumulator { }; if packet.values.len() != defs.len() { - warn!( + debug!( id = packet.id.0, expected = defs.len(), actual = packet.values.len(), @@ -188,10 +192,11 @@ impl DataAccumulator { // `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()); + 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.clone(), acc.into_update()); + measurement_updates.insert(measurement_def.id, acc.into_update()); } } diff --git a/backend/crates/station/src/pipeline/frontend.rs b/backend/crates/station/src/pipeline/frontend.rs deleted file mode 100644 index d7d33dcf5..000000000 --- a/backend/crates/station/src/pipeline/frontend.rs +++ /dev/null @@ -1,121 +0,0 @@ -//! Tracks `websocket ↔ front` session liveness and keep-alives (`connection/heartbeat`). -//! -//! `websocket` forwards session lifecycle transitions and keep-alive signals via -//! [`FrontendEvent`], and [`FrontendWatchdog`] owns both the per-session -//! heartbeat timer and the post-disconnect reconnect grace timer. - -use std::collections::HashMap; -use std::time::Duration; - -use tokio::time::Instant; - -/// Frontend session events forwarded from `websocket` to `pipeline`. -/// -/// Each active WebSocket connection is identified by a unique session ID (`u64`) -/// so a silently dead tab expires on its own without blocking disconnect detection. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum FrontendEvent { - /// A frontend WebSocket client connected. - Connected(u64), - /// A keep-alive (`connection/heartbeat`) arrived from this frontend session. - Heartbeat(u64), - /// A frontend WebSocket client disconnected. If it was the last live - /// session, the reconnect grace window starts. - Disconnected(u64), -} - -/// Tracks active frontend sessions, their keep-alive deadlines, and the -/// post-disconnect reconnect deadline. -#[derive(Debug)] -pub(super) struct FrontendWatchdog { - heartbeat_timeout: Duration, - grace_timeout: Duration, - /// Active sessions mapped to the instant their keep-alive expires. - sessions: HashMap, - /// True once at least one frontend has connected (startup with 0 clients is not fatal). - had_client: bool, - /// Armed while waiting for a client to reconnect after all sessions closed cleanly. - reconnect_deadline: Option, - /// Ensures a fatal disconnect problem is reported at most once. - reported_fatal: bool, -} - -impl FrontendWatchdog { - /// Creates a watchdog with separate keep-alive and post-disconnect grace timeouts. - pub(super) fn new(heartbeat_timeout: Duration, grace_timeout: Duration) -> Self { - Self { - heartbeat_timeout, - grace_timeout, - sessions: HashMap::new(), - had_client: false, - reconnect_deadline: None, - reported_fatal: false, - } - } - - /// Returns the next timer deadline that `run_loop` should wake up for: - /// either the reconnect grace deadline or the earliest session heartbeat expiry. - pub(super) fn deadline(&self) -> Option { - if self.reported_fatal { - return None; - } - self.reconnect_deadline - .or_else(|| self.sessions.values().copied().min()) - } - - /// Processes a [`FrontendEvent`] at `now`. - /// - /// Returns `Some(reason)` only when a zero-duration grace timeout makes a - /// disconnect fatal immediately. - pub(super) fn on_event(&mut self, event: FrontendEvent, now: Instant) -> Option<&'static str> { - match event { - FrontendEvent::Connected(id) | FrontendEvent::Heartbeat(id) => { - self.sessions.insert(id, now + self.heartbeat_timeout); - self.had_client = true; - // A live or returning client cancels any pending reconnect deadline. - self.reconnect_deadline = None; - None - } - FrontendEvent::Disconnected(id) => { - self.sessions.remove(&id); - if self.had_client && self.sessions.is_empty() && !self.reported_fatal { - if self.grace_timeout.is_zero() { - self.reported_fatal = true; - return Some("all frontend connections lost"); - } - self.reconnect_deadline = Some(now + self.grace_timeout); - } - None - } - } - } - - /// Processes an elapsed timer at `now`, expiring stale heartbeats and - /// checking the reconnect grace deadline. - pub(super) fn on_timeout(&mut self, now: Instant) -> Option<&'static str> { - if self.reported_fatal { - return None; - } - - if let Some(deadline) = self.reconnect_deadline - && now >= deadline - { - self.reconnect_deadline = None; - if self.had_client && self.sessions.is_empty() { - self.reported_fatal = true; - return Some("all frontend connections lost (reconnect timeout expired)"); - } - } - - let before = self.sessions.len(); - self.sessions.retain(|_, expires_at| *expires_at > now); - if before > 0 && self.sessions.is_empty() { - // The heartbeat timeout already elapsed the disconnect window, so - // losing the last live session to a missed keep-alive is fatal immediately. - self.reported_fatal = true; - return Some("last frontend connection timed out on heartbeat"); - } - - None - } -} diff --git a/backend/crates/station/src/pipeline/message.rs b/backend/crates/station/src/pipeline/message.rs index 09e7f3676..5e514117a 100644 --- a/backend/crates/station/src/pipeline/message.rs +++ b/backend/crates/station/src/pipeline/message.rs @@ -1,25 +1,35 @@ use std::time::SystemTime; use super::timestamp; -use crate::event::{Problem, ProblemKind}; -use crate::payload::{MessagePayload, MessageUpdate}; -use software_core::model::{MessageLevel, AdjId, BoardId, MessagePacket, OrderPacket, PacketType, PodData}; +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; -/// Looks up a board's human-readable name from [`PodData`], falling back to -/// `"board-"` if the ID is absent. +/// 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 { - // `map_or_else` evaluates the fallback closure lazily so `"board-"` is - // only allocated when the lookup misses. pod_data - .boards - .get(&board) - .map_or_else(|| format!("board-{}", board.0), |b| b.name.clone()) + .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 frontend -/// [`MessageUpdate`], resolving severity from the ADJ [`Index`]. +/// 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, @@ -27,106 +37,94 @@ pub(super) fn from_board_message( pod_data: &PodData, index: &Index, ) -> MessageUpdate { - let kind = match index.packet(message.id) { - Some(def) => match def.packet_type { - PacketType::Message(level) => MessageLevel::from(level), - _ => { - warn!( - id = message.id.0, - "message packet id does not map to PacketType::Message" - ); - MessageLevel::Info - } - }, + 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 } }; - let name = if message.origin.is_empty() { - message.id.0.to_string() - } else { - message.origin.clone() - }; - MessageUpdate { kind, - payload: MessagePayload::Text(message.message.clone()), + payload: message.message.clone(), board: board_name(pod_data, board), - origin: String::new(), - name, + origin: message.origin.clone(), + name: kind.name().to_owned(), timestamp: timestamp::from_short(at, message.timestamp), } } -/// Converts a backend [`Problem`] into a [`MessageUpdate`], returning `None` -/// for [`ProblemKind::Silent`] problems that should not be shown on the front. -pub(super) fn from_problem(problem: Problem, pod_data: &PodData) -> Option { - let kind = match problem.kind { - ProblemKind::Shown => MessageLevel::Warning, - ProblemKind::Fatal => MessageLevel::Fault, - ProblemKind::Silent => return None, +/// 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, }; - let board = problem - .board - .map_or_else(|| "backend".to_string(), |id| board_name(pod_data, id)); - - Some(MessageUpdate { + Some(BackendMessage::new( kind, - payload: MessagePayload::Text(problem.text), - board, - origin: String::new(), - name: "backend".to_string(), - timestamp: timestamp::from_system_time(problem.at), - }) + notice.board.map(|board| board_name(pod_data, board)), + notice.text, + timestamp::from_system_time(notice.at), + )) } -/// Builds an informational [`MessageUpdate`] confirming that TCP wrote an -/// order. Uses `"all"` as the board label for broadcast fault orders (`None`). +/// 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, + order: &OrderPacket, pod_data: &PodData, -) -> MessageUpdate { - let board_label = board.map_or_else(|| "all".to_string(), |id| board_name(pod_data, id)); + 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"), + }; - MessageUpdate { - kind: MessageLevel::Info, - payload: MessagePayload::Text(format!("Order {} sent", order.id.0)), - board: board_label, - origin: String::new(), - name: order.id.0.to_string(), - timestamp: timestamp::from_system_time(at), - } + BackendMessage::new( + MessageLevel::Info, + board.map(|board| board_name(pod_data, board)), + text, + timestamp::from_system_time(at), + ) } -/// Builds a warning [`MessageUpdate`] explaining why an order failed to send. -/// Resolves the target board from the ADJ [`Index`], or `"all"` for fault ID 0. +/// 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: String, + order: &OrderPacket, + reason: &str, pod_data: &PodData, index: &Index, -) -> MessageUpdate { - // Order ID 0 is the reserved broadcast fault order targeting every board. - let board_label = if order.id == AdjId(0) { - "all".to_string() - } else if let Some(def) = index.packet(order.id) { - board_name(pod_data, def.board) +) -> BackendMessage { + let board = if order.id == FAULT_ID { + None } else { - "backend".to_string() + index + .packet(order.id) + .map(|def| board_name(pod_data, def.board)) }; - MessageUpdate { - kind: MessageLevel::Warning, - payload: MessagePayload::Text(reason), - board: board_label, - origin: String::new(), - name: order.id.0.to_string(), - timestamp: timestamp::from_system_time(at), - } + 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 index dc0146bc3..3f899ef35 100644 --- a/backend/crates/station/src/pipeline/tests.rs +++ b/backend/crates/station/src/pipeline/tests.rs @@ -6,18 +6,16 @@ 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 + 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::{Config, FrontendEvent, spawn, timestamp}; -use crate::event::{Problem, ProblemKind, ToPipeline}; -use crate::payload::{ - MeasurementUpdate, MessagePayload, MessageTimestamp, ProtectionUpdate, -}; +use super::{Config, spawn, timestamp}; +use crate::event::{Notice, NoticeKind, ToPipeline}; +use crate::payload::{MeasurementUpdate, MessageTimestamp, ProtectionUpdate}; use crate::websocket::broker::Broker; /// Builds a minimal ADJ fixture with one board (`PCU`, ID 5) containing a @@ -94,7 +92,7 @@ fn sample_fixture() -> (Arc, Arc) { /// Verifies that every non-telemetry `ToPipeline` variant is transformed and /// forwarded to its corresponding broker topic immediately. #[tokio::test] -async fn forwards_connections_protections_messages_problems_and_orders_immediately() +async fn forwards_connections_protections_and_board_messages_immediately() -> Result<(), Box> { let (pod_data, index) = sample_fixture(); let (broker, client) = Broker::new(); @@ -102,20 +100,11 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate 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 (_fe_tx, fe_rx) = mpsc::channel(16); - let (problems_tx, _problems_rx) = mpsc::channel(16); - let pipe_task = spawn( - Config::default(), - rx, - fe_rx, - problems_tx, - client, - pod_data, - index, - ); + let pipe_task = spawn(Config::default(), rx, client, pod_data, index); // 1. Connection update tx.send(ToPipeline::Received(Arc::new(Notification { @@ -177,61 +166,117 @@ async fn forwards_connections_protections_messages_problems_and_orders_immediate })), }))) .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.name, "pcu.c"); - assert_eq!( - got_msg.payload, - MessagePayload::Text("temp high".to_string()) - ); + 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); - // 4. Problem (Fatal -> Fault) - tx.send(ToPipeline::Problem(Problem { - at: UNIX_EPOCH + Duration::from_secs(1_700_000_003), - board: Some(BoardId(5)), - kind: ProblemKind::Fatal, - text: "decode failed".to_string(), - })) - .await?; - let got_problem = timeout(Duration::from_secs(1), msg_sub.recv()).await??; - assert_eq!(got_problem.kind, MessageLevel::Fault); - assert_eq!(got_problem.board, "PCU"); - assert_eq!( - got_problem.payload, - MessagePayload::Text("decode failed".to_string()) - ); + drop(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 pipe_task = spawn(Config::default(), 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); + } - // 5. OrderSent & OrderFailed + // 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: UNIX_EPOCH + Duration::from_secs(1_700_000_004), + at, board: Some(BoardId(5)), order: OrderPacket::new(AdjId(1001), vec![]), }) .await?; - let got_sent = timeout(Duration::from_secs(1), msg_sub.recv()).await??; - assert_eq!(got_sent.kind, MessageLevel::Info); - assert_eq!(got_sent.name, "1001"); - assert_eq!(got_sent.board, "PCU"); - + tx.send(ToPipeline::OrderSent { + at, + board: None, + order: OrderPacket::new(AdjId(0), vec![]), + }) + .await?; tx.send(ToPipeline::OrderFailed { - at: UNIX_EPOCH + Duration::from_secs(1_700_000_005), + at, order: OrderPacket::new(AdjId(1001), vec![]), - reason: "board disconnected".to_string(), + reason: "PCU is not connected".to_string(), }) .await?; - let got_failed = timeout(Duration::from_secs(1), msg_sub.recv()).await??; - assert_eq!(got_failed.kind, MessageLevel::Warning); - assert_eq!(got_failed.name, "1001"); - assert_eq!( - got_failed.payload, - MessagePayload::Text("board disconnected".to_string()) - ); + 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); 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(()) } @@ -249,17 +294,7 @@ async fn batches_data_every_100ms_with_window_average_last_and_cycle_time() let broker_task = tokio::spawn(broker.run()); let (tx, rx) = mpsc::channel(32); - let (_fe_tx, fe_rx) = mpsc::channel(16); - let (problems_tx, _problems_rx) = mpsc::channel(16); - let pipe_task = spawn( - Config::default(), - rx, - fe_rx, - problems_tx, - client, - pod_data, - index, - ); + let pipe_task = spawn(Config::default(), rx, client, pod_data, index); tokio::task::yield_now().await; let t0 = UNIX_EPOCH + Duration::from_secs(1_700_000_000); @@ -286,9 +321,9 @@ async fn batches_data_every_100ms_with_window_average_last_and_cycle_time() } tokio::task::yield_now().await; - // Advance once to trigger pipeline's 100 ms flush into the broker, yield - // twice so both tasks process the queued update, then advance again to - // trigger the broker's own 100 ms batch flush to `watch` subscribers. + // 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; @@ -348,122 +383,8 @@ async fn batches_data_every_100ms_with_window_average_last_and_cycle_time() Ok(()) } -/// Verifies that reconnecting within the 3 s grace window cancels the fatal -/// disconnect, while staying disconnected past 3 s reports `ProblemKind::Fatal`. -#[tokio::test(start_paused = true)] -async fn frontend_disconnect_allows_reconnect_and_reports_fatal_after_grace_period() --> Result<(), Box> { - let (pod_data, index) = sample_fixture(); - let (broker, client) = Broker::new(); - let broker_task = tokio::spawn(broker.run()); - - let (tx, rx) = mpsc::channel(16); - let (fe_tx, fe_rx) = mpsc::channel(16); - let (problems_tx, mut problems_rx) = mpsc::channel(16); - let pipe_task = spawn( - Config::default(), - rx, - fe_rx, - problems_tx, - client, - pod_data, - index, - ); - tokio::task::yield_now().await; - - // Session 1 connects, disconnects, then session 2 connects after 2 s (within 3 s grace). - fe_tx.send(FrontendEvent::Connected(1)).await?; - fe_tx.send(FrontendEvent::Disconnected(1)).await?; - tokio::task::yield_now().await; - advance(Duration::from_secs(2)).await; - fe_tx.send(FrontendEvent::Connected(2)).await?; - tokio::task::yield_now().await; - - // Advance 2 s (past session 1's old 3 s grace deadline, before session 2's heartbeat expiry). - advance(Duration::from_secs(2)).await; - assert!( - problems_rx.try_recv().is_err(), - "reconnecting within the grace period must cancel the fatal problem" - ); - - // Session 2 disconnects and does not return within 3 s. - fe_tx.send(FrontendEvent::Disconnected(2)).await?; - tokio::task::yield_now().await; - advance(Duration::from_millis(2_999)).await; - assert!(problems_rx.try_recv().is_err()); - - advance(Duration::from_millis(1)).await; - let problem = timeout(Duration::from_millis(10), problems_rx.recv()) - .await? - .ok_or("expected fatal problem on reconnect timeout")?; - assert_eq!(problem.kind, ProblemKind::Fatal); - assert_eq!(problem.board, None); - - drop(tx); - timeout(Duration::from_secs(1), pipe_task).await??; - timeout(Duration::from_secs(1), broker_task).await??; - Ok(()) -} - -/// Verifies that `connection/heartbeat` keep-alives renew a session's 3 s -/// deadline, stale sessions expire independently, and losing the last live -/// session to a heartbeat timeout reports `ProblemKind::Fatal` immediately. -#[tokio::test(start_paused = true)] -async fn frontend_heartbeat_renews_liveness_and_expires_last_session_as_fatal() --> Result<(), Box> { - let (pod_data, index) = sample_fixture(); - let (broker, client) = Broker::new(); - let broker_task = tokio::spawn(broker.run()); - - let (tx, rx) = mpsc::channel(16); - let (fe_tx, fe_rx) = mpsc::channel(16); - let (problems_tx, mut problems_rx) = mpsc::channel(16); - let pipe_task = spawn( - Config::default(), - rx, - fe_rx, - problems_tx, - client, - pod_data, - index, - ); - tokio::task::yield_now().await; - - // Two sessions connect at t = 0 (both expire at t = 3 s). - fe_tx.send(FrontendEvent::Connected(1)).await?; - fe_tx.send(FrontendEvent::Connected(2)).await?; - tokio::task::yield_now().await; - - // At t = 2 s, session 1 sends a keep-alive (now expires at t = 5 s); session 2 goes silent. - advance(Duration::from_secs(2)).await; - fe_tx.send(FrontendEvent::Heartbeat(1)).await?; - tokio::task::yield_now().await; - - // At t = 3 s, session 2 times out, but session 1 is still alive -> not fatal. - advance(Duration::from_secs(1)).await; - tokio::task::yield_now().await; - assert!(problems_rx.try_recv().is_err()); - - // At t = 4.999 s, session 1 is still within its keep-alive window. - advance(Duration::from_millis(1_999)).await; - assert!(problems_rx.try_recv().is_err()); - - // At t = 5.000 s, session 1 expires -> last live frontend lost, fatal immediately. - advance(Duration::from_millis(1)).await; - let problem = timeout(Duration::from_millis(10), problems_rx.recv()) - .await? - .ok_or("expected fatal problem when last frontend heartbeat expires")?; - assert_eq!(problem.kind, ProblemKind::Fatal); - assert_eq!(problem.board, None); - - drop(tx); - timeout(Duration::from_secs(1), pipe_task).await??; - timeout(Duration::from_secs(1), broker_task).await??; - Ok(()) -} - /// Verifies `timestamp::from_system_time` on boundary dates (Unix epoch and -/// a Gregorian leap day with millisecond counter). +/// 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); @@ -501,41 +422,33 @@ fn utc_calendar_conversion_handles_epoch_and_leap_day() { /// processing `Packet::Data` once the backlog drops below the low-water mark. #[tokio::test(start_paused = true)] async fn pauses_udp_data_when_saturated_and_resumes_when_unsaturated() - -> Result<(), Box> { +-> Result<(), Box> { let (pod_data, index) = sample_fixture(); let (broker, client) = Broker::new(); let sub = client.subscriber(); let mut data_sub = sub.subscribe_data(); - let mut msg_sub = sub.subscribe_messages()?; + let mut backend_sub = sub.subscribe_backend_messages()?; let broker_task = tokio::spawn(broker.run()); // Capacity 16 -> default high_water = 13 (80%), low_water = 4 (25%). let (tx, rx) = mpsc::channel(16); - let (_fe_tx, fe_rx) = mpsc::channel(16); - let (problems_tx, _problems_rx) = mpsc::channel(16); - let pipe_task = spawn( - Config::default(), - rx, - fe_rx, - problems_tx, - client, - pod_data, - index, - ); + let pipe_task = spawn(Config::default(), rx, client, pod_data, index); let t0 = UNIX_EPOCH + Duration::from_secs(1_700_000_000); - let send_data = |step: u32| ToPipeline::Received(Arc::new(Notification { - board: BoardId(5), - at: t0 + Duration::from_millis(u64::from(step) * 5), - event: Event::Received(Packet::Data(DataPacket::new( - AdjId(551), - vec![ - Value::Number(f64::from(step)), - Value::Bool(true), - Value::Enum("Idle".to_string()), - ], - ))), - })); + let send_data = |step: u32| { + ToPipeline::Received(Arc::new(Notification { + board: BoardId(5), + at: t0 + Duration::from_millis(u64::from(step) * 5), + event: Event::Received(Packet::Data(DataPacket::new( + AdjId(551), + vec![ + Value::Number(f64::from(step)), + Value::Bool(true), + Value::Enum("Idle".to_string()), + ], + ))), + })) + }; // Enqueue 14 items before `pipe_task` runs (>= high_water 13): // 7 Data frames -> 1 OrderSent -> 6 Data frames. @@ -547,14 +460,14 @@ async fn pauses_udp_data_when_saturated_and_resumes_when_unsaturated() board: Some(BoardId(5)), order: OrderPacket::new(AdjId(1001), vec![]), }) - .await?; + .await?; for step in 8..=13 { tx.send(send_data(step)).await?; } // OrderSent must still be forwarded immediately while saturated. - let got_sent = timeout(Duration::from_secs(1), msg_sub.recv()).await??; - assert_eq!(got_sent.name, "1001"); + let got_sent = timeout(Duration::from_secs(1), backend_sub.recv()).await??; + assert_eq!(got_sent.text, "Order Start sent"); // Flush the 100 ms window: frames 1..=8 were dropped while saturated, // and frames 9..=13 were processed after the queue drained to <= 4. From c2facbdbd0ba199d4272d88ddbfe8b57a09370d6 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sat, 5 Dec 2026 19:28:30 +0100 Subject: [PATCH 15/17] fix(backend, pipeline): remove saturation status --- backend/crates/station/src/event.rs | 35 +++- backend/crates/station/src/event/README.md | 86 +++++--- .../crates/station/src/event/manual_tests.rs | 18 +- backend/crates/station/src/event/router.rs | 67 +++++- backend/crates/station/src/event/tests.rs | 119 ++++++++++- backend/crates/station/src/main.rs | 43 +++- backend/crates/station/src/pipeline.rs | 193 ++++++------------ backend/crates/station/src/pipeline/README.md | 47 +++-- backend/crates/station/src/pipeline/tests.rs | 175 +++++++--------- 9 files changed, 461 insertions(+), 322 deletions(-) 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 1aad27c93..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 @@ -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 - (`backend/message`). 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/main.rs b/backend/crates/station/src/main.rs index ab048ae59..ae3e0befb 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -163,6 +163,7 @@ async fn serve( notices, logging, pipeline, + pipeline_data, } = event::channels(&config); // Not built yet: TCP, websocket, and modules that report notices. @@ -182,7 +183,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 +254,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 +319,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 index 1a46d086a..ec8823187 100644 --- a/backend/crates/station/src/pipeline.rs +++ b/backend/crates/station/src/pipeline.rs @@ -1,5 +1,9 @@ -//! Transforms [`crate::event::ToPipeline`] items into frontend WebSocket payloads -//! and publishes them through [`crate::websocket::broker::BrokerClient`]. +//! 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 //! @@ -9,11 +13,14 @@ //! - **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. Idle packets are not republished. -//! - **Wait, don't drop.** Reads continuously from `channels.pipeline` and -//! awaits broker capacity instead of dropping decoded events. -//! - **Clean shutdown.** When `event` closes the input channel (`None`), any -//! pending telemetry is flushed to the broker before the task exits. +//! `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 //! @@ -47,49 +54,45 @@ use software_core::protocol::Index; use tokio::sync::mpsc; use tokio::task::JoinHandle; use tokio::time::{Instant, MissedTickBehavior, interval_at}; -use tracing::{error, info, warn}; +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, - /// Queue fill percentage (1–100) at which `pipeline` pauses UDP `Data` updates. - pub saturation_high_percent: u8, - /// Queue fill percentage (0–100) at or below which `pipeline` resumes UDP `Data` updates. - pub saturation_low_percent: u8, } impl Default for Config { fn default() -> Self { Self { data_flush_interval: Duration::from_millis(100), - saturation_high_percent: 80, - saturation_low_percent: 25, } } } -/// Spawns the pipeline task consuming `rx` (`event`) and publishing payloads -/// to `broker`. +/// Spawns the pipeline task consuming `rx` (⑥) and `data_rx` (⑨), both from +/// `event`, and publishing payloads to `broker`. /// -/// The task exits cleanly once `rx` closes and pending telemetry is flushed, -/// or immediately if `broker` has already shut down. +/// 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, broker, pod_data, index)) + tokio::spawn(run_loop(config, rx, data_rx, broker, pod_data, index)) } /// Runs the main pipeline loop, interleaving periodic 100 ms telemetry -/// flushes and incoming [`ToPipeline`] items. +/// 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, @@ -102,11 +105,6 @@ async fn run_loop( tick.set_missed_tick_behavior(MissedTickBehavior::Skip); let mut accumulator = DataAccumulator::default(); - let mut saturation = SaturationState::new( - rx.max_capacity(), - config.saturation_high_percent, - config.saturation_low_percent, - ); // Track connection state for every board declared in the ADJ (all start disconnected). let mut board_connections: HashMap = @@ -126,50 +124,57 @@ async fn run_loop( // Holds the latest snapshot per packet ID because `Broker::publish_data` replaces the whole map. let mut latest_data: HashMap = HashMap::new(); - loop { - // `biased;` polls branches in top-to-bottom order instead of randomly. - // Checking the 100 ms flush tick first prevents sustained high-rate - // UDP traffic from starving flushes. + // 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 (skipped while saturated). + // 1. Periodic 100 ms telemetry flush. _ = tick.tick() => { - if !saturation.is_saturated() - && !flush_data(&broker, &index, &mut accumulator, &mut latest_data).await + 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; } } - // 2. Incoming routed items from `event`. - item = rx.recv() => { - match item { - Some(msg) => { - saturation.observe(rx.len()); - if saturation.is_saturated() && is_udp_data(&msg) { - saturation.record_drop(); - continue; - } - if !handle_item( - msg, - &broker, - &pod_data, - &index, - &mut accumulator, - &mut board_connections, - ) - .await - { - return; - } - } - None => { - let _ = flush_data(&broker, &index, &mut accumulator, &mut latest_data).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. @@ -208,9 +213,8 @@ async fn handle_item( } } -/// Maps a wire-level [`Notification`] (connection transition or decoded packet) -/// to its WebSocket topic or the 100 ms telemetry accumulator. -/// +/// 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( @@ -230,6 +234,8 @@ async fn handle_notification( 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 @@ -306,68 +312,3 @@ fn connection_snapshot( .collect(), ) } - -/// Returns `true` for high-rate UDP telemetry frames that can be shed while saturated. -fn is_udp_data(item: &ToPipeline) -> bool { - matches!( - item, - ToPipeline::Received(notification) - if matches!(notification.event, Event::Received(Packet::Data(_))) - ) -} - -/// Tracks channel-backlog saturation with hysteresis so `pipeline` pauses UDP -/// `Data` updates under heavy load without dropping discrete events. -struct SaturationState { - high_water: usize, - low_water: usize, - saturated: bool, - dropped_data: u64, -} - -impl SaturationState { - fn new(capacity: usize, high_percent: u8, low_percent: u8) -> Self { - let high_pct = usize::from(high_percent.clamp(1, 100)); - let low_pct = usize::from(low_percent.min(high_percent)); - let high_water = (capacity * high_pct).div_ceil(100).max(1); - let low_water = ((capacity * low_pct) / 100).min(high_water.saturating_sub(1)); - Self { - high_water, - low_water, - saturated: false, - dropped_data: 0, - } - } - - fn is_saturated(&self) -> bool { - self.saturated - } - - /// Updates saturation state using `queued_after_recv` (items still waiting - /// in `rx` immediately after popping one item). - fn observe(&mut self, queued_after_recv: usize) { - let depth = queued_after_recv.saturating_add(1); - if !self.saturated && depth >= self.high_water { - self.saturated = true; - self.dropped_data = 0; - warn!( - queued = depth, - high_water = self.high_water, - "pipeline saturated; pausing UDP data updates" - ); - } else if self.saturated && queued_after_recv <= self.low_water { - self.saturated = false; - info!( - queued = queued_after_recv, - low_water = self.low_water, - dropped_data = self.dropped_data, - "pipeline unsaturated; resuming UDP data updates" - ); - self.dropped_data = 0; - } - } - - fn record_drop(&mut self) { - self.dropped_data = self.dropped_data.saturating_add(1); - } -} diff --git a/backend/crates/station/src/pipeline/README.md b/backend/crates/station/src/pipeline/README.md index 0f7cc45b8..2b91874be 100644 --- a/backend/crates/station/src/pipeline/README.md +++ b/backend/crates/station/src/pipeline/README.md @@ -1,8 +1,10 @@ # Pipeline (`station::pipeline`) -Transforms [`crate::event::ToPipeline`] items into frontend WebSocket payloads +Transforms what `event` routes to the front into frontend WebSocket payloads (`station::payload`) and publishes them through -[`crate::websocket::broker::BrokerClient`]. +[`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 @@ -12,14 +14,14 @@ connection state, and aggregates high-rate UDP telemetry into 100 ms windows. ## Overview ```text - event ─(channels.pipeline: ToPipeline)─► pipeline - ├── immediate ──► BrokerClient - │ ├── connection/update - │ ├── protection/update - │ ├── message/update (board messages) - │ └── backend/message (notices, order outcomes) - └── 100 ms tick ─► BrokerClient - └── podData/update + 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 @@ -39,7 +41,7 @@ pipeline/ | Input | Condition / inner event | Topic | Broker method | Delivery | | --- | --- | --- | --- | --- | | `ToPipeline::Received` | `Event::Connected` / `Event::Disconnected` | `connection/update` | `publish_connections`, on change | Immediate | -| `ToPipeline::Received` | `Event::Received(Packet::Data(_))` | `podData/update` | `publish_data` | 100 ms window | +| ⑨ 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) | — | @@ -106,19 +108,23 @@ flushed every `Config::data_flush_interval` (default `100 ms`). ## Loop Priority, Contract & Shutdown -- **Biased `select!` priority:** `run_loop` polls the 100 ms flush tick before - incoming `ToPipeline` items, so sustained high-rate UDP traffic cannot - starve telemetry flushes. -- **Wait, don't drop.** `pipeline` reads continuously from `channels.pipeline` - and awaits `BrokerClient` capacity rather than dropping decoded events. +- **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.** - - When `event` closes `channels.pipeline` (`recv()` returns `None`), + - 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 ⑥ closed. + error and exits immediately; `event` then sees ⑥ and ⑨ closed. ## Usage @@ -127,7 +133,8 @@ use station::pipeline::{self, Config}; let pipeline_handle = pipeline::spawn( Config::default(), - channels.pipeline, + channels.pipeline, // ⑥ + channels.pipeline_data, // ⑨ broker_client, pod_data, index, @@ -145,6 +152,8 @@ Unit tests in `pipeline/tests.rs` wire `pipeline::spawn` to a real `Broker` nothing the backend produces on `message/update`; - 100 ms windowing for `Packet::Data` (cumulative `count`, mean `cycleTime`, window `average`, `last`, and flush on shutdown); +- telemetry still read after ⑥ closes, and the task ending, with a final + flush, only once both queues are closed; - UTC calendar conversion on epoch and leap-day timestamps. ```sh diff --git a/backend/crates/station/src/pipeline/tests.rs b/backend/crates/station/src/pipeline/tests.rs index 3f899ef35..0aae86764 100644 --- a/backend/crates/station/src/pipeline/tests.rs +++ b/backend/crates/station/src/pipeline/tests.rs @@ -104,7 +104,8 @@ async fn forwards_connections_protections_and_board_messages_immediately() let broker_task = tokio::spawn(broker.run()); let (tx, rx) = mpsc::channel(32); - let pipe_task = spawn(Config::default(), rx, client, pod_data, index); + 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 { @@ -176,7 +177,7 @@ async fn forwards_connections_protections_and_board_messages_immediately() assert_eq!(got_msg.payload, "temp high"); assert_eq!(got_msg.timestamp.hour, 1); - drop(tx); + 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`. @@ -197,7 +198,8 @@ async fn publishes_notices_and_order_outcomes_as_backend_messages() let broker_task = tokio::spawn(broker.run()); let (tx, rx) = mpsc::channel(32); - let pipe_task = spawn(Config::default(), rx, client, pod_data, index); + 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. @@ -272,7 +274,7 @@ async fn publishes_notices_and_order_outcomes_as_backend_messages() assert_eq!(got.text, text); } - drop(tx); + 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`. @@ -294,7 +296,8 @@ async fn batches_data_every_100ms_with_window_average_last_and_cycle_time() let broker_task = tokio::spawn(broker.run()); let (tx, rx) = mpsc::channel(32); - let pipe_task = spawn(Config::default(), rx, client, pod_data, index); + 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); @@ -305,19 +308,20 @@ async fn batches_data_every_100ms_with_window_average_last_and_cycle_time() ]; for (at, voltage, active, state) in samples { - tx.send(ToPipeline::Received(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?; + 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; @@ -351,22 +355,12 @@ async fn batches_data_every_100ms_with_window_average_last_and_cycle_time() ); // Next window resets the measurement average while preserving cumulative count. - tx.send(ToPipeline::Received(Arc::new(Notification { - board: BoardId(5), - at: t0 + Duration::from_millis(150), - event: Event::Received(Packet::Data(DataPacket::new( - AdjId(551), - vec![ - Value::Number(50.0), - Value::Bool(false), - Value::Enum("Idle".to_string()), - ], - ))), - }))) - .await?; + data_tx + .send(data_notification(t0 + Duration::from_millis(150), 50.0)) + .await?; - // Dropping `tx` flushes remaining data immediately and stops both tasks cleanly. - drop(tx); + // 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??; @@ -417,89 +411,60 @@ fn utc_calendar_conversion_handles_epoch_and_leap_day() { ); } -/// Verifies that `pipeline` sheds UDP `Packet::Data` updates when `channels.pipeline` -/// saturates (while still forwarding discrete events like `OrderSent`), and resumes -/// processing `Packet::Data` once the backlog drops below the low-water mark. -#[tokio::test(start_paused = true)] -async fn pauses_udp_data_when_saturated_and_resumes_when_unsaturated() +/// 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 sub = client.subscriber(); - let mut data_sub = sub.subscribe_data(); - let mut backend_sub = sub.subscribe_backend_messages()?; + let data_sub = client.subscriber().subscribe_data(); let broker_task = tokio::spawn(broker.run()); - // Capacity 16 -> default high_water = 13 (80%), low_water = 4 (25%). - let (tx, rx) = mpsc::channel(16); - let pipe_task = spawn(Config::default(), rx, client, pod_data, index); - - let t0 = UNIX_EPOCH + Duration::from_secs(1_700_000_000); - let send_data = |step: u32| { - ToPipeline::Received(Arc::new(Notification { - board: BoardId(5), - at: t0 + Duration::from_millis(u64::from(step) * 5), - event: Event::Received(Packet::Data(DataPacket::new( - AdjId(551), - vec![ - Value::Number(f64::from(step)), - Value::Bool(true), - Value::Enum("Idle".to_string()), - ], - ))), - })) - }; - - // Enqueue 14 items before `pipe_task` runs (>= high_water 13): - // 7 Data frames -> 1 OrderSent -> 6 Data frames. - for step in 1..=7 { - tx.send(send_data(step)).await?; - } - tx.send(ToPipeline::OrderSent { - at: t0 + Duration::from_millis(40), - board: Some(BoardId(5)), - order: OrderPacket::new(AdjId(1001), vec![]), - }) - .await?; - for step in 8..=13 { - tx.send(send_data(step)).await?; - } + 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); - // OrderSent must still be forwarded immediately while saturated. - let got_sent = timeout(Duration::from_secs(1), backend_sub.recv()).await??; - assert_eq!(got_sent.text, "Order Start sent"); + // ⑥ 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"); - // Flush the 100 ms window: frames 1..=8 were dropped while saturated, - // and frames 9..=13 were processed after the queue drained to <= 4. - 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, 5); - assert_eq!( - first.measurement_updates[&AdjId(3001)], - MeasurementUpdate::Numeric { - last: 13.0, - average: 11.0, - } - ); + drop(data_tx); + timeout(Duration::from_secs(1), pipe_task).await??; + timeout(Duration::from_secs(1), broker_task).await??; - // Queue is now empty (unsaturated): next UDP Data frame is processed normally. - tx.send(send_data(99)).await?; - tokio::task::yield_now().await; - advance(Duration::from_millis(100)).await; - timeout(Duration::from_millis(10), data_sub.changed()).await??; - let second = data_sub.borrow_and_update().0[&AdjId(551)].clone(); - assert_eq!(second.count, 6); + let packet = data_sub.borrow().0[&AdjId(551)].clone(); + assert_eq!(packet.count, 1); assert_eq!( - second.measurement_updates[&AdjId(3001)], + packet.measurement_updates[&AdjId(3001)], MeasurementUpdate::Numeric { - last: 99.0, - average: 99.0, + last: 7.0, + average: 7.0, } ); - - drop(tx); - timeout(Duration::from_secs(1), pipe_task).await??; - timeout(Duration::from_secs(1), broker_task).await??; Ok(()) } + +/// 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()), + ], + ))), + }) +} From 73da6d090b35a4532d27d232d7d24c2dee992ad1 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sun, 6 Dec 2026 10:11:55 +0100 Subject: [PATCH 16/17] docs(backend, pipeline): pipeline exists; main still uses stand-ins - station README and lib.rs list every module, pipeline included. - main.rs and readme-demo.md: the pipeline stand-in counts telemetry and shows connections, notices and orders; the real pipeline needs the websocket broker, which main does not start yet. --- backend/crates/station/README.md | 32 ++++++++++++++++-------------- backend/crates/station/src/lib.rs | 8 +++++--- backend/crates/station/src/main.rs | 9 +++++---- backend/readme-demo.md | 10 ++++++---- 4 files changed, 33 insertions(+), 26 deletions(-) diff --git a/backend/crates/station/README.md b/backend/crates/station/README.md index 337a50a73..f73390e3b 100644 --- a/backend/crates/station/README.md +++ b/backend/crates/station/README.md @@ -4,24 +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. - -Mientras tanto, `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`: -`cargo run -p station --release`. Ver -[`../../readme-demo.md`](../../readme-demo.md). - -`event`, la comunicación entre los módulos de station, está documentado en -[`src/event/README.md`](src/event/README.md). - +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/lib.rs b/backend/crates/station/src/lib.rs index 87e8ac401..46ea1e5e1 100644 --- a/backend/crates/station/src/lib.rs +++ b/backend/crates/station/src/lib.rs @@ -7,12 +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 pipeline; - diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index ae3e0befb..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. //! diff --git a/backend/readme-demo.md b/backend/readme-demo.md index 644b186e6..b4a8452f5 100644 --- a/backend/readme-demo.md +++ b/backend/readme-demo.md @@ -9,10 +9,12 @@ `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 de `logging` y `pipeline`, que todavía no existen: el de - logging cuenta los paquetes por placa y escribe un resumen por segundo; el - de pipeline escribe en el log lo que vería el front (problemas, órdenes que - no salieron). + 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): From 86d22213e2d3e6543898d35808b26d9900f8b74b Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sun, 6 Dec 2026 10:22:21 +0100 Subject: [PATCH 17/17] test(backend, pipeline): snapshot, connections, broker closed, accumulator - The fixture gets a second board (BCU, data packet 661). - Every flush publishes the whole podData map; an empty window nothing. - Every board disconnected at startup; connections only on change. - pipeline stops when the broker is gone, closing both queues. - Accumulator: non-data ids, clock stepping back, malformed packets. --- backend/crates/station/src/pipeline/README.md | 9 +- backend/crates/station/src/pipeline/tests.rs | 311 +++++++++++++++++- 2 files changed, 314 insertions(+), 6 deletions(-) diff --git a/backend/crates/station/src/pipeline/README.md b/backend/crates/station/src/pipeline/README.md index 2b91874be..503f82391 100644 --- a/backend/crates/station/src/pipeline/README.md +++ b/backend/crates/station/src/pipeline/README.md @@ -144,16 +144,23 @@ let pipeline_handle = pipeline::spawn( ## Tests Unit tests in `pipeline/tests.rs` wire `pipeline::spawn` to a real `Broker` -(no sockets) and check: +(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 diff --git a/backend/crates/station/src/pipeline/tests.rs b/backend/crates/station/src/pipeline/tests.rs index 0aae86764..15d4a9b73 100644 --- a/backend/crates/station/src/pipeline/tests.rs +++ b/backend/crates/station/src/pipeline/tests.rs @@ -13,14 +13,17 @@ 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::{MeasurementUpdate, MessageTimestamp, ProtectionUpdate}; +use crate::payload::{ConnectionUpdate, MeasurementUpdate, MessageTimestamp, ProtectionUpdate}; use crate::websocket::broker::Broker; -/// Builds a minimal ADJ fixture with one board (`PCU`, ID 5) containing a -/// 3-measurement `Data` packet (ID 551), an `Order` packet (ID 1001), and a -/// `Warning` message definition (ID 10). +/// 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), @@ -82,8 +85,32 @@ fn sample_fixture() -> (Arc, Arc) { ]), }; + 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)]), + boards: HashMap::from([(pcu.id, pcu), (bcu.id, bcu)]), }); let index = Arc::new(Index::new(&pod_data, None)); (pod_data, index) @@ -452,6 +479,245 @@ async fn stops_only_once_both_queues_close_and_flushes_what_is_left() 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 { @@ -468,3 +734,38 @@ fn data_notification(at: std::time::SystemTime, voltage: f64) -> Arc 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 +}