From 74b08446511f2c633245ab0f83d3b2e278ba42ac Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 24 Nov 2026 11:39:17 +0100 Subject: [PATCH 01/14] wip(backend, websocket): initial module structure --- backend/crates/station/src/main.rs | 4 ++++ backend/crates/station/src/websocket.rs | 6 ++++++ backend/crates/station/src/websocket/broker.rs | 0 backend/crates/station/src/websocket/handler.rs | 0 backend/crates/station/src/websocket/receiver.rs | 0 backend/crates/station/src/websocket/sender.rs | 0 6 files changed, 10 insertions(+) create mode 100644 backend/crates/station/src/websocket.rs create mode 100644 backend/crates/station/src/websocket/broker.rs create mode 100644 backend/crates/station/src/websocket/handler.rs create mode 100644 backend/crates/station/src/websocket/receiver.rs create mode 100644 backend/crates/station/src/websocket/sender.rs diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index d872008d1..9fa834996 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -11,3 +11,7 @@ fn main() { let _greeting = software_core::hello_world::greet(&name); tracing::info!("demo finalizada"); } + +mod http; +mod vehicle; +mod websocket; diff --git a/backend/crates/station/src/websocket.rs b/backend/crates/station/src/websocket.rs new file mode 100644 index 000000000..d789e536d --- /dev/null +++ b/backend/crates/station/src/websocket.rs @@ -0,0 +1,6 @@ +mod handler; +mod receiver; +mod sender; +mod broker; + + diff --git a/backend/crates/station/src/websocket/broker.rs b/backend/crates/station/src/websocket/broker.rs new file mode 100644 index 000000000..e69de29bb diff --git a/backend/crates/station/src/websocket/handler.rs b/backend/crates/station/src/websocket/handler.rs new file mode 100644 index 000000000..e69de29bb diff --git a/backend/crates/station/src/websocket/receiver.rs b/backend/crates/station/src/websocket/receiver.rs new file mode 100644 index 000000000..e69de29bb diff --git a/backend/crates/station/src/websocket/sender.rs b/backend/crates/station/src/websocket/sender.rs new file mode 100644 index 000000000..e69de29bb From 5ce19d26d074509acf6d4d744b7c951194afd715 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 24 Nov 2026 23:58:32 +0100 Subject: [PATCH 02/14] feat(backend, model): websocket payloads and examples --- backend/crates/core/src/model.rs | 3 + backend/crates/core/src/model/websocket.rs | 26 +++++ .../core/src/model/websocket/connection.rs | 16 ++++ .../crates/core/src/model/websocket/data.rs | 42 ++++++++ .../model/websocket/example/connection.json | 13 +++ .../src/model/websocket/example/data.json | 35 +++++++ .../websocket/example/logger_enable.json | 4 + .../websocket/example/logger_response.json | 4 + .../websocket/example/logger_variables.json | 8 ++ .../src/model/websocket/example/message.json | 18 ++++ .../src/model/websocket/example/order.json | 13 +++ .../model/websocket/example/protection.json | 13 +++ .../model/websocket/example/state_orders.json | 10 ++ .../core/src/model/websocket/message.rs | 88 +++++++++++++++++ .../crates/core/src/model/websocket/order.rs | 32 +++++++ .../core/src/model/websocket/protection.rs | 95 +++++++++++++++++++ backend/crates/core/src/utils/serialize.rs | 21 ++++ 17 files changed, 441 insertions(+) create mode 100644 backend/crates/core/src/model/websocket.rs create mode 100644 backend/crates/core/src/model/websocket/connection.rs create mode 100644 backend/crates/core/src/model/websocket/data.rs create mode 100644 backend/crates/core/src/model/websocket/example/connection.json create mode 100644 backend/crates/core/src/model/websocket/example/data.json create mode 100644 backend/crates/core/src/model/websocket/example/logger_enable.json create mode 100644 backend/crates/core/src/model/websocket/example/logger_response.json create mode 100644 backend/crates/core/src/model/websocket/example/logger_variables.json create mode 100644 backend/crates/core/src/model/websocket/example/message.json create mode 100644 backend/crates/core/src/model/websocket/example/order.json create mode 100644 backend/crates/core/src/model/websocket/example/protection.json create mode 100644 backend/crates/core/src/model/websocket/example/state_orders.json create mode 100644 backend/crates/core/src/model/websocket/message.rs create mode 100644 backend/crates/core/src/model/websocket/order.rs create mode 100644 backend/crates/core/src/model/websocket/protection.rs diff --git a/backend/crates/core/src/model.rs b/backend/crates/core/src/model.rs index 74b79b99a..80ec948a2 100644 --- a/backend/crates/core/src/model.rs +++ b/backend/crates/core/src/model.rs @@ -20,6 +20,9 @@ mod value; #[cfg(feature = "http")] pub mod http; +#[cfg(feature = "websocket")] +pub mod websocket; + pub use board::{Board, PacketDef, PacketType, PodData}; pub use id::{AdjId, BoardId, MacAddress, Port}; pub use measurement::{Measurement, MeasurementKind, NumericKind, Range}; diff --git a/backend/crates/core/src/model/websocket.rs b/backend/crates/core/src/model/websocket.rs new file mode 100644 index 000000000..4fe844983 --- /dev/null +++ b/backend/crates/core/src/model/websocket.rs @@ -0,0 +1,26 @@ +//! JSON payloads for frontend WebSocket topics (feature `websocket`). +//! +//! Existing topics preserve the Go backend's JSON shapes; `protection/update` +//! adds a compact event. Socket handling, subscriptions and publication belong +//! to `station`. See `websocket/README.md`. + +mod connection; +mod data; +mod message; +mod order; +mod protection; + +pub use connection::{Connection, ConnectionUpdate}; +pub use data::{DataPacketUpdate, DataUpdate, MeasurementUpdate}; +pub use message::{MessageKind, MessagePayload, MessageTimestamp, MessageUpdate}; +pub use order::{OrderField, OrderSend, StateOrdersUpdate}; +pub use protection::{ProtectionPayload, ProtectionUpdate}; + +/// Payload of `logger/enable`: the requested recording state. +pub type LoggerEnable = bool; + +/// Payload of `logger/response`: the actual recording state. +pub type LoggerResponse = bool; + +/// Payload of `logger/variables`: selected measurement names. +pub type LoggerVariables = Vec; diff --git a/backend/crates/core/src/model/websocket/connection.rs b/backend/crates/core/src/model/websocket/connection.rs new file mode 100644 index 000000000..2e4a2d8c7 --- /dev/null +++ b/backend/crates/core/src/model/websocket/connection.rs @@ -0,0 +1,16 @@ +use std::collections::HashMap; + +use serde::Serialize; + +/// Payload of `connection/update`, keyed by board name. +pub type ConnectionUpdate = HashMap; + +/// Whether a board is connected to the backend. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Connection { + /// Board name, also used as the key in `ConnectionUpdate`. + pub name: String, + /// Current connection state. + pub is_connected: bool, +} diff --git a/backend/crates/core/src/model/websocket/data.rs b/backend/crates/core/src/model/websocket/data.rs new file mode 100644 index 000000000..8901f7e26 --- /dev/null +++ b/backend/crates/core/src/model/websocket/data.rs @@ -0,0 +1,42 @@ +use std::collections::HashMap; + +use serde::Serialize; + +use crate::{model::AdjId, utils::serialize::serialize_adj_id}; + +/// Payload of `podData/update`, keyed by packet id (JSON object keys are strings). +pub type DataUpdate = HashMap; + +/// Current telemetry and statistics for one packet. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DataPacketUpdate { + /// ADJ packet id, serialized as a number. + #[serde(serialize_with = "serialize_adj_id")] + pub id: AdjId, + /// Hexadecimal representation of the received packet. + pub hex_value: String, + /// Number of packets received under this id. + pub count: u64, + /// Averaged interval between packets, in the legacy timestamp's units. + pub cycle_time: u64, + /// Updates keyed by the measurement's textual alias. + pub measurement_updates: HashMap, +} + +/// A number carries statistics; booleans and enums are JSON primitives. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum MeasurementUpdate { + /// Numeric measurement and its moving average. + Numeric { + /// Most recently received value. + last: f64, + /// Moving average of the received values. + average: f64, + }, + /// Most recently received boolean. + Boolean(bool), + /// Most recently received enum variant. + Enum(String), +} diff --git a/backend/crates/core/src/model/websocket/example/connection.json b/backend/crates/core/src/model/websocket/example/connection.json new file mode 100644 index 000000000..ab23a4751 --- /dev/null +++ b/backend/crates/core/src/model/websocket/example/connection.json @@ -0,0 +1,13 @@ +{ + "topic": "connection/update", + "payload": { + "LCU": { + "name": "LCU", + "isConnected": true + }, + "HVBMS": { + "name": "HVBMS", + "isConnected": false + } + } +} diff --git a/backend/crates/core/src/model/websocket/example/data.json b/backend/crates/core/src/model/websocket/example/data.json new file mode 100644 index 000000000..312fdc7ba --- /dev/null +++ b/backend/crates/core/src/model/websocket/example/data.json @@ -0,0 +1,35 @@ +{ + "topic": "podData/update", + "payload": { + "936": { + "id": 936, + "hexValue": "a80300000e42", + "count": 124, + "cycleTime": 100000000, + "measurementUpdates": { + "temperature_1": { + "last": 35.5, + "average": 35.0 + } + } + }, + "1201": { + "id": 1201, + "hexValue": "b10401", + "count": 58, + "cycleTime": 100000000, + "measurementUpdates": { + "contactor_closed": true + } + }, + "1202": { + "id": 1202, + "hexValue": "b20401", + "count": 58, + "cycleTime": 100000000, + "measurementUpdates": { + "state": "Operational" + } + } + } +} diff --git a/backend/crates/core/src/model/websocket/example/logger_enable.json b/backend/crates/core/src/model/websocket/example/logger_enable.json new file mode 100644 index 000000000..a63e1bf11 --- /dev/null +++ b/backend/crates/core/src/model/websocket/example/logger_enable.json @@ -0,0 +1,4 @@ +{ + "topic": "logger/enable", + "payload": true +} diff --git a/backend/crates/core/src/model/websocket/example/logger_response.json b/backend/crates/core/src/model/websocket/example/logger_response.json new file mode 100644 index 000000000..fc7277b4c --- /dev/null +++ b/backend/crates/core/src/model/websocket/example/logger_response.json @@ -0,0 +1,4 @@ +{ + "topic": "logger/response", + "payload": true +} diff --git a/backend/crates/core/src/model/websocket/example/logger_variables.json b/backend/crates/core/src/model/websocket/example/logger_variables.json new file mode 100644 index 000000000..6fb7698f8 --- /dev/null +++ b/backend/crates/core/src/model/websocket/example/logger_variables.json @@ -0,0 +1,8 @@ +{ + "topic": "logger/variables", + "payload": [ + "temperature_1", + "contactor_closed", + "state" + ] +} diff --git a/backend/crates/core/src/model/websocket/example/message.json b/backend/crates/core/src/model/websocket/example/message.json new file mode 100644 index 000000000..65d1f75cb --- /dev/null +++ b/backend/crates/core/src/model/websocket/example/message.json @@ -0,0 +1,18 @@ +{ + "topic": "message/update", + "payload": { + "kind": "info", + "payload": "Order Sent", + "board": "LCU", + "name": "1001", + "timestamp": { + "counter": 0, + "second": 5, + "minute": 30, + "hour": 12, + "day": 24, + "month": 11, + "year": 2026 + } + } +} diff --git a/backend/crates/core/src/model/websocket/example/order.json b/backend/crates/core/src/model/websocket/example/order.json new file mode 100644 index 000000000..853111e21 --- /dev/null +++ b/backend/crates/core/src/model/websocket/example/order.json @@ -0,0 +1,13 @@ +{ + "topic": "order/send", + "payload": { + "id": 1001, + "fields": { + "target_speed": { + "value": 12.5, + "isEnabled": true, + "type": "float32" + } + } + } +} diff --git a/backend/crates/core/src/model/websocket/example/protection.json b/backend/crates/core/src/model/websocket/example/protection.json new file mode 100644 index 000000000..8ae2375a1 --- /dev/null +++ b/backend/crates/core/src/model/websocket/example/protection.json @@ -0,0 +1,13 @@ +{ + "topic": "protection/update", + "payload": { + "id": 11192, + "value": 105.5, + "timestamp": { + "hour": 12, + "minute": 30, + "second": 6, + "subsecond": 0 + } + } +} diff --git a/backend/crates/core/src/model/websocket/example/state_orders.json b/backend/crates/core/src/model/websocket/example/state_orders.json new file mode 100644 index 000000000..0ee68edda --- /dev/null +++ b/backend/crates/core/src/model/websocket/example/state_orders.json @@ -0,0 +1,10 @@ +{ + "topic": "order/stateOrders", + "payload": { + "LCU": [ + 1001, + 1002 + ], + "HVBMS": [] + } +} diff --git a/backend/crates/core/src/model/websocket/message.rs b/backend/crates/core/src/model/websocket/message.rs new file mode 100644 index 000000000..f6ce745bb --- /dev/null +++ b/backend/crates/core/src/model/websocket/message.rs @@ -0,0 +1,88 @@ +use serde::Serialize; + +use crate::model::{MessageLevel, Severity}; + +use super::ProtectionPayload; + +/// Payload of `message/update`, preserving the legacy event envelope. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct MessageUpdate { + /// Event severity, represented by the legacy JSON field `kind`. + pub kind: MessageKind, + /// Text or protection details. + pub payload: MessagePayload, + /// Name of the board that produced the event. + pub board: String, + /// Display name of the event; order-sent notices use the order id as text. + pub name: String, + /// Original RTC fields, without a timezone conversion. + pub timestamp: MessageTimestamp, +} + +/// Both message shapes accepted by the existing frontend. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum MessagePayload { + /// An informational notice or a board's free-text message. + Text(String), + /// Protection details, as published on `message/update` by Go. + Protection(ProtectionPayload), +} + +/// Event severity: legacy values plus ADJv3's `panic` message level. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum MessageKind { + /// Informational message. + Info, + /// Unexpected condition. + Warning, + /// Fault condition. + Fault, + /// A legacy protection returned to its appropriate range. + Ok, + /// Unrecoverable firmware error. + Panic, +} + +impl From for MessageKind { + fn from(level: MessageLevel) -> Self { + match level { + MessageLevel::Fault => Self::Fault, + MessageLevel::Warning => Self::Warning, + MessageLevel::Info => Self::Info, + MessageLevel::Panic => Self::Panic, + } + } +} + +impl From for MessageKind { + fn from(severity: Severity) -> Self { + match severity { + Severity::Fault => Self::Fault, + Severity::Warning => Self::Warning, + } + } +} + +/// Legacy RTC timestamp used by the frontend's event display. +/// +/// This is not `ShortTimestamp`: the latter has no date and its subsecond unit +/// is unresolved. Event construction must supply the date and counter explicitly. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub struct MessageTimestamp { + /// RTC counter; kept separate from `ShortTimestamp::subsecond`. + pub counter: u16, + /// Second of the minute. + pub second: u8, + /// Minute of the hour. + pub minute: u8, + /// Hour of the day. + pub hour: u8, + /// Day of the month. + pub day: u8, + /// Month of the year. + pub month: u8, + /// Calendar year. + pub year: u16, +} diff --git a/backend/crates/core/src/model/websocket/order.rs b/backend/crates/core/src/model/websocket/order.rs new file mode 100644 index 000000000..5b8cb221f --- /dev/null +++ b/backend/crates/core/src/model/websocket/order.rs @@ -0,0 +1,32 @@ +use std::collections::HashMap; + +use serde::Deserialize; + +use crate::{model::AdjId, utils::serialize::deserialize_adj_id}; + +/// Payload of `order/send`; conversion to an `OrderPacket` requires the ADJ. +#[derive(Debug, Clone, PartialEq, Deserialize)] +pub struct OrderSend { + /// Requested order's ADJ id. + #[serde(deserialize_with = "deserialize_adj_id")] + pub id: AdjId, + /// Parameters keyed by their textual aliases, rather than wire position. + pub fields: HashMap, +} + +/// One parameter supplied by the frontend. +#[derive(Debug, Clone, PartialEq, Deserialize)] +pub struct OrderField { + /// Raw JSON value; its type and range must be checked against the ADJ. + /// Keeping it raw also preserves integer precision before validation. + pub value: serde_json::Value, + /// Whether the frontend enables this parameter. + #[serde(rename = "isEnabled")] + pub is_enabled: bool, + /// Legacy type name, such as `uint16`, `float32`, `bool` or `enum`. + #[serde(rename = "type")] + pub field_type: String, +} + +/// Payload of `order/stateOrders`: board names mapped to enabled order ids. +pub type StateOrdersUpdate = HashMap>; diff --git a/backend/crates/core/src/model/websocket/protection.rs b/backend/crates/core/src/model/websocket/protection.rs new file mode 100644 index 000000000..6dbd1cafa --- /dev/null +++ b/backend/crates/core/src/model/websocket/protection.rs @@ -0,0 +1,95 @@ +use serde::Serialize; +use serde_json::Value as JsonValue; + +use crate::{ + model::{AdjId, ProtectionPacket, ShortTimestamp, Value}, + utils::serialize::{serialize_adj_id, serialize_value}, +}; + +/// Payload of `protection/update`: the triggered id, measured value and time. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct ProtectionUpdate { + /// Compound protection id; its definition is available in the ADJ catalog. + #[serde(serialize_with = "serialize_adj_id")] + pub id: AdjId, + /// Value that triggered the protection, serialized as a JSON primitive. + #[serde(serialize_with = "serialize_value")] + pub value: Value, + /// Time received from the board, preserving the raw subsecond byte. + #[serde(with = "ShortTimestampJson")] + pub timestamp: ShortTimestamp, +} + +impl From for ProtectionUpdate { + fn from(packet: ProtectionPacket) -> Self { + Self { + id: packet.id, + value: packet.value, + timestamp: packet.timestamp, + } + } +} + +#[derive(Serialize)] +#[serde(remote = "ShortTimestamp")] +struct ShortTimestampJson { + hour: u8, + minute: u8, + second: u8, + subsecond: u8, +} + +/// Legacy protection details used only by `message/update`. +/// +/// Values retain their JSON number or boolean representation. ADJ validation +/// and conversion from domain packets belong to the publisher. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(tag = "kind", content = "data", rename_all = "SCREAMING_SNAKE_CASE")] +pub enum ProtectionPayload { + /// A value dropped below its lower bound. + LowerBound { + /// Lower bound. + bound: JsonValue, + /// Value that triggered the protection. + value: JsonValue, + }, + /// A value exceeded its upper bound. + UpperBound { + /// Upper bound. + bound: JsonValue, + /// Value that triggered the protection. + value: JsonValue, + }, + /// A value left the allowed interval. + OutOfBounds { + /// Lower and upper bounds, in that order. + bounds: [JsonValue; 2], + /// Value that triggered the protection. + value: JsonValue, + }, + /// A value matched the protected value. + Equals { + /// Value that triggered the protection. + value: JsonValue, + }, + /// A value differed from the expected value. + NotEquals { + /// Expected value. + want: JsonValue, + /// Value that triggered the protection. + value: JsonValue, + }, + /// The legacy time-accumulation protection. + TimeAccumulation { + /// Value that triggered the protection. + value: JsonValue, + /// Threshold. + bound: JsonValue, + /// Time limit in seconds. + timelimit: f32, + }, + /// Legacy firmware error text. + ErrorHandler(String), + /// Legacy warning text. + Warning(String), +} diff --git a/backend/crates/core/src/utils/serialize.rs b/backend/crates/core/src/utils/serialize.rs index cb61543b9..9c57bb7b3 100644 --- a/backend/crates/core/src/utils/serialize.rs +++ b/backend/crates/core/src/utils/serialize.rs @@ -1,4 +1,6 @@ +use crate::model::Value; use crate::model::{AdjId, BoardId, NumericKind, ProtectionKind, Severity}; +use serde::{Deserialize, Deserializer}; use serde::{Serialize, Serializer}; #[cfg(feature = "http")] @@ -29,6 +31,25 @@ pub(crate) fn serialize_adj_id( serializer.serialize_u16(id.0) } +// Deserializer works the other way around as Serializer +pub(crate) fn deserialize_adj_id<'de, D: Deserializer<'de>>( + deserializer: D, +) -> Result { + u16::deserialize(deserializer).map(AdjId) +} + +// Serializes the value of a protection message +pub(crate) fn serialize_value( + value: &Value, + serializer: S, +) -> Result { + match value { + Value::Number(value) => serializer.serialize_f64(*value), + Value::Bool(value) => serializer.serialize_bool(*value), + Value::Enum(value) => serializer.serialize_str(value), + } +} + // Serialize numeric kind to match ADJv3 types. pub(crate) fn get_numeric_kind(kind: &NumericKind) -> &str { match kind { From 91d744deaa3423e404ef9175fd9bd2963962e934 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 24 Nov 2026 23:59:18 +0100 Subject: [PATCH 03/14] docs(backend, model): update READMEs adding submodule and feature websocket --- backend/crates/core/Cargo.toml | 2 + backend/crates/core/src/model/README.md | 14 + .../crates/core/src/model/websocket/README.md | 279 ++++++++++++++++++ 3 files changed, 295 insertions(+) create mode 100644 backend/crates/core/src/model/websocket/README.md diff --git a/backend/crates/core/Cargo.toml b/backend/crates/core/Cargo.toml index ac855d65f..7042ba762 100644 --- a/backend/crates/core/Cargo.toml +++ b/backend/crates/core/Cargo.toml @@ -33,6 +33,8 @@ host = ["logger", "dep:whoami", "dep:rlimit"] trace = ["dep:tracing-subscriber", "dep:tracing-appender"] # Structure responses for HTTP petitions http = [] +# JSON payloads for frontend WebSocket topics; no socket or runtime dependency. +websocket = [] [dependencies] bytes.workspace = true diff --git a/backend/crates/core/src/model/README.md b/backend/crates/core/src/model/README.md index 40001c283..ff64eb94e 100644 --- a/backend/crates/core/src/model/README.md +++ b/backend/crates/core/src/model/README.md @@ -8,6 +8,9 @@ The domain types describe vehicle definitions and decoded packets. With the `http` feature enabled, `model::http` also exposes separate, serializable catalog response models; see [section 7](#7-http-http-feature). +With the `websocket` feature, `model::websocket` exposes the live-update and +request payloads used by the frontend; see [section 8](#8-websocket-websocket-feature). + ## 1. `board.rs` All structs and enums needed for the Pod can be found defined in this file. ### 1.1 `PacketType` @@ -301,3 +304,14 @@ This module defines no HTTP server, routes, CORS, or cache policy. See the [HTTP response models README](http/README.md) for usage, JSON type notation, field omission rules, and concrete examples. + +## 8. `websocket` (`websocket` feature) + +`model/websocket.rs` publicly re-exports the payload types for telemetry, +connections, orders, messages, protection events, and logger control. +Published structures implement `serde::Serialize`; order requests implement +`serde::Deserialize`. These models describe the payload inside a +`{topic, payload}` message; socket handling and the broker belong to `station`. + +See the [WebSocket message models README](websocket/README.md) for the topic +list, usage, JSON type notation, and complete message examples. diff --git a/backend/crates/core/src/model/websocket/README.md b/backend/crates/core/src/model/websocket/README.md new file mode 100644 index 000000000..6947c9117 --- /dev/null +++ b/backend/crates/core/src/model/websocket/README.md @@ -0,0 +1,279 @@ +# WebSocket Message Models (`model::websocket`) + +JSON models for telemetry, connections, orders, messages, protection events +and logger control. The `websocket` feature enables the types in +`model/websocket.rs` and `model/websocket/`. + +The Rust types describe the payload of each topic. Messages sent over the +WebSocket wrap that payload in `{topic, payload}`, as shown in the templates +and example files below. Connections, subscriptions, channels and the broker +belong to the application (`station`). + +## Topics + +| Topic | Payload type | Direction | JSON example | +| --- | --- | --- | --- | +| `podData/update` | `DataUpdate` | Backend → frontend | [data.json](example/data.json) | +| `connection/update` | `ConnectionUpdate` | Backend → frontend | [connection.json](example/connection.json) | +| `order/send` | `OrderSend` | Frontend → backend | [order.json](example/order.json) | +| `order/stateOrders` | `StateOrdersUpdate` | Backend → frontend | [state_orders.json](example/state_orders.json) | +| `message/update` | `MessageUpdate` | Backend → frontend | [message.json](example/message.json) | +| `protection/update` | `ProtectionUpdate` | Backend → frontend | [protection.json](example/protection.json) | +| `logger/enable` | `LoggerEnable` | Frontend → backend | [logger_enable.json](example/logger_enable.json) | +| `logger/response` | `LoggerResponse` | Backend → frontend | [logger_response.json](example/logger_response.json) | +| `logger/variables` | `LoggerVariables` | Frontend → backend | [logger_variables.json](example/logger_variables.json) | + +Directions describe the topic's data flow. A subscription request is handled +separately by the broker. Each example is an illustrative complete message, +independent of the bundled ADJ fixture and HTTP catalog examples. + +## Usage + +Enable the feature in the application's dependency: + +```bash +cargo add software-core -F websocket +``` + +With a decoded `packet: ProtectionPacket`: + +```rust +use software_core::model::websocket::{OrderSend, ProtectionUpdate}; + +let request: OrderSend = serde_json::from_str(r#"{"id":1002,"fields":{}}"#)?; +let protection = ProtectionUpdate::from(packet); +let payload_json = serde_json::to_string(&protection)?; +``` + +Published structures implement `serde::Serialize`; `OrderSend` and `OrderField` +implement `serde::Deserialize`. The logger aliases use the primitive types' +Serde implementations. All payload types are re-exported from +`model::websocket`. + +Deserializing an order checks its JSON structure. Parameter types, ranges and +their correspondence with the ADJ must be validated by the application before +converting it to an `OrderPacket`. + +## JSON Structure Templates + +These templates keep the JSON object and array structure, replacing values +with their types: `number`, `string`, or `boolean`. Quoted topic names and +discriminators are literals; keys in angle brackets represent map entries. +Comments describe alternative values and constraints. These are documentation +templates, not valid JSON messages; the linked `.json` files contain concrete +values. + +Maps and arrays show representative entries and may be empty. Numeric IDs +are unsigned 16-bit integers. When an ID is an object key, JSON represents +it as a string. + +### Telemetry (`DataUpdate`) + +```jsonc +{ + "topic": "podData/update", + "payload": { + "": { + "id": number, + "hexValue": string, + "count": number, + "cycleTime": number, + "measurementUpdates": { + "": { + "last": number, + "average": number + }, + "": boolean, + "": string + } + } + } +} +``` + +The outer key matches the packet's `id`. `count` is the received packet count; +`cycleTime` is the averaged interval between packet receptions. The publisher +supplies these statistics and the hexadecimal packet representation. + +`MeasurementUpdate` has three JSON forms: `{last, average}` for a number, +a boolean, or an enum variant string. There is no additional discriminator +around a measurement value. + +### Connections (`ConnectionUpdate`) + +```jsonc +{ + "topic": "connection/update", + "payload": { + "": { + "name": string, + "isConnected": boolean + } + } +} +``` + +The map key matches `name`. The state describes the connection between the +backend and the board. + +### Send Order (`OrderSend`) + +```jsonc +{ + "topic": "order/send", + "payload": { + "id": number, + "fields": { + "": { + "value": number, // A boolean or enum string is also possible. + "isEnabled": boolean, + "type": string + } + } + } +} +``` + +An order without parameters has `fields: {}`. Parameter names are aliases; +the application uses the ADJ to place their values in wire order. The `value` +field remains raw JSON until validation, preserving integer precision. + +Numeric `type` names are `"uint8"`, `"uint16"`, `"uint32"`, `"uint64"`, +`"int8"`, `"int16"`, `"int32"`, `"int64"`, `"float32"` and `"float64"`. +Boolean and enum parameters use `"bool"` and `"enum"`, respectively. + +### Enabled Orders (`StateOrdersUpdate`) + +```jsonc +{ + "topic": "order/stateOrders", + "payload": { + "": [number] + } +} +``` + +Each array contains the IDs of the board's currently enabled orders. A board +with no enabled orders is represented by an empty array. + +### Messages (`MessageUpdate`) + +```jsonc +{ + "topic": "message/update", + "payload": { + "kind": string, // "info", "warning", "fault", "ok" or "panic". + "payload": string, // Alternatively, the detailed object shown below. + "board": string, + "name": string, + "timestamp": { + "counter": number, + "second": number, + "minute": number, + "hour": number, + "day": number, + "month": number, + "year": number + } + } +} +``` + +`MessagePayload::Text` is a JSON string. `MessagePayload::Protection` is an +object with its own `kind` and `data`. The outer `kind` always describes +severity; the inner `kind` describes the condition: + +```jsonc +{ + "kind": "UPPER_BOUND", + "data": { + "bound": number, + "value": number + } +} +``` + +The detailed forms are: + +| Inner `kind` | `data` template | +| --- | --- | +| `LOWER_BOUND` | `{"bound": number, "value": number}` | +| `UPPER_BOUND` | `{"bound": number, "value": number}` | +| `OUT_OF_BOUNDS` | `{"bounds": [number, number], "value": number}` | +| `EQUALS` | `{"value": number}` | +| `NOT_EQUALS` | `{"want": number, "value": number}` | +| `TIME_ACCUMULATION` | `{"value": number, "bound": number, "timelimit": number}` | +| `ERROR_HANDLER` | `string` | +| `WARNING` | `string` | + +Measured values and thresholds can also be booleans when appropriate for +the condition. `bounds` contains exactly two elements, lower then upper; +`timelimit` is expressed in seconds. The application validates the detailed +values against the ADJ. + +### Protection Events (`ProtectionUpdate`) + +```jsonc +{ + "topic": "protection/update", + "payload": { + "id": number, + "value": number, // A boolean or enum string is also possible. + "timestamp": { + "hour": number, + "minute": number, + "second": number, + "subsecond": number + } + } +} +``` + +The payload contains only the compound protection ID, the value that triggered +it and the board's timestamp. The ADJ catalog supplies the protection's name, +condition and severity. `ProtectionUpdate::from(packet)` builds this payload +directly from a domain `ProtectionPacket`. + +### Logger Control (`LoggerEnable`, `LoggerResponse`, `LoggerVariables`) + +Request the desired recording state: + +```jsonc +{ + "topic": "logger/enable", + "payload": boolean +} +``` + +Report the actual recording state: + +```jsonc +{ + "topic": "logger/response", + "payload": boolean +} +``` + +Select the measurement names to record: + +```jsonc +{ + "topic": "logger/variables", + "payload": [string] +} +``` + +## IDs, Ordering, and Timestamps + +- Protection IDs are composed as `(position << 13) | measurement_id`. + The high 3 bits hold the one-based protection position (`1–7`); the low + 13 bits identify the watched measurement. +- Map keys have no guaranteed order. An empty map is `{}` and an empty + list is `[]`. Declared structure fields remain present. +- `message/update` uses `MessageTimestamp`, with RTC counter and calendar + fields. These values are represented without timezone conversion. +- `protection/update` uses `ShortTimestamp`, containing the time of day and + a raw `subsecond` byte. That byte's unit is unresolved and is not converted + to milliseconds. It carries no calendar date. +- Constructing a `MessageTimestamp` from a `ShortTimestamp` requires receive + context for the date and an explicit policy for the counter. From 19b00a4e9c737595cf963fa63409354a7c5263b9 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Wed, 25 Nov 2026 01:09:32 +0100 Subject: [PATCH 04/14] fix(backend, model -> websocket): move payloads to websocket in station and broker in progress --- backend/Cargo.lock | 1 + backend/crates/core/Cargo.toml | 2 - backend/crates/core/src/model.rs | 3 - backend/crates/core/src/model/README.md | 14 -- backend/crates/core/src/utils/serialize.rs | 19 --- backend/crates/station/Cargo.toml | 4 + backend/crates/station/src/http/server.rs | 118 +++++++++++++- backend/crates/station/src/websocket.rs | 44 +++++- .../crates/station/src/websocket/broker.rs | 145 ++++++++++++++++++ backend/crates/station/src/websocket/error.rs | 16 ++ .../crates/station/src/websocket/handler.rs | 19 +++ .../src/websocket/payload.rs} | 1 + .../src/websocket/payload}/README.md | 24 ++- .../src/websocket/payload}/connection.rs | 3 +- .../src/websocket/payload}/data.rs | 7 +- .../payload}/example/connection.json | 0 .../src/websocket/payload}/example/data.json | 0 .../payload}/example/logger_enable.json | 0 .../payload}/example/logger_response.json | 0 .../payload}/example/logger_variables.json | 0 .../websocket/payload}/example/message.json | 0 .../src/websocket/payload}/example/order.json | 1 - .../payload}/example/protection.json | 0 .../payload}/example/state_orders.json | 0 .../src/websocket/payload}/message.rs | 6 +- .../src/websocket/payload}/order.rs | 10 +- .../src/websocket/payload}/protection.rs | 8 +- .../src/websocket/payload/serialize.rs | 28 ++++ .../crates/station/src/websocket/receiver.rs | 126 +++++++++++++++ .../crates/station/src/websocket/sender.rs | 41 +++++ 30 files changed, 563 insertions(+), 77 deletions(-) create mode 100644 backend/crates/station/src/websocket/error.rs rename backend/crates/{core/src/model/websocket.rs => station/src/websocket/payload.rs} (98%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/README.md (92%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/connection.rs (99%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/data.rs (94%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/example/connection.json (100%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/example/data.json (100%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/example/logger_enable.json (100%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/example/logger_response.json (100%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/example/logger_variables.json (100%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/example/message.json (100%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/example/order.json (86%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/example/protection.json (100%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/example/state_orders.json (100%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/message.rs (98%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/order.rs (84%) rename backend/crates/{core/src/model/websocket => station/src/websocket/payload}/protection.rs (94%) create mode 100644 backend/crates/station/src/websocket/payload/serialize.rs diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 5ed9308bd..356fa5ac0 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -2958,6 +2958,7 @@ name = "station" version = "0.1.0" dependencies = [ "axum", + "futures-util", "serde", "serde_json", "software-core", diff --git a/backend/crates/core/Cargo.toml b/backend/crates/core/Cargo.toml index 7042ba762..ac855d65f 100644 --- a/backend/crates/core/Cargo.toml +++ b/backend/crates/core/Cargo.toml @@ -33,8 +33,6 @@ host = ["logger", "dep:whoami", "dep:rlimit"] trace = ["dep:tracing-subscriber", "dep:tracing-appender"] # Structure responses for HTTP petitions http = [] -# JSON payloads for frontend WebSocket topics; no socket or runtime dependency. -websocket = [] [dependencies] bytes.workspace = true diff --git a/backend/crates/core/src/model.rs b/backend/crates/core/src/model.rs index 80ec948a2..74b79b99a 100644 --- a/backend/crates/core/src/model.rs +++ b/backend/crates/core/src/model.rs @@ -20,9 +20,6 @@ mod value; #[cfg(feature = "http")] pub mod http; -#[cfg(feature = "websocket")] -pub mod websocket; - pub use board::{Board, PacketDef, PacketType, PodData}; pub use id::{AdjId, BoardId, MacAddress, Port}; pub use measurement::{Measurement, MeasurementKind, NumericKind, Range}; diff --git a/backend/crates/core/src/model/README.md b/backend/crates/core/src/model/README.md index ff64eb94e..40001c283 100644 --- a/backend/crates/core/src/model/README.md +++ b/backend/crates/core/src/model/README.md @@ -8,9 +8,6 @@ The domain types describe vehicle definitions and decoded packets. With the `http` feature enabled, `model::http` also exposes separate, serializable catalog response models; see [section 7](#7-http-http-feature). -With the `websocket` feature, `model::websocket` exposes the live-update and -request payloads used by the frontend; see [section 8](#8-websocket-websocket-feature). - ## 1. `board.rs` All structs and enums needed for the Pod can be found defined in this file. ### 1.1 `PacketType` @@ -304,14 +301,3 @@ This module defines no HTTP server, routes, CORS, or cache policy. See the [HTTP response models README](http/README.md) for usage, JSON type notation, field omission rules, and concrete examples. - -## 8. `websocket` (`websocket` feature) - -`model/websocket.rs` publicly re-exports the payload types for telemetry, -connections, orders, messages, protection events, and logger control. -Published structures implement `serde::Serialize`; order requests implement -`serde::Deserialize`. These models describe the payload inside a -`{topic, payload}` message; socket handling and the broker belong to `station`. - -See the [WebSocket message models README](websocket/README.md) for the topic -list, usage, JSON type notation, and complete message examples. diff --git a/backend/crates/core/src/utils/serialize.rs b/backend/crates/core/src/utils/serialize.rs index 9c57bb7b3..62c544ae8 100644 --- a/backend/crates/core/src/utils/serialize.rs +++ b/backend/crates/core/src/utils/serialize.rs @@ -31,25 +31,6 @@ pub(crate) fn serialize_adj_id( serializer.serialize_u16(id.0) } -// Deserializer works the other way around as Serializer -pub(crate) fn deserialize_adj_id<'de, D: Deserializer<'de>>( - deserializer: D, -) -> Result { - u16::deserialize(deserializer).map(AdjId) -} - -// Serializes the value of a protection message -pub(crate) fn serialize_value( - value: &Value, - serializer: S, -) -> Result { - match value { - Value::Number(value) => serializer.serialize_f64(*value), - Value::Bool(value) => serializer.serialize_bool(*value), - Value::Enum(value) => serializer.serialize_str(value), - } -} - // Serialize numeric kind to match ADJv3 types. pub(crate) fn get_numeric_kind(kind: &NumericKind) -> &str { match kind { diff --git a/backend/crates/station/Cargo.toml b/backend/crates/station/Cargo.toml index 9eed62cbe..d481d8fb2 100644 --- a/backend/crates/station/Cargo.toml +++ b/backend/crates/station/Cargo.toml @@ -17,9 +17,13 @@ toml.workspace = true tracing.workspace = true tracing-subscriber.workspace = true serde_json.workspace = true +futures-util = { version = "0.3", default-features = false, features = ["std", "sink"] } tower = "0.5.3" axum = { version = "0.8.9", features = ["ws", "http1", "http2"] } tower-http = { version = "0.6.11", features = ["cors", "set-header"] } +[dev-dependencies] +tokio = { workspace = true, features = ["test-util"] } + [lints] workspace = true diff --git a/backend/crates/station/src/http/server.rs b/backend/crates/station/src/http/server.rs index 0bb27dedf..3526a44b0 100644 --- a/backend/crates/station/src/http/server.rs +++ b/backend/crates/station/src/http/server.rs @@ -57,7 +57,7 @@ pub(super) mod tests { }; use software_core::adj::{Adj, load_from_dir}; use tokio::{ - io::{AsyncBufReadExt, AsyncWriteExt, BufReader}, + io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}, net::{TcpListener, TcpStream}, sync::{mpsc, oneshot}, time::timeout, @@ -279,6 +279,122 @@ pub(super) mod tests { Ok(()) } + #[tokio::test] + async fn websocket_subscription_receives_connection_snapshots() + -> Result<(), Box> { + use super::super::super::websocket::payload::Connection; + + let (broker, client) = crate::websocket::broker::Broker::new(); + let broker_worker = tokio::spawn(broker.run()); + let (connections, receiver) = mpsc::channel(1); + let worker = tokio::spawn(crate::websocket::run(receiver, client.clone())); + let app = setup_router(&Adj::default(), Some(connections))?; + let (headers, mut first) = handshake(app.clone()).await?; + assert!(headers.starts_with("HTTP/1.1 101 Switching Protocols\r\n")); + let (_headers, mut second) = handshake(app).await?; + + timeout(Duration::from_secs(5), async { + send_text( + &mut first, + r#"{"topic":"connection/heartbeat","payload":{}}"#, + ) + .await?; + // Other frontend topics can be added incrementally without closing the socket. + send_text( + &mut first, + r#"{"topic":"podData/update","payload":{"subscribe":true}}"#, + ) + .await?; + send_text( + &mut first, + r#"{"topic":"connection/update","payload":{"subscribe":true}}"#, + ) + .await?; + assert_eq!( + read_json(&mut first).await?, + serde_json::json!({ + "topic": "connection/update", "payload": {} + }) + ); + + client + .publish_connection(Connection { + name: "LCU".into(), + is_connected: true, + }) + .await?; + let expected = serde_json::json!({ + "topic": "connection/update", + "payload": {"LCU": {"name": "LCU", "isConnected": true}} + }); + assert_eq!(read_json(&mut first).await?, expected); + + // A client receives nothing before subscribing, then receives the current map. + assert!( + timeout(Duration::from_millis(50), second.read_u8()) + .await + .is_err() + ); + send_text(&mut second, r#"{"topic":"connection/update","payload":{}}"#).await?; + assert_eq!(read_json(&mut second).await?, expected); + + client + .publish_connection(Connection { + name: "HVBMS".into(), + is_connected: false, + }) + .await?; + let expected = serde_json::json!({ + "topic": "connection/update", + "payload": { + "LCU": {"name": "LCU", "isConnected": true}, + "HVBMS": {"name": "HVBMS", "isConnected": false} + } + }); + assert_eq!(read_json(&mut first).await?, expected); + assert_eq!(read_json(&mut second).await?, expected); + + for socket in [&mut first, &mut second] { + socket.write_all(&[0x88, 0x80, 0, 0, 0, 0]).await?; + assert_eq!(socket.read_u8().await?, 0x88); + } + Ok::<_, Box>(()) + }) + .await??; + drop(client); + worker.await?; + timeout(Duration::from_secs(5), broker_worker).await??; + Ok(()) + } + + async fn send_text( + client: &mut TcpStream, + text: &str, + ) -> Result<(), Box> { + // Test requests fit a short masked frame; a zero mask leaves the JSON unchanged. + let length = u8::try_from(text.len())?; + assert!(length < 126); + client.write_all(&[0x81, 0x80 | length, 0, 0, 0, 0]).await?; + client.write_all(text.as_bytes()).await?; + Ok(()) + } + + async fn read_json( + client: &mut TcpStream, + ) -> Result> { + assert_eq!(client.read_u8().await?, 0x81); + let header = client.read_u8().await?; + assert_eq!(header & 0x80, 0, "server frames must not be masked"); + let length = match header { + 126 => usize::from(client.read_u16().await?), + 127 => usize::try_from(client.read_u64().await?)?, + length => usize::from(length), + }; + let mut body = vec![0; length]; + client.read_exact(&mut body).await?; + Ok(serde_json::from_slice(&body)?) + } + #[tokio::test] async fn websocket_without_a_consumer_returns_unavailable() -> Result<(), Box> { diff --git a/backend/crates/station/src/websocket.rs b/backend/crates/station/src/websocket.rs index d789e536d..7071721bd 100644 --- a/backend/crates/station/src/websocket.rs +++ b/backend/crates/station/src/websocket.rs @@ -1,6 +1,48 @@ +//! Connects upgraded HTTP sockets to broker subscriptions. + +use axum::extract::ws::WebSocket; +use serde::{Deserialize, Serialize}; +use tokio::sync::mpsc; + +use self::broker::BrokerClient; + +pub mod broker; +mod error; mod handler; mod receiver; mod sender; -mod broker; +pub(super) mod payload; + +const CONNECTION_UPDATE: &str = "connection/update"; +const HEARTBEAT: &str = "connection/heartbeat"; +/// JSON envelope shared with the frontend. +#[derive(Debug, Serialize, Deserialize)] +pub struct WsMessage { + /// Topic of the message, can be: + /// - order/send + /// - podData/update + /// - connection/update + /// - order/stateOrders + /// - message/update + /// - protection/update + /// - logger/enable + /// - logger/response + /// - logger/variables + pub topic: String, + /// Topic-specific JSON payload + pub payload: serde_json::Value, +} +/// Handles each connection independently while HTTP keeps accepting sockets. +pub async fn run(mut connections: mpsc::Receiver, broker: BrokerClient) { + // Spawn one tokio task per Websocket connection + while let Some(socket) = connections.recv().await { + let broker = broker.clone(); + tokio::spawn(async move { + if let Err(error) = handler::handle(socket, broker).await { + tracing::warn!(%error, "WebSocket connection ended with an error"); + } + }); + } +} diff --git a/backend/crates/station/src/websocket/broker.rs b/backend/crates/station/src/websocket/broker.rs index e69de29bb..a9d9275ac 100644 --- a/backend/crates/station/src/websocket/broker.rs +++ b/backend/crates/station/src/websocket/broker.rs @@ -0,0 +1,145 @@ +//! Publishes the current board connection state to subscribers. + +use super::payload::{Connection, ConnectionUpdate}; +use tokio::sync::{mpsc, watch}; + +pub use super::error::Error; + +/// Owns the connection state and processes incoming updates. +#[derive(Debug)] +pub struct Broker { + updates: mpsc::Receiver, + connections: watch::Sender, +} + +/// Clonable access to connection publication and subscriptions. +#[derive(Debug, Clone)] +pub struct BrokerClient { + updates: mpsc::Sender, + connections: watch::Receiver, +} + +impl Broker { + /// Creates a broker and its client, initially with no known connections. + pub fn new() -> (Self, BrokerClient) { + let (updates, receiver) = mpsc::channel(32); + let (connections, state) = watch::channel(ConnectionUpdate::new()); + ( + Self { + updates: receiver, + connections, + }, + BrokerClient { + updates, + connections: state, + }, + ) + } + + /// Processes updates until all publishing clients have been dropped. + pub async fn run(mut self) { + while let Some(connection) = self.updates.recv().await { + self.connections.send_modify(|state| { + state.insert(connection.name.clone(), connection); + }); + } + } +} + +impl BrokerClient { + /// Queues a board connection update, waiting if the input channel is full. + pub async fn publish_connection(&self, connection: Connection) -> Result<(), Error> { + self.updates + .send(connection) + .await + .map_err(|_| Error::BrokerClosed) + } + + /// Subscribes to the complete connection map, starting at its current state. + /// Read that state with `borrow_and_update()`, then wait on `changed()`. + pub fn subscribe_connections(&self) -> watch::Receiver { + let mut receiver = self.connections.clone(); + receiver.borrow_and_update(); + receiver + } +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use tokio::time::timeout; + + use super::*; + + #[tokio::test] + async fn subscribers_receive_complete_state_and_late_subscribers_start_current() + -> Result<(), Box> { + let (broker, client) = Broker::new(); + let publisher = client.clone(); + let mut first = client.subscribe_connections(); + let mut second = client.subscribe_connections(); + assert!(first.borrow_and_update().is_empty()); + assert!(second.borrow_and_update().is_empty()); + let worker = tokio::spawn(broker.run()); + + for (name, is_connected) in [("LCU", true), ("HVBMS", true), ("LCU", false)] { + publisher + .publish_connection(Connection { + name: name.into(), + is_connected, + }) + .await?; + timeout(Duration::from_secs(1), first.changed()).await??; + timeout(Duration::from_secs(1), second.changed()).await??; + let state = first.borrow_and_update().clone(); + assert_eq!(state, *second.borrow_and_update()); + assert_eq!(state[name].is_connected, is_connected); + assert_eq!(state[name].name, name); + } + + let mut late = client.subscribe_connections(); + assert!(!late.has_changed()?); + let state = late.borrow_and_update().clone(); + assert_eq!(state.len(), 2); + assert!(!state["LCU"].is_connected); + assert!(state["HVBMS"].is_connected); + + drop(publisher); + drop(client); + timeout(Duration::from_secs(1), worker).await??; + assert!(late.changed().await.is_err()); + Ok(()) + } + + #[tokio::test] + async fn publication_fails_when_broker_is_closed() { + let (broker, client) = Broker::new(); + drop(broker); + let result = client + .publish_connection(Connection { + name: "LCU".into(), + is_connected: true, + }) + .await; + assert!(matches!(result, Err(Error::BrokerClosed))); + } + + #[tokio::test] + async fn broker_drains_queued_updates_before_stopping() -> Result<(), Box> + { + let (broker, client) = Broker::new(); + let state = client.subscribe_connections(); + client + .publish_connection(Connection { + name: "LCU".into(), + is_connected: true, + }) + .await?; + drop(client); + + timeout(Duration::from_secs(1), broker.run()).await?; + assert!(state.borrow()["LCU"].is_connected); + Ok(()) + } +} diff --git a/backend/crates/station/src/websocket/error.rs b/backend/crates/station/src/websocket/error.rs new file mode 100644 index 000000000..5fc0f3eb8 --- /dev/null +++ b/backend/crates/station/src/websocket/error.rs @@ -0,0 +1,16 @@ +/// Errors handling WebSocket connections and broker communication. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// The broker no longer accepts updates. + #[error("WebSocket broker is closed")] + BrokerClosed, + /// Reading or writing the socket failed. + #[error("WebSocket I/O failed: {0}")] + Socket(#[from] axum::Error), + /// The message or its payload could not be converted to JSON models. + #[error("invalid WebSocket JSON: {0}")] + Json(#[from] serde_json::Error), + /// No valid application message arrived before the deadline. + #[error("WebSocket heartbeat timed out")] + HeartbeatTimeout, +} diff --git a/backend/crates/station/src/websocket/handler.rs b/backend/crates/station/src/websocket/handler.rs index e69de29bb..e6422f457 100644 --- a/backend/crates/station/src/websocket/handler.rs +++ b/backend/crates/station/src/websocket/handler.rs @@ -0,0 +1,19 @@ +use std::time::Duration; + +use axum::extract::ws::WebSocket; +use futures_util::{SinkExt, StreamExt}; +use tokio::{sync::watch, time::timeout}; + +use super::{broker::BrokerClient, error::Error, receiver, sender}; + +/// Runs reading and writing together; either side finishing ends the session. +pub(super) async fn handle(socket: WebSocket, broker: BrokerClient) -> Result<(), Error> { + let (mut write, read) = socket.split(); + let (subscription, subscribed) = watch::channel(false); + let result = tokio::select! { + result = receiver::run(read, subscription) => result, + result = sender::run(&mut write, &broker, subscribed) => result, + }; + let _ = timeout(Duration::from_secs(1), write.close()).await; + result +} diff --git a/backend/crates/core/src/model/websocket.rs b/backend/crates/station/src/websocket/payload.rs similarity index 98% rename from backend/crates/core/src/model/websocket.rs rename to backend/crates/station/src/websocket/payload.rs index 4fe844983..4f840cb68 100644 --- a/backend/crates/core/src/model/websocket.rs +++ b/backend/crates/station/src/websocket/payload.rs @@ -9,6 +9,7 @@ mod data; mod message; mod order; mod protection; +mod serialize; pub use connection::{Connection, ConnectionUpdate}; pub use data::{DataPacketUpdate, DataUpdate, MeasurementUpdate}; diff --git a/backend/crates/core/src/model/websocket/README.md b/backend/crates/station/src/websocket/payload/README.md similarity index 92% rename from backend/crates/core/src/model/websocket/README.md rename to backend/crates/station/src/websocket/payload/README.md index 6947c9117..b57f3bba4 100644 --- a/backend/crates/core/src/model/websocket/README.md +++ b/backend/crates/station/src/websocket/payload/README.md @@ -1,13 +1,15 @@ -# WebSocket Message Models (`model::websocket`) +# WebSocket Message Models (`websocket::payload`) JSON models for telemetry, connections, orders, messages, protection events -and logger control. The `websocket` feature enables the types in -`model/websocket.rs` and `model/websocket/`. +and logger control. The types live in station's `websocket/payload.rs` and +`websocket/payload/`, alongside the WebSocket implementation. The Rust types describe the payload of each topic. Messages sent over the WebSocket wrap that payload in `{topic, payload}`, as shown in the templates and example files below. Connections, subscriptions, channels and the broker -belong to the application (`station`). +are handled by the surrounding [WebSocket module](../README.md). Shared +serialization helpers live in [serialize.rs](serialize.rs), and domain types +such as `AdjId`, `Value` and `ProtectionPacket` come from `software_core::model`. ## Topics @@ -29,16 +31,11 @@ independent of the bundled ADJ fixture and HTTP catalog examples. ## Usage -Enable the feature in the application's dependency: - -```bash -cargo add software-core -F websocket -``` - -With a decoded `packet: ProtectionPacket`: +The payload module is compiled as part of station, without a separate feature. +Within station, with a decoded `packet: software_core::model::ProtectionPacket`: ```rust -use software_core::model::websocket::{OrderSend, ProtectionUpdate}; +use crate::websocket::payload::{OrderSend, ProtectionUpdate}; let request: OrderSend = serde_json::from_str(r#"{"id":1002,"fields":{}}"#)?; let protection = ProtectionUpdate::from(packet); @@ -48,7 +45,7 @@ let payload_json = serde_json::to_string(&protection)?; Published structures implement `serde::Serialize`; `OrderSend` and `OrderField` implement `serde::Deserialize`. The logger aliases use the primitive types' Serde implementations. All payload types are re-exported from -`model::websocket`. +`crate::websocket::payload` within station. Deserializing an order checks its JSON structure. Parameter types, ranges and their correspondence with the ADJ must be validated by the application before @@ -126,7 +123,6 @@ backend and the board. "fields": { "": { "value": number, // A boolean or enum string is also possible. - "isEnabled": boolean, "type": string } } diff --git a/backend/crates/core/src/model/websocket/connection.rs b/backend/crates/station/src/websocket/payload/connection.rs similarity index 99% rename from backend/crates/core/src/model/websocket/connection.rs rename to backend/crates/station/src/websocket/payload/connection.rs index 2e4a2d8c7..4fbe97955 100644 --- a/backend/crates/core/src/model/websocket/connection.rs +++ b/backend/crates/station/src/websocket/payload/connection.rs @@ -1,6 +1,5 @@ -use std::collections::HashMap; - use serde::Serialize; +use std::collections::HashMap; /// Payload of `connection/update`, keyed by board name. pub type ConnectionUpdate = HashMap; diff --git a/backend/crates/core/src/model/websocket/data.rs b/backend/crates/station/src/websocket/payload/data.rs similarity index 94% rename from backend/crates/core/src/model/websocket/data.rs rename to backend/crates/station/src/websocket/payload/data.rs index 8901f7e26..702081784 100644 --- a/backend/crates/core/src/model/websocket/data.rs +++ b/backend/crates/station/src/websocket/payload/data.rs @@ -1,8 +1,7 @@ -use std::collections::HashMap; - +use super::serialize::serialize_adj_id; use serde::Serialize; - -use crate::{model::AdjId, utils::serialize::serialize_adj_id}; +use software_core::model::AdjId; +use std::collections::HashMap; /// Payload of `podData/update`, keyed by packet id (JSON object keys are strings). pub type DataUpdate = HashMap; diff --git a/backend/crates/core/src/model/websocket/example/connection.json b/backend/crates/station/src/websocket/payload/example/connection.json similarity index 100% rename from backend/crates/core/src/model/websocket/example/connection.json rename to backend/crates/station/src/websocket/payload/example/connection.json diff --git a/backend/crates/core/src/model/websocket/example/data.json b/backend/crates/station/src/websocket/payload/example/data.json similarity index 100% rename from backend/crates/core/src/model/websocket/example/data.json rename to backend/crates/station/src/websocket/payload/example/data.json diff --git a/backend/crates/core/src/model/websocket/example/logger_enable.json b/backend/crates/station/src/websocket/payload/example/logger_enable.json similarity index 100% rename from backend/crates/core/src/model/websocket/example/logger_enable.json rename to backend/crates/station/src/websocket/payload/example/logger_enable.json diff --git a/backend/crates/core/src/model/websocket/example/logger_response.json b/backend/crates/station/src/websocket/payload/example/logger_response.json similarity index 100% rename from backend/crates/core/src/model/websocket/example/logger_response.json rename to backend/crates/station/src/websocket/payload/example/logger_response.json diff --git a/backend/crates/core/src/model/websocket/example/logger_variables.json b/backend/crates/station/src/websocket/payload/example/logger_variables.json similarity index 100% rename from backend/crates/core/src/model/websocket/example/logger_variables.json rename to backend/crates/station/src/websocket/payload/example/logger_variables.json diff --git a/backend/crates/core/src/model/websocket/example/message.json b/backend/crates/station/src/websocket/payload/example/message.json similarity index 100% rename from backend/crates/core/src/model/websocket/example/message.json rename to backend/crates/station/src/websocket/payload/example/message.json diff --git a/backend/crates/core/src/model/websocket/example/order.json b/backend/crates/station/src/websocket/payload/example/order.json similarity index 86% rename from backend/crates/core/src/model/websocket/example/order.json rename to backend/crates/station/src/websocket/payload/example/order.json index 853111e21..0aa349cb0 100644 --- a/backend/crates/core/src/model/websocket/example/order.json +++ b/backend/crates/station/src/websocket/payload/example/order.json @@ -5,7 +5,6 @@ "fields": { "target_speed": { "value": 12.5, - "isEnabled": true, "type": "float32" } } diff --git a/backend/crates/core/src/model/websocket/example/protection.json b/backend/crates/station/src/websocket/payload/example/protection.json similarity index 100% rename from backend/crates/core/src/model/websocket/example/protection.json rename to backend/crates/station/src/websocket/payload/example/protection.json diff --git a/backend/crates/core/src/model/websocket/example/state_orders.json b/backend/crates/station/src/websocket/payload/example/state_orders.json similarity index 100% rename from backend/crates/core/src/model/websocket/example/state_orders.json rename to backend/crates/station/src/websocket/payload/example/state_orders.json diff --git a/backend/crates/core/src/model/websocket/message.rs b/backend/crates/station/src/websocket/payload/message.rs similarity index 98% rename from backend/crates/core/src/model/websocket/message.rs rename to backend/crates/station/src/websocket/payload/message.rs index f6ce745bb..deee233e8 100644 --- a/backend/crates/core/src/model/websocket/message.rs +++ b/backend/crates/station/src/websocket/payload/message.rs @@ -1,8 +1,6 @@ -use serde::Serialize; - -use crate::model::{MessageLevel, Severity}; - use super::ProtectionPayload; +use serde::Serialize; +use software_core::model::{MessageLevel, Severity}; /// Payload of `message/update`, preserving the legacy event envelope. #[derive(Debug, Clone, PartialEq, Serialize)] diff --git a/backend/crates/core/src/model/websocket/order.rs b/backend/crates/station/src/websocket/payload/order.rs similarity index 84% rename from backend/crates/core/src/model/websocket/order.rs rename to backend/crates/station/src/websocket/payload/order.rs index 5b8cb221f..ed6453df1 100644 --- a/backend/crates/core/src/model/websocket/order.rs +++ b/backend/crates/station/src/websocket/payload/order.rs @@ -1,8 +1,7 @@ -use std::collections::HashMap; - +use super::serialize::deserialize_adj_id; use serde::Deserialize; - -use crate::{model::AdjId, utils::serialize::deserialize_adj_id}; +use software_core::model::AdjId; +use std::collections::HashMap; /// Payload of `order/send`; conversion to an `OrderPacket` requires the ADJ. #[derive(Debug, Clone, PartialEq, Deserialize)] @@ -20,9 +19,6 @@ pub struct OrderField { /// Raw JSON value; its type and range must be checked against the ADJ. /// Keeping it raw also preserves integer precision before validation. pub value: serde_json::Value, - /// Whether the frontend enables this parameter. - #[serde(rename = "isEnabled")] - pub is_enabled: bool, /// Legacy type name, such as `uint16`, `float32`, `bool` or `enum`. #[serde(rename = "type")] pub field_type: String, diff --git a/backend/crates/core/src/model/websocket/protection.rs b/backend/crates/station/src/websocket/payload/protection.rs similarity index 94% rename from backend/crates/core/src/model/websocket/protection.rs rename to backend/crates/station/src/websocket/payload/protection.rs index 6dbd1cafa..fddde0c71 100644 --- a/backend/crates/core/src/model/websocket/protection.rs +++ b/backend/crates/station/src/websocket/payload/protection.rs @@ -1,10 +1,8 @@ -use serde::Serialize; +use super::serialize::{serialize_adj_id, serialize_value}; +use serde::{Serialize}; use serde_json::Value as JsonValue; -use crate::{ - model::{AdjId, ProtectionPacket, ShortTimestamp, Value}, - utils::serialize::{serialize_adj_id, serialize_value}, -}; +use software_core::model::{AdjId, ProtectionPacket, ShortTimestamp, Value}; /// Payload of `protection/update`: the triggered id, measured value and time. #[derive(Debug, Clone, PartialEq, Serialize)] diff --git a/backend/crates/station/src/websocket/payload/serialize.rs b/backend/crates/station/src/websocket/payload/serialize.rs new file mode 100644 index 000000000..2d26e35ee --- /dev/null +++ b/backend/crates/station/src/websocket/payload/serialize.rs @@ -0,0 +1,28 @@ +use serde::{Deserialize, Deserializer, Serializer}; +use software_core::model::{AdjId, Value}; + +// Serializes the value of a protection message +pub(super) fn serialize_value( + value: &Value, + serializer: S, +) -> Result { + match value { + Value::Number(value) => serializer.serialize_f64(*value), + Value::Bool(value) => serializer.serialize_bool(*value), + Value::Enum(value) => serializer.serialize_str(value), + } +} + +// Deserializer works the other way around as Serializer +pub(super) fn deserialize_adj_id<'de, D: Deserializer<'de>>( + deserializer: D, +) -> Result { + u16::deserialize(deserializer).map(AdjId) +} + +pub(super) fn serialize_adj_id( + id: &AdjId, + serializer: S, +) -> Result { + serializer.serialize_u16(id.0) +} diff --git a/backend/crates/station/src/websocket/receiver.rs b/backend/crates/station/src/websocket/receiver.rs index e69de29bb..cc03c0541 100644 --- a/backend/crates/station/src/websocket/receiver.rs +++ b/backend/crates/station/src/websocket/receiver.rs @@ -0,0 +1,126 @@ +use std::time::Duration; + +use axum::extract::ws::Message as Frame; +use futures_util::{Stream, StreamExt}; +use serde::Deserialize; +use tokio::{ + sync::watch, + time::{Instant, timeout_at}, +}; + +use super::{CONNECTION_UPDATE, HEARTBEAT, WsMessage, error::Error}; + +const HEARTBEAT_TIMEOUT: Duration = Duration::from_secs(3); + +#[derive(Deserialize)] +struct Subscription { + subscribe: Option, +} + +/// Handles subscriptions and renews the deadline on each valid JSON message. +pub(super) async fn run( + mut read: impl Stream> + Unpin, + subscription: watch::Sender, +) -> Result<(), Error> { + let mut deadline = Instant::now() + HEARTBEAT_TIMEOUT; + loop { + let frame = timeout_at(deadline, read.next()) + .await + .map_err(|_| Error::HeartbeatTimeout)?; + let Some(frame) = frame else { + return Ok(()); + }; + match frame? { + Frame::Text(text) => { + let message: WsMessage = serde_json::from_str(&text)?; + match message.topic.as_str() { + CONNECTION_UPDATE => { + let request: Subscription = serde_json::from_value(message.payload)?; + let subscribed = request.subscribe.unwrap_or(true); + subscription.send_if_modified(|current| { + let changed = *current != subscribed; + *current = subscribed; + changed + }); + } + HEARTBEAT => {} + topic => tracing::warn!(topic, "unsupported WebSocket topic"), + } + deadline = Instant::now() + HEARTBEAT_TIMEOUT; + } + Frame::Close(_) => return Ok(()), + _ => {} + } + } +} + +#[cfg(test)] +mod tests { + use futures_util::stream; + use tokio::time::advance; + + use super::*; + + #[tokio::test(start_paused = true)] + async fn inactivity_expires() { + let (subscription, _state) = watch::channel(false); + assert!(matches!( + run(stream::pending(), subscription).await, + Err(Error::HeartbeatTimeout) + )); + } + + #[tokio::test(start_paused = true)] + async fn subscription_messages_also_renew_the_deadline() + -> Result<(), Box> { + let (input, mut frames) = tokio::sync::mpsc::channel(1); + let read = stream::poll_fn(move |cx| frames.poll_recv(cx)); + let (subscription, mut state) = watch::channel(false); + let worker = tokio::spawn(run(read, subscription)); + tokio::task::yield_now().await; + + advance(Duration::from_secs(2)).await; + input + .send(Ok(Frame::Text( + r#"{"topic":"connection/update","payload":{"subscribe":true}}"#.into(), + ))) + .await?; + state.changed().await?; + advance(Duration::from_secs(2)).await; + assert!(!worker.is_finished()); + advance(Duration::from_secs(1)).await; + assert!(matches!(worker.await?, Err(Error::HeartbeatTimeout))); + Ok(()) + } + + #[tokio::test] + async fn heartbeats_do_not_subscribe_or_publish() -> Result<(), Error> { + let (subscription, state) = watch::channel(false); + let frames = stream::iter([ + Ok(Frame::Text( + r#"{"topic":"connection/heartbeat","payload":{}}"#.into(), + )), + Ok(Frame::Close(None)), + ]); + run(frames, subscription).await?; + assert!(!*state.borrow()); + Ok(()) + } + + #[tokio::test] + async fn subscription_requests_can_unsubscribe() -> Result<(), Error> { + let (subscription, state) = watch::channel(false); + let frames = stream::iter([ + Ok(Frame::Text( + r#"{"topic":"connection/update","payload":{}}"#.into(), + )), + Ok(Frame::Text( + r#"{"topic":"connection/update","payload":{"subscribe":false}}"#.into(), + )), + Ok(Frame::Close(None)), + ]); + run(frames, subscription).await?; + assert!(!*state.borrow()); + Ok(()) + } +} diff --git a/backend/crates/station/src/websocket/sender.rs b/backend/crates/station/src/websocket/sender.rs index e69de29bb..432de565e 100644 --- a/backend/crates/station/src/websocket/sender.rs +++ b/backend/crates/station/src/websocket/sender.rs @@ -0,0 +1,41 @@ +use axum::extract::ws::{Message as Frame, WebSocket}; +use futures_util::{SinkExt, stream::SplitSink}; +use tokio::sync::watch; + +use super::{CONNECTION_UPDATE, WsMessage, broker::BrokerClient, error::Error}; + +/// Sends the current state on subscription, followed by complete state updates. +pub(super) async fn run( + write: &mut SplitSink, + broker: &BrokerClient, + mut subscribed: watch::Receiver, +) -> Result<(), Error> { + let mut connections = broker.subscribe_connections(); + loop { + if !*subscribed.borrow_and_update() { + if subscribed.changed().await.is_err() { + return Ok(()); + } + continue; + } + + let payload = serde_json::to_value(&*connections.borrow_and_update())?; + let message = WsMessage { + topic: CONNECTION_UPDATE.into(), + payload, + }; + write + .send(Frame::Text(serde_json::to_string(&message)?.into())) + .await?; + + tokio::select! { + biased; + result = subscribed.changed() => { + if result.is_err() { return Ok(()); } + } + result = connections.changed() => { + result.map_err(|_| Error::BrokerClosed)?; + } + } + } +} From 4e6d5b82267f749b313d9f75a06b2ecfd2a17471 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Wed, 25 Nov 2026 01:38:17 +0100 Subject: [PATCH 05/14] fmt(backend, websocket): format --- backend/crates/station/src/websocket/payload/protection.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/crates/station/src/websocket/payload/protection.rs b/backend/crates/station/src/websocket/payload/protection.rs index fddde0c71..42e9e9496 100644 --- a/backend/crates/station/src/websocket/payload/protection.rs +++ b/backend/crates/station/src/websocket/payload/protection.rs @@ -1,5 +1,5 @@ use super::serialize::{serialize_adj_id, serialize_value}; -use serde::{Serialize}; +use serde::Serialize; use serde_json::Value as JsonValue; use software_core::model::{AdjId, ProtectionPacket, ShortTimestamp, Value}; From 3cf93d67f102794642d9772b17c35b32f53a0f3c Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Wed, 25 Nov 2026 01:38:53 +0100 Subject: [PATCH 06/14] feat(backend, websocket): add topic subscriptions and validated order forwarding and some tests in http --- backend/crates/station/src/http/server.rs | 353 +++++++++++++++++- backend/crates/station/src/websocket.rs | 54 ++- .../crates/station/src/websocket/broker.rs | 284 +++++++++++++- backend/crates/station/src/websocket/error.rs | 31 ++ .../crates/station/src/websocket/handler.rs | 16 +- backend/crates/station/src/websocket/order.rs | 180 +++++++++ .../crates/station/src/websocket/receiver.rs | 175 +++++++-- .../crates/station/src/websocket/sender.rs | 141 +++++-- 8 files changed, 1146 insertions(+), 88 deletions(-) create mode 100644 backend/crates/station/src/websocket/order.rs diff --git a/backend/crates/station/src/http/server.rs b/backend/crates/station/src/http/server.rs index 3526a44b0..1f5584852 100644 --- a/backend/crates/station/src/http/server.rs +++ b/backend/crates/station/src/http/server.rs @@ -282,12 +282,12 @@ pub(super) mod tests { #[tokio::test] async fn websocket_subscription_receives_connection_snapshots() -> Result<(), Box> { - use super::super::super::websocket::payload::Connection; + use crate::websocket::payload::{Connection, StateOrdersUpdate}; let (broker, client) = crate::websocket::broker::Broker::new(); let broker_worker = tokio::spawn(broker.run()); let (connections, receiver) = mpsc::channel(1); - let worker = tokio::spawn(crate::websocket::run(receiver, client.clone())); + let worker = tokio::spawn(crate::websocket::run(receiver, client.clone(), None)); let app = setup_router(&Adj::default(), Some(connections))?; let (headers, mut first) = handshake(app.clone()).await?; assert!(headers.starts_with("HTTP/1.1 101 Switching Protocols\r\n")); @@ -302,7 +302,7 @@ pub(super) mod tests { // Other frontend topics can be added incrementally without closing the socket. send_text( &mut first, - r#"{"topic":"podData/update","payload":{"subscribe":true}}"#, + r#"{"topic":"not-a-topic","payload":{"subscribe":true}}"#, ) .await?; send_text( @@ -354,6 +354,175 @@ pub(super) mod tests { assert_eq!(read_json(&mut first).await?, expected); assert_eq!(read_json(&mut second).await?, expected); + send_text( + &mut first, + r#"{"topic":"order/stateOrders","payload":{"subscribe":true}}"#, + ) + .await?; + assert_eq!( + read_json(&mut first).await?, + serde_json::json!({ + "topic": "order/stateOrders", "payload": {} + }) + ); + send_text( + &mut second, + r#"{"topic":"logger/response","payload":{"subscribe":true}}"#, + ) + .await?; + assert_eq!( + read_json(&mut second).await?, + serde_json::json!({ + "topic": "logger/response", "payload": false + }) + ); + + client + .publish_state_orders(StateOrdersUpdate::from([("LCU".into(), vec![1001])])) + .await?; + assert_eq!( + read_json(&mut first).await?, + serde_json::json!({ + "topic": "order/stateOrders", "payload": {"LCU": [1001]} + }) + ); + assert!( + timeout(Duration::from_millis(50), second.read_u8()) + .await + .is_err() + ); + + client.publish_logger(true).await?; + assert_eq!( + read_json(&mut second).await?, + serde_json::json!({ + "topic": "logger/response", "payload": true + }) + ); + assert!( + timeout(Duration::from_millis(50), first.read_u8()) + .await + .is_err() + ); + + // The logger snapshot confirms the preceding unsubscribe was handled. + send_text( + &mut first, + r#"{"topic":"order/stateOrders","payload":{"subscribe":false}}"#, + ) + .await?; + send_text( + &mut first, + r#"{"topic":"logger/response","payload":{"subscribe":true}}"#, + ) + .await?; + assert_eq!( + read_json(&mut first).await?, + serde_json::json!({ + "topic": "logger/response", "payload": true + }) + ); + client + .publish_state_orders(StateOrdersUpdate::from([("LCU".into(), vec![])])) + .await?; + assert!( + timeout(Duration::from_millis(50), first.read_u8()) + .await + .is_err() + ); + + // Resubscribing recovers the latest full state, including empty lists. + send_text(&mut first, r#"{"topic":"order/stateOrders","payload":{}}"#).await?; + assert_eq!( + read_json(&mut first).await?, + serde_json::json!({ + "topic": "order/stateOrders", "payload": {"LCU": []} + }) + ); + client.publish_logger(false).await?; + let expected = serde_json::json!({"topic": "logger/response", "payload": false}); + assert_eq!(read_json(&mut first).await?, expected); + assert_eq!(read_json(&mut second).await?, expected); + + for socket in [&mut first, &mut second] { + socket.write_all(&[0x88, 0x80, 0, 0, 0, 0]).await?; + assert_eq!(socket.read_u8().await?, 0x88); + } + Ok::<_, Box>(()) + }) + .await??; + drop(client); + worker.await?; + timeout(Duration::from_secs(5), broker_worker).await??; + Ok(()) + } + + #[tokio::test] + async fn websocket_telemetry_sends_complete_snapshots() -> Result<(), Box> + { + use crate::websocket::payload::{DataPacketUpdate, MeasurementUpdate}; + use software_core::model::AdjId; + + let (broker, client) = crate::websocket::broker::Broker::new(); + let broker_worker = tokio::spawn(broker.run()); + let (connections, receiver) = mpsc::channel(1); + let worker = tokio::spawn(crate::websocket::run(receiver, client.clone(), None)); + let app = setup_router(&Adj::default(), Some(connections))?; + let (_, mut first) = handshake(app.clone()).await?; + let (_, mut second) = handshake(app).await?; + + timeout(Duration::from_secs(5), async { + send_text( + &mut first, + r#"{"topic":"podData/update","payload":{"subscribe":true}}"#, + ) + .await?; + assert_eq!( + read_json(&mut first).await?, + serde_json::json!({ + "topic": "podData/update", "payload": {} + }) + ); + + let packet = DataPacketUpdate { + id: AdjId(1000), + hex_value: "e8030000bc41".into(), + count: 1, + cycle_time: 100_000_000, + measurement_updates: std::collections::HashMap::from([( + "temperature".into(), + MeasurementUpdate::Numeric { + last: 23.5, + average: 23.0, + }, + )]), + }; + client.publish_data(packet.clone()).await?; + let expected = serde_json::json!({ + "topic": "podData/update", + "payload": {"1000": { + "id": 1000, "hexValue": "e8030000bc41", "count": 1, "cycleTime": 100_000_000, + "measurementUpdates": {"temperature": {"last": 23.5, "average": 23.0}} + }} + }); + assert_eq!(read_json(&mut first).await?, expected); + + send_text(&mut second, r#"{"topic":"podData/update","payload":{}}"#).await?; + assert_eq!(read_json(&mut second).await?, expected); + client + .publish_data(DataPacketUpdate { + id: AdjId(1001), + hex_value: "e9030000bc41".into(), + ..packet + }) + .await?; + let updated = read_json(&mut first).await?; + assert_eq!(updated["topic"], "podData/update"); + assert_eq!(updated["payload"].as_object().map(|map| map.len()), Some(2)); + assert_eq!(updated["payload"]["1000"], expected["payload"]["1000"]); + assert_eq!(updated["payload"]["1001"]["id"], 1001); + assert_eq!(read_json(&mut second).await?, updated); + for socket in [&mut first, &mut second] { socket.write_all(&[0x88, 0x80, 0, 0, 0, 0]).await?; assert_eq!(socket.read_u8().await?, 0x88); @@ -367,14 +536,184 @@ pub(super) mod tests { Ok(()) } + #[tokio::test] + async fn websocket_event_subscriptions_deliver_live_payloads() + -> Result<(), Box> { + use crate::websocket::{ + broker::Broker, + payload::{ + MessageKind, MessagePayload, MessageTimestamp, MessageUpdate, ProtectionUpdate, + }, + }; + use serde_json::json; + use software_core::model::{AdjId, ShortTimestamp, Value}; + + let (broker, client) = Broker::new(); + let broker_worker = tokio::spawn(broker.run()); + let (sockets, receiver) = mpsc::channel(1); + let worker = tokio::spawn(crate::websocket::run(receiver, client.clone(), None)); + let message = MessageUpdate { + kind: MessageKind::Info, + payload: MessagePayload::Text("Order Sent".into()), + board: "LCU".into(), + name: "1001".into(), + timestamp: MessageTimestamp { + counter: 0, + second: 5, + minute: 30, + hour: 12, + day: 24, + month: 11, + year: 2026, + }, + }; + let protection = ProtectionUpdate { + id: AdjId(11192), + value: Value::Number(105.5), + timestamp: ShortTimestamp { + hour: 12, + minute: 30, + second: 6, + subsecond: 0, + }, + }; + let expected_message: serde_json::Value = + serde_json::from_str(include_str!("../websocket/payload/example/message.json"))?; + let expected_protection: serde_json::Value = + serde_json::from_str(include_str!("../websocket/payload/example/protection.json"))?; + let (_, mut socket) = handshake(setup_router(&Adj::default(), Some(sockets))?).await?; + + timeout(Duration::from_secs(5), async { + let mut logger = client.subscribe_logger(); + client + .publish_message(MessageUpdate { + payload: MessagePayload::Text("Before subscribing".into()), + ..message.clone() + }) + .await?; + client.publish_logger(true).await?; + logger.changed().await?; + send_text(&mut socket, r#"{"topic":"message/update","payload":{}}"#).await?; + send_text( + &mut socket, + r#"{"topic":"protection/update","payload":{"subscribe":true}}"#, + ) + .await?; + // The state snapshot confirms the preceding subscriptions were processed. + send_text(&mut socket, r#"{"topic":"logger/response","payload":{}}"#).await?; + assert_eq!( + read_json(&mut socket).await?, + json!({"topic": "logger/response", "payload": true}) + ); + + client.publish_message(message.clone()).await?; + assert_eq!(read_json(&mut socket).await?, expected_message); + client.publish_protection(protection.clone()).await?; + assert_eq!(read_json(&mut socket).await?, expected_protection); + + send_text( + &mut socket, + r#"{"topic":"message/update","payload":{"subscribe":false}}"#, + ) + .await?; + send_text(&mut socket, r#"{"topic":"connection/update","payload":{}}"#).await?; + assert_eq!( + read_json(&mut socket).await?, + json!({"topic": "connection/update", "payload": {}}) + ); + client + .publish_message(MessageUpdate { + payload: MessagePayload::Text("While unsubscribed".into()), + ..message + }) + .await?; + client.publish_protection(protection).await?; + assert_eq!(read_json(&mut socket).await?, expected_protection); + assert!( + timeout(Duration::from_millis(50), socket.read_u8()) + .await + .is_err() + ); + + socket.write_all(&[0x88, 0x80, 0, 0, 0, 0]).await?; + assert_eq!(socket.read_u8().await?, 0x88); + Ok::<_, Box>(()) + }) + .await??; + drop(client); + worker.await?; + timeout(Duration::from_secs(5), broker_worker).await??; + Ok(()) + } + + #[tokio::test] + async fn websocket_forwards_validated_orders_in_adj_order() + -> Result<(), Box> { + use crate::websocket::{OrderForwarder, broker::Broker}; + use software_core::{ + model::{AdjId, OrderPacket, Value}, + protocol::Index, + }; + use std::sync::Arc; + + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../core/src/adj/test/adj"); + let adj = load_from_dir(&path)?; + let index = Arc::new(Index::new(&adj.pod_data, None)); + let (order_tx, mut orders) = mpsc::channel(1); + let forwarder = OrderForwarder::new(index, order_tx); + let (broker, client) = Broker::new(); + let broker_worker = tokio::spawn(broker.run()); + let (connections, receiver) = mpsc::channel(1); + let worker = tokio::spawn(crate::websocket::run(receiver, client, Some(forwarder))); + let (_, mut socket) = handshake(setup_router(&adj, Some(connections))?).await?; + + timeout(Duration::from_secs(5), async { + for invalid in [ + r#"{"topic":"order/send","payload":{"id":65535,"fields":{}}}"#, + r#"{"topic":"order/send","payload":{"id":809,"fields":{}}}"#, + r#"{"topic":"order/send","payload":{"id":801,"fields":{"extra":{"value":0,"type":"uint8"}}}}"#, + r#"{"topic":"order/send","payload":{"id":809,"fields":{"desired_current":{"value":12.5,"type":"float64"},"lpu_id":{"value":2,"type":"uint32"}}}}"#, + r#"{"topic":"order/send","payload":{"id":809,"fields":{"desired_current":{"value":12.5,"type":"float32"},"lpu_id":{"value":2.5,"type":"uint32"}}}}"#, + ] { + send_text(&mut socket, invalid).await?; + } + send_text(&mut socket, r#"{"topic":"order/send","payload":{"id":809,"fields":{"desired_current":{"value":12.5,"type":"float32"},"lpu_id":{"value":2,"type":"uint32"}}}}"#).await?; + let stop = r#"{"topic":"order/send","payload":{"id":801,"fields":{}}}"#; + send_text(&mut socket, stop).await?; + + // The snapshot confirms both requests reached the receiver before we free the queue. + send_text(&mut socket, r#"{"topic":"connection/update","payload":{}}"#).await?; + assert_eq!(read_json(&mut socket).await?["topic"], "connection/update"); + assert_eq!(orders.recv().await, Some(OrderPacket::new( + AdjId(809), vec![Value::Number(2.0), Value::Number(12.5)], + ))); + assert!(matches!(orders.try_recv(), Err(mpsc::error::TryRecvError::Empty))); + + send_text(&mut socket, stop).await?; + assert_eq!(orders.recv().await, Some(OrderPacket::new(AdjId(801), vec![]))); + + socket.write_all(&[0x88, 0x80, 0, 0, 0, 0]).await?; + assert_eq!(socket.read_u8().await?, 0x88); + Ok::<_, Box>(()) + }).await??; + worker.await?; + timeout(Duration::from_secs(5), broker_worker).await??; + Ok(()) + } + async fn send_text( client: &mut TcpStream, text: &str, ) -> Result<(), Box> { - // Test requests fit a short masked frame; a zero mask leaves the JSON unchanged. - let length = u8::try_from(text.len())?; - assert!(length < 126); - client.write_all(&[0x81, 0x80 | length, 0, 0, 0, 0]).await?; + // A zero mask leaves the test JSON unchanged. + let length = u16::try_from(text.len())?; + if length < 126 { + client.write_all(&[0x81, 0x80 | length as u8]).await?; + } else { + client.write_all(&[0x81, 0xfe]).await?; + client.write_u16(length).await?; + } + client.write_all(&[0; 4]).await?; client.write_all(text.as_bytes()).await?; Ok(()) } diff --git a/backend/crates/station/src/websocket.rs b/backend/crates/station/src/websocket.rs index 7071721bd..0fce10c17 100644 --- a/backend/crates/station/src/websocket.rs +++ b/backend/crates/station/src/websocket.rs @@ -5,17 +5,60 @@ use serde::{Deserialize, Serialize}; use tokio::sync::mpsc; use self::broker::BrokerClient; +pub(crate) use self::order::OrderForwarder; pub mod broker; mod error; mod handler; +mod order; +pub(super) mod payload; mod receiver; mod sender; -pub(super) mod payload; const CONNECTION_UPDATE: &str = "connection/update"; +const STATE_ORDERS: &str = "order/stateOrders"; +const LOGGER_RESPONSE: &str = "logger/response"; +const DATA_UPDATE: &str = "podData/update"; +const MESSAGE_UPDATE: &str = "message/update"; +const PROTECTION_UPDATE: &str = "protection/update"; +const ORDER_SEND: &str = "order/send"; const HEARTBEAT: &str = "connection/heartbeat"; +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +enum Topic { + Connections, + StateOrders, + Logger, + Data, + Messages, + Protections, +} + +impl Topic { + fn from_name(name: &str) -> Option { + match name { + CONNECTION_UPDATE => Some(Self::Connections), + STATE_ORDERS => Some(Self::StateOrders), + LOGGER_RESPONSE => Some(Self::Logger), + DATA_UPDATE => Some(Self::Data), + MESSAGE_UPDATE => Some(Self::Messages), + PROTECTION_UPDATE => Some(Self::Protections), + _ => None, + } + } + + fn name(self) -> &'static str { + match self { + Self::Connections => CONNECTION_UPDATE, + Self::StateOrders => STATE_ORDERS, + Self::Logger => LOGGER_RESPONSE, + Self::Data => DATA_UPDATE, + Self::Messages => MESSAGE_UPDATE, + Self::Protections => PROTECTION_UPDATE, + } + } +} + /// JSON envelope shared with the frontend. #[derive(Debug, Serialize, Deserialize)] pub struct WsMessage { @@ -35,12 +78,17 @@ pub struct WsMessage { } /// Handles each connection independently while HTTP keeps accepting sockets. -pub async fn run(mut connections: mpsc::Receiver, broker: BrokerClient) { +pub async fn run( + mut connections: mpsc::Receiver, + broker: BrokerClient, + orders: Option, +) { // Spawn one tokio task per Websocket connection while let Some(socket) = connections.recv().await { let broker = broker.clone(); + let orders = orders.clone(); tokio::spawn(async move { - if let Err(error) = handler::handle(socket, broker).await { + if let Err(error) = handler::handle(socket, broker, orders.as_ref()).await { tracing::warn!(%error, "WebSocket connection ended with an error"); } }); diff --git a/backend/crates/station/src/websocket/broker.rs b/backend/crates/station/src/websocket/broker.rs index a9d9275ac..64079557e 100644 --- a/backend/crates/station/src/websocket/broker.rs +++ b/backend/crates/station/src/websocket/broker.rs @@ -1,47 +1,120 @@ -//! Publishes the current board connection state to subscribers. +//! Publishes current state and forwards messages and protection events. -use super::payload::{Connection, ConnectionUpdate}; -use tokio::sync::{mpsc, watch}; +use std::time::Duration; + +use super::payload::{ + Connection, ConnectionUpdate, DataPacketUpdate, DataUpdate, LoggerResponse, MessageUpdate, + ProtectionUpdate, StateOrdersUpdate, +}; +use tokio::{ + sync::{broadcast, mpsc, watch}, + time::{Instant, MissedTickBehavior, interval_at}, +}; pub use super::error::Error; -/// Owns the connection state and processes incoming updates. +const EVENT_CAPACITY: usize = 128; + +#[derive(Debug)] +enum Update { + Connection(Connection), + StateOrders(StateOrdersUpdate), + Logger(LoggerResponse), + Data(DataPacketUpdate), + Message(MessageUpdate), + Protection(ProtectionUpdate), +} + +/// Owns the topic states and processes incoming updates. #[derive(Debug)] pub struct Broker { - updates: mpsc::Receiver, + updates: mpsc::Receiver, connections: watch::Sender, + state_orders: watch::Sender, + logger: watch::Sender, + data: watch::Sender, + messages: broadcast::Sender, + protections: broadcast::Sender, } -/// Clonable access to connection publication and subscriptions. +/// Clonable access to publication and subscriptions. #[derive(Debug, Clone)] pub struct BrokerClient { - updates: mpsc::Sender, + updates: mpsc::Sender, connections: watch::Receiver, + state_orders: watch::Receiver, + logger: watch::Receiver, + data: watch::Receiver, + messages: broadcast::WeakSender, + protections: broadcast::WeakSender, } impl Broker { - /// Creates a broker and its client, initially with no known connections. + /// Starts with empty state maps and a stopped logger. pub fn new() -> (Self, BrokerClient) { let (updates, receiver) = mpsc::channel(32); let (connections, state) = watch::channel(ConnectionUpdate::new()); + let (state_orders, orders) = watch::channel(StateOrdersUpdate::new()); + let (logger, recording) = watch::channel(false); + let (data, telemetry) = watch::channel(DataUpdate::new()); + let (messages, _) = broadcast::channel(EVENT_CAPACITY); + let (protections, _) = broadcast::channel(EVENT_CAPACITY); + let message_topic = messages.downgrade(); + let protection_topic = protections.downgrade(); ( Self { updates: receiver, connections, + state_orders, + logger, + data, + messages, + protections, }, BrokerClient { updates, connections: state, + state_orders: orders, + logger: recording, + data: telemetry, + messages: message_topic, + protections: protection_topic, }, ) } /// Processes updates until all publishing clients have been dropped. pub async fn run(mut self) { - while let Some(connection) = self.updates.recv().await { - self.connections.send_modify(|state| { - state.insert(connection.name.clone(), connection); - }); + let period = Duration::from_millis(100); + let mut tick = interval_at(Instant::now() + period, period); + tick.set_missed_tick_behavior(MissedTickBehavior::Skip); + let mut pending = DataUpdate::new(); + loop { + tokio::select! { + update = self.updates.recv() => { + match update { + Some(Update::Connection(connection)) => self.connections.send_modify(|state| { + state.insert(connection.name.clone(), connection); + }), + Some(Update::StateOrders(orders)) => { self.state_orders.send_replace(orders); } + Some(Update::Logger(recording)) => { self.logger.send_replace(recording); } + Some(Update::Data(packet)) => { pending.insert(packet.id.0, packet); } + Some(Update::Message(message)) => { let _ = self.messages.send(message); } + Some(Update::Protection(protection)) => { let _ = self.protections.send(protection); } + None => { + self.flush_data(&mut pending); + return; + } + } + } + _ = tick.tick() => self.flush_data(&mut pending), + } + } + } + + fn flush_data(&self, pending: &mut DataUpdate) { + if !pending.is_empty() { + self.data.send_modify(|state| state.extend(pending.drain())); } } } @@ -49,8 +122,37 @@ impl Broker { impl BrokerClient { /// Queues a board connection update, waiting if the input channel is full. pub async fn publish_connection(&self, connection: Connection) -> Result<(), Error> { + self.publish(Update::Connection(connection)).await + } + + /// Queues the complete map of enabled orders, replacing the previous map. + pub async fn publish_state_orders(&self, orders: StateOrdersUpdate) -> Result<(), Error> { + self.publish(Update::StateOrders(orders)).await + } + + /// Queues the actual logger state reported by the backend. + pub async fn publish_logger(&self, recording: LoggerResponse) -> Result<(), Error> { + self.publish(Update::Logger(recording)).await + } + + /// Queues a complete, prepared packet update for the next 100 ms batch. + pub async fn publish_data(&self, packet: DataPacketUpdate) -> Result<(), Error> { + self.publish(Update::Data(packet)).await + } + + /// Queues a message for current subscribers. + pub async fn publish_message(&self, message: MessageUpdate) -> Result<(), Error> { + self.publish(Update::Message(message)).await + } + + /// Queues a protection event for current subscribers. + pub async fn publish_protection(&self, protection: ProtectionUpdate) -> Result<(), Error> { + self.publish(Update::Protection(protection)).await + } + + async fn publish(&self, update: Update) -> Result<(), Error> { self.updates - .send(connection) + .send(update) .await .map_err(|_| Error::BrokerClosed) } @@ -58,17 +160,48 @@ impl BrokerClient { /// Subscribes to the complete connection map, starting at its current state. /// Read that state with `borrow_and_update()`, then wait on `changed()`. pub fn subscribe_connections(&self) -> watch::Receiver { - let mut receiver = self.connections.clone(); - receiver.borrow_and_update(); - receiver + subscribe(&self.connections) + } + + /// Subscribes to the complete map of enabled order ids by board name. + pub fn subscribe_state_orders(&self) -> watch::Receiver { + subscribe(&self.state_orders) + } + + /// Subscribes to the actual recording state, initially `false`. + pub fn subscribe_logger(&self) -> watch::Receiver { + subscribe(&self.logger) } + + /// Subscribes to the complete telemetry map, initially empty. + pub fn subscribe_data(&self) -> watch::Receiver { + subscribe(&self.data) + } + + /// Subscribes to future messages. + pub fn subscribe_messages(&self) -> Result, Error> { + let sender = self.messages.upgrade().ok_or(Error::BrokerClosed)?; + Ok(sender.subscribe()) + } + + /// Subscribes to future protection events. + pub fn subscribe_protections(&self) -> Result, Error> { + let sender = self.protections.upgrade().ok_or(Error::BrokerClosed)?; + Ok(sender.subscribe()) + } +} + +fn subscribe(state: &watch::Receiver) -> watch::Receiver { + let mut receiver = state.clone(); + receiver.borrow_and_update(); + receiver } #[cfg(test)] mod tests { use std::time::Duration; - use tokio::time::timeout; + use tokio::time::{advance, timeout}; use super::*; @@ -123,6 +256,102 @@ mod tests { }) .await; assert!(matches!(result, Err(Error::BrokerClosed))); + assert!(matches!( + client.publish_state_orders(StateOrdersUpdate::new()).await, + Err(Error::BrokerClosed) + )); + assert!(matches!( + client.publish_logger(true).await, + Err(Error::BrokerClosed) + )); + assert!(matches!( + client.publish_data(packet(1000, 1)).await, + Err(Error::BrokerClosed) + )); + } + + #[tokio::test(start_paused = true)] + async fn telemetry_batches_latest_packets_and_keeps_the_complete_state() + -> Result<(), Box> { + let (broker, client) = Broker::new(); + let mut data = client.subscribe_data(); + let mut logger = client.subscribe_logger(); + assert!(data.borrow_and_update().is_empty()); + let worker = tokio::spawn(broker.run()); + tokio::task::yield_now().await; + + client.publish_data(packet(1000, 1)).await?; + client.publish_data(packet(2000, 1)).await?; + client.publish_data(packet(1000, 2)).await?; + // The logger update is a barrier: the preceding inputs have been processed. + client.publish_logger(true).await?; + logger.changed().await?; + assert!(!data.has_changed()?); + advance(Duration::from_millis(99)).await; + assert!(!data.has_changed()?); + advance(Duration::from_millis(1)).await; + timeout(Duration::from_millis(1), data.changed()).await??; + let snapshot = data.borrow_and_update().clone(); + assert_eq!(snapshot.len(), 2); + assert_eq!(snapshot[&1000].count, 2); + assert_eq!(snapshot[&2000].count, 1); + + let late = client.subscribe_data(); + assert_eq!(*late.borrow(), snapshot); + assert!(!late.has_changed()?); + advance(Duration::from_millis(100)).await; + tokio::task::yield_now().await; + assert!(!data.has_changed()?, "idle ticks must not publish"); + + client.publish_data(packet(2000, 2)).await?; + client.publish_logger(false).await?; + logger.changed().await?; + advance(Duration::from_millis(100)).await; + timeout(Duration::from_millis(1), data.changed()).await??; + assert_eq!(data.borrow()[&1000].count, 2); + assert_eq!(data.borrow()[&2000].count, 2); + + drop(client); + timeout(Duration::from_secs(1), worker).await??; + Ok(()) + } + + #[tokio::test] + async fn orders_and_logger_keep_independent_current_states() + -> Result<(), Box> { + let (broker, client) = Broker::new(); + let mut orders = client.subscribe_state_orders(); + let mut logger = client.subscribe_logger(); + assert!(orders.borrow_and_update().is_empty()); + assert!(!*logger.borrow_and_update()); + let worker = tokio::spawn(broker.run()); + + let initial = StateOrdersUpdate::from([("LCU".into(), vec![1001, 1002])]); + client.publish_state_orders(initial.clone()).await?; + timeout(Duration::from_secs(1), orders.changed()).await??; + assert_eq!(*orders.borrow_and_update(), initial); + assert!(!logger.has_changed()?); + + client.publish_logger(true).await?; + timeout(Duration::from_secs(1), logger.changed()).await??; + assert!(*logger.borrow_and_update()); + assert!(!orders.has_changed()?); + + // A full snapshot replaces previous boards and can clear enabled orders. + let current = StateOrdersUpdate::from([("HVBMS".into(), vec![])]); + client.publish_state_orders(current.clone()).await?; + timeout(Duration::from_secs(1), orders.changed()).await??; + assert_eq!(*orders.borrow_and_update(), current); + let late_orders = client.subscribe_state_orders(); + let late_logger = client.subscribe_logger(); + assert_eq!(*late_orders.borrow(), current); + assert!(*late_logger.borrow()); + assert!(!late_orders.has_changed()?); + assert!(!late_logger.has_changed()?); + + drop(client); + timeout(Duration::from_secs(1), worker).await??; + Ok(()) } #[tokio::test] @@ -136,10 +365,31 @@ mod tests { is_connected: true, }) .await?; + let orders = client.subscribe_state_orders(); + let logger = client.subscribe_logger(); + client + .publish_state_orders(StateOrdersUpdate::from([("LCU".into(), vec![1001])])) + .await?; + client.publish_logger(true).await?; + let data = client.subscribe_data(); + client.publish_data(packet(1000, 1)).await?; drop(client); timeout(Duration::from_secs(1), broker.run()).await?; assert!(state.borrow()["LCU"].is_connected); + assert_eq!(orders.borrow()["LCU"], [1001]); + assert!(*logger.borrow()); + assert_eq!(data.borrow()[&1000].count, 1); Ok(()) } + + fn packet(id: u16, count: u64) -> DataPacketUpdate { + DataPacketUpdate { + id: software_core::model::AdjId(id), + hex_value: String::new(), + count, + cycle_time: 100_000_000, + measurement_updates: Default::default(), + } + } } diff --git a/backend/crates/station/src/websocket/error.rs b/backend/crates/station/src/websocket/error.rs index 5fc0f3eb8..bfe127d9b 100644 --- a/backend/crates/station/src/websocket/error.rs +++ b/backend/crates/station/src/websocket/error.rs @@ -1,9 +1,17 @@ +use software_core::model::AdjId; + /// Errors handling WebSocket connections and broker communication. #[derive(Debug, thiserror::Error)] pub enum Error { /// The broker no longer accepts updates. #[error("WebSocket broker is closed")] BrokerClosed, + /// The socket writer fell behind the subscription requests. + #[error("WebSocket subscription queue is full")] + SubscriptionQueueFull, + /// The client fell behind on an event topic. + #[error("WebSocket subscriber missed {missed} events on {topic}")] + EventLagged { topic: &'static str, missed: u64 }, /// Reading or writing the socket failed. #[error("WebSocket I/O failed: {0}")] Socket(#[from] axum::Error), @@ -14,3 +22,26 @@ pub enum Error { #[error("WebSocket heartbeat timed out")] HeartbeatTimeout, } + +#[derive(Debug, thiserror::Error)] +pub(super) enum OrderError { + #[error("invalid order payload: {0}")] + Json(#[from] serde_json::Error), + #[error("unknown order id {0:?}")] + UnknownOrder(AdjId), + #[error("missing order field {0:?}")] + MissingField(String), + #[error("unexpected order field {0:?}")] + UnexpectedField(String), + #[error("order field {field:?} must have type {expected}")] + WrongFieldType { + field: String, + expected: &'static str, + }, + #[error("invalid value for order field {0:?}")] + InvalidValue(String), + #[error("vehicle order queue is full")] + QueueFull, + #[error("vehicle order receiver is unavailable")] + VehicleUnavailable, +} diff --git a/backend/crates/station/src/websocket/handler.rs b/backend/crates/station/src/websocket/handler.rs index e6422f457..aca901803 100644 --- a/backend/crates/station/src/websocket/handler.rs +++ b/backend/crates/station/src/websocket/handler.rs @@ -2,17 +2,21 @@ use std::time::Duration; use axum::extract::ws::WebSocket; use futures_util::{SinkExt, StreamExt}; -use tokio::{sync::watch, time::timeout}; +use tokio::{sync::mpsc, time::timeout}; -use super::{broker::BrokerClient, error::Error, receiver, sender}; +use super::{OrderForwarder, broker::BrokerClient, error::Error, receiver, sender}; /// Runs reading and writing together; either side finishing ends the session. -pub(super) async fn handle(socket: WebSocket, broker: BrokerClient) -> Result<(), Error> { +pub(super) async fn handle( + socket: WebSocket, + broker: BrokerClient, + orders: Option<&OrderForwarder>, +) -> Result<(), Error> { let (mut write, read) = socket.split(); - let (subscription, subscribed) = watch::channel(false); + let (changes, subscriptions) = mpsc::channel(16); let result = tokio::select! { - result = receiver::run(read, subscription) => result, - result = sender::run(&mut write, &broker, subscribed) => result, + result = receiver::run(read, &broker, orders, changes) => result, + result = sender::run(&mut write, subscriptions) => result, }; let _ = timeout(Duration::from_secs(1), write.close()).await; result diff --git a/backend/crates/station/src/websocket/order.rs b/backend/crates/station/src/websocket/order.rs new file mode 100644 index 000000000..7cc3655a4 --- /dev/null +++ b/backend/crates/station/src/websocket/order.rs @@ -0,0 +1,180 @@ +use super::error::OrderError; +use serde_json::Value as JsonValue; +use software_core::{ + model::{MeasurementKind, NumericKind, OrderPacket, PacketType, Value}, + protocol::{Index, wire}, +}; +use std::sync::Arc; +use tokio::sync::mpsc; + +use super::payload::{OrderField, OrderSend}; + +/// Validates frontend requests against the ADJ and forwards them to the vehicle. +#[derive(Debug, Clone)] +pub(crate) struct OrderForwarder { + index: Arc, + orders: mpsc::Sender, +} + +impl OrderForwarder { + pub(crate) fn new(index: Arc, orders: mpsc::Sender) -> Self { + Self { index, orders } + } + + pub(super) fn forward(&self, payload: JsonValue) -> Result<(), OrderError> { + let request = serde_json::from_value(payload)?; + let packet = to_packet(request, &self.index)?; + self.orders.try_send(packet).map_err(|error| match error { + mpsc::error::TrySendError::Full(_) => OrderError::QueueFull, + mpsc::error::TrySendError::Closed(_) => OrderError::VehicleUnavailable, + }) + } +} + +fn to_packet(mut request: OrderSend, index: &Index) -> Result { + let Some(PacketType::Order(measurements)) = + index.packet(request.id).map(|packet| &packet.packet_type) + else { + return Err(OrderError::UnknownOrder(request.id)); + }; + + let mut values = Vec::with_capacity(measurements.len()); + for measurement in measurements { + let alias = &measurement.alias; + let field = request + .fields + .remove(alias) + .ok_or_else(|| OrderError::MissingField(alias.clone()))?; + values.push(field_value(&field, alias, &measurement.kind)?); + } + if let Some(extra) = request.fields.into_keys().next() { + return Err(OrderError::UnexpectedField(extra)); + } + Ok(OrderPacket::new(request.id, values)) +} + +fn field_value( + field: &OrderField, + alias: &str, + kind: &MeasurementKind, +) -> Result { + let expected = match kind { + MeasurementKind::Numeric { wire_type } => numeric_type_name(*wire_type), + MeasurementKind::Boolean => "bool", + MeasurementKind::Enum { .. } => "enum", + }; + if field.field_type != expected { + return Err(OrderError::WrongFieldType { + field: alias.into(), + expected, + }); + } + + let value = match kind { + MeasurementKind::Numeric { wire_type } => { + number(&field.value, *wire_type).map(Value::Number) + } + MeasurementKind::Boolean => field.value.as_bool().map(Value::Bool), + MeasurementKind::Enum { options } => field.value.as_str().and_then(|name| { + let index = options.iter().position(|option| option == name)?; + // The order encoder takes the one-byte index into the ADJ's options. + u8::try_from(index) + .ok() + .map(|index| Value::Number(f64::from(index))) + }), + } + .ok_or_else(|| OrderError::InvalidValue(alias.into()))?; + + wire::encode_value(&value, kind).map_err(|_| OrderError::InvalidValue(alias.into()))?; + Ok(value) +} + +fn number(value: &JsonValue, kind: NumericKind) -> Option { + let JsonValue::Number(raw) = value else { + return None; + }; + let number = raw.as_f64()?; + if matches!(kind, NumericKind::F32 | NumericKind::F64) { + return Some(number); + } + + let integer = raw + .as_i64() + .map(i128::from) + .or_else(|| raw.as_u64().map(i128::from)); + if let Some(integer) = integer { + // OrderPacket stores numbers as f64. Avoid changing a large integer in transit. + if number as i128 != integer { + return None; + } + } else if number.fract() != 0.0 || number.abs() >= (1_u64 << 53) as f64 { + return None; + } + // The 64-bit upper bounds round up when represented as f64. + match kind { + NumericKind::U64 if number >= u64::MAX as f64 => None, + NumericKind::I64 if number >= i64::MAX as f64 => None, + _ => Some(number), + } +} + +fn numeric_type_name(kind: NumericKind) -> &'static str { + match kind { + NumericKind::U8 => "uint8", + NumericKind::U16 => "uint16", + NumericKind::U32 => "uint32", + NumericKind::U64 => "uint64", + NumericKind::I8 => "int8", + NumericKind::I16 => "int16", + NumericKind::I32 => "int32", + NumericKind::I64 => "int64", + NumericKind::F32 => "float32", + NumericKind::F64 => "float64", + } +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + + #[test] + fn integer_fields_reject_values_the_packet_or_wire_would_change() { + let cases = [ + (NumericKind::U32, json!(2.5)), + (NumericKind::I64, json!(1_u64 << 63)), + (NumericKind::U64, json!((1_u64 << 53) + 1)), + (NumericKind::U64, json!(u64::MAX)), + ]; + for (kind, value) in cases { + assert!(number(&value, kind).is_none()); + } + assert_eq!(number(&json!(2.0), NumericKind::U32), Some(2.0)); + assert_eq!( + number(&json!(1_u64 << 63), NumericKind::U64), + Some((1_u64 << 63) as f64) + ); + } + + #[test] + fn enum_order_field_is_converted_to_the_encoder_index() -> Result<(), OrderError> { + let kind = MeasurementKind::Enum { + options: vec!["idle".into(), "ready".into()], + }; + let field = OrderField { + value: json!("ready"), + field_type: "enum".into(), + }; + assert_eq!(field_value(&field, "mode", &kind)?, Value::Number(1.0)); + let unknown = OrderField { + value: json!("unknown"), + ..field + }; + assert!(matches!( + field_value(&unknown, "mode", &kind), + Err(OrderError::InvalidValue(_)) + )); + Ok(()) + } +} diff --git a/backend/crates/station/src/websocket/receiver.rs b/backend/crates/station/src/websocket/receiver.rs index cc03c0541..e9d16adeb 100644 --- a/backend/crates/station/src/websocket/receiver.rs +++ b/backend/crates/station/src/websocket/receiver.rs @@ -1,14 +1,21 @@ -use std::time::Duration; - use axum::extract::ws::Message as Frame; use futures_util::{Stream, StreamExt}; use serde::Deserialize; +use std::{collections::HashSet, time::Duration}; use tokio::{ - sync::watch, + sync::{broadcast, mpsc, watch}, time::{Instant, timeout_at}, }; -use super::{CONNECTION_UPDATE, HEARTBEAT, WsMessage, error::Error}; +use super::{ + HEARTBEAT, ORDER_SEND, OrderForwarder, Topic, WsMessage, + broker::BrokerClient, + error::{Error, OrderError}, + payload::{ + ConnectionUpdate, DataUpdate, LoggerResponse, MessageUpdate, ProtectionUpdate, + StateOrdersUpdate, + }, +}; const HEARTBEAT_TIMEOUT: Duration = Duration::from_secs(3); @@ -17,11 +24,48 @@ struct Subscription { subscribe: Option, } -/// Handles subscriptions and renews the deadline on each valid JSON message. +/// Carries a new topic receiver, or `None` to unsubscribe. +#[derive(Debug)] +pub(super) enum SubscriptionChange { + Connections(Option>), + StateOrders(Option>), + Logger(Option>), + Data(Option>), + Messages(Option>), + Protections(Option>), +} + +impl SubscriptionChange { + fn new(broker: &BrokerClient, topic: Topic, enabled: bool) -> Result { + Ok(match topic { + Topic::Connections => { + Self::Connections(enabled.then(|| broker.subscribe_connections())) + } + Topic::StateOrders => { + Self::StateOrders(enabled.then(|| broker.subscribe_state_orders())) + } + Topic::Logger => Self::Logger(enabled.then(|| broker.subscribe_logger())), + Topic::Data => Self::Data(enabled.then(|| broker.subscribe_data())), + Topic::Messages => { + Self::Messages(enabled.then(|| broker.subscribe_messages()).transpose()?) + } + Topic::Protections => Self::Protections( + enabled + .then(|| broker.subscribe_protections()) + .transpose()?, + ), + }) + } +} + +/// Handles frontend requests and renews the deadline on each valid JSON message. pub(super) async fn run( mut read: impl Stream> + Unpin, - subscription: watch::Sender, + broker: &BrokerClient, + orders: Option<&OrderForwarder>, + changes: mpsc::Sender, ) -> Result<(), Error> { + let mut subscriptions = HashSet::new(); let mut deadline = Instant::now() + HEARTBEAT_TIMEOUT; loop { let frame = timeout_at(deadline, read.next()) @@ -33,18 +77,34 @@ pub(super) async fn run( match frame? { Frame::Text(text) => { let message: WsMessage = serde_json::from_str(&text)?; - match message.topic.as_str() { - CONNECTION_UPDATE => { - let request: Subscription = serde_json::from_value(message.payload)?; - let subscribed = request.subscribe.unwrap_or(true); - subscription.send_if_modified(|current| { - let changed = *current != subscribed; - *current = subscribed; - changed - }); + if message.topic == ORDER_SEND { + let result = orders + .ok_or(OrderError::VehicleUnavailable) + .and_then(|orders| orders.forward(message.payload)); + if let Err(error) = result { + tracing::warn!(topic = ORDER_SEND, %error, "order rejected"); + } + } else if let Some(topic) = Topic::from_name(&message.topic) { + let request: Subscription = serde_json::from_value(message.payload)?; + let enabled = request.subscribe.unwrap_or(true); + let changed = if enabled { + subscriptions.insert(topic) + } else { + subscriptions.remove(&topic) + }; + if changed { + // Start buffering events as soon as the request is accepted. + let change = SubscriptionChange::new(broker, topic, enabled)?; + match changes.try_send(change) { + Ok(()) => {} + Err(mpsc::error::TrySendError::Full(_)) => { + return Err(Error::SubscriptionQueueFull); + } + Err(mpsc::error::TrySendError::Closed(_)) => return Ok(()), + } } - HEARTBEAT => {} - topic => tracing::warn!(topic, "unsupported WebSocket topic"), + } else if message.topic != HEARTBEAT { + tracing::warn!(topic = %message.topic, "unsupported WebSocket topic"); } deadline = Instant::now() + HEARTBEAT_TIMEOUT; } @@ -60,12 +120,14 @@ mod tests { use tokio::time::advance; use super::*; + use crate::websocket::broker::Broker; #[tokio::test(start_paused = true)] async fn inactivity_expires() { - let (subscription, _state) = watch::channel(false); + let (_broker, client) = Broker::new(); + let (changes, _subscriptions) = mpsc::channel(1); assert!(matches!( - run(stream::pending(), subscription).await, + run(stream::pending(), &client, None, changes).await, Err(Error::HeartbeatTimeout) )); } @@ -75,8 +137,9 @@ mod tests { -> Result<(), Box> { let (input, mut frames) = tokio::sync::mpsc::channel(1); let read = stream::poll_fn(move |cx| frames.poll_recv(cx)); - let (subscription, mut state) = watch::channel(false); - let worker = tokio::spawn(run(read, subscription)); + let (_broker, client) = Broker::new(); + let (changes, mut subscriptions) = mpsc::channel(1); + let worker = tokio::spawn(async move { run(read, &client, None, changes).await }); tokio::task::yield_now().await; advance(Duration::from_secs(2)).await; @@ -85,7 +148,10 @@ mod tests { r#"{"topic":"connection/update","payload":{"subscribe":true}}"#.into(), ))) .await?; - state.changed().await?; + assert!(matches!( + subscriptions.recv().await, + Some(SubscriptionChange::Connections(Some(_))) + )); advance(Duration::from_secs(2)).await; assert!(!worker.is_finished()); advance(Duration::from_secs(1)).await; @@ -95,21 +161,23 @@ mod tests { #[tokio::test] async fn heartbeats_do_not_subscribe_or_publish() -> Result<(), Error> { - let (subscription, state) = watch::channel(false); + let (_broker, client) = Broker::new(); + let (changes, mut subscriptions) = mpsc::channel(1); let frames = stream::iter([ Ok(Frame::Text( r#"{"topic":"connection/heartbeat","payload":{}}"#.into(), )), Ok(Frame::Close(None)), ]); - run(frames, subscription).await?; - assert!(!*state.borrow()); + run(frames, &client, None, changes).await?; + assert!(subscriptions.recv().await.is_none()); Ok(()) } #[tokio::test] async fn subscription_requests_can_unsubscribe() -> Result<(), Error> { - let (subscription, state) = watch::channel(false); + let (_broker, client) = Broker::new(); + let (changes, mut subscriptions) = mpsc::channel(2); let frames = stream::iter([ Ok(Frame::Text( r#"{"topic":"connection/update","payload":{}}"#.into(), @@ -119,8 +187,59 @@ mod tests { )), Ok(Frame::Close(None)), ]); - run(frames, subscription).await?; - assert!(!*state.borrow()); + run(frames, &client, None, changes).await?; + assert!(matches!( + subscriptions.recv().await, + Some(SubscriptionChange::Connections(Some(_))) + )); + assert!(matches!( + subscriptions.recv().await, + Some(SubscriptionChange::Connections(None)) + )); + assert!(subscriptions.recv().await.is_none()); + Ok(()) + } + + #[tokio::test] + async fn repeated_event_subscriptions_keep_the_existing_receiver() -> Result<(), Error> { + let (_broker, client) = Broker::new(); + let (changes, mut subscriptions) = mpsc::channel(4); + let frames = stream::iter([ + Ok(Frame::Text( + r#"{"topic":"message/update","payload":{}}"#.into(), + )), + Ok(Frame::Text( + r#"{"topic":"protection/update","payload":{"subscribe":true}}"#.into(), + )), + Ok(Frame::Text( + r#"{"topic":"message/update","payload":{"subscribe":true}}"#.into(), + )), + Ok(Frame::Text( + r#"{"topic":"message/update","payload":{"subscribe":false}}"#.into(), + )), + Ok(Frame::Text( + r#"{"topic":"message/update","payload":{"subscribe":true}}"#.into(), + )), + Ok(Frame::Close(None)), + ]); + run(frames, &client, None, changes).await?; + assert!(matches!( + subscriptions.recv().await, + Some(SubscriptionChange::Messages(Some(_))) + )); + assert!(matches!( + subscriptions.recv().await, + Some(SubscriptionChange::Protections(Some(_))) + )); + assert!(matches!( + subscriptions.recv().await, + Some(SubscriptionChange::Messages(None)) + )); + assert!(matches!( + subscriptions.recv().await, + Some(SubscriptionChange::Messages(Some(_))) + )); + assert!(subscriptions.recv().await.is_none()); Ok(()) } } diff --git a/backend/crates/station/src/websocket/sender.rs b/backend/crates/station/src/websocket/sender.rs index 432de565e..a537641a3 100644 --- a/backend/crates/station/src/websocket/sender.rs +++ b/backend/crates/station/src/websocket/sender.rs @@ -1,41 +1,128 @@ +use std::future::pending; + use axum::extract::ws::{Message as Frame, WebSocket}; use futures_util::{SinkExt, stream::SplitSink}; -use tokio::sync::watch; +use serde::Serialize; +use tokio::sync::{broadcast, mpsc, watch}; -use super::{CONNECTION_UPDATE, WsMessage, broker::BrokerClient, error::Error}; +use super::{Topic, WsMessage, error::Error, receiver::SubscriptionChange}; -/// Sends the current state on subscription, followed by complete state updates. +/// Sends subscribed state snapshots and events over the socket. pub(super) async fn run( write: &mut SplitSink, - broker: &BrokerClient, - mut subscribed: watch::Receiver, + mut subscriptions: mpsc::Receiver, ) -> Result<(), Error> { - let mut connections = broker.subscribe_connections(); + let (mut connections, mut orders, mut logger, mut data) = (None, None, None, None); + let (mut messages, mut protections) = (None, None); loop { - if !*subscribed.borrow_and_update() { - if subscribed.changed().await.is_err() { - return Ok(()); + let frame = tokio::select! { + biased; + change = subscriptions.recv() => { + let Some(change) = change else { return Ok(()); }; + let snapshot = match change { + SubscriptionChange::Connections(next) => subscribe_state(Topic::Connections, &mut connections, next)?, + SubscriptionChange::StateOrders(next) => subscribe_state(Topic::StateOrders, &mut orders, next)?, + SubscriptionChange::Logger(next) => subscribe_state(Topic::Logger, &mut logger, next)?, + SubscriptionChange::Data(next) => subscribe_state(Topic::Data, &mut data, next)?, + SubscriptionChange::Messages(next) => { messages = next; None } + SubscriptionChange::Protections(next) => { protections = next; None } + }; + let Some(snapshot) = snapshot else { continue; }; + snapshot } - continue; - } - - let payload = serde_json::to_value(&*connections.borrow_and_update())?; - let message = WsMessage { - topic: CONNECTION_UPDATE.into(), - payload, + next = next_event(Topic::Protections, &mut protections) => next?, + next = next_event(Topic::Messages, &mut messages) => next?, + next = next_state(Topic::Connections, &mut connections) => next?, + next = next_state(Topic::StateOrders, &mut orders) => next?, + next = next_state(Topic::Logger, &mut logger) => next?, + next = next_state(Topic::Data, &mut data) => next?, }; - write - .send(Frame::Text(serde_json::to_string(&message)?.into())) - .await?; + write.send(frame).await?; + } +} - tokio::select! { - biased; - result = subscribed.changed() => { - if result.is_err() { return Ok(()); } - } - result = connections.changed() => { - result.map_err(|_| Error::BrokerClosed)?; - } +fn subscribe_state( + topic: Topic, + state: &mut Option>, + subscription: Option>, +) -> Result, Error> { + *state = subscription; + state + .as_mut() + .map(|state| state_frame(topic, state)) + .transpose() +} + +async fn next_state( + topic: Topic, + state: &mut Option>, +) -> Result { + let Some(state) = state else { + return pending().await; + }; + state.changed().await.map_err(|_| Error::BrokerClosed)?; + state_frame(topic, state) +} + +fn state_frame(topic: Topic, state: &mut watch::Receiver) -> Result { + encode(topic, &*state.borrow_and_update()) +} + +async fn next_event( + topic: Topic, + events: &mut Option>, +) -> Result { + let Some(events) = events else { + return pending().await; + }; + let event = events.recv().await.map_err(|error| match error { + broadcast::error::RecvError::Closed => Error::BrokerClosed, + broadcast::error::RecvError::Lagged(missed) => Error::EventLagged { + topic: topic.name(), + missed, + }, + })?; + encode(topic, &event) +} + +fn encode(topic: Topic, payload: &impl Serialize) -> Result { + let message = WsMessage { + topic: topic.name().into(), + payload: serde_json::to_value(payload)?, + }; + Ok(Frame::Text(serde_json::to_string(&message)?.into())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn lagged_event_receiver_reports_its_loss_without_affecting_another_subscriber() + -> Result<(), Box> { + let (events, stalled) = broadcast::channel(2); + let mut stalled = Some(stalled); + let mut current = Some(events.subscribe()); + + for count in 1..=3 { + events.send(count)?; + let frame = next_event(Topic::Messages, &mut current).await?; + let message: WsMessage = serde_json::from_str(frame.to_text()?)?; + assert_eq!(message.payload, count); } + + assert!(matches!( + next_event(Topic::Messages, &mut stalled).await, + Err(Error::EventLagged { + topic: "message/update", + missed: 1 + }) + )); + drop(stalled); + events.send(4)?; + let frame = next_event(Topic::Messages, &mut current).await?; + let message: WsMessage = serde_json::from_str(frame.to_text()?)?; + assert_eq!(message.payload, 4); + Ok(()) } } From c16a9df0ea4996baa6a9325b3e9e30000e908eb1 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Wed, 25 Nov 2026 02:22:08 +0100 Subject: [PATCH 07/14] feat(backend, websocket): forward logger commands and make heartbeat timeout configurable --- backend/crates/station/src/http/server.rs | 540 +++--------------- backend/crates/station/src/websocket.rs | 53 +- .../crates/station/src/websocket/broker.rs | 12 +- backend/crates/station/src/websocket/error.rs | 18 +- .../crates/station/src/websocket/handler.rs | 10 +- backend/crates/station/src/websocket/order.rs | 5 + .../crates/station/src/websocket/payload.rs | 8 +- .../src/websocket/payload/connection.rs | 1 + .../station/src/websocket/payload/data.rs | 4 +- .../station/src/websocket/payload/message.rs | 8 +- .../station/src/websocket/payload/order.rs | 9 +- .../src/websocket/payload/protection.rs | 5 +- .../src/websocket/payload/serialize.rs | 5 +- .../crates/station/src/websocket/receiver.rs | 100 +++- .../crates/station/src/websocket/sender.rs | 4 + 15 files changed, 272 insertions(+), 510 deletions(-) diff --git a/backend/crates/station/src/http/server.rs b/backend/crates/station/src/http/server.rs index 1f5584852..ea6078ac0 100644 --- a/backend/crates/station/src/http/server.rs +++ b/backend/crates/station/src/http/server.rs @@ -48,14 +48,18 @@ pub(super) fn setup_router( } #[cfg(test)] -pub(super) mod tests { - use std::{io, path::Path, time::Duration}; +mod tests { + use std::{io, path::Path, sync::Arc, time::Duration}; use axum::{ body::{Body, to_bytes}, http::{Method, Request, StatusCode, header}, }; - use software_core::adj::{Adj, load_from_dir}; + use software_core::{ + adj::{Adj, load_from_dir}, + model::{AdjId, OrderPacket, ShortTimestamp, Value}, + protocol::Index, + }; use tokio::{ io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}, net::{TcpListener, TcpStream}, @@ -65,6 +69,9 @@ pub(super) mod tests { use tower::ServiceExt; use super::setup_router; + use crate::websocket::{ + self, Commands, OrderForwarder, broker::Broker, payload::ProtectionUpdate, + }; pub(in crate::http) const PATHS: [&str; 3] = [ "/backend/adj/DataPackets", @@ -199,17 +206,10 @@ pub(super) mod tests { // Upgrades require a real HTTP connection: oneshot does not provide Hyper's // OnUpgrade extension. The server only runs for the duration of the test. - async fn handshake( + pub(super) async fn handshake( app: axum::Router, ) -> Result<(String, TcpStream), Box> { let listener = TcpListener::bind("127.0.0.1:0").await?; - handshake_on(listener, app).await - } - - pub(in crate::http) async fn handshake_on( - listener: TcpListener, - app: axum::Router, - ) -> Result<(String, TcpStream), Box> { let address = listener.local_addr()?; let (shutdown, stopped) = oneshot::channel(); let server = tokio::spawn(async move { @@ -280,490 +280,130 @@ pub(super) mod tests { } #[tokio::test] - async fn websocket_subscription_receives_connection_snapshots() + async fn websocket_delivers_protections_and_forwards_orders() -> Result<(), Box> { - use crate::websocket::payload::{Connection, StateOrdersUpdate}; - - let (broker, client) = crate::websocket::broker::Broker::new(); - let broker_worker = tokio::spawn(broker.run()); - let (connections, receiver) = mpsc::channel(1); - let worker = tokio::spawn(crate::websocket::run(receiver, client.clone(), None)); - let app = setup_router(&Adj::default(), Some(connections))?; - let (headers, mut first) = handshake(app.clone()).await?; + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../core/src/adj/test/adj"); + let adj = load_from_dir(&path)?; + let (order_tx, mut orders) = mpsc::channel(1); + let commands = Commands { + orders: Some(OrderForwarder::new( + Arc::new(Index::new(&adj.pod_data, None)), + order_tx, + )), + ..Commands::default() + }; + let (broker, client) = Broker::new(); + let broker_task = tokio::spawn(broker.run()); + let (sockets, receiver) = mpsc::channel(1); + let socket_task = tokio::spawn(websocket::run( + receiver, + client.clone(), + commands, + Duration::from_secs(10), + )); + let (headers, mut socket) = handshake(setup_router(&adj, Some(sockets))?).await?; assert!(headers.starts_with("HTTP/1.1 101 Switching Protocols\r\n")); - let (_headers, mut second) = handshake(app).await?; timeout(Duration::from_secs(5), async { - send_text( - &mut first, - r#"{"topic":"connection/heartbeat","payload":{}}"#, - ) - .await?; - // Other frontend topics can be added incrementally without closing the socket. - send_text( - &mut first, - r#"{"topic":"not-a-topic","payload":{"subscribe":true}}"#, - ) - .await?; - send_text( - &mut first, - r#"{"topic":"connection/update","payload":{"subscribe":true}}"#, - ) - .await?; - assert_eq!( - read_json(&mut first).await?, - serde_json::json!({ - "topic": "connection/update", "payload": {} - }) - ); - - client - .publish_connection(Connection { - name: "LCU".into(), - is_connected: true, - }) - .await?; - let expected = serde_json::json!({ - "topic": "connection/update", - "payload": {"LCU": {"name": "LCU", "isConnected": true}} - }); - assert_eq!(read_json(&mut first).await?, expected); - - // A client receives nothing before subscribing, then receives the current map. - assert!( - timeout(Duration::from_millis(50), second.read_u8()) - .await - .is_err() - ); - send_text(&mut second, r#"{"topic":"connection/update","payload":{}}"#).await?; - assert_eq!(read_json(&mut second).await?, expected); - - client - .publish_connection(Connection { - name: "HVBMS".into(), - is_connected: false, - }) - .await?; - let expected = serde_json::json!({ - "topic": "connection/update", - "payload": { - "LCU": {"name": "LCU", "isConnected": true}, - "HVBMS": {"name": "HVBMS", "isConnected": false} - } - }); - assert_eq!(read_json(&mut first).await?, expected); - assert_eq!(read_json(&mut second).await?, expected); - - send_text( - &mut first, - r#"{"topic":"order/stateOrders","payload":{"subscribe":true}}"#, - ) - .await?; - assert_eq!( - read_json(&mut first).await?, - serde_json::json!({ - "topic": "order/stateOrders", "payload": {} - }) - ); - send_text( - &mut second, - r#"{"topic":"logger/response","payload":{"subscribe":true}}"#, - ) - .await?; - assert_eq!( - read_json(&mut second).await?, - serde_json::json!({ - "topic": "logger/response", "payload": false - }) - ); - - client - .publish_state_orders(StateOrdersUpdate::from([("LCU".into(), vec![1001])])) - .await?; - assert_eq!( - read_json(&mut first).await?, - serde_json::json!({ - "topic": "order/stateOrders", "payload": {"LCU": [1001]} - }) - ); - assert!( - timeout(Duration::from_millis(50), second.read_u8()) - .await - .is_err() - ); - - client.publish_logger(true).await?; + send_text(&mut socket, r#"{"topic":"protection/update","payload":{}}"#).await?; + // Receiving the snapshot confirms the preceding event subscription is active. + send_text(&mut socket, r#"{"topic":"connection/update","payload":{}}"#).await?; assert_eq!( - read_json(&mut second).await?, - serde_json::json!({ - "topic": "logger/response", "payload": true - }) - ); - assert!( - timeout(Duration::from_millis(50), first.read_u8()) - .await - .is_err() + read_json(&mut socket).await?, + serde_json::json!({"topic": "connection/update", "payload": {}}) ); - // The logger snapshot confirms the preceding unsubscribe was handled. - send_text( - &mut first, - r#"{"topic":"order/stateOrders","payload":{"subscribe":false}}"#, - ) - .await?; - send_text( - &mut first, - r#"{"topic":"logger/response","payload":{"subscribe":true}}"#, - ) - .await?; - assert_eq!( - read_json(&mut first).await?, - serde_json::json!({ - "topic": "logger/response", "payload": true - }) - ); client - .publish_state_orders(StateOrdersUpdate::from([("LCU".into(), vec![])])) - .await?; - assert!( - timeout(Duration::from_millis(50), first.read_u8()) - .await - .is_err() - ); - - // Resubscribing recovers the latest full state, including empty lists. - send_text(&mut first, r#"{"topic":"order/stateOrders","payload":{}}"#).await?; - assert_eq!( - read_json(&mut first).await?, - serde_json::json!({ - "topic": "order/stateOrders", "payload": {"LCU": []} - }) - ); - client.publish_logger(false).await?; - let expected = serde_json::json!({"topic": "logger/response", "payload": false}); - assert_eq!(read_json(&mut first).await?, expected); - assert_eq!(read_json(&mut second).await?, expected); - - for socket in [&mut first, &mut second] { - socket.write_all(&[0x88, 0x80, 0, 0, 0, 0]).await?; - assert_eq!(socket.read_u8().await?, 0x88); - } - Ok::<_, Box>(()) - }) - .await??; - drop(client); - worker.await?; - timeout(Duration::from_secs(5), broker_worker).await??; - Ok(()) - } - - #[tokio::test] - async fn websocket_telemetry_sends_complete_snapshots() -> Result<(), Box> - { - use crate::websocket::payload::{DataPacketUpdate, MeasurementUpdate}; - use software_core::model::AdjId; - - let (broker, client) = crate::websocket::broker::Broker::new(); - let broker_worker = tokio::spawn(broker.run()); - let (connections, receiver) = mpsc::channel(1); - let worker = tokio::spawn(crate::websocket::run(receiver, client.clone(), None)); - let app = setup_router(&Adj::default(), Some(connections))?; - let (_, mut first) = handshake(app.clone()).await?; - let (_, mut second) = handshake(app).await?; - - timeout(Duration::from_secs(5), async { - send_text( - &mut first, - r#"{"topic":"podData/update","payload":{"subscribe":true}}"#, - ) - .await?; - assert_eq!( - read_json(&mut first).await?, - serde_json::json!({ - "topic": "podData/update", "payload": {} - }) - ); - - let packet = DataPacketUpdate { - id: AdjId(1000), - hex_value: "e8030000bc41".into(), - count: 1, - cycle_time: 100_000_000, - measurement_updates: std::collections::HashMap::from([( - "temperature".into(), - MeasurementUpdate::Numeric { - last: 23.5, - average: 23.0, + .publish_protection(ProtectionUpdate { + id: AdjId(11192), + value: Value::Number(105.5), + timestamp: ShortTimestamp { + hour: 12, + minute: 30, + second: 6, + subsecond: 0, }, - )]), - }; - client.publish_data(packet.clone()).await?; - let expected = serde_json::json!({ - "topic": "podData/update", - "payload": {"1000": { - "id": 1000, "hexValue": "e8030000bc41", "count": 1, "cycleTime": 100_000_000, - "measurementUpdates": {"temperature": {"last": 23.5, "average": 23.0}} - }} - }); - assert_eq!(read_json(&mut first).await?, expected); - - send_text(&mut second, r#"{"topic":"podData/update","payload":{}}"#).await?; - assert_eq!(read_json(&mut second).await?, expected); - client - .publish_data(DataPacketUpdate { - id: AdjId(1001), - hex_value: "e9030000bc41".into(), - ..packet - }) - .await?; - let updated = read_json(&mut first).await?; - assert_eq!(updated["topic"], "podData/update"); - assert_eq!(updated["payload"].as_object().map(|map| map.len()), Some(2)); - assert_eq!(updated["payload"]["1000"], expected["payload"]["1000"]); - assert_eq!(updated["payload"]["1001"]["id"], 1001); - assert_eq!(read_json(&mut second).await?, updated); - - for socket in [&mut first, &mut second] { - socket.write_all(&[0x88, 0x80, 0, 0, 0, 0]).await?; - assert_eq!(socket.read_u8().await?, 0x88); - } - Ok::<_, Box>(()) - }) - .await??; - drop(client); - worker.await?; - timeout(Duration::from_secs(5), broker_worker).await??; - Ok(()) - } - - #[tokio::test] - async fn websocket_event_subscriptions_deliver_live_payloads() - -> Result<(), Box> { - use crate::websocket::{ - broker::Broker, - payload::{ - MessageKind, MessagePayload, MessageTimestamp, MessageUpdate, ProtectionUpdate, - }, - }; - use serde_json::json; - use software_core::model::{AdjId, ShortTimestamp, Value}; - - let (broker, client) = Broker::new(); - let broker_worker = tokio::spawn(broker.run()); - let (sockets, receiver) = mpsc::channel(1); - let worker = tokio::spawn(crate::websocket::run(receiver, client.clone(), None)); - let message = MessageUpdate { - kind: MessageKind::Info, - payload: MessagePayload::Text("Order Sent".into()), - board: "LCU".into(), - name: "1001".into(), - timestamp: MessageTimestamp { - counter: 0, - second: 5, - minute: 30, - hour: 12, - day: 24, - month: 11, - year: 2026, - }, - }; - let protection = ProtectionUpdate { - id: AdjId(11192), - value: Value::Number(105.5), - timestamp: ShortTimestamp { - hour: 12, - minute: 30, - second: 6, - subsecond: 0, - }, - }; - let expected_message: serde_json::Value = - serde_json::from_str(include_str!("../websocket/payload/example/message.json"))?; - let expected_protection: serde_json::Value = - serde_json::from_str(include_str!("../websocket/payload/example/protection.json"))?; - let (_, mut socket) = handshake(setup_router(&Adj::default(), Some(sockets))?).await?; - - timeout(Duration::from_secs(5), async { - let mut logger = client.subscribe_logger(); - client - .publish_message(MessageUpdate { - payload: MessagePayload::Text("Before subscribing".into()), - ..message.clone() }) .await?; - client.publish_logger(true).await?; - logger.changed().await?; - send_text(&mut socket, r#"{"topic":"message/update","payload":{}}"#).await?; - send_text( - &mut socket, - r#"{"topic":"protection/update","payload":{"subscribe":true}}"#, - ) - .await?; - // The state snapshot confirms the preceding subscriptions were processed. - send_text(&mut socket, r#"{"topic":"logger/response","payload":{}}"#).await?; - assert_eq!( - read_json(&mut socket).await?, - json!({"topic": "logger/response", "payload": true}) - ); - - client.publish_message(message.clone()).await?; - assert_eq!(read_json(&mut socket).await?, expected_message); - client.publish_protection(protection.clone()).await?; - assert_eq!(read_json(&mut socket).await?, expected_protection); + let expected: serde_json::Value = serde_json::from_str(include_str!( + "../websocket/payload/example/protection.json" + ))?; + assert_eq!(read_json(&mut socket).await?, expected); send_text( &mut socket, - r#"{"topic":"message/update","payload":{"subscribe":false}}"#, + r#"{"topic":"order/send","payload":{"id":809,"fields":{"desired_current":{"value":12.5,"type":"float32"},"lpu_id":{"value":2,"type":"uint32"}}}}"#, ) .await?; - send_text(&mut socket, r#"{"topic":"connection/update","payload":{}}"#).await?; assert_eq!( - read_json(&mut socket).await?, - json!({"topic": "connection/update", "payload": {}}) - ); - client - .publish_message(MessageUpdate { - payload: MessagePayload::Text("While unsubscribed".into()), - ..message - }) - .await?; - client.publish_protection(protection).await?; - assert_eq!(read_json(&mut socket).await?, expected_protection); - assert!( - timeout(Duration::from_millis(50), socket.read_u8()) - .await - .is_err() + orders.recv().await, + Some(OrderPacket::new( + AdjId(809), + vec![Value::Number(2.0), Value::Number(12.5)], + )) ); - socket.write_all(&[0x88, 0x80, 0, 0, 0, 0]).await?; - assert_eq!(socket.read_u8().await?, 0x88); + drop(socket); + socket_task.await?; + drop(client); + broker_task.await?; Ok::<_, Box>(()) }) .await??; - drop(client); - worker.await?; - timeout(Duration::from_secs(5), broker_worker).await??; - Ok(()) - } - - #[tokio::test] - async fn websocket_forwards_validated_orders_in_adj_order() - -> Result<(), Box> { - use crate::websocket::{OrderForwarder, broker::Broker}; - use software_core::{ - model::{AdjId, OrderPacket, Value}, - protocol::Index, - }; - use std::sync::Arc; - - let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../core/src/adj/test/adj"); - let adj = load_from_dir(&path)?; - let index = Arc::new(Index::new(&adj.pod_data, None)); - let (order_tx, mut orders) = mpsc::channel(1); - let forwarder = OrderForwarder::new(index, order_tx); - let (broker, client) = Broker::new(); - let broker_worker = tokio::spawn(broker.run()); - let (connections, receiver) = mpsc::channel(1); - let worker = tokio::spawn(crate::websocket::run(receiver, client, Some(forwarder))); - let (_, mut socket) = handshake(setup_router(&adj, Some(connections))?).await?; - - timeout(Duration::from_secs(5), async { - for invalid in [ - r#"{"topic":"order/send","payload":{"id":65535,"fields":{}}}"#, - r#"{"topic":"order/send","payload":{"id":809,"fields":{}}}"#, - r#"{"topic":"order/send","payload":{"id":801,"fields":{"extra":{"value":0,"type":"uint8"}}}}"#, - r#"{"topic":"order/send","payload":{"id":809,"fields":{"desired_current":{"value":12.5,"type":"float64"},"lpu_id":{"value":2,"type":"uint32"}}}}"#, - r#"{"topic":"order/send","payload":{"id":809,"fields":{"desired_current":{"value":12.5,"type":"float32"},"lpu_id":{"value":2.5,"type":"uint32"}}}}"#, - ] { - send_text(&mut socket, invalid).await?; - } - send_text(&mut socket, r#"{"topic":"order/send","payload":{"id":809,"fields":{"desired_current":{"value":12.5,"type":"float32"},"lpu_id":{"value":2,"type":"uint32"}}}}"#).await?; - let stop = r#"{"topic":"order/send","payload":{"id":801,"fields":{}}}"#; - send_text(&mut socket, stop).await?; - - // The snapshot confirms both requests reached the receiver before we free the queue. - send_text(&mut socket, r#"{"topic":"connection/update","payload":{}}"#).await?; - assert_eq!(read_json(&mut socket).await?["topic"], "connection/update"); - assert_eq!(orders.recv().await, Some(OrderPacket::new( - AdjId(809), vec![Value::Number(2.0), Value::Number(12.5)], - ))); - assert!(matches!(orders.try_recv(), Err(mpsc::error::TryRecvError::Empty))); - - send_text(&mut socket, stop).await?; - assert_eq!(orders.recv().await, Some(OrderPacket::new(AdjId(801), vec![]))); - - socket.write_all(&[0x88, 0x80, 0, 0, 0, 0]).await?; - assert_eq!(socket.read_u8().await?, 0x88); - Ok::<_, Box>(()) - }).await??; - worker.await?; - timeout(Duration::from_secs(5), broker_worker).await??; Ok(()) } async fn send_text( - client: &mut TcpStream, + socket: &mut TcpStream, text: &str, ) -> Result<(), Box> { - // A zero mask leaves the test JSON unchanged. let length = u16::try_from(text.len())?; if length < 126 { - client.write_all(&[0x81, 0x80 | length as u8]).await?; + socket.write_all(&[0x81, 0x80 | length as u8]).await?; } else { - client.write_all(&[0x81, 0xfe]).await?; - client.write_u16(length).await?; + socket.write_all(&[0x81, 0xfe]).await?; + socket.write_u16(length).await?; } - client.write_all(&[0; 4]).await?; - client.write_all(text.as_bytes()).await?; + // The zero mask keeps the test payload bytes unchanged. + socket.write_all(&[0; 4]).await?; + socket.write_all(text.as_bytes()).await?; Ok(()) } async fn read_json( - client: &mut TcpStream, + socket: &mut TcpStream, ) -> Result> { - assert_eq!(client.read_u8().await?, 0x81); - let header = client.read_u8().await?; - assert_eq!(header & 0x80, 0, "server frames must not be masked"); - let length = match header { - 126 => usize::from(client.read_u16().await?), - 127 => usize::try_from(client.read_u64().await?)?, - length => usize::from(length), + assert_eq!(socket.read_u8().await?, 0x81); + let length = match socket.read_u8().await? { + length @ 0..=125 => usize::from(length), + 126 => usize::from(socket.read_u16().await?), + _ => panic!("expected a short, unmasked server frame"), }; let mut body = vec![0; length]; - client.read_exact(&mut body).await?; + socket.read_exact(&mut body).await?; Ok(serde_json::from_slice(&body)?) } #[tokio::test] - async fn websocket_without_a_consumer_returns_unavailable() - -> Result<(), Box> { - let app = setup_router(&Adj::default(), None)?; - let (headers, _client) = handshake(app).await?; - assert!(headers.starts_with("HTTP/1.1 503 Service Unavailable\r\n")); - Ok(()) - } - - #[tokio::test] - async fn websocket_with_a_closed_channel_returns_unavailable() + async fn websocket_returns_unavailable_when_handoff_cannot_accept_a_socket() -> Result<(), Box> { - let (connections, receiver) = mpsc::channel(1); + let (closed, receiver) = mpsc::channel(1); drop(receiver); - let app = setup_router(&Adj::default(), Some(connections))?; - let (headers, _client) = handshake(app).await?; - assert!(headers.starts_with("HTTP/1.1 503 Service Unavailable\r\n")); - Ok(()) - } - - #[tokio::test] - async fn websocket_with_a_full_channel_returns_unavailable() - -> Result<(), Box> { - let (connections, _receiver) = mpsc::channel(1); - // Simulate an occupied slot without requiring another test socket. - let reservation = connections.clone().try_reserve_owned()?; - let app = setup_router(&Adj::default(), Some(connections))?; - let (headers, _client) = handshake(app).await?; - assert!(headers.starts_with("HTTP/1.1 503 Service Unavailable\r\n")); - drop(reservation); + let (full, _receiver) = mpsc::channel(1); + let _reservation = full.clone().try_reserve_owned()?; + + for (case, connections) in [ + ("missing", None), + ("closed", Some(closed)), + ("full", Some(full)), + ] { + let app = setup_router(&Adj::default(), connections)?; + let (headers, _client) = handshake(app).await?; + assert!( + headers.starts_with("HTTP/1.1 503 Service Unavailable\r\n"), + "expected 503 for {case} channel, got {headers}", + ); + } Ok(()) } diff --git a/backend/crates/station/src/websocket.rs b/backend/crates/station/src/websocket.rs index 0fce10c17..c98c72854 100644 --- a/backend/crates/station/src/websocket.rs +++ b/backend/crates/station/src/websocket.rs @@ -1,4 +1,9 @@ -//! Connects upgraded HTTP sockets to broker subscriptions. +//! Connects upgraded HTTP sockets to station's broker and command queues. +//! +//! Each connection has a reader that accepts subscriptions and commands and a +//! writer that turns the subscribed broker updates into JSON messages. + +use std::time::Duration; use axum::extract::ws::WebSocket; use serde::{Deserialize, Serialize}; @@ -6,6 +11,7 @@ use tokio::sync::mpsc; use self::broker::BrokerClient; pub(crate) use self::order::OrderForwarder; +use self::payload::{LoggerEnable, LoggerVariables}; pub mod broker; mod error; @@ -17,13 +23,32 @@ mod sender; const CONNECTION_UPDATE: &str = "connection/update"; const STATE_ORDERS: &str = "order/stateOrders"; +const LOGGER_ENABLE: &str = "logger/enable"; const LOGGER_RESPONSE: &str = "logger/response"; +const LOGGER_VARIABLES: &str = "logger/variables"; const DATA_UPDATE: &str = "podData/update"; const MESSAGE_UPDATE: &str = "message/update"; const PROTECTION_UPDATE: &str = "protection/update"; const ORDER_SEND: &str = "order/send"; const HEARTBEAT: &str = "connection/heartbeat"; +/// Requests queued for the logger. The logger publishes its applied state separately. +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum LoggerCommand { + Enable(LoggerEnable), + Variables(LoggerVariables), +} + +/// Destinations for requests received over WebSocket. +#[derive(Debug, Clone, Default)] +pub(crate) struct Commands { + /// Validates frontend orders before queuing them for the vehicle. + pub(crate) orders: Option, + /// Queues recording and variable selection requests for the logger. + pub(crate) logger: Option>, +} + +/// Topics a frontend can subscribe to. Commands and heartbeats are routed by the reader. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] enum Topic { Connections, @@ -62,33 +87,25 @@ impl Topic { /// JSON envelope shared with the frontend. #[derive(Debug, Serialize, Deserialize)] pub struct WsMessage { - /// Topic of the message, can be: - /// - order/send - /// - podData/update - /// - connection/update - /// - order/stateOrders - /// - message/update - /// - protection/update - /// - logger/enable - /// - logger/response - /// - logger/variables + /// Wire name used to route the message, such as `connection/update`. pub topic: String, - /// Topic-specific JSON payload + /// Topic-specific JSON payload. pub payload: serde_json::Value, } -/// Handles each connection independently while HTTP keeps accepting sockets. -pub async fn run( +/// Runs one task per upgraded socket so a slow client stays isolated. +/// Closing the HTTP handoff channel ends socket intake. Existing sessions end independently. +pub(crate) async fn run( mut connections: mpsc::Receiver, broker: BrokerClient, - orders: Option, + commands: Commands, + heartbeat_timeout: Duration, ) { - // Spawn one tokio task per Websocket connection while let Some(socket) = connections.recv().await { let broker = broker.clone(); - let orders = orders.clone(); + let commands = commands.clone(); tokio::spawn(async move { - if let Err(error) = handler::handle(socket, broker, orders.as_ref()).await { + if let Err(error) = handler::handle(socket, broker, &commands, heartbeat_timeout).await { tracing::warn!(%error, "WebSocket connection ended with an error"); } }); diff --git a/backend/crates/station/src/websocket/broker.rs b/backend/crates/station/src/websocket/broker.rs index 64079557e..ba7ce289d 100644 --- a/backend/crates/station/src/websocket/broker.rs +++ b/backend/crates/station/src/websocket/broker.rs @@ -1,4 +1,7 @@ //! Publishes current state and forwards messages and protection events. +//! +//! Each `watch` topic holds a complete snapshot and may coalesce intermediate +//! updates. Each event topic has its own bounded `broadcast` backlog for live subscribers. use std::time::Duration; @@ -38,6 +41,7 @@ pub struct Broker { } /// Clonable access to publication and subscriptions. +/// A successful publish means the update entered the broker's input queue. #[derive(Debug, Clone)] pub struct BrokerClient { updates: mpsc::Sender, @@ -45,6 +49,7 @@ pub struct BrokerClient { state_orders: watch::Receiver, logger: watch::Receiver, data: watch::Receiver, + // Weak handles let event channels close when the broker exits. messages: broadcast::WeakSender, protections: broadcast::WeakSender, } @@ -83,10 +88,12 @@ impl Broker { ) } - /// Processes updates until all publishing clients have been dropped. + /// Processes updates as they arrive. After the last client drops, drains the input + /// queue and flushes any pending telemetry before exiting. pub async fn run(mut self) { let period = Duration::from_millis(100); let mut tick = interval_at(Instant::now() + period, period); + // Skip catch-up ticks and keep only the latest packet per ID in each batch. tick.set_missed_tick_behavior(MissedTickBehavior::Skip); let mut pending = DataUpdate::new(); loop { @@ -99,6 +106,7 @@ impl Broker { Some(Update::StateOrders(orders)) => { self.state_orders.send_replace(orders); } Some(Update::Logger(recording)) => { self.logger.send_replace(recording); } Some(Update::Data(packet)) => { pending.insert(packet.id.0, packet); } + // Zero subscribers is normal for a live event. Some(Update::Message(message)) => { let _ = self.messages.send(message); } Some(Update::Protection(protection)) => { let _ = self.protections.send(protection); } None => { @@ -114,6 +122,7 @@ impl Broker { fn flush_data(&self, pending: &mut DataUpdate) { if !pending.is_empty() { + // Preserve the last value for packets that were quiet during this batch. self.data.send_modify(|state| state.extend(pending.drain())); } } @@ -193,6 +202,7 @@ impl BrokerClient { fn subscribe(state: &watch::Receiver) -> watch::Receiver { let mut receiver = state.clone(); + // Callers read the initial snapshot directly. `changed()` then waits for a newer one. receiver.borrow_and_update(); receiver } diff --git a/backend/crates/station/src/websocket/error.rs b/backend/crates/station/src/websocket/error.rs index bfe127d9b..15b4889c8 100644 --- a/backend/crates/station/src/websocket/error.rs +++ b/backend/crates/station/src/websocket/error.rs @@ -6,16 +6,16 @@ pub enum Error { /// The broker no longer accepts updates. #[error("WebSocket broker is closed")] BrokerClosed, - /// The socket writer fell behind the subscription requests. + /// The session ends when the writer can no longer keep up with subscription changes. #[error("WebSocket subscription queue is full")] SubscriptionQueueFull, - /// The client fell behind on an event topic. + /// The event buffer overwrote unread events. The session logs the loss and closes. #[error("WebSocket subscriber missed {missed} events on {topic}")] EventLagged { topic: &'static str, missed: u64 }, /// Reading or writing the socket failed. #[error("WebSocket I/O failed: {0}")] Socket(#[from] axum::Error), - /// The message or its payload could not be converted to JSON models. + /// A WebSocket message or payload failed JSON encoding or decoding. #[error("invalid WebSocket JSON: {0}")] Json(#[from] serde_json::Error), /// No valid application message arrived before the deadline. @@ -23,6 +23,7 @@ pub enum Error { HeartbeatTimeout, } +/// Rejections of individual order requests. The reader logs these and keeps the session open. #[derive(Debug, thiserror::Error)] pub(super) enum OrderError { #[error("invalid order payload: {0}")] @@ -45,3 +46,14 @@ pub(super) enum OrderError { #[error("vehicle order receiver is unavailable")] VehicleUnavailable, } + +/// Rejections of individual logger requests. The reader logs these and keeps the session open. +#[derive(Debug, thiserror::Error)] +pub(super) enum LoggerError { + #[error("invalid logger payload: {0}")] + Json(#[from] serde_json::Error), + #[error("logger command queue is full")] + QueueFull, + #[error("logger command receiver is unavailable")] + Unavailable, +} diff --git a/backend/crates/station/src/websocket/handler.rs b/backend/crates/station/src/websocket/handler.rs index aca901803..f39e2bdd8 100644 --- a/backend/crates/station/src/websocket/handler.rs +++ b/backend/crates/station/src/websocket/handler.rs @@ -4,20 +4,22 @@ use axum::extract::ws::WebSocket; use futures_util::{SinkExt, StreamExt}; use tokio::{sync::mpsc, time::timeout}; -use super::{OrderForwarder, broker::BrokerClient, error::Error, receiver, sender}; +use super::{Commands, broker::BrokerClient, error::Error, receiver, sender}; -/// Runs reading and writing together; either side finishing ends the session. +/// Runs reading and writing concurrently. The first side to finish ends the session. pub(super) async fn handle( socket: WebSocket, broker: BrokerClient, - orders: Option<&OrderForwarder>, + commands: &Commands, + heartbeat_timeout: Duration ) -> Result<(), Error> { let (mut write, read) = socket.split(); let (changes, subscriptions) = mpsc::channel(16); let result = tokio::select! { - result = receiver::run(read, &broker, orders, changes) => result, + result = receiver::run(read, &broker, commands, changes, heartbeat_timeout) => result, result = sender::run(&mut write, subscriptions) => result, }; + // Bound the socket close and preserve the result that ended the session. let _ = timeout(Duration::from_secs(1), write.close()).await; result } diff --git a/backend/crates/station/src/websocket/order.rs b/backend/crates/station/src/websocket/order.rs index 7cc3655a4..c01f2c613 100644 --- a/backend/crates/station/src/websocket/order.rs +++ b/backend/crates/station/src/websocket/order.rs @@ -31,6 +31,7 @@ impl OrderForwarder { } } +/// Resolves aliases and emits values in the ADJ's wire order. fn to_packet(mut request: OrderSend, index: &Index) -> Result { let Some(PacketType::Order(measurements)) = index.packet(request.id).map(|packet| &packet.packet_type) @@ -47,6 +48,7 @@ fn to_packet(mut request: OrderSend, index: &Index) -> Result Option { let JsonValue::Number(raw) = value else { return None; @@ -108,6 +112,7 @@ fn number(value: &JsonValue, kind: NumericKind) -> Option { return None; } } else if number.fract() != 0.0 || number.abs() >= (1_u64 << 53) as f64 { + // Float-form integers must stay within the range where adjacent integers remain distinct. return None; } // The 64-bit upper bounds round up when represented as f64. diff --git a/backend/crates/station/src/websocket/payload.rs b/backend/crates/station/src/websocket/payload.rs index 4f840cb68..edcb33277 100644 --- a/backend/crates/station/src/websocket/payload.rs +++ b/backend/crates/station/src/websocket/payload.rs @@ -1,8 +1,8 @@ -//! JSON payloads for frontend WebSocket topics (feature `websocket`). +//! JSON payloads for station's frontend topics. //! -//! Existing topics preserve the Go backend's JSON shapes; `protection/update` -//! adds a compact event. Socket handling, subscriptions and publication belong -//! to `station`. See `websocket/README.md`. +//! Each model describes the `payload` inside a `{topic, payload}` message. +//! Serde adapters define the frontend JSON representation for shared domain types. +//! See `websocket/payload/README.md` for the wire shapes and examples. mod connection; mod data; diff --git a/backend/crates/station/src/websocket/payload/connection.rs b/backend/crates/station/src/websocket/payload/connection.rs index 4fbe97955..93ca602c2 100644 --- a/backend/crates/station/src/websocket/payload/connection.rs +++ b/backend/crates/station/src/websocket/payload/connection.rs @@ -2,6 +2,7 @@ use serde::Serialize; use std::collections::HashMap; /// Payload of `connection/update`, keyed by board name. +/// Boards remain in the snapshot with `isConnected: false` after a disconnect. pub type ConnectionUpdate = HashMap; /// Whether a board is connected to the backend. diff --git a/backend/crates/station/src/websocket/payload/data.rs b/backend/crates/station/src/websocket/payload/data.rs index 702081784..c410a1469 100644 --- a/backend/crates/station/src/websocket/payload/data.rs +++ b/backend/crates/station/src/websocket/payload/data.rs @@ -3,7 +3,7 @@ use serde::Serialize; use software_core::model::AdjId; use std::collections::HashMap; -/// Payload of `podData/update`, keyed by packet id (JSON object keys are strings). +/// Latest telemetry per packet for `podData/update`. Packet IDs are JSON object keys. pub type DataUpdate = HashMap; /// Current telemetry and statistics for one packet. @@ -23,7 +23,7 @@ pub struct DataPacketUpdate { pub measurement_updates: HashMap, } -/// A number carries statistics; booleans and enums are JSON primitives. +/// Numeric measurements carry statistics. Booleans and enum names use JSON primitives. #[derive(Debug, Clone, PartialEq, Serialize)] #[serde(untagged)] pub enum MeasurementUpdate { diff --git a/backend/crates/station/src/websocket/payload/message.rs b/backend/crates/station/src/websocket/payload/message.rs index deee233e8..8cb6496c8 100644 --- a/backend/crates/station/src/websocket/payload/message.rs +++ b/backend/crates/station/src/websocket/payload/message.rs @@ -63,13 +63,13 @@ impl From for MessageKind { } } -/// Legacy RTC timestamp used by the frontend's event display. +/// Calendar timestamp used by the frontend's event display. /// -/// This is not `ShortTimestamp`: the latter has no date and its subsecond unit -/// is unresolved. Event construction must supply the date and counter explicitly. +/// The event publisher supplies the date and RTC counter. The board's +/// `ShortTimestamp` contains the time of day and a raw subsecond byte. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] pub struct MessageTimestamp { - /// RTC counter; kept separate from `ShortTimestamp::subsecond`. + /// RTC counter supplied by the publisher. pub counter: u16, /// Second of the minute. pub second: u8, diff --git a/backend/crates/station/src/websocket/payload/order.rs b/backend/crates/station/src/websocket/payload/order.rs index ed6453df1..c40dbd6ea 100644 --- a/backend/crates/station/src/websocket/payload/order.rs +++ b/backend/crates/station/src/websocket/payload/order.rs @@ -3,23 +3,22 @@ use serde::Deserialize; use software_core::model::AdjId; use std::collections::HashMap; -/// Payload of `order/send`; conversion to an `OrderPacket` requires the ADJ. +/// Payload of `order/send`. The ADJ defines how to convert it to an `OrderPacket`. #[derive(Debug, Clone, PartialEq, Deserialize)] pub struct OrderSend { /// Requested order's ADJ id. #[serde(deserialize_with = "deserialize_adj_id")] pub id: AdjId, - /// Parameters keyed by their textual aliases, rather than wire position. + /// Parameters keyed by their ADJ aliases. The converter puts them in wire order. pub fields: HashMap, } /// One parameter supplied by the frontend. #[derive(Debug, Clone, PartialEq, Deserialize)] pub struct OrderField { - /// Raw JSON value; its type and range must be checked against the ADJ. - /// Keeping it raw also preserves integer precision before validation. + /// Raw JSON value retained so integer precision can be checked before conversion to `f64`. pub value: serde_json::Value, - /// Legacy type name, such as `uint16`, `float32`, `bool` or `enum`. + /// Frontend type name, such as `uint16` or `bool`. The converter checks it against the ADJ. #[serde(rename = "type")] pub field_type: String, } diff --git a/backend/crates/station/src/websocket/payload/protection.rs b/backend/crates/station/src/websocket/payload/protection.rs index 42e9e9496..d6eb1bd47 100644 --- a/backend/crates/station/src/websocket/payload/protection.rs +++ b/backend/crates/station/src/websocket/payload/protection.rs @@ -7,13 +7,13 @@ use software_core::model::{AdjId, ProtectionPacket, ShortTimestamp, Value}; /// Payload of `protection/update`: the triggered id, measured value and time. #[derive(Debug, Clone, PartialEq, Serialize)] pub struct ProtectionUpdate { - /// Compound protection id; its definition is available in the ADJ catalog. + /// Compound ID used to look up the protection definition in the ADJ catalog. #[serde(serialize_with = "serialize_adj_id")] pub id: AdjId, /// Value that triggered the protection, serialized as a JSON primitive. #[serde(serialize_with = "serialize_value")] pub value: Value, - /// Time received from the board, preserving the raw subsecond byte. + /// Time of day supplied by the board, with its original subsecond byte. #[serde(with = "ShortTimestampJson")] pub timestamp: ShortTimestamp, } @@ -28,6 +28,7 @@ impl From for ProtectionUpdate { } } +// Defines the frontend timestamp fields locally via Serde's remote derive. #[derive(Serialize)] #[serde(remote = "ShortTimestamp")] struct ShortTimestampJson { diff --git a/backend/crates/station/src/websocket/payload/serialize.rs b/backend/crates/station/src/websocket/payload/serialize.rs index 2d26e35ee..395f31bc4 100644 --- a/backend/crates/station/src/websocket/payload/serialize.rs +++ b/backend/crates/station/src/websocket/payload/serialize.rs @@ -1,7 +1,7 @@ use serde::{Deserialize, Deserializer, Serializer}; use software_core::model::{AdjId, Value}; -// Serializes the value of a protection message +/// Emits a scalar JSON value for a protection event. Enums use the variant name. pub(super) fn serialize_value( value: &Value, serializer: S, @@ -13,13 +13,14 @@ pub(super) fn serialize_value( } } -// Deserializer works the other way around as Serializer +/// Reads an ADJ ID from an unsigned 16-bit JSON integer. pub(super) fn deserialize_adj_id<'de, D: Deserializer<'de>>( deserializer: D, ) -> Result { u16::deserialize(deserializer).map(AdjId) } +/// Writes an ADJ ID as a JSON integer. pub(super) fn serialize_adj_id( id: &AdjId, serializer: S, diff --git a/backend/crates/station/src/websocket/receiver.rs b/backend/crates/station/src/websocket/receiver.rs index e9d16adeb..23bc28965 100644 --- a/backend/crates/station/src/websocket/receiver.rs +++ b/backend/crates/station/src/websocket/receiver.rs @@ -8,23 +8,23 @@ use tokio::{ }; use super::{ - HEARTBEAT, ORDER_SEND, OrderForwarder, Topic, WsMessage, + Commands, HEARTBEAT, LOGGER_ENABLE, LOGGER_VARIABLES, LoggerCommand, ORDER_SEND, Topic, + WsMessage, broker::BrokerClient, - error::{Error, OrderError}, + error::{Error, LoggerError, OrderError}, payload::{ ConnectionUpdate, DataUpdate, LoggerResponse, MessageUpdate, ProtectionUpdate, StateOrdersUpdate, }, }; -const HEARTBEAT_TIMEOUT: Duration = Duration::from_secs(3); - #[derive(Deserialize)] struct Subscription { + /// An empty object also opts in. `false` unsubscribes. subscribe: Option, } -/// Carries a new topic receiver, or `None` to unsubscribe. +/// Hands the writer an already-open topic receiver, or `None` to unsubscribe. #[derive(Debug)] pub(super) enum SubscriptionChange { Connections(Option>), @@ -58,15 +58,17 @@ impl SubscriptionChange { } } -/// Handles frontend requests and renews the deadline on each valid JSON message. +/// Routes frontend requests and tracks application-level liveness. pub(super) async fn run( mut read: impl Stream> + Unpin, broker: &BrokerClient, - orders: Option<&OrderForwarder>, + commands: &Commands, changes: mpsc::Sender, + heartbeat_timeout: Duration, ) -> Result<(), Error> { let mut subscriptions = HashSet::new(); - let mut deadline = Instant::now() + HEARTBEAT_TIMEOUT; + // Keep one deadline across frames. Only decoded application messages renew it. + let mut deadline = Instant::now() + heartbeat_timeout; loop { let frame = timeout_at(deadline, read.next()) .await @@ -77,16 +79,26 @@ pub(super) async fn run( match frame? { Frame::Text(text) => { let message: WsMessage = serde_json::from_str(&text)?; + // Nonblocking command queues keep heartbeat processing responsive. if message.topic == ORDER_SEND { - let result = orders + let result = commands + .orders + .as_ref() .ok_or(OrderError::VehicleUnavailable) .and_then(|orders| orders.forward(message.payload)); if let Err(error) = result { tracing::warn!(topic = ORDER_SEND, %error, "order rejected"); } + } else if matches!(message.topic.as_str(), LOGGER_ENABLE | LOGGER_VARIABLES) { + if let Err(error) = + forward_logger(commands.logger.as_ref(), &message.topic, message.payload) + { + tracing::warn!(topic = %message.topic, %error, "logger request rejected"); + } } else if let Some(topic) = Topic::from_name(&message.topic) { let request: Subscription = serde_json::from_value(message.payload)?; let enabled = request.subscribe.unwrap_or(true); + // Repeated requests keep the existing subscription and its cursor. let changed = if enabled { subscriptions.insert(topic) } else { @@ -106,7 +118,7 @@ pub(super) async fn run( } else if message.topic != HEARTBEAT { tracing::warn!(topic = %message.topic, "unsupported WebSocket topic"); } - deadline = Instant::now() + HEARTBEAT_TIMEOUT; + deadline = Instant::now() + heartbeat_timeout; } Frame::Close(_) => return Ok(()), _ => {} @@ -114,6 +126,25 @@ pub(super) async fn run( } } +fn forward_logger( + logger: Option<&mpsc::Sender>, + topic: &str, + payload: serde_json::Value, +) -> Result<(), LoggerError> { + let command = if topic == LOGGER_ENABLE { + LoggerCommand::Enable(serde_json::from_value(payload)?) + } else { + LoggerCommand::Variables(serde_json::from_value(payload)?) + }; + logger + .ok_or(LoggerError::Unavailable)? + .try_send(command) + .map_err(|error| match error { + mpsc::error::TrySendError::Full(_) => LoggerError::QueueFull, + mpsc::error::TrySendError::Closed(_) => LoggerError::Unavailable, + }) +} + #[cfg(test)] mod tests { use futures_util::stream; @@ -122,12 +153,21 @@ mod tests { use super::*; use crate::websocket::broker::Broker; + const HEARTBEAT_TIMEOUT: Duration = Duration::from_secs(3); + #[tokio::test(start_paused = true)] async fn inactivity_expires() { let (_broker, client) = Broker::new(); let (changes, _subscriptions) = mpsc::channel(1); assert!(matches!( - run(stream::pending(), &client, None, changes).await, + run( + stream::pending(), + &client, + &Commands::default(), + changes, + HEARTBEAT_TIMEOUT + ) + .await, Err(Error::HeartbeatTimeout) )); } @@ -139,7 +179,16 @@ mod tests { let read = stream::poll_fn(move |cx| frames.poll_recv(cx)); let (_broker, client) = Broker::new(); let (changes, mut subscriptions) = mpsc::channel(1); - let worker = tokio::spawn(async move { run(read, &client, None, changes).await }); + let worker = tokio::spawn(async move { + run( + read, + &client, + &Commands::default(), + changes, + HEARTBEAT_TIMEOUT, + ) + .await + }); tokio::task::yield_now().await; advance(Duration::from_secs(2)).await; @@ -169,7 +218,14 @@ mod tests { )), Ok(Frame::Close(None)), ]); - run(frames, &client, None, changes).await?; + run( + frames, + &client, + &Commands::default(), + changes, + HEARTBEAT_TIMEOUT, + ) + .await?; assert!(subscriptions.recv().await.is_none()); Ok(()) } @@ -187,7 +243,14 @@ mod tests { )), Ok(Frame::Close(None)), ]); - run(frames, &client, None, changes).await?; + run( + frames, + &client, + &Commands::default(), + changes, + HEARTBEAT_TIMEOUT, + ) + .await?; assert!(matches!( subscriptions.recv().await, Some(SubscriptionChange::Connections(Some(_))) @@ -222,7 +285,14 @@ mod tests { )), Ok(Frame::Close(None)), ]); - run(frames, &client, None, changes).await?; + run( + frames, + &client, + &Commands::default(), + changes, + HEARTBEAT_TIMEOUT, + ) + .await?; assert!(matches!( subscriptions.recv().await, Some(SubscriptionChange::Messages(Some(_))) diff --git a/backend/crates/station/src/websocket/sender.rs b/backend/crates/station/src/websocket/sender.rs index a537641a3..cbccbe07e 100644 --- a/backend/crates/station/src/websocket/sender.rs +++ b/backend/crates/station/src/websocket/sender.rs @@ -16,6 +16,7 @@ pub(super) async fn run( let (mut messages, mut protections) = (None, None); loop { let frame = tokio::select! { + // Apply subscription changes first, then give ready protection events priority. biased; change = subscriptions.recv() => { let Some(change) = change else { return Ok(()); }; @@ -41,6 +42,7 @@ pub(super) async fn run( } } +/// Installs a subscription and builds its initial snapshot, or drops it on unsubscribe. fn subscribe_state( topic: Topic, state: &mut Option>, @@ -58,6 +60,7 @@ async fn next_state( state: &mut Option>, ) -> Result { let Some(state) = state else { + // A disabled topic stays idle while select polls other branches. return pending().await; }; state.changed().await.map_err(|_| Error::BrokerClosed)?; @@ -65,6 +68,7 @@ async fn next_state( } fn state_frame(topic: Topic, state: &mut watch::Receiver) -> Result { + // Build an owned frame so the watch borrow ends before the socket write awaits. encode(topic, &*state.borrow_and_update()) } From be9130a05ae68a0312242525db22df977acfd4cb Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Wed, 25 Nov 2026 02:22:44 +0100 Subject: [PATCH 08/14] docs(backend, websocket): add websocket README and update payload one --- .../crates/station/src/websocket/README.md | 80 +++++++++++++++++++ .../station/src/websocket/payload/README.md | 8 +- 2 files changed, 85 insertions(+), 3 deletions(-) create mode 100644 backend/crates/station/src/websocket/README.md diff --git a/backend/crates/station/src/websocket/README.md b/backend/crates/station/src/websocket/README.md new file mode 100644 index 000000000..07d7c75f3 --- /dev/null +++ b/backend/crates/station/src/websocket/README.md @@ -0,0 +1,80 @@ +# WebSocket + +`broker.rs` provides `Broker` and the clonable `BrokerClient` for state and event topics, +using the types from `crate::websocket::payload`. +See the [payload models README](payload/README.md) for all topic payloads, +JSON templates, and complete message examples. Their serialization helpers +live in [`payload/serialize.rs`](payload/serialize.rs). + +| Topic | Publish through `BrokerClient` | Subscribe through `BrokerClient` | Initial state | +| --- | --- | --- | --- | +| `connection/update` | `publish_connection(connection)` | `subscribe_connections()` | `{}` | +| `order/stateOrders` | `publish_state_orders(orders)` | `subscribe_state_orders()` | `{}` | +| `logger/response` | `publish_logger(recording)` | `subscribe_logger()` | `false` | +| `podData/update` | `publish_data(packet)` | `subscribe_data()` | `{}` | +| `message/update` | `publish_message(message)` | `subscribe_messages()` | No initial event | +| `protection/update` | `publish_protection(protection)` | `subscribe_protections()` | No initial event | + +- `Broker::new()` creates both objects and the initial topic states. +- `Broker::run()` consumes a bounded `mpsc` channel of typed updates and + publishes state through `watch` and events through `broadcast`. It stops after all + `BrokerClient` instances are dropped and pending updates have been processed. +- Publication waits for capacity and returns `Error::BrokerClosed` if the + broker closed. Connection updates merge one board into the current map; + order updates replace the entire map, including empty lists or an empty map. +- State subscriptions return a `watch` receiver. Read the initial state with + `borrow_and_update()`, then await `changed()` and read again. Intermediate + changes may be coalesced; each value contains the complete current state. +- Each event topic has a separate `broadcast` buffer of 128 events. A + subscription starts with the next event. If a receiver reports `Lagged`, + the socket task logs the topic and number of missed events and closes that + session. + +`logger/enable` and `logger/variables` queue `LoggerCommand::Enable(bool)` and +`LoggerCommand::Variables(Vec)` for the logger. Both use the same +bounded `mpsc` queue. Invalid payloads and requests that cannot be queued are +logged, and the WebSocket session stays open. The logger reports its applied +state through `BrokerClient::publish_logger`, which feeds `logger/response`. + +`publish_data` accepts a complete, prepared `DataPacketUpdate`. The broker +buffers the latest update per packet id and merges it into the published +telemetry map every 100 ms when changes exist. Unchanged packets remain in +that map; repeated updates for one id within a batch are coalesced. Idle ticks +do not publish, and missed ticks are skipped rather than sent in a burst. +Pending telemetry is flushed when the broker finishes processing its input. +The publisher supplies packet counts, cycle times, measurement values and +averages; the broker preserves them as received. + +The station binary currently runs a greeting demo. To expose `/backend/ws`, +bind a listener and call `http::serve` with the sender of a bounded socket +channel. Start `Broker::run` and pass the channel receiver, a `BrokerClient`, +the command destinations, and a heartbeat timeout to `websocket::run`. +Each socket has independent reading and writing futures, coordinated by +`handler.rs`. Either future finishing closes the session. + +Connect to `/backend/ws` on the listener's address and port and send this +message to subscribe to `connection/update`. + +```json +{"topic":"connection/update","payload":{"subscribe":true}} +``` + +The same subscription format applies to all topics in the table. The sender +publishes the current state immediately for `watch` topics, then complete +updates. For event topics it sends events published after subscribing. +An empty payload `{}` also subscribes. Set `subscribe` to `false` to stop +receiving a topic. Duplicate requests to subscribe or unsubscribe are +idempotent. The receiver opens each topic subscription and passes it to the +socket writer through a bounded `mpsc` queue. A full queue closes that session. + +`receiver.rs` consumes `connection/heartbeat` without publishing a response. +It uses `timeout_at` with the caller's heartbeat timeout. Each valid JSON +application message renews the deadline. WebSocket ping/pong frames do not renew it. +Unknown topics are logged and ignored while their handlers are implemented. + +`sender.rs` releases each watch borrow before awaiting socket I/O. + +`order/send` checks parameter aliases, types and wire ranges against the ADJ. +It arranges values in ADJ order and queues the resulting `OrderPacket` for +the vehicle module. Rejected requests, including a full or closed order queue, +are logged and the WebSocket session stays open. diff --git a/backend/crates/station/src/websocket/payload/README.md b/backend/crates/station/src/websocket/payload/README.md index b57f3bba4..acb5d8a70 100644 --- a/backend/crates/station/src/websocket/payload/README.md +++ b/backend/crates/station/src/websocket/payload/README.md @@ -130,9 +130,11 @@ backend and the board. } ``` -An order without parameters has `fields: {}`. Parameter names are aliases; -the application uses the ADJ to place their values in wire order. The `value` -field remains raw JSON until validation, preserving integer precision. +An order without parameters has `fields: {}`. Parameter names are aliases. +The application uses the ADJ to place their values in wire order. The `value` +field remains raw JSON until validation. Integer fields must contain whole +numbers that fit both the wire type and the packet's `f64` representation. +Enum fields use the option name from the ADJ. Numeric `type` names are `"uint8"`, `"uint16"`, `"uint32"`, `"uint64"`, `"int8"`, `"int16"`, `"int32"`, `"int64"`, `"float32"` and `"float64"`. From a8e949552392e3f7db7c9a1fa84148dd57f1e268 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Wed, 25 Nov 2026 17:27:52 +0100 Subject: [PATCH 09/14] feat(backend, websocket): add lib.rs to station --- backend/crates/core/src/utils/serialize.rs | 2 - backend/crates/station/README.md | 12 +- backend/crates/station/src/http/README.md | 122 ++++-------------- backend/crates/station/src/lib.rs | 3 + backend/crates/station/src/main.rs | 3 - backend/crates/station/src/websocket.rs | 4 +- .../crates/station/src/websocket/README.md | 12 +- .../crates/station/src/websocket/payload.rs | 4 +- .../station/src/websocket/payload/README.md | 3 +- 9 files changed, 46 insertions(+), 119 deletions(-) create mode 100644 backend/crates/station/src/lib.rs diff --git a/backend/crates/core/src/utils/serialize.rs b/backend/crates/core/src/utils/serialize.rs index 62c544ae8..cb61543b9 100644 --- a/backend/crates/core/src/utils/serialize.rs +++ b/backend/crates/core/src/utils/serialize.rs @@ -1,6 +1,4 @@ -use crate::model::Value; use crate::model::{AdjId, BoardId, NumericKind, ProtectionKind, Severity}; -use serde::{Deserialize, Deserializer}; use serde::{Serialize, Serializer}; #[cfg(feature = "http")] diff --git a/backend/crates/station/README.md b/backend/crates/station/README.md index 00e8661df..e0faef483 100644 --- a/backend/crates/station/README.md +++ b/backend/crates/station/README.md @@ -4,14 +4,16 @@ 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). -Ver [`../../ARCHITECTURE.md`](../../ARCHITECTURE.md) para el diseño completo. +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`. -## Arrancar +## Ejecutar la demo ```sh -cargo run -p station -- --config ./dev-config.toml +cargo run -p station -- "Hyperloop UPV" ``` -*(Pendiente: crear `dev-config.toml` y `config.toml`, portados de -`backend_old/cmd/`.)* +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. diff --git a/backend/crates/station/src/http/README.md b/backend/crates/station/src/http/README.md index 9c905dbd2..d72fbee9a 100644 --- a/backend/crates/station/src/http/README.md +++ b/backend/crates/station/src/http/README.md @@ -7,14 +7,12 @@ from the frontend. It does not load the ADJ or handle WebSocket messages. | File | Responsibility | | --- | --- | -| [`../http.rs`](../http.rs) | Module entry points, with or without a WebSocket consumer. | -| [`configure.rs`](configure.rs) | Provisional HTTP configuration, validation, server preparation, and configuration tests. | -| [`server.rs`](server.rs) | Router construction, server execution, and route/WebSocket tests. | +| [`../http.rs`](../http.rs) | Server entry point, with an optional WebSocket consumer. | +| [`server.rs`](server.rs) | Router construction and HTTP and WebSocket tests. | | [`handlers.rs`](handlers.rs) | Shared state, pre-serialized catalog responses, and WebSocket handoff. | -The response models and transformations from `Adj` belong to -[`software_core::adj`](../../../core/src/adj.rs). Their JSON examples are in -[`core/src/adj/http/example`](../../../core/src/adj/http/example). +The server builds catalog responses from the given `Adj`. The +[HTTP models README](../../../core/src/model/http/README.md) contains the JSON examples. ## Routes @@ -23,7 +21,7 @@ The response models and transformations from `Adj` belong to | GET | `/backend/adj/DataPackets` | Boards and data packet definitions, without measurement protections. | | GET | `/backend/adj/OrderPackets` | Boards and order definitions, including parameter protections. | | GET | `/backend/adj/ProtectionPackets` | Flat protection catalog and protection-type display metadata. | -| GET with WebSocket upgrade headers | `/backend` | Upgrades the connection and hands the socket to the configured channel. | +| GET with WebSocket upgrade headers | `/backend/ws` | Upgrades the connection and hands the socket to the configured channel. | Catalog responses return `200 OK` with `Content-Type: application/json`. @@ -39,33 +37,29 @@ Each request clones the relevant `Bytes` handle and sends the existing JSON buffer. It does not rebuild the catalog, copy the whole buffer, or serialize the response again. No application-level mutex is needed for these reads. -The catalogs are a snapshot of the ADJ at startup; they are not refreshed -automatically. Serialization errors are propagated before requests are served. -This in-memory reuse is separate from browser caching. `configure_server` -applies the configured `Cache-Control` policy to the catalog routes. The older -listener-based entry points do not set an explicit cache policy. +The catalogs represent the ADJ loaded at startup. Serialization errors are +returned before requests are served. The router sets `Cache-Control: no-cache` +and uses permissive CORS. ## Starting the server -The caller supplies a bound `tokio::net::TcpListener` and an already-loaded -`&Adj`. The listener determines the address and port. Both entry points are -async and run until the server stops. +The caller passes a bound `tokio::net::TcpListener` and an already-loaded +`&Adj` to `station::http::serve`. The listener determines the address and port. +The function runs until the server stops. -Without a WebSocket consumer: +Pass `None` to serve the catalogs by themselves. ```rust -http::serve(listener, &adj).await?; +station::http::serve(listener, &adj, None).await?; ``` -With a bounded `tokio::sync::mpsc::Sender` whose -receiver belongs to the future WebSocket module: +To enable WebSocket upgrades, pass the sender of a bounded `tokio::sync::mpsc` +channel and give its receiver to [`station::websocket::run`](../websocket/README.md). ```rust -http::serve_with_websocket(listener, &adj, Some(sender)).await?; +station::http::serve(listener, &adj, Some(sender)).await?; ``` -Passing `None` to `serve_with_websocket` has the same behavior as `serve`. - ## WebSocket handoff The HTTP handler only performs the handshake and transfers ownership of the @@ -80,87 +74,17 @@ Before approving an upgrade, it reserves a slot in the bounded channel: capacity, it returns `503 Service Unavailable` instead of upgrading. - Invalid upgrade requests are rejected by Axum's `WebSocketUpgrade` extractor. -The future WebSocket module must consume the receiver and manage each socket's -lifetime, messages, and closure. Keeping a receiver alive without reading it -does not provide a functioning WebSocket service; the queue will eventually -fill. If the receiver disappears during the handoff, the socket is dropped. - -## Configuration - -`HttpConfig` is defined provisionally in `configure.rs` and reexported by `http`. -It does not depend on the future application configuration module or read files -and environment variables. - -| Field | Purpose | -| --- | --- | -| `bind_addr` | Explicit IP address and port to bind; port zero requests an available port. | -| `allowed_origins` | Exact HTTP(S) origins allowed by CORS; an empty list allows none. | -| `cache_policy` | Catalog policy: `NoStore`, `NoCache`, or `Unspecified`. | - -`HttpConfig::new(bind_addr)` uses no allowed CORS origins and defaults to -`CachePolicy::NoStore` (`Cache-Control: no-store`). `NoCache` allows storage -but requires revalidation before reuse; `Unspecified` sets no Cache-Control -header. These policies do not affect the server's reusable JSON buffers and -are not applied to WebSocket upgrades. - -The configuration path prepares the server without starting it: - -```rust -let mut config = http::HttpConfig::new("127.0.0.1:8080".parse()?); -config.allowed_origins = vec!["http://localhost:9000".into()]; - -let (listener, router) = http::configure_server(&config, &adj, None).await?; -axum::serve(listener, router).await?; -``` - -`configure_server` validates origins and serializes the catalogs before binding -the listener. Invalid settings and binding errors are returned to the caller; -there is no fallback to another address or port. To enable socket handoff, -replace `None` with `Some(sender)` as described above. - -CORS permits GET and HEAD from explicitly listed origins, handles preflight -requests, and does not enable credentials. Wildcards and origin URLs with -embedded credentials, paths (including a trailing slash), queries, fragments, -or invalid ports are rejected. The opaque origin `null` can be explicitly -listed for local-file clients, but it is not exclusive to Electron: other -opaque origins share it too. - -CORS controls browser access to responses; it is not HTTP authentication. -WebSocket Origin validation is still not implemented and is independent of -CORS. The existing `serve` and `serve_with_websocket` entry points remain -available for the current test startup and do not apply `HttpConfig` policies. - -## Manual checks - -From the backend workspace root, the current `main.rs` test startup can be run -with: - -```sh -cargo run -p station --locked -``` - -It currently loads the ADJ fixture and listens on `127.0.0.1:8080`. These are -temporary test settings, not configuration defaults. It uses `http::serve`, so -valid WebSocket upgrade requests receive `503` until a consumer is integrated. - -In another terminal: - -```sh -curl -i http://127.0.0.1:8080/backend/adj/DataPackets -curl -i http://127.0.0.1:8080/backend/adj/OrderPackets -curl -i http://127.0.0.1:8080/backend/adj/ProtectionPackets -``` +The WebSocket module consumes the receiver and manages each session. +If the receiver disappears during the handoff, the socket is dropped. ## Tests -From the backend workspace root: +Run the HTTP tests from the backend workspace root. ```sh -cargo test -p station http:: --locked +cargo test -p station --lib --locked http:: ``` -The tests cover catalog contents and repeated responses, empty catalogs, -configuration validation, binding errors, cache headers, CORS and preflight -handling, WebSocket upgrade and socket delivery over a real TCP connection, -unavailable channels (missing, closed, or full), and requests without upgrade -headers. +The tests cover catalog responses, cache headers, CORS, and WebSocket upgrades +over TCP. The end-to-end test checks that a protection event reaches the client +and a validated order reaches the vehicle queue. diff --git a/backend/crates/station/src/lib.rs b/backend/crates/station/src/lib.rs new file mode 100644 index 000000000..bcc30f85f --- /dev/null +++ b/backend/crates/station/src/lib.rs @@ -0,0 +1,3 @@ +pub mod http; +mod vehicle; +pub mod websocket; diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index 9fa834996..f7c37dc45 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -12,6 +12,3 @@ fn main() { tracing::info!("demo finalizada"); } -mod http; -mod vehicle; -mod websocket; diff --git a/backend/crates/station/src/websocket.rs b/backend/crates/station/src/websocket.rs index c98c72854..ba4b2cc57 100644 --- a/backend/crates/station/src/websocket.rs +++ b/backend/crates/station/src/websocket.rs @@ -41,7 +41,7 @@ pub(crate) enum LoggerCommand { /// Destinations for requests received over WebSocket. #[derive(Debug, Clone, Default)] -pub(crate) struct Commands { +pub struct Commands { /// Validates frontend orders before queuing them for the vehicle. pub(crate) orders: Option, /// Queues recording and variable selection requests for the logger. @@ -95,7 +95,7 @@ pub struct WsMessage { /// Runs one task per upgraded socket so a slow client stays isolated. /// Closing the HTTP handoff channel ends socket intake. Existing sessions end independently. -pub(crate) async fn run( +pub async fn run( mut connections: mpsc::Receiver, broker: BrokerClient, commands: Commands, diff --git a/backend/crates/station/src/websocket/README.md b/backend/crates/station/src/websocket/README.md index 07d7c75f3..acd385381 100644 --- a/backend/crates/station/src/websocket/README.md +++ b/backend/crates/station/src/websocket/README.md @@ -45,10 +45,14 @@ Pending telemetry is flushed when the broker finishes processing its input. The publisher supplies packet counts, cycle times, measurement values and averages; the broker preserves them as received. -The station binary currently runs a greeting demo. To expose `/backend/ws`, -bind a listener and call `http::serve` with the sender of a bounded socket -channel. Start `Broker::run` and pass the channel receiver, a `BrokerClient`, -the command destinations, and a heartbeat timeout to `websocket::run`. +The station binary currently runs a greeting demo. To expose `/backend/ws` +from a caller, bind a listener and pass it and the sender of a bounded socket +channel to `station::http::serve`. Create the broker and client with +`station::websocket::broker::Broker::new()` and start `broker.run()` as a Tokio task. +Pass the socket receiver, the `BrokerClient`, the command destinations, and a +heartbeat timeout to `station::websocket::run`. +`Commands::default()` leaves the order and logger destinations unset. + Each socket has independent reading and writing futures, coordinated by `handler.rs`. Either future finishing closes the session. diff --git a/backend/crates/station/src/websocket/payload.rs b/backend/crates/station/src/websocket/payload.rs index edcb33277..a2f6d5069 100644 --- a/backend/crates/station/src/websocket/payload.rs +++ b/backend/crates/station/src/websocket/payload.rs @@ -12,8 +12,8 @@ mod protection; mod serialize; pub use connection::{Connection, ConnectionUpdate}; -pub use data::{DataPacketUpdate, DataUpdate, MeasurementUpdate}; -pub use message::{MessageKind, MessagePayload, MessageTimestamp, MessageUpdate}; +pub use data::{DataPacketUpdate, DataUpdate}; +pub use message::{MessageUpdate}; pub use order::{OrderField, OrderSend, StateOrdersUpdate}; pub use protection::{ProtectionPayload, ProtectionUpdate}; diff --git a/backend/crates/station/src/websocket/payload/README.md b/backend/crates/station/src/websocket/payload/README.md index acb5d8a70..f5f2b2a48 100644 --- a/backend/crates/station/src/websocket/payload/README.md +++ b/backend/crates/station/src/websocket/payload/README.md @@ -44,8 +44,7 @@ let payload_json = serde_json::to_string(&protection)?; Published structures implement `serde::Serialize`; `OrderSend` and `OrderField` implement `serde::Deserialize`. The logger aliases use the primitive types' -Serde implementations. All payload types are re-exported from -`crate::websocket::payload` within station. +Serde implementations. The payload module is internal to the station library. Deserializing an order checks its JSON structure. Parameter types, ranges and their correspondence with the ADJ must be validated by the application before From cf536764aa0229655ae9ae03a9ea3fc1295a41e6 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Wed, 25 Nov 2026 20:13:58 +0100 Subject: [PATCH 10/14] feat(backend, websocket): detect loss of the last frontend and send "event" --- backend/crates/station/src/http/server.rs | 14 +- backend/crates/station/src/main.rs | 3 +- backend/crates/station/src/websocket.rs | 126 ++++++++++++++++-- .../crates/station/src/websocket/README.md | 6 + .../crates/station/src/websocket/handler.rs | 29 +++- 5 files changed, 157 insertions(+), 21 deletions(-) diff --git a/backend/crates/station/src/http/server.rs b/backend/crates/station/src/http/server.rs index ea6078ac0..7feb0abb8 100644 --- a/backend/crates/station/src/http/server.rs +++ b/backend/crates/station/src/http/server.rs @@ -64,7 +64,7 @@ mod tests { io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}, net::{TcpListener, TcpStream}, sync::{mpsc, oneshot}, - time::timeout, + time::{Instant, timeout}, }; use tower::ServiceExt; @@ -280,7 +280,7 @@ mod tests { } #[tokio::test] - async fn websocket_delivers_protections_and_forwards_orders() + async fn websocket_routes_messages_until_the_last_frontend_disconnects() -> Result<(), Box> { let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../core/src/adj/test/adj"); let adj = load_from_dir(&path)?; @@ -295,13 +295,14 @@ mod tests { let (broker, client) = Broker::new(); let broker_task = tokio::spawn(broker.run()); let (sockets, receiver) = mpsc::channel(1); + let heartbeat_timeout = Duration::from_secs(3); let socket_task = tokio::spawn(websocket::run( receiver, client.clone(), commands, - Duration::from_secs(10), + heartbeat_timeout, )); - let (headers, mut socket) = handshake(setup_router(&adj, Some(sockets))?).await?; + let (headers, mut socket) = handshake(setup_router(&adj, Some(sockets.clone()))?).await?; assert!(headers.starts_with("HTTP/1.1 101 Switching Protocols\r\n")); timeout(Duration::from_secs(5), async { @@ -343,8 +344,11 @@ mod tests { )) ); + let disconnected_at = Instant::now(); drop(socket); - socket_task.await?; + assert_eq!(socket_task.await?, Err(websocket::FrontendDisconnected)); + assert!(disconnected_at.elapsed() >= heartbeat_timeout); + drop(sockets); drop(client); broker_task.await?; Ok::<_, Box>(()) diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index f7c37dc45..40cba4f65 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -6,9 +6,10 @@ fn main() { let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); tracing_subscriber::fmt().with_env_filter(filter).init(); + // TODO(event): When starting the backend here, convert FrontendDisconnected + // into a ProblemKind::Fatal with no board and send it on channels.problems. tracing::info!("iniciando demo de station"); let name = std::env::args().nth(1).unwrap_or_else(|| "World".into()); let _greeting = software_core::hello_world::greet(&name); tracing::info!("demo finalizada"); } - diff --git a/backend/crates/station/src/websocket.rs b/backend/crates/station/src/websocket.rs index ba4b2cc57..3c002f914 100644 --- a/backend/crates/station/src/websocket.rs +++ b/backend/crates/station/src/websocket.rs @@ -7,9 +7,13 @@ use std::time::Duration; use axum::extract::ws::WebSocket; use serde::{Deserialize, Serialize}; -use tokio::sync::mpsc; +use tokio::{ + sync::mpsc, + time::{Instant, sleep_until}, +}; use self::broker::BrokerClient; +use self::handler::SessionEnd; pub(crate) use self::order::OrderForwarder; use self::payload::{LoggerEnable, LoggerVariables}; @@ -93,21 +97,123 @@ pub struct WsMessage { pub payload: serde_json::Value, } +/// The last frontend's heartbeat or reconnect deadline expired. +#[derive(Debug, PartialEq, Eq, thiserror::Error)] +#[error("lost connection to the last frontend")] +pub struct FrontendDisconnected; + /// Runs one task per upgraded socket so a slow client stays isolated. -/// Closing the HTTP handoff channel ends socket intake. Existing sessions end independently. +/// +/// Returns `FrontendDisconnected` after the last session times out or the +/// reconnect window expires. Closing the HTTP handoff channel ends socket +/// intake. Existing sessions end independently. +/// +/// The caller should report `FrontendDisconnected` to `event` when station +/// wires the two modules together. pub async fn run( mut connections: mpsc::Receiver, broker: BrokerClient, commands: Commands, heartbeat_timeout: Duration, -) { - while let Some(socket) = connections.recv().await { - let broker = broker.clone(); - let commands = commands.clone(); - tokio::spawn(async move { - if let Err(error) = handler::handle(socket, broker, &commands, heartbeat_timeout).await { - tracing::warn!(%error, "WebSocket connection ended with an error"); +) -> Result<(), FrontendDisconnected> { + let (session_ends, mut ended) = mpsc::channel(16); + let mut sessions = FrontendSessions::default(); + + loop { + tokio::select! { + biased; + _ = async { + if let Some(deadline) = sessions.reconnect_deadline { + sleep_until(deadline).await; + } + }, if sessions.reconnect_deadline.is_some() => return Err(FrontendDisconnected), + socket = connections.recv() => { + let Some(socket) = socket else { return Ok(()); }; + sessions.connected(); + let broker = broker.clone(); + let commands = commands.clone(); + let session_ends = session_ends.clone(); + tokio::spawn(async move { + handler::handle(socket, broker, &commands, heartbeat_timeout, session_ends).await; + }); + } + Some(end) = ended.recv() => { + sessions.ended(end, heartbeat_timeout)?; + } + } + } +} + +/// Tracks the active frontend sessions and the reconnect window after the last one ends. +#[derive(Default)] +struct FrontendSessions { + /// Sessions accepted by the supervisor whose handlers have yet to report an end. + active: usize, + /// Set after the last session reports `SessionEnd::Closed` and cleared on reconnect. + reconnect_deadline: Option, +} + +impl FrontendSessions { + fn connected(&mut self) { + self.active += 1; + self.reconnect_deadline = None; + } + + fn ended( + &mut self, + end: SessionEnd, + reconnect_window: Duration, + ) -> Result<(), FrontendDisconnected> { + self.active -= 1; + if self.active > 0 { + return Ok(()); + } + match end { + SessionEnd::HeartbeatTimeout => Err(FrontendDisconnected), + SessionEnd::Closed(at) => { + self.reconnect_deadline = Some(at + reconnect_window); + Ok(()) } - }); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const HEARTBEAT_TIMEOUT: Duration = Duration::from_secs(3); + + #[test] + fn reconnect_cancels_the_deadline_after_the_last_socket_closes() + -> Result<(), FrontendDisconnected> { + let mut sessions = FrontendSessions::default(); + let at = Instant::now(); + + assert_eq!(sessions.reconnect_deadline, None); + sessions.connected(); + sessions.connected(); + sessions.ended(SessionEnd::Closed(at), HEARTBEAT_TIMEOUT)?; + assert_eq!(sessions.reconnect_deadline, None); + sessions.ended(SessionEnd::Closed(at), HEARTBEAT_TIMEOUT)?; + assert_eq!(sessions.reconnect_deadline, Some(at + HEARTBEAT_TIMEOUT)); + + sessions.connected(); + assert_eq!(sessions.reconnect_deadline, None); + Ok(()) + } + + #[test] + fn the_last_heartbeat_timeout_is_fatal_immediately() -> Result<(), FrontendDisconnected> { + let mut sessions = FrontendSessions::default(); + sessions.connected(); + sessions.connected(); + + sessions.ended(SessionEnd::HeartbeatTimeout, HEARTBEAT_TIMEOUT)?; + assert_eq!( + sessions.ended(SessionEnd::HeartbeatTimeout, HEARTBEAT_TIMEOUT), + Err(FrontendDisconnected) + ); + Ok(()) } } diff --git a/backend/crates/station/src/websocket/README.md b/backend/crates/station/src/websocket/README.md index acd385381..7c77a2463 100644 --- a/backend/crates/station/src/websocket/README.md +++ b/backend/crates/station/src/websocket/README.md @@ -56,6 +56,12 @@ heartbeat timeout to `station::websocket::run`. Each socket has independent reading and writing futures, coordinated by `handler.rs`. Either future finishing closes the session. +With a heartbeat timeout of three seconds, the loss of the last frontend makes +`websocket::run` return `FrontendDisconnected`. A heartbeat timeout already +satisfies that period. Other socket closures allow three seconds to reconnect. +The station startup task can report this error as a `ProblemKind::Fatal` on +`channels.problems` so `event` requests the fault and stops the backend. + Connect to `/backend/ws` on the listener's address and port and send this message to subscribe to `connection/update`. diff --git a/backend/crates/station/src/websocket/handler.rs b/backend/crates/station/src/websocket/handler.rs index f39e2bdd8..b8b80d00e 100644 --- a/backend/crates/station/src/websocket/handler.rs +++ b/backend/crates/station/src/websocket/handler.rs @@ -2,24 +2,43 @@ use std::time::Duration; use axum::extract::ws::WebSocket; use futures_util::{SinkExt, StreamExt}; -use tokio::{sync::mpsc, time::timeout}; +use tokio::{ + sync::mpsc, + time::{Instant, timeout}, +}; use super::{Commands, broker::BrokerClient, error::Error, receiver, sender}; +/// Reports why a session ended before the handler closes the socket. +pub(super) enum SessionEnd { + /// The full heartbeat timeout elapsed while waiting for an application message. + HeartbeatTimeout, + /// The session ended at this instant. For the last session, this starts the reconnect window. + Closed(Instant), +} + /// Runs reading and writing concurrently. The first side to finish ends the session. pub(super) async fn handle( socket: WebSocket, broker: BrokerClient, commands: &Commands, - heartbeat_timeout: Duration -) -> Result<(), Error> { + heartbeat_timeout: Duration, + session_ends: mpsc::Sender, +) { let (mut write, read) = socket.split(); let (changes, subscriptions) = mpsc::channel(16); let result = tokio::select! { result = receiver::run(read, &broker, commands, changes, heartbeat_timeout) => result, result = sender::run(&mut write, subscriptions) => result, }; - // Bound the socket close and preserve the result that ended the session. + let end = match result { + Err(Error::HeartbeatTimeout) => SessionEnd::HeartbeatTimeout, + _ => SessionEnd::Closed(Instant::now()), + }; + // Report the end of the session before waiting on socket I/O. + let _ = session_ends.send(end).await; + if let Err(error) = result { + tracing::warn!(%error, "WebSocket connection ended with an error"); + } let _ = timeout(Duration::from_secs(1), write.close()).await; - result } From eb988305278e14cb972bb7e9243524d1bdde4064 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Wed, 25 Nov 2026 23:59:48 +0100 Subject: [PATCH 11/14] fix(frontend-kit): new websocket endpoint --- frontend/frontend-kit/kit/src/core/websocket.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/frontend-kit/kit/src/core/websocket.ts b/frontend/frontend-kit/kit/src/core/websocket.ts index 859c6ef70..d9a619810 100644 --- a/frontend/frontend-kit/kit/src/core/websocket.ts +++ b/frontend/frontend-kit/kit/src/core/websocket.ts @@ -26,7 +26,7 @@ import { type SocketConfig, type TopicOptions } from "./types"; const DEFAULT_CONFIG = { host: "127.0.0.1", port: 4000, - path: "/backend", + path: "/backend/ws", secure: false, heartbeatIntervalMs: 1000, } as const; From 37f4c5afab8cc5b5707b38d6f1d1105e65401c4b Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Thu, 26 Nov 2026 00:06:10 +0100 Subject: [PATCH 12/14] fix(backend, payload): create module payload --- backend/crates/station/src/http/server.rs | 7 ++++--- backend/crates/station/src/lib.rs | 1 + backend/crates/station/src/{websocket => }/payload.rs | 0 .../crates/station/src/{websocket => }/payload/README.md | 0 .../station/src/{websocket => }/payload/connection.rs | 0 .../crates/station/src/{websocket => }/payload/data.rs | 0 .../src/{websocket => }/payload/example/connection.json | 0 .../src/{websocket => }/payload/example/data.json | 0 .../{websocket => }/payload/example/logger_enable.json | 0 .../{websocket => }/payload/example/logger_response.json | 0 .../payload/example/logger_variables.json | 0 .../src/{websocket => }/payload/example/message.json | 0 .../src/{websocket => }/payload/example/order.json | 0 .../src/{websocket => }/payload/example/protection.json | 0 .../{websocket => }/payload/example/state_orders.json | 0 .../station/src/{websocket => }/payload/message.rs | 0 .../crates/station/src/{websocket => }/payload/order.rs | 0 .../station/src/{websocket => }/payload/protection.rs | 0 .../station/src/{websocket => }/payload/serialize.rs | 0 backend/crates/station/src/websocket.rs | 3 +-- backend/crates/station/src/websocket/broker.rs | 2 +- backend/crates/station/src/websocket/order.rs | 2 +- backend/crates/station/src/websocket/receiver.rs | 9 +++++---- 23 files changed, 13 insertions(+), 11 deletions(-) rename backend/crates/station/src/{websocket => }/payload.rs (100%) rename backend/crates/station/src/{websocket => }/payload/README.md (100%) rename backend/crates/station/src/{websocket => }/payload/connection.rs (100%) rename backend/crates/station/src/{websocket => }/payload/data.rs (100%) rename backend/crates/station/src/{websocket => }/payload/example/connection.json (100%) rename backend/crates/station/src/{websocket => }/payload/example/data.json (100%) rename backend/crates/station/src/{websocket => }/payload/example/logger_enable.json (100%) rename backend/crates/station/src/{websocket => }/payload/example/logger_response.json (100%) rename backend/crates/station/src/{websocket => }/payload/example/logger_variables.json (100%) rename backend/crates/station/src/{websocket => }/payload/example/message.json (100%) rename backend/crates/station/src/{websocket => }/payload/example/order.json (100%) rename backend/crates/station/src/{websocket => }/payload/example/protection.json (100%) rename backend/crates/station/src/{websocket => }/payload/example/state_orders.json (100%) rename backend/crates/station/src/{websocket => }/payload/message.rs (100%) rename backend/crates/station/src/{websocket => }/payload/order.rs (100%) rename backend/crates/station/src/{websocket => }/payload/protection.rs (100%) rename backend/crates/station/src/{websocket => }/payload/serialize.rs (100%) diff --git a/backend/crates/station/src/http/server.rs b/backend/crates/station/src/http/server.rs index 7feb0abb8..df73c4e86 100644 --- a/backend/crates/station/src/http/server.rs +++ b/backend/crates/station/src/http/server.rs @@ -69,8 +69,9 @@ mod tests { use tower::ServiceExt; use super::setup_router; - use crate::websocket::{ - self, Commands, OrderForwarder, broker::Broker, payload::ProtectionUpdate, + use crate::{ + payload::ProtectionUpdate, + websocket::{self, Commands, OrderForwarder, broker::Broker}, }; pub(in crate::http) const PATHS: [&str; 3] = [ @@ -327,7 +328,7 @@ mod tests { }) .await?; let expected: serde_json::Value = serde_json::from_str(include_str!( - "../websocket/payload/example/protection.json" + "../payload/example/protection.json" ))?; assert_eq!(read_json(&mut socket).await?, expected); diff --git a/backend/crates/station/src/lib.rs b/backend/crates/station/src/lib.rs index bcc30f85f..b7e482da0 100644 --- a/backend/crates/station/src/lib.rs +++ b/backend/crates/station/src/lib.rs @@ -1,3 +1,4 @@ pub mod http; mod vehicle; pub mod websocket; +pub mod payload; \ No newline at end of file diff --git a/backend/crates/station/src/websocket/payload.rs b/backend/crates/station/src/payload.rs similarity index 100% rename from backend/crates/station/src/websocket/payload.rs rename to backend/crates/station/src/payload.rs diff --git a/backend/crates/station/src/websocket/payload/README.md b/backend/crates/station/src/payload/README.md similarity index 100% rename from backend/crates/station/src/websocket/payload/README.md rename to backend/crates/station/src/payload/README.md diff --git a/backend/crates/station/src/websocket/payload/connection.rs b/backend/crates/station/src/payload/connection.rs similarity index 100% rename from backend/crates/station/src/websocket/payload/connection.rs rename to backend/crates/station/src/payload/connection.rs diff --git a/backend/crates/station/src/websocket/payload/data.rs b/backend/crates/station/src/payload/data.rs similarity index 100% rename from backend/crates/station/src/websocket/payload/data.rs rename to backend/crates/station/src/payload/data.rs diff --git a/backend/crates/station/src/websocket/payload/example/connection.json b/backend/crates/station/src/payload/example/connection.json similarity index 100% rename from backend/crates/station/src/websocket/payload/example/connection.json rename to backend/crates/station/src/payload/example/connection.json diff --git a/backend/crates/station/src/websocket/payload/example/data.json b/backend/crates/station/src/payload/example/data.json similarity index 100% rename from backend/crates/station/src/websocket/payload/example/data.json rename to backend/crates/station/src/payload/example/data.json diff --git a/backend/crates/station/src/websocket/payload/example/logger_enable.json b/backend/crates/station/src/payload/example/logger_enable.json similarity index 100% rename from backend/crates/station/src/websocket/payload/example/logger_enable.json rename to backend/crates/station/src/payload/example/logger_enable.json diff --git a/backend/crates/station/src/websocket/payload/example/logger_response.json b/backend/crates/station/src/payload/example/logger_response.json similarity index 100% rename from backend/crates/station/src/websocket/payload/example/logger_response.json rename to backend/crates/station/src/payload/example/logger_response.json diff --git a/backend/crates/station/src/websocket/payload/example/logger_variables.json b/backend/crates/station/src/payload/example/logger_variables.json similarity index 100% rename from backend/crates/station/src/websocket/payload/example/logger_variables.json rename to backend/crates/station/src/payload/example/logger_variables.json diff --git a/backend/crates/station/src/websocket/payload/example/message.json b/backend/crates/station/src/payload/example/message.json similarity index 100% rename from backend/crates/station/src/websocket/payload/example/message.json rename to backend/crates/station/src/payload/example/message.json diff --git a/backend/crates/station/src/websocket/payload/example/order.json b/backend/crates/station/src/payload/example/order.json similarity index 100% rename from backend/crates/station/src/websocket/payload/example/order.json rename to backend/crates/station/src/payload/example/order.json diff --git a/backend/crates/station/src/websocket/payload/example/protection.json b/backend/crates/station/src/payload/example/protection.json similarity index 100% rename from backend/crates/station/src/websocket/payload/example/protection.json rename to backend/crates/station/src/payload/example/protection.json diff --git a/backend/crates/station/src/websocket/payload/example/state_orders.json b/backend/crates/station/src/payload/example/state_orders.json similarity index 100% rename from backend/crates/station/src/websocket/payload/example/state_orders.json rename to backend/crates/station/src/payload/example/state_orders.json diff --git a/backend/crates/station/src/websocket/payload/message.rs b/backend/crates/station/src/payload/message.rs similarity index 100% rename from backend/crates/station/src/websocket/payload/message.rs rename to backend/crates/station/src/payload/message.rs diff --git a/backend/crates/station/src/websocket/payload/order.rs b/backend/crates/station/src/payload/order.rs similarity index 100% rename from backend/crates/station/src/websocket/payload/order.rs rename to backend/crates/station/src/payload/order.rs diff --git a/backend/crates/station/src/websocket/payload/protection.rs b/backend/crates/station/src/payload/protection.rs similarity index 100% rename from backend/crates/station/src/websocket/payload/protection.rs rename to backend/crates/station/src/payload/protection.rs diff --git a/backend/crates/station/src/websocket/payload/serialize.rs b/backend/crates/station/src/payload/serialize.rs similarity index 100% rename from backend/crates/station/src/websocket/payload/serialize.rs rename to backend/crates/station/src/payload/serialize.rs diff --git a/backend/crates/station/src/websocket.rs b/backend/crates/station/src/websocket.rs index 3c002f914..0b71c4a29 100644 --- a/backend/crates/station/src/websocket.rs +++ b/backend/crates/station/src/websocket.rs @@ -11,17 +11,16 @@ use tokio::{ sync::mpsc, time::{Instant, sleep_until}, }; +use super::payload::{LoggerEnable, LoggerVariables}; use self::broker::BrokerClient; use self::handler::SessionEnd; pub(crate) use self::order::OrderForwarder; -use self::payload::{LoggerEnable, LoggerVariables}; pub mod broker; mod error; mod handler; mod order; -pub(super) mod payload; mod receiver; mod sender; diff --git a/backend/crates/station/src/websocket/broker.rs b/backend/crates/station/src/websocket/broker.rs index ba7ce289d..6e3614d42 100644 --- a/backend/crates/station/src/websocket/broker.rs +++ b/backend/crates/station/src/websocket/broker.rs @@ -5,7 +5,7 @@ use std::time::Duration; -use super::payload::{ +use crate::payload::{ Connection, ConnectionUpdate, DataPacketUpdate, DataUpdate, LoggerResponse, MessageUpdate, ProtectionUpdate, StateOrdersUpdate, }; diff --git a/backend/crates/station/src/websocket/order.rs b/backend/crates/station/src/websocket/order.rs index c01f2c613..c13c30e6e 100644 --- a/backend/crates/station/src/websocket/order.rs +++ b/backend/crates/station/src/websocket/order.rs @@ -7,7 +7,7 @@ use software_core::{ use std::sync::Arc; use tokio::sync::mpsc; -use super::payload::{OrderField, OrderSend}; +use crate::payload::{OrderField, OrderSend}; /// Validates frontend requests against the ADJ and forwards them to the vehicle. #[derive(Debug, Clone)] diff --git a/backend/crates/station/src/websocket/receiver.rs b/backend/crates/station/src/websocket/receiver.rs index 23bc28965..49cf64c9e 100644 --- a/backend/crates/station/src/websocket/receiver.rs +++ b/backend/crates/station/src/websocket/receiver.rs @@ -7,15 +7,16 @@ use tokio::{ time::{Instant, timeout_at}, }; +use crate::payload::{ + ConnectionUpdate, DataUpdate, LoggerResponse, MessageUpdate, ProtectionUpdate, + StateOrdersUpdate, +}; + use super::{ Commands, HEARTBEAT, LOGGER_ENABLE, LOGGER_VARIABLES, LoggerCommand, ORDER_SEND, Topic, WsMessage, broker::BrokerClient, error::{Error, LoggerError, OrderError}, - payload::{ - ConnectionUpdate, DataUpdate, LoggerResponse, MessageUpdate, ProtectionUpdate, - StateOrdersUpdate, - }, }; #[derive(Deserialize)] From 7b9f1bf973fe6a4a7a3ece2b59b5a8603d4943cf Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Thu, 26 Nov 2026 00:13:40 +0100 Subject: [PATCH 13/14] docs(payload): update after movement --- backend/crates/station/src/payload/README.md | 44 +++++++++++++------ .../crates/station/src/websocket/README.md | 6 +-- 2 files changed, 34 insertions(+), 16 deletions(-) diff --git a/backend/crates/station/src/payload/README.md b/backend/crates/station/src/payload/README.md index f5f2b2a48..6f1de496c 100644 --- a/backend/crates/station/src/payload/README.md +++ b/backend/crates/station/src/payload/README.md @@ -1,16 +1,28 @@ -# WebSocket Message Models (`websocket::payload`) +# WebSocket Message Models (`payload`) JSON models for telemetry, connections, orders, messages, protection events -and logger control. The types live in station's `websocket/payload.rs` and -`websocket/payload/`, alongside the WebSocket implementation. +and logger control. The public module is `station::payload`, declared in +[`../payload.rs`](../payload.rs), with its implementation in `src/payload/`. The Rust types describe the payload of each topic. Messages sent over the WebSocket wrap that payload in `{topic, payload}`, as shown in the templates and example files below. Connections, subscriptions, channels and the broker -are handled by the surrounding [WebSocket module](../README.md). Shared +are handled by the [WebSocket module](../websocket/README.md). Shared serialization helpers live in [serialize.rs](serialize.rs), and domain types such as `AdjId`, `Value` and `ProtectionPacket` come from `software_core::model`. +## Files + +| File | Models and responsibility | +| --- | --- | +| [`../payload.rs`](../payload.rs) | Public re-exports and logger payload aliases. | +| [`data.rs`](data.rs) | `DataUpdate`, `DataPacketUpdate` and measurement values. | +| [`connection.rs`](connection.rs) | `ConnectionUpdate` and `Connection`. | +| [`order.rs`](order.rs) | `OrderSend`, `OrderField` and `StateOrdersUpdate`. | +| [`message.rs`](message.rs) | `MessageUpdate`, its severity, content and calendar timestamp. | +| [`protection.rs`](protection.rs) | `ProtectionUpdate`, conversion from `ProtectionPacket` and legacy `ProtectionPayload`. | +| [`serialize.rs`](serialize.rs) | Internal Serde adapters for `AdjId` and `Value`. | + ## Topics | Topic | Payload type | Direction | JSON example | @@ -32,10 +44,10 @@ independent of the bundled ADJ fixture and HTTP catalog examples. ## Usage The payload module is compiled as part of station, without a separate feature. -Within station, with a decoded `packet: software_core::model::ProtectionPacket`: +With a decoded `packet: software_core::model::ProtectionPacket`: ```rust -use crate::websocket::payload::{OrderSend, ProtectionUpdate}; +use station::payload::{OrderSend, ProtectionUpdate}; let request: OrderSend = serde_json::from_str(r#"{"id":1002,"fields":{}}"#)?; let protection = ProtectionUpdate::from(packet); @@ -44,11 +56,15 @@ let payload_json = serde_json::to_string(&protection)?; Published structures implement `serde::Serialize`; `OrderSend` and `OrderField` implement `serde::Deserialize`. The logger aliases use the primitive types' -Serde implementations. The payload module is internal to the station library. +Serde implementations. Within station itself, import these types through +`crate::payload`. The implementation submodules are private; use the types +re-exported by `payload`. -Deserializing an order checks its JSON structure. Parameter types, ranges and -their correspondence with the ADJ must be validated by the application before -converting it to an `OrderPacket`. +Deserializing an order checks its JSON structure and the unsigned 16-bit ID. +The [WebSocket order handler](../websocket/order.rs) then validates the order +ID, parameter aliases, types and wire ranges against the ADJ, arranges the +values in ADJ order and queues an `OrderPacket` for the vehicle. Callers that +deserialize `OrderSend` directly must perform that validation themselves. ## JSON Structure Templates @@ -88,8 +104,9 @@ it as a string. ``` The outer key matches the packet's `id`. `count` is the received packet count; -`cycleTime` is the averaged interval between packet receptions. The publisher -supplies these statistics and the hexadecimal packet representation. +`cycleTime` is the averaged interval between packet receptions, in the legacy +timestamp's units. This module does not convert it. The publisher supplies +these statistics and the hexadecimal packet representation. `MeasurementUpdate` has three JSON forms: `{last, average}` for a number, a boolean, or an enum variant string. There is no additional discriminator @@ -110,7 +127,8 @@ around a measurement value. ``` The map key matches `name`. The state describes the connection between the -backend and the board. +backend and the board. Disconnected boards remain in the broker's snapshot +with `isConnected: false`. ### Send Order (`OrderSend`) diff --git a/backend/crates/station/src/websocket/README.md b/backend/crates/station/src/websocket/README.md index 7c77a2463..20fdf3a91 100644 --- a/backend/crates/station/src/websocket/README.md +++ b/backend/crates/station/src/websocket/README.md @@ -1,10 +1,10 @@ # WebSocket `broker.rs` provides `Broker` and the clonable `BrokerClient` for state and event topics, -using the types from `crate::websocket::payload`. -See the [payload models README](payload/README.md) for all topic payloads, +using the types from `crate::payload`, exposed publicly as `station::payload`. +See the [payload models README](../payload/README.md) for all topic payloads, JSON templates, and complete message examples. Their serialization helpers -live in [`payload/serialize.rs`](payload/serialize.rs). +live in [`../payload/serialize.rs`](../payload/serialize.rs). | Topic | Publish through `BrokerClient` | Subscribe through `BrokerClient` | Initial state | | --- | --- | --- | --- | From 152ad49d73e50bf45d94985040c0d2682f86827a Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Thu, 26 Nov 2026 00:21:09 +0100 Subject: [PATCH 14/14] feat(backend, payload): return of isEnabled to websocket payloads for order/send --- backend/crates/station/src/http/server.rs | 2 +- backend/crates/station/src/payload/README.md | 4 ++ .../station/src/payload/example/order.json | 1 + backend/crates/station/src/payload/order.rs | 45 +++++++++++++++++++ backend/crates/station/src/websocket/order.rs | 2 + 5 files changed, 53 insertions(+), 1 deletion(-) diff --git a/backend/crates/station/src/http/server.rs b/backend/crates/station/src/http/server.rs index df73c4e86..f69f2e434 100644 --- a/backend/crates/station/src/http/server.rs +++ b/backend/crates/station/src/http/server.rs @@ -334,7 +334,7 @@ mod tests { send_text( &mut socket, - r#"{"topic":"order/send","payload":{"id":809,"fields":{"desired_current":{"value":12.5,"type":"float32"},"lpu_id":{"value":2,"type":"uint32"}}}}"#, + r#"{"topic":"order/send","payload":{"id":809,"fields":{"desired_current":{"value":12.5,"isEnabled":false,"type":"float32"},"lpu_id":{"value":2,"isEnabled":true,"type":"uint32"}}}}"#, ) .await?; assert_eq!( diff --git a/backend/crates/station/src/payload/README.md b/backend/crates/station/src/payload/README.md index 6f1de496c..85ce46480 100644 --- a/backend/crates/station/src/payload/README.md +++ b/backend/crates/station/src/payload/README.md @@ -140,6 +140,7 @@ with `isConnected: false`. "fields": { "": { "value": number, // A boolean or enum string is also possible. + "isEnabled": boolean, "type": string } } @@ -148,6 +149,9 @@ with `isConnected: false`. ``` An order without parameters has `fields: {}`. Parameter names are aliases. +`isEnabled` preserves the legacy frontend flag and defaults to `false` when +omitted. As in the Go backend, it does not skip validation or encoding: +all parameters declared by the ADJ must be supplied, even with `isEnabled: false`. The application uses the ADJ to place their values in wire order. The `value` field remains raw JSON until validation. Integer fields must contain whole numbers that fit both the wire type and the packet's `f64` representation. diff --git a/backend/crates/station/src/payload/example/order.json b/backend/crates/station/src/payload/example/order.json index 0aa349cb0..853111e21 100644 --- a/backend/crates/station/src/payload/example/order.json +++ b/backend/crates/station/src/payload/example/order.json @@ -5,6 +5,7 @@ "fields": { "target_speed": { "value": 12.5, + "isEnabled": true, "type": "float32" } } diff --git a/backend/crates/station/src/payload/order.rs b/backend/crates/station/src/payload/order.rs index c40dbd6ea..615b1a0ca 100644 --- a/backend/crates/station/src/payload/order.rs +++ b/backend/crates/station/src/payload/order.rs @@ -18,6 +18,10 @@ pub struct OrderSend { pub struct OrderField { /// Raw JSON value retained so integer precision can be checked before conversion to `f64`. pub value: serde_json::Value, + /// Legacy frontend flag, defaulting to false when omitted. + /// As in Go, it does not exclude the parameter from validation or wire encoding. + #[serde(default, rename = "isEnabled")] + pub is_enabled: bool, /// Frontend type name, such as `uint16` or `bool`. The converter checks it against the ADJ. #[serde(rename = "type")] pub field_type: String, @@ -25,3 +29,44 @@ pub struct OrderField { /// Payload of `order/stateOrders`: board names mapped to enabled order ids. pub type StateOrdersUpdate = HashMap>; + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::OrderSend; + + #[test] + fn order_fields_read_is_enabled_with_the_legacy_default() -> Result<(), serde_json::Error> { + for enabled in [Some(true), Some(false), None] { + let mut field = json!({"value": 12.5, "type": "float32"}); + if let Some(enabled) = enabled { + field["isEnabled"] = json!(enabled); + } + let request: OrderSend = serde_json::from_value(json!({ + "id": 1001, + "fields": {"target_speed": field} + }))?; + assert_eq!( + request.fields["target_speed"].is_enabled, + enabled.unwrap_or(false) + ); + } + Ok(()) + } + + #[test] + fn order_fields_reject_non_boolean_is_enabled() { + for enabled in [json!("true"), json!(1), json!(null)] { + assert!( + serde_json::from_value::(json!({ + "id": 1001, + "fields": { + "target_speed": {"value": 12.5, "type": "float32", "isEnabled": enabled} + } + })) + .is_err() + ); + } + } +} diff --git a/backend/crates/station/src/websocket/order.rs b/backend/crates/station/src/websocket/order.rs index c13c30e6e..c1805ec4d 100644 --- a/backend/crates/station/src/websocket/order.rs +++ b/backend/crates/station/src/websocket/order.rs @@ -46,6 +46,7 @@ fn to_packet(mut request: OrderSend, index: &Index) -> Result