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/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/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/http/server.rs b/backend/crates/station/src/http/server.rs index 0bb27dedf..f69f2e434 100644 --- a/backend/crates/station/src/http/server.rs +++ b/backend/crates/station/src/http/server.rs @@ -48,23 +48,31 @@ 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, AsyncWriteExt, BufReader}, + io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}, net::{TcpListener, TcpStream}, sync::{mpsc, oneshot}, - time::timeout, + time::{Instant, timeout}, }; use tower::ServiceExt; use super::setup_router; + use crate::{ + payload::ProtectionUpdate, + websocket::{self, Commands, OrderForwarder, broker::Broker}, + }; pub(in crate::http) const PATHS: [&str; 3] = [ "/backend/adj/DataPackets", @@ -199,17 +207,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,35 +281,134 @@ pub(super) mod tests { } #[tokio::test] - async fn websocket_without_a_consumer_returns_unavailable() + async fn websocket_routes_messages_until_the_last_frontend_disconnects() -> 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")); + 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 heartbeat_timeout = Duration::from_secs(3); + let socket_task = tokio::spawn(websocket::run( + receiver, + client.clone(), + commands, + heartbeat_timeout, + )); + 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 { + 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 socket).await?, + serde_json::json!({"topic": "connection/update", "payload": {}}) + ); + + client + .publish_protection(ProtectionUpdate { + id: AdjId(11192), + value: Value::Number(105.5), + timestamp: ShortTimestamp { + hour: 12, + minute: 30, + second: 6, + subsecond: 0, + }, + }) + .await?; + let expected: serde_json::Value = serde_json::from_str(include_str!( + "../payload/example/protection.json" + ))?; + assert_eq!(read_json(&mut socket).await?, expected); + + send_text( + &mut socket, + 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!( + orders.recv().await, + Some(OrderPacket::new( + AdjId(809), + vec![Value::Number(2.0), Value::Number(12.5)], + )) + ); + + let disconnected_at = Instant::now(); + drop(socket); + assert_eq!(socket_task.await?, Err(websocket::FrontendDisconnected)); + assert!(disconnected_at.elapsed() >= heartbeat_timeout); + drop(sockets); + drop(client); + broker_task.await?; + Ok::<_, Box>(()) + }) + .await??; Ok(()) } - #[tokio::test] - async fn websocket_with_a_closed_channel_returns_unavailable() - -> Result<(), Box> { - let (connections, 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")); + async fn send_text( + socket: &mut TcpStream, + text: &str, + ) -> Result<(), Box> { + let length = u16::try_from(text.len())?; + if length < 126 { + socket.write_all(&[0x81, 0x80 | length as u8]).await?; + } else { + socket.write_all(&[0x81, 0xfe]).await?; + socket.write_u16(length).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( + socket: &mut TcpStream, + ) -> Result> { + 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]; + socket.read_exact(&mut body).await?; + Ok(serde_json::from_slice(&body)?) + } + #[tokio::test] - async fn websocket_with_a_full_channel_returns_unavailable() + async fn websocket_returns_unavailable_when_handoff_cannot_accept_a_socket() -> 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 (closed, receiver) = mpsc::channel(1); + drop(receiver); + 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/lib.rs b/backend/crates/station/src/lib.rs new file mode 100644 index 000000000..b7e482da0 --- /dev/null +++ b/backend/crates/station/src/lib.rs @@ -0,0 +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/main.rs b/backend/crates/station/src/main.rs index d872008d1..40cba4f65 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -6,6 +6,8 @@ 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); diff --git a/backend/crates/station/src/payload.rs b/backend/crates/station/src/payload.rs new file mode 100644 index 000000000..a2f6d5069 --- /dev/null +++ b/backend/crates/station/src/payload.rs @@ -0,0 +1,27 @@ +//! JSON payloads for station's frontend topics. +//! +//! 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; +mod message; +mod order; +mod protection; +mod serialize; + +pub use connection::{Connection, ConnectionUpdate}; +pub use data::{DataPacketUpdate, DataUpdate}; +pub use message::{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/station/src/payload/README.md b/backend/crates/station/src/payload/README.md new file mode 100644 index 000000000..85ce46480 --- /dev/null +++ b/backend/crates/station/src/payload/README.md @@ -0,0 +1,298 @@ +# WebSocket Message Models (`payload`) + +JSON models for telemetry, connections, orders, messages, protection events +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 [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 | +| --- | --- | --- | --- | +| `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 + +The payload module is compiled as part of station, without a separate feature. +With a decoded `packet: software_core::model::ProtectionPacket`: + +```rust +use station::payload::{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. 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 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 + +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, 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 +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. Disconnected boards remain in the broker's snapshot +with `isConnected: false`. + +### 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. +`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. +Enum fields use the option name from the ADJ. + +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. diff --git a/backend/crates/station/src/payload/connection.rs b/backend/crates/station/src/payload/connection.rs new file mode 100644 index 000000000..93ca602c2 --- /dev/null +++ b/backend/crates/station/src/payload/connection.rs @@ -0,0 +1,16 @@ +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. +#[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/station/src/payload/data.rs b/backend/crates/station/src/payload/data.rs new file mode 100644 index 000000000..c410a1469 --- /dev/null +++ b/backend/crates/station/src/payload/data.rs @@ -0,0 +1,41 @@ +use super::serialize::serialize_adj_id; +use serde::Serialize; +use software_core::model::AdjId; +use std::collections::HashMap; + +/// Latest telemetry per packet for `podData/update`. Packet IDs are JSON object keys. +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, +} + +/// Numeric measurements carry statistics. Booleans and enum names use 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/station/src/payload/example/connection.json b/backend/crates/station/src/payload/example/connection.json new file mode 100644 index 000000000..ab23a4751 --- /dev/null +++ b/backend/crates/station/src/payload/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/station/src/payload/example/data.json b/backend/crates/station/src/payload/example/data.json new file mode 100644 index 000000000..312fdc7ba --- /dev/null +++ b/backend/crates/station/src/payload/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/station/src/payload/example/logger_enable.json b/backend/crates/station/src/payload/example/logger_enable.json new file mode 100644 index 000000000..a63e1bf11 --- /dev/null +++ b/backend/crates/station/src/payload/example/logger_enable.json @@ -0,0 +1,4 @@ +{ + "topic": "logger/enable", + "payload": true +} diff --git a/backend/crates/station/src/payload/example/logger_response.json b/backend/crates/station/src/payload/example/logger_response.json new file mode 100644 index 000000000..fc7277b4c --- /dev/null +++ b/backend/crates/station/src/payload/example/logger_response.json @@ -0,0 +1,4 @@ +{ + "topic": "logger/response", + "payload": true +} diff --git a/backend/crates/station/src/payload/example/logger_variables.json b/backend/crates/station/src/payload/example/logger_variables.json new file mode 100644 index 000000000..6fb7698f8 --- /dev/null +++ b/backend/crates/station/src/payload/example/logger_variables.json @@ -0,0 +1,8 @@ +{ + "topic": "logger/variables", + "payload": [ + "temperature_1", + "contactor_closed", + "state" + ] +} diff --git a/backend/crates/station/src/payload/example/message.json b/backend/crates/station/src/payload/example/message.json new file mode 100644 index 000000000..65d1f75cb --- /dev/null +++ b/backend/crates/station/src/payload/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/station/src/payload/example/order.json b/backend/crates/station/src/payload/example/order.json new file mode 100644 index 000000000..853111e21 --- /dev/null +++ b/backend/crates/station/src/payload/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/station/src/payload/example/protection.json b/backend/crates/station/src/payload/example/protection.json new file mode 100644 index 000000000..8ae2375a1 --- /dev/null +++ b/backend/crates/station/src/payload/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/station/src/payload/example/state_orders.json b/backend/crates/station/src/payload/example/state_orders.json new file mode 100644 index 000000000..0ee68edda --- /dev/null +++ b/backend/crates/station/src/payload/example/state_orders.json @@ -0,0 +1,10 @@ +{ + "topic": "order/stateOrders", + "payload": { + "LCU": [ + 1001, + 1002 + ], + "HVBMS": [] + } +} diff --git a/backend/crates/station/src/payload/message.rs b/backend/crates/station/src/payload/message.rs new file mode 100644 index 000000000..8cb6496c8 --- /dev/null +++ b/backend/crates/station/src/payload/message.rs @@ -0,0 +1,86 @@ +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)] +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, + } + } +} + +/// Calendar timestamp used by the frontend's event display. +/// +/// 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 supplied by the publisher. + 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/station/src/payload/order.rs b/backend/crates/station/src/payload/order.rs new file mode 100644 index 000000000..615b1a0ca --- /dev/null +++ b/backend/crates/station/src/payload/order.rs @@ -0,0 +1,72 @@ +use super::serialize::deserialize_adj_id; +use serde::Deserialize; +use software_core::model::AdjId; +use std::collections::HashMap; + +/// 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 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 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, +} + +/// 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/payload/protection.rs b/backend/crates/station/src/payload/protection.rs new file mode 100644 index 000000000..d6eb1bd47 --- /dev/null +++ b/backend/crates/station/src/payload/protection.rs @@ -0,0 +1,94 @@ +use super::serialize::{serialize_adj_id, serialize_value}; +use serde::Serialize; +use serde_json::Value as JsonValue; + +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 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 of day supplied by the board, with its original 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, + } + } +} + +// Defines the frontend timestamp fields locally via Serde's remote derive. +#[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/station/src/payload/serialize.rs b/backend/crates/station/src/payload/serialize.rs new file mode 100644 index 000000000..395f31bc4 --- /dev/null +++ b/backend/crates/station/src/payload/serialize.rs @@ -0,0 +1,29 @@ +use serde::{Deserialize, Deserializer, Serializer}; +use software_core::model::{AdjId, Value}; + +/// Emits a scalar JSON value for a protection event. Enums use the variant name. +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), + } +} + +/// 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, +) -> Result { + serializer.serialize_u16(id.0) +} diff --git a/backend/crates/station/src/websocket.rs b/backend/crates/station/src/websocket.rs new file mode 100644 index 000000000..0b71c4a29 --- /dev/null +++ b/backend/crates/station/src/websocket.rs @@ -0,0 +1,218 @@ +//! 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}; +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; + +pub mod broker; +mod error; +mod handler; +mod order; +mod receiver; +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 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, + 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 { + /// Wire name used to route the message, such as `connection/update`. + pub topic: String, + /// Topic-specific JSON payload. + 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. +/// +/// 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, +) -> 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 new file mode 100644 index 000000000..20fdf3a91 --- /dev/null +++ b/backend/crates/station/src/websocket/README.md @@ -0,0 +1,90 @@ +# WebSocket + +`broker.rs` provides `Broker` and the clonable `BrokerClient` for state and event topics, +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). + +| 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` +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. + +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`. + +```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/broker.rs b/backend/crates/station/src/websocket/broker.rs new file mode 100644 index 000000000..6e3614d42 --- /dev/null +++ b/backend/crates/station/src/websocket/broker.rs @@ -0,0 +1,405 @@ +//! 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; + +use crate::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; + +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, + connections: watch::Sender, + state_orders: watch::Sender, + logger: watch::Sender, + data: watch::Sender, + messages: broadcast::Sender, + protections: broadcast::Sender, +} + +/// 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, + connections: watch::Receiver, + 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, +} + +impl Broker { + /// 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 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 { + 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); } + // 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 => { + self.flush_data(&mut pending); + return; + } + } + } + _ = tick.tick() => self.flush_data(&mut pending), + } + } + } + + 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())); + } + } +} + +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(update) + .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 { + 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(); + // Callers read the initial snapshot directly. `changed()` then waits for a newer one. + receiver.borrow_and_update(); + receiver +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use tokio::time::{advance, 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))); + 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] + 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?; + 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 new file mode 100644 index 000000000..15b4889c8 --- /dev/null +++ b/backend/crates/station/src/websocket/error.rs @@ -0,0 +1,59 @@ +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 session ends when the writer can no longer keep up with subscription changes. + #[error("WebSocket subscription queue is full")] + SubscriptionQueueFull, + /// 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), + /// 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. + #[error("WebSocket heartbeat timed out")] + 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}")] + 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, +} + +/// 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 new file mode 100644 index 000000000..b8b80d00e --- /dev/null +++ b/backend/crates/station/src/websocket/handler.rs @@ -0,0 +1,44 @@ +use std::time::Duration; + +use axum::extract::ws::WebSocket; +use futures_util::{SinkExt, StreamExt}; +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, + 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, + }; + 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; +} diff --git a/backend/crates/station/src/websocket/order.rs b/backend/crates/station/src/websocket/order.rs new file mode 100644 index 000000000..c1805ec4d --- /dev/null +++ b/backend/crates/station/src/websocket/order.rs @@ -0,0 +1,187 @@ +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 crate::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, + }) + } +} + +/// 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) + 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()))?; + // The legacy isEnabled flag does not change the positional wire layout. + values.push(field_value(&field, alias, &measurement.kind)?); + } + // Removing each declared field leaves only parameters the ADJ does not recognize. + 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()))?; + + // Apply the same range checks as the vehicle's encoder before queuing the order. + wire::encode_value(&value, kind).map_err(|_| OrderError::InvalidValue(alias.into()))?; + Ok(value) +} + +/// Checks that an integer survives conversion to the packet's `f64` representation. +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 { + // 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. + 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"), + is_enabled: true, + 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 new file mode 100644 index 000000000..49cf64c9e --- /dev/null +++ b/backend/crates/station/src/websocket/receiver.rs @@ -0,0 +1,316 @@ +use axum::extract::ws::Message as Frame; +use futures_util::{Stream, StreamExt}; +use serde::Deserialize; +use std::{collections::HashSet, time::Duration}; +use tokio::{ + sync::{broadcast, mpsc, watch}, + 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}, +}; + +#[derive(Deserialize)] +struct Subscription { + /// An empty object also opts in. `false` unsubscribes. + subscribe: Option, +} + +/// Hands the writer an already-open 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()?, + ), + }) + } +} + +/// Routes frontend requests and tracks application-level liveness. +pub(super) async fn run( + mut read: impl Stream> + Unpin, + broker: &BrokerClient, + commands: &Commands, + changes: mpsc::Sender, + heartbeat_timeout: Duration, +) -> Result<(), Error> { + let mut subscriptions = HashSet::new(); + // 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 + .map_err(|_| Error::HeartbeatTimeout)?; + let Some(frame) = frame else { + return Ok(()); + }; + 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 = 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 { + 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(()), + } + } + } else if message.topic != HEARTBEAT { + tracing::warn!(topic = %message.topic, "unsupported WebSocket topic"); + } + deadline = Instant::now() + heartbeat_timeout; + } + Frame::Close(_) => return Ok(()), + _ => {} + } + } +} + +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; + use tokio::time::advance; + + 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, + &Commands::default(), + changes, + HEARTBEAT_TIMEOUT + ) + .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 (_broker, client) = Broker::new(); + let (changes, mut subscriptions) = mpsc::channel(1); + 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; + input + .send(Ok(Frame::Text( + r#"{"topic":"connection/update","payload":{"subscribe":true}}"#.into(), + ))) + .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; + assert!(matches!(worker.await?, Err(Error::HeartbeatTimeout))); + Ok(()) + } + + #[tokio::test] + async fn heartbeats_do_not_subscribe_or_publish() -> Result<(), Error> { + 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, + &client, + &Commands::default(), + changes, + HEARTBEAT_TIMEOUT, + ) + .await?; + assert!(subscriptions.recv().await.is_none()); + Ok(()) + } + + #[tokio::test] + async fn subscription_requests_can_unsubscribe() -> Result<(), Error> { + 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(), + )), + Ok(Frame::Text( + r#"{"topic":"connection/update","payload":{"subscribe":false}}"#.into(), + )), + Ok(Frame::Close(None)), + ]); + run( + frames, + &client, + &Commands::default(), + changes, + HEARTBEAT_TIMEOUT, + ) + .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, + &Commands::default(), + changes, + HEARTBEAT_TIMEOUT, + ) + .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 new file mode 100644 index 000000000..cbccbe07e --- /dev/null +++ b/backend/crates/station/src/websocket/sender.rs @@ -0,0 +1,132 @@ +use std::future::pending; + +use axum::extract::ws::{Message as Frame, WebSocket}; +use futures_util::{SinkExt, stream::SplitSink}; +use serde::Serialize; +use tokio::sync::{broadcast, mpsc, watch}; + +use super::{Topic, WsMessage, error::Error, receiver::SubscriptionChange}; + +/// Sends subscribed state snapshots and events over the socket. +pub(super) async fn run( + write: &mut SplitSink, + mut subscriptions: mpsc::Receiver, +) -> Result<(), Error> { + let (mut connections, mut orders, mut logger, mut data) = (None, None, None, None); + 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(()); }; + 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 + } + 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).await?; + } +} + +/// Installs a subscription and builds its initial snapshot, or drops it on unsubscribe. +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 { + // A disabled topic stays idle while select polls other branches. + return pending().await; + }; + state.changed().await.map_err(|_| Error::BrokerClosed)?; + state_frame(topic, 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()) +} + +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(()) + } +} 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;