diff --git a/backend/Cargo.lock b/backend/Cargo.lock index b54c46b90..51ba1dae3 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -1947,6 +1947,7 @@ checksum = "26699905cc795a23e3949585cc7ba3ee8ade090872a27e4316304a777297894a" dependencies = [ "jiff-core", "jiff-static", + "jiff-tzdb", "jiff-tzdb-platform", "log", "portable-atomic", @@ -2960,9 +2961,11 @@ version = "0.1.0" dependencies = [ "axum", "futures-util", + "jiff", "serde", "serde_json", "software-core", + "tempfile", "thiserror", "tokio", "toml", diff --git a/backend/Cargo.toml b/backend/Cargo.toml index d14dd7807..24f3baa88 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -20,6 +20,7 @@ repository = "https://github.com/Hyperloop-UPV/software" software-core = { path = "crates/core" } bytes = "1" +jiff = { version = "0.2", features = ["tzdb-bundle-always"] } serde = { version = "1", features = ["derive"] } serde_json = "1" thiserror = "2" diff --git a/backend/crates/core/src/logger/csv.rs b/backend/crates/core/src/logger/csv.rs index 8c2fbd723..57638eda2 100644 --- a/backend/crates/core/src/logger/csv.rs +++ b/backend/crates/core/src/logger/csv.rs @@ -255,6 +255,12 @@ impl Row<'_, W> { self.number(format_args!("{value}")) } + /// Appends the instant field. Cannot use `Self::int()`, + /// because an instant is an u128 + pub fn instant(self, value: u128) -> Self { + self.number(format_args!("{value}")) + } + /// Appends a boolean field, as `true` or `false`. pub fn bool(self, value: bool) -> Self { self.number(format_args!("{value}")) diff --git a/backend/crates/station/Cargo.toml b/backend/crates/station/Cargo.toml index d481d8fb2..f15e5fce8 100644 --- a/backend/crates/station/Cargo.toml +++ b/backend/crates/station/Cargo.toml @@ -9,7 +9,8 @@ authors.workspace = true repository.workspace = true [dependencies] -software-core = { workspace = true, features = ["net", "git", "http"] } +software-core = { workspace = true, features = ["net", "git", "http", "logger"] } +jiff.workspace = true serde.workspace = true thiserror.workspace = true tokio.workspace = true @@ -23,6 +24,7 @@ axum = { version = "0.8.9", features = ["ws", "http1", "http2"] } tower-http = { version = "0.6.11", features = ["cors", "set-header"] } [dev-dependencies] +tempfile = "3.27" tokio = { workspace = true, features = ["test-util"] } [lints] diff --git a/backend/crates/station/src/lib.rs b/backend/crates/station/src/lib.rs index 46ea1e5e1..0b7e25850 100644 --- a/backend/crates/station/src/lib.rs +++ b/backend/crates/station/src/lib.rs @@ -7,6 +7,7 @@ //! - [`event`]: the communication between the modules (see //! `src/event/README.md`). //! - [`http`]: the HTTP API (ADJ catalogs and the WebSocket upgrade). +//! - [`logging`]: recording configuration, sessions, and event consumption. //! - [`payload`]: the messages that travel over the WebSocket. //! - [`pipeline`]: turns what `event` routes into what the front shows (see //! `src/pipeline/README.md`). @@ -14,7 +15,8 @@ pub mod event; pub mod http; +pub mod logging; pub mod payload; pub mod pipeline; mod vehicle; -pub mod websocket; +pub mod websocket; \ No newline at end of file diff --git a/backend/crates/station/src/logging.rs b/backend/crates/station/src/logging.rs new file mode 100644 index 000000000..d37b94180 --- /dev/null +++ b/backend/crates/station/src/logging.rs @@ -0,0 +1,93 @@ +//! Backend recording policy, built on `software_core::logger`. +//! +//! Configuration, session metadata, CSV recording, event consumption and the +//! dedicated writer are implemented. Frontend and startup integration remain +//! the application's responsibility. +//! File writing stays in `software_core::logger`; this module decides what +//! to record, where it belongs and when to flush it. +//! The full specification and pending decisions are in `logging/README.md`. +//! +//! Lifecycle: +//! - At backend startup, create a `YYYY-MM-DDTHH-MM-SS` directory and its +//! `others/` directory for the ADJ validator output, settings and JSONL trace. +//! - `play` prepares a new recording session after discarding inactive backlog. +//! - `stop` drains the ready input prefix up to its reception-time cutoff, +//! flushes buffers and closes session files. +//! - `emergency_stop` performs the same drain on frontend disconnection or +//! backend shutdown. Backend shutdown also finishes the writer and flushes +//! the backend trace; frontend disconnection must allow a later session. +//! +//! The writer owns session state and consumes event's existing bounded channel +//! directly. Independent lifecycle controls remain usable when data is full. +//! Async controls return after their transition completes; observers receive +//! status snapshots through a watch channel. Input stays open between sessions. + +mod catalog; +mod commands; +mod control; +mod data; +mod error; +mod messages; +mod order; +mod output; +mod protections; +mod service; +mod session; +mod settings; +mod status; +mod writer; + +#[cfg(test)] +mod test_support; + +pub use crate::event::ToLogging; +pub use commands::serve_commands; +pub use error::Error; +pub use service::Logging; +pub use session::{BackendRun, MeasurementKey, Session, SessionId, SessionSelection}; +pub use settings::{Config, Settings, TimeUnit}; +pub use status::{Phase, SessionInfo, Status, StatusReceiver, StopReason, StopReport}; +pub use writer::WriterOptions; + +#[cfg(test)] +mod tests { + + use super::{Config, TimeUnit}; + use serde_json::json; + use std::time::Duration; + + type TestResult = Result<(), Box>; + + #[test] + fn config_matches_frontend_units_and_rejects_unknown_units() -> TestResult { + let units = [ + ("ns", TimeUnit::Nanoseconds), + ("us", TimeUnit::Microseconds), + ("ms", TimeUnit::Milliseconds), + ("s", TimeUnit::Seconds), + ]; + for (name, unit) in units { + let config: Config = toml::from_str(&format!( + "time_unit = {name:?}\nlogging_path = \"recordings\"" + ))?; + assert_eq!(config.time_unit, unit); + assert_eq!(serde_json::to_value(unit)?, json!(name)); + } + assert!(toml::from_str::("time_unit = \"minutes\"").is_err()); + assert_eq!(toml::from_str::("")?, Config::default()); + Ok(()) + } + + #[test] + fn integer_conversion_truncates_fractions_without_overflow() { + let elapsed = Duration::new(2, 35_123_456); + assert_eq!(TimeUnit::Seconds.convert(elapsed), 2); + assert_eq!(TimeUnit::Milliseconds.convert(elapsed), 2035); + assert_eq!(TimeUnit::Microseconds.convert(elapsed), 2_035_123); + assert_eq!(TimeUnit::Nanoseconds.convert(elapsed), 2_035_123_456); + assert_eq!( + TimeUnit::Nanoseconds.convert(Duration::MAX), + Duration::MAX.as_nanos() + ); + } +} diff --git a/backend/crates/station/src/logging/README.md b/backend/crates/station/src/logging/README.md new file mode 100644 index 000000000..c1b895a03 --- /dev/null +++ b/backend/crates/station/src/logging/README.md @@ -0,0 +1,664 @@ +# Station Logging + +This module manages backend logging sessions: what is recorded, when a session +starts and ends, how its files are organized, and when buffers are flushed. +Write operations use +[software_core::logger](../../../core/src/logger/README.md). + +The agreed WebSocket wiring and remaining integration work are collected in +[WEBSOCKET_INTEGRATION.md](WEBSOCKET_INTEGRATION.md). + +## Current Status + +The module uses the native `event` and `core::net` types now present in this +checkout. Application startup and frontend integration remain pending. + +The input contract is `tokio::sync::mpsc::Receiver`. The +application passes the `Arc` and `Arc` that `net` and +`event` already share to `Logging`. +The CSV writers consume decoded `model` packets and borrow their metadata from +these shared definitions; callers no longer assemble `DataRecord`, +`ProtectionRecord`, `MessageRecord` or `OrderRecord` DTOs. + +Production code and logging tests compile against those modules directly. +Tests build native ADJ definitions and send decoded packets through the real +`ToLogging` channel; no duplicate event contracts or temporary stubs are used. + +Session preparation and the buffer lifecycle are retained. The writer now +consumes event's existing bounded channel directly, with no second data queue +or forwarding task. The application's channel for `play`, `stop` and +`emergency_stop` is still to be defined. Startup integration, trace setup and +the validator remain pending. + +### Input and Shared ADJ + +`event` creates the inter-module queue and passes its receiver to logging: + +```text +event -> mpsc -> writer thread -> logger -> CSV + ^ + ADJ / Index +``` + +`service.rs` is a small lifecycle facade. The writer owns session state and all +CSV handles. A separate internal channel carries lifecycle requests, so controls +do not need a free slot in the data channel. `status.rs` exposes snapshots and +notifications through a Tokio watch channel. There is no manual `record` or +capture API: the writer uses the reception timestamp carried by each event. +The application's future control-channel contract remains separate from these +internal controls. + +`ToLogging` has these variants in the reviewed branch: + +- `Received(Arc)`: carries `board: BoardId`, `at: SystemTime` + and a connection event or a decoded `Packet`. +- `OrderSent { at, board, order }`: confirms that an order was written to TCP. + Logging uses `at` for both elapsed and calendar time and stores the packet + with its ADJ name in a CSV column and its resolved parameters as a JSON array. + +`Catalog` keeps the supplied ADJ and protocol index shared. It builds a small +measurement locator once, using `(BoardId, AdjId)` as keys. It resolves: + +- Board names from `PodData`. +- Positional data values through the packet's ADJ measurement definitions. +- Measurement aliases for CSV filenames, while filters and file maps use IDs. +- Protection severity, kind, thresholds and associated measurement from ADJ. +- Message severity through the supplied `protocol::Index`; message origin and + text are borrowed directly from `MessagePacket`. + +The supplied ADJ and Index must describe the same checkout used by networking. +Unknown IDs, board/packet mismatches and invalid data value counts are rejected +before writing CSV rows. Connection notifications are consumed without a CSV +row; they do not define a session-control protocol. + +### Available Internal API + +`Config` represents `[logging]`, defaulting to `time_unit = "us"` and +`logging_path = "."`. Supported units are `ns`, `us`, `ms` and `s`. + +`BackendRun::new(config, adj_commit_hash)` creates the run directory and writes +`others/logger_settings.json`. `new_at` accepts an earlier startup timestamp. +Dates use `Europe/Madrid`, including daylight-saving rules. A colliding backend +run directory is an error; a colliding session directory is replaced. + +`Logging::new(run, pod_data, index, receiver, notices, options)` starts the +writer thread and moves event's receiver into it. `notices` is a clone of +event's ② sender (`Channels::notices`), used to report write errors. +Share the service through `Arc`. + +The writer keeps consuming events while inactive, so stopping a session does +not close event's receiver. Input channel closure flushes the active session +and ends the worker. `shutdown()` also closes input and joins the worker. + +`SessionSelection` contains `MeasurementKey { board: BoardId, measurement_id: +AdjId }`, connected board IDs, and the original selection JSON. Its control +payload is pending. Selection validation resolves names and aliases through +ADJ before any existing session directory is replaced. + +The existing internal methods remain available: `play`, `stop`, +`emergency_stop`, `shutdown`, `status` and `subscribe`. They have not been +connected to a new frontend control channel. + +### Example of the Data-Channel Wiring + +This example does not start a session: session control will be specified later. +The consumer can already run and drain notifications while inactive. + +```rust +use std::sync::Arc; +use software_core::{model::PodData, protocol::Index}; +use station::{ + event::{Notice, ToLogging}, + logging::{BackendRun, Error, Logging, WriterOptions}, +}; +use tokio::sync::mpsc; + +fn start_logging_consumer( + run: BackendRun, + pod_data: Arc, + index: Arc, + receiver: mpsc::Receiver, + notices: mpsc::Sender, +) -> Result, Error> { + Ok(Arc::new(Logging::new( + run, pod_data, index, receiver, notices, WriterOptions::default(), + )?)) +} +``` + +### Contract Follow-ups + +These are deliberately not filled in with reconstructed or guessed data: + +- **Controls:** the session-control channel and multi-frontend disconnect rule + remain pending. + +## Module Diagnostics + +Logging emits structured `tracing` events at three levels: + +| Level | Events | +| --- | --- | +| `INFO` | Writer ready, session started after opening files, session stopped after draining and attempting every file close, and service closed. | +| `WARN` | Rejected configuration or selection, discarded invalid input, and a write-error notice that could not be queued on ②. | +| `ERROR` | Writer startup/runtime failure, session creation failure, file write/flush/close failure, exhausted session IDs, or unexpected writer exit. | + +Events include session IDs, directories, stop reasons and full error chains +where applicable. Identical +file failures are reported once per session; the final stop event summarizes +the reason and error count without repeating their causes. A closed service +event includes whether the retained status contains an error; closure alone +does not imply that recording succeeded. + +Repeated play/stop calls with no state change do not emit lifecycle events. +Successful measurements, orders, protections and messages do not each emit a +diagnostic event, and periodic successful flushes remain silent. The module +does not emit `DEBUG` or `TRACE` events. + +The application owns the subscriber and its filter. For example, +`RUST_LOG=station::logging=info` enables these module events with an +`EnvFilter` subscriber. The module neither installs a subscriber nor writes +the pending `others/` JSONL trace itself. + +## File Structure for a Backend Run + +Each backend startup creates a directory named after its start date and time, +using the `YYYY-MM-DDTHH-MM-SS` format. It contains `others/` and the directories +for the logging sessions started during that run. + +Each session is created when **Start logger** is pressed in the frontend. Its +directory uses the same format, but with the session's start date and time. + +```text +/logger/ +└── 2026-11-27T15-30-00/ # Backend startup + ├── others/ + │ ├── .txt + │ ├── logger_settings.json + │ └── .jsonl + ├── 2026-11-27T15-31-05/ # First session + │ ├── logger_settings.json + │ ├── data/ + │ │ └── / + │ │ ├── .csv + │ │ └── .csv + │ ├── protections/ + │ │ └── .csv + │ ├── order/ + │ │ └── order.csv + │ └── messages/ + │ └── messages.csv + └── 2026-11-27T15-35-20/ # Another session in the same run + └── ... +``` + +Names inside `<...>` are placeholders, not final filenames. The exact names +of the validator TXT file and the trace JSONL file are still pending. + +Relative and empty `logging_path` values are resolved against the backend's +working directory, matching the old backend's behavior. + +If a new session has the same name as an existing one, the agreed behavior is +to overwrite it. Replacement must avoid mixing old files with the new session's +selection. A collision can occur when starting, stopping, and starting again +within the same second. Another `play()` while a session is active returns +the existing session unchanged, preventing a double click from truncating it. + +## Metadata: logger_settings.json + +The name uses an **underscore**, both in `others/` and in each session, to +match the file expected by the frontend viewer. + +### Backend Run Settings + +`others/logger_settings.json` initially contains: + +```json +{ + "adj_commit_hash": "", + "time_unit": "us", + "date": "2026-11-27T15-30-00" +} +``` + +| Field | Meaning | +| --- | --- | +| `adj_commit_hash` | Commit hash of the ADJ used by the backend. | +| `time_unit` | Unit used for the instants recorded in the CSV files. | +| `date` | Startup date and time, exactly matching the parent directory name. | + +This structure may be extended in the future. + +### Session Settings + +Each session keeps its own copy of the settings, with these changes: + +- `date` becomes that session's start date and time, matching its directory + name. +- `selected_variables` is added to represent the variables selected for + recording during that session. Its exact JSON schema is still pending. + +The selection may change between sessions. Only selected variables are +recorded, and only files corresponding to that selection are created; +no CSV files are created for unselected measurements. + +Metadata is written using `logger::write_json`. + +## Record Timing + +### instant + +`instant` is an **integer** representing the elapsed time since the logging +session started. It is neither a Unix timestamp nor the time since backend +startup. + +The counter starts at zero when each session begins. This does not require +the first row to contain zero: if the first measurement arrives 35 ms after +startup, its `instant` will be `35` with `time_unit = "ms"`, or `35000` with +`"us"`. + +The session stores its startup time as `SystemTime`. The writer subtracts that +origin from the upstream `Notification::at` or `OrderSent::at`, then converts +the duration to `time_unit`. Queue delays are not added to `instant`. An event +whose `at` precedes the session origin is discarded instead of receiving a +fabricated zero. + +Using the machine's calendar clock is intentional: changing that clock during +a session may make elapsed instants jump. No additional monotonic clock or +timestamp field is required by this contract. The board's `ShortTimestamp` +is separate from the backend reception time used for `instant`. + +The units verified in the frontend are: + +| time_unit | Unit | +| --- | --- | +| `ns` | Nanoseconds | +| `us` | Microseconds | +| `ms` | Milliseconds | +| `s` | Seconds | + +### Order Timestamp + +In addition to `instant`, orders include a calendar date and time in the +`YYYY-MM-DDTHH-MM-SS` format, followed by the `Europe/Madrid` UTC offset +applicable to that date: + +```text +2026-07-15T15-30-05+02:00 # CEST, summer +2026-11-27T15-30-05+01:00 # CET, winter +``` + +The offset is not always `+02:00`. This additional information has been agreed +for the orders' `timestamp` column; directory names retain the +`YYYY-MM-DDTHH-MM-SS` format. + +## CSV Format + +**No CSV file has a header.** The column lists in this document describe the +field order and must not be written as the first row. + +Text fields, including order JSON and message text, must use the CSV escaping +provided by `logger::Row::text`. This correctly preserves commas, quotation +marks, and line breaks within a field. Rows must not be built by manually +joining fields with commas. + +### Measurements: data/ + +A directory is created for each board with a selected measurement, using its +name. It contains one CSV per selected measurement, named after its ADJ +`alias` (selection and lookups use the numeric ID; only the filename uses the +alias): + +```text +data//.csv +``` + +Columns, in order: + +```text +instant,from,to,value +``` + +| Field | Content | +| --- | --- | +| `instant` | Time since the session started, in `time_unit`. | +| `from` | Name of the source board. | +| `to` | `backend` or the name of another destination board. | +| `value` | Measurement value. | + +### Orders: order/order.csv + +There is a single `order.csv` file inside `order/`. + +Columns, in order: + +```text +instant,from,to,id,name,parameters,timestamp +``` + +| Field | Content | +| --- | --- | +| `instant` | Time since the session started, in `time_unit`. | +| `from` | `backend`. | +| `to` | ADJ board name, or `all` when `OrderSent.board` is `None`. | +| `id` | Order ID. | +| `name` | Order name from the ADJ. | +| `parameters` | Compact JSON array of objects containing only measurement `id`, `alias` and confirmed `value`, in ADJ parameter order. | +| `timestamp` | TCP confirmation date and time from `OrderSent.at`, using the format and offset described above. | + +Orders are recorded from `event::ToLogging::OrderSent` while a session is +active. Its `at` supplies both the elapsed `instant` and calendar `timestamp`. +Only confirmed sends are recorded; incoming network `Packet::Order` events +produce no order row. Logger controls arrive separately from WebSocket. + +The `parameters` cell is directly a JSON array, for example: + +```json +[{"id":3032,"alias":"duty_command","value":75}] +``` + +Names and parameter definitions are resolved with `Index::packet(order.id)`; +parameter values are paired positionally with `PacketType::Order` fields. +The order ID and name appear only in their CSV columns. Each parameter's `id` +is its measurement ID, not the order ID. The array has no enclosing object, +repeated order metadata or `type` field. Orders without parameters use `[]`. + +This seven-column layout replaces the previous six-column layout with a +`payload` object. Readers must handle the new `name` and `parameters` columns; +existing recordings are not rewritten. + +Unknown orders, wrong packet kinds, mismatched destinations, incorrect +parameter counts and non-finite numbers (NaN, ±infinity, which JSON cannot +represent) are discarded with a warning before writing; the session keeps +recording. The reserved +broadcast fault (ID 0, destination `all`) requires no Index entry and is recorded +with `name` equal to `Fault` and `parameters` equal to `[]`; it must have no values. + +Values retain their packet order and use JSON numbers, booleans and strings +for model `Number`, `Bool` and `Enum` values. JSON escapes embedded newlines; +`logger::Row::text` then escapes the JSON array and the order name for CSV. +There is no separate JSONL file or extra newline within the JSON array cell. + +### Protections: protections/ + +One file is created per connected board: + +```text +protections/.csv +``` + +Columns, in order: + +```text +instant,from,to,protection_id,severity,protection_type,threshold_1,threshold_2,measurement_id,value,time +``` + +| Field | Content | +| --- | --- | +| `instant` | Time since the session started, in `time_unit`. | +| `from` | Event source. | +| `to` | Event destination. | +| `protection_id` | ID of the triggered protection. | +| `severity` | Severity level. | +| `protection_type` | Protection type. | +| `threshold_1` | First trigger value or threshold of the protection. | +| `threshold_2` | Second threshold for `range` protections; empty for other types. | +| `measurement_id` | ID of the associated measurement. | +| `value` | Measurement value that triggered the protection. | +| `time` | The resolved ADJ definition's `Protection.time`, formatted as duration and unit; `0` when the duration is zero. | + +Both threshold fields are always present, even when the second one is empty. +The thresholds and the value that triggered the event are separate fields. + +The time-accumulation field is a property of the protection definition resolved +from the received compound ID. Logging records it without measuring an elapsed +accumulation or changing the packet protocol. It is independent of the session +clock, `time_unit` and the packet's time-of-day timestamp. A duration can +accompany any protection kind, such as `above` or `range`. + +Nonzero durations follow the HTTP catalog's formatting rule without losing +precision: use `ms` for multiples of a millisecond, otherwise `us` for multiples +of a microsecond, otherwise `ns`. For example, 500 ms becomes `500ms`, one second +becomes `1000ms`, and 1500 microseconds becomes `1500us`. Zero is written as `0`. + +### Messages: messages/messages.csv + +There is a single `messages.csv` file inside `messages/`. + +The agreed columns, in order, are: + +```text +instant,from,to,board,source,severity,message +``` + +| Field | Content | +| --- | --- | +| `instant` | Time since the session started, in `time_unit`. | +| `from` | Event source. | +| `to` | Event destination. | +| `board` | Name of the board that emitted the message. | +| `source` | The `origin` field of the message received over TCP. | +| `severity` | Message severity. | +| `message` | Text of the received message. | + +File and line are kept together in `source` when the message contains that +information. The received `origin` is preserved without moving the line to +another column or reconstructing its format. + +## Frontend Control and Shutdown + +The internal functions are `play()`, `stop()`, and `emergency_stop()`. +`serve_commands` connects them to the frontend: it consumes websocket's +`LoggerCommand` queue and answers on `logger/response` through the broker. + +- `logger/variables` replaces the selection for the next start, as + `"/"` entries (what testing-view sends). A session + that is already recording keeps its own. Unknown entries are skipped with a + warning. +- Until a selection arrives, a start records every data measurement of every + board: competition-view only sends `logger/enable`. An empty list records no + measurement files. +- Every `logger/enable` is answered with the actual recording state, even + when nothing changes, because the frontend waits for the answer. A session + that ends on its own is answered with `false` too. +- Protection files are prepared for every board, whatever the selection. + +The task holds a broker client, so it ends when the writer closes; the broker +can then stop. + +### play() + +Prepares a new session's directory, settings, variable selection, and files. +Discards the finite inactive backlog, establishes the time origin and starts +writing records once the session is ready. Events with older reception times +are ignored even if they arrive later. + +The states are: + +```text +Inactive -> Starting -> Recording -> Stopping -> Inactive +``` + +### stop() + +Stops the session in this order: + +1. Captures the stop request's reception-time cutoff. +2. Processes the finite number of ready events observed when handling the + control, excluding events timestamped after that cutoff. +3. Flushes the buffers and closes the session files. +4. Returns the stop result to the frontend. + +Pending events from one session must not be written into another. +The `others/` directory belongs to the backend run and is preserved between +sessions. + +The writer serializes control calls and gives them priority over data. +Cancelling a control future does not cancel a queued transition or its drain. +Controls use their own channel and remain usable when data capacity is +exhausted. The stop drain has a fixed size, so producers cannot extend it +indefinitely. The input receiver stays open and resumes consuming without +recording. Sends that have not yet queued a ready event at the stop boundary +are outside that drain. + +### emergency_stop() + +Used when the backend shuts down and also when the frontend closes or +disconnects. It reuses the session stop logic and waits for its buffers to be +flushed and its files to be closed before completing the controlled shutdown. + +If the backend remains running after the frontend disconnects, starting +another session later must be possible. The trace belongs to the backend and +may remain active; its final flush takes place during backend shutdown. + +Backend shutdown should finish with `shutdown().await` to join the writer. +The application must separately flush its trace when that integration exists. +`Drop` provides a synchronous fallback drain and join, while explicit controls +are required to receive write errors. + +When multiple frontends are connected, it remains undecided whether a +session stops when any frontend disconnects or only when the frontend that +started it disconnects. + +## Efficient Writing + +The service uses a dedicated thread for synchronous +`software_core::logger` writes, separate from asynchronous network tasks: + +```text +Event reception + | + v +Attach reception timestamp + | + v +Event's existing bounded mpsc channel + | + v +Writer thread and format components + | + v +software_core::logger + | + v +Buffered files +``` + +The writer owns the files. It keeps them open throughout the session +and reuses the buffers already provided by `logger`, avoiding opening, writing, +and closing a file for every record. + +Buffers are flushed periodically and when a per-file byte threshold is reached, +using `bytes_since_flush()`. After each row, only the affected file is checked; +periodic flushing visits dirty files. A private Tokio runtime on the writer +thread waits for events, controls and flush deadlines. When inactive, it drains +events without writing them. Stopping explicitly closes every file and reports +errors. + +`WriterOptions` configures these initial defaults: + +| Option | Default | +| --- | --- | +| `flush_interval` | 250 ms | +| `flush_bytes` | 64 KiB per file | + +Both limits must be positive. Data capacity belongs to event's +`EventConfig::logging_queue`; logging does not configure another queue. +Control commands do not consume data capacity. CSV row buffers are reused. +Unsigned integer fields preserve the +session clock's `u128` values without narrowing or converting to floating point. + +### A Full Input Queue + +A full data channel is ordinary backpressure: `event` waits for a free slot, +and the writer keeps recording. The session is not stopped and nothing is +dropped; the telemetry copy that `event` drops when the frontend falls behind +is pipeline's, never logging's. + +### Write Errors + +A write or flush error stops recording. The writer attempts the ready +input prefix and closes every file, including healthy files after another +file fails. The stop report contains the errors and uses `StopReason::WriteError`; +`stop`, `emergency_stop` and `shutdown` return an error instead of reporting a +successful drain. Failed files cannot be assumed to contain all accepted data. + +The operator is told: the writer sends a `Warning` notice ("recording stopped, +its files may be incomplete: ") on `event`'s notices queue (②), +which the frontend shows as a message from the backend. The backend keeps +running and a new session can be started. The notice is sent with `try_send`, +never awaited: `event`'s router may be waiting for room in logging's input at +that moment, and waiting on ② would then block both. If ② is full or closed, +the writer traces a warning; the error itself is already traced. + +## Files in others/ + +`others/` contains three files for the entire backend run: + +| File | Content | Design status | +| --- | --- | --- | +| Validator TXT | Output of `adj-validator`. | Name and method of obtaining the output pending. | +| `logger_settings.json` | Backend startup metadata. | Initial fields defined. | +| Trace JSONL | Backend trace, with one JSON object per line. | Name, levels/filters, and integration pending. | + +The old backend was investigated: it runs the Python script included in the +ADJ repository with `--no-color`, captures stdout and stderr together, attempts +to save the output, and then checks the process result. That implementation +serves as a reference, but **running the validator and obtaining its output +were left undecided**. This flow has not been implemented in the new backend. + +## Responsibilities of Module Files + +| File | Responsibility | +| --- | --- | +| `../logging.rs` | Public API exports. | +| `catalog.rs` | Shared ADJ/Index lookups and measurement locators. | +| `commands.rs` | Frontend logger commands (`logger/variables`, `logger/enable`) applied to sessions, answered on `logger/response`. | +| `service.rs` | Small public facade for construction, lifecycle controls and status access. | +| `control.rs` | Private writer lifecycle requests and acknowledgements. | +| `status.rs` | Public lifecycle snapshots, stop reports and notifications. | +| `session.rs` | Selection, identity, paths and clocks of each session; writer stamps are private. | +| `settings.rs` | Backend run and session metadata. | +| `writer.rs` | Event consumer, session state, CSV ownership, flushing, and shutdown. | +| `output.rs` | Shared value formatting and flush/close error handling. | +| `data.rs` | Measurement files by board and variable. | +| `protections.rs` | Protection files by board. | +| `order.rs` | Order recording in a single CSV. | +| `messages.rs` | Message recording in a single CSV. | +| `error.rs` | Configuration, session, control, and write errors. | + +`station::logging` knows about the ADJ, boards, selections, and sessions. +`software_core::logger` provides CSV, text, and JSON writing, field escaping, +buffers, and explicit flush and close operations. + +## Pending Decisions + +- Names of the validator TXT file and trace JSONL file. +- Running `adj-validator` and obtaining its output. +- Trace levels and filters, and their connection to the JSONL file. +- Exact schema of `selected_variables` in JSON and the session-control channel. +- Disconnection stop rule when multiple frontends are connected. +- Frontend notification format and integration through the application modules. +- Wiring `WriterOptions` into application configuration if these defaults need UI controls. + +## Verification + +Run the logging tests with `cargo test -p station --lib logging --offline`, or +the whole station suite with `cargo test -p station --offline`. The HTTP +WebSocket tests in the full suite need permission to open local sockets. + +`test_support.rs` supplies shared native ADJ, Index and packet fixtures. +Service tests cover variable selection, restarts, old reception timestamps, +buffer flushing, concurrent producers, write failures, cancelled control +replies, fallback drop and input closure. An integration scenario connects +`event::channels` and the real event router to `Logging`, stops and restarts +sessions, then checks the persisted CSVs and orderly shutdown. + +Writer tests check headerless CSVs, escaping, protection metadata and duration +precision, event-supplied reception times, serialized OrderPacket values and timezone offsets, +large integer instants and failed closes. +Order tests also cover event routing, confirmation timestamps, broadcast +destinations and rejected non-finite numbers. Connecting the real logging +service to application startup remains pending. + +`rustfmt` and `git diff --check` validate formatting and whitespace. diff --git a/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md b/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md new file mode 100644 index 000000000..7aadaffb8 --- /dev/null +++ b/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md @@ -0,0 +1,268 @@ +# Logging Integration with WebSocket + +This document collects the agreed behavior and remaining work for integrating +both branches. It describes the planned adaptation; creating this file does not +connect the modules. File organization and CSV formats are documented in the +[README](README.md). + +Reviewed references: `backend/websocket` and `origin/backend/websocket`, both at +commit `152ad49d`, on December 3, 2026. Check the types again if the branch changes +before the merge. + +## 1. Agreed Behavior + +- Logging starts once with the backend and keeps running throughout its lifetime. +- The service consumes events even when no session is recording. +- A session starts when the frontend enables the logger, using the variable + selection for that session. +- Stopping a session drains its buffers and closes its files. The service remains + available to start another session. +- Variables may change between sessions. A selection received while recording is + saved for the next session. +- Backend shutdown must flush buffers and wait for the writer to finish. + +**Service running** and **session recording** are separate states. +`logger/response = false` means no session is recording; the logging service may +still be running and consuming events. + +## 2. Topics and Channels + +| Topic | Direction | Payload | Meaning | +| --- | --- | --- | --- | +| `logger/enable` | Frontend → backend | `bool` | Request a session start or stop. | +| `logger/variables` | Frontend → backend | `Vec` | Select variables for the next session. | +| `logger/response` | Backend → frontend | `bool` | Report the actual recording state. | + +WebSocket combines both incoming requests into one bounded channel: + +```rust +enum LoggerCommand { + Enable(bool), + Variables(Vec), +} +``` + +`Commands.logger` holds an `Option>`, and +`logging::serve_commands` consumes the corresponding receiver. `LoggerCommand`, +the `Commands` fields and `OrderForwarder::new` are public, so the backend's +startup can build the `Commands`. + +Responses are published through `BrokerClient::publish_logger(bool)`. This uses +the broker's shared input and its logger `watch` state; it is not another dedicated +command `mpsc` between logging and WebSocket. The frontend subscribes to +`logger/response` to receive the initial state and subsequent updates. + +The planned connections are: + +```text +event ── bounded mpsc ───────────────────▶ writer +WebSocket ── bounded mpsc ────────────▶ writer +backend ── independent stop/shutdown signal ────────▶ writer +writer ── watch ──▶ integration ──▶ broker ──▶ WebSocket/frontend +writer ── notices ② (try_send, write errors) ──▶ event ──▶ pipeline ──▶ frontend +``` + +All recorded content, including orders, arrives from `event`. WebSocket supplies +the logger commands. + +## 3. Changes to the Current Code + +| Element | Current implementation | Planned change | +| --- | --- | --- | +| `writer.input` | `mpsc::Receiver` | Keep the channel from `event`. | +| `writer.controls` | Internal `mpsc::UnboundedReceiver` | Replace it with the bounded `LoggerCommand` receiver. | +| `writer.updates` | `watch::Sender` | Keep the complete state for observers. | +| `Control::{Play, Stop, Shutdown}` | Internal requests with `oneshot` replies | Remove or adapt them when changing the control input; avoid a second queue forwarding the same commands. | +| `Logging::{play, stop, emergency_stop, shutdown}` | API built on that internal channel | Review its implementation and callers alongside the channel change. | +| Startup in `main` | Uses `stand_in_logging` | Construct the real service and pass it the receivers. | + +The logic that prepares, stops and closes sessions remains necessary. Changing +the channel does not mean removing those operations. + +`LoggerCommand` includes neither `Shutdown` nor an emergency-stop request. +Those cases need an independent signal that remains usable when the frontend +queue is full and during synchronous `Drop`. The specific mechanism remains to +be chosen; do not introduce another unbounded channel by default. + +## 4. Backend Startup + +- [ ] Pass the `Arc` and `Arc` that `net` and `event` already + share, so logging resolves packets exactly as networking decoded them. +- [ ] Supply the ADJ hash and the `logging_path`/`time_unit` configuration. +- [ ] Create `BackendRun` and `others/logger_settings.json` at startup. To reflect + a startup time captured before loading the ADJ, capture that timestamp and use + `BackendRun::new_at`. +- [ ] Create a single bounded `LoggerCommand` queue and connect both ends. + Define its capacity in the startup configuration. +- [ ] Start the writer with the event receiver, command receiver, shutdown signal + and observable state, without opening a recording session yet. +- [ ] Start the broker and state publication with `false`. +- [ ] Replace the stand-in without introducing two consumers for the same receiver. + +## 5. Variable Selection and Session Start + +In `testing-view`, `startLogging()` sends `logger/variables` first, followed by +`logger/enable = true`. These are separate messages, not an atomic request. +Both enter the same `mpsc` if WebSocket accepts the sends. + +In `competition-view`, only `logger/enable = true` is sent. The frontend expects +all variables to be recorded when there is no explicit selection. + +When receiving `Variables(...)`: + +- Resolve the board and measurement through the ADJ and validate the selection. +- Prepare the `MeasurementKey { board: BoardId, measurement_id: AdjId }` entries. +- Retain the selection for the next start and its representation in + `logger_settings.json`. +- Keep an already recording session's selection unchanged. + +The frontend builds entries as `${boardName}/${m.id}`. Check the catalog it +actually consumes: the backend HTTP catalog distinguishes numeric `id` from +textual `alias`. Do not assume `"LCU/speed"` and `"LCU/3000"` are equivalent +without agreeing on and testing their resolution. + +When receiving `Enable(true)`: + +1. Take a snapshot of the validated selection for that session. +2. Discard the inactive backlog and establish the session's time origin. +3. Prepare directories, metadata and files for the selected variables. +4. Publish `Recording` and respond with `true` after successful preparation. + +A repeated start while recording retains the existing session. A new start in +the same second as a previously stopped session replaces its directory, as +agreed, after the previous files have been closed. + +## 6. Session Stop and Shutdown + +When receiving `Enable(false)`, drain the session's pending input prefix, flush +buffers, close all session files and publish the final state. The stop must +finish even if events keep arriving. + +Keep the event receiver open after a normal stop, session emergency stop or +write failure. `event` treats losing the logging consumer as fatal. +While the service remains alive, it must consume events without recording them +when inactive. + +Coordinate backend shutdown in this order: + +1. Stop producers and allow `event` to deliver pending data. +2. Let logging process its input and close the session files. +3. Wait for the writer and collect write or close errors. +4. Keep the broker available for final state publication while useful; then close + the adapters and broker. + +The independent signal allows shutdown requests even when the command queue is +full. Using it must not close the event input prematurely while `event` still +needs to deliver data. `Drop` retains a fallback exit path; explicit shutdown +must allow errors to be collected. + +## 7. Responses and Errors + +`updates` holds `Status`: phase, session, last stop and last error. +The integration observes that state and publishes the `logger/response` boolean. +The writer must keep draining data without waiting for frontend network I/O. + +| Situation | Expected response | +| --- | --- | +| Service started without a session | `false`. | +| Session preparation completed | `true`. | +| Start rejected while inactive | `false`, retaining the error. | +| Stop completed | `false`. | +| Session stopped by a write error | `false`, retaining the reason. | + +Do not confirm a start before opening the files or a stop before attempting to +drain and close the buffers. During stopping, retain the previous state until +completion. Repeated `Enable` requests need a response even if the state does +not change, because the frontend waits for confirmation. + +`logger/response` contains only a boolean: it cannot explain an error or confirm +which variables were accepted. A session stopped by a write error is already +explained by a `Warning` notice on ②. Define how the remaining details (a +rejected start or selection) are reported through the same notices. + +The `watch` retains the latest state and may coalesce intermediate changes. +If every incident must be reported, do not rely solely on observing boolean +transitions. Also publish the current state when creating the observer to avoid +missing a startup change. + +## 8. Cases Requiring an Explicit Decision + +| Case | What needs to be resolved | +| --- | --- | +| `Variables` has never been received | Support competition-view's behavior: all variables; specify which boards this includes. | +| `Variables([])` | Decide whether this means no variables or all variables. Distinguish it from never receiving a selection. | +| Unknown or malformed variable | Define the response and avoid silently starting with an older selection. | +| Switching frontend between sessions | Prevent competition-view from unintentionally inheriting testing-view's filter. The current command does not identify its sender. | +| Two frontends send commands | Define the global scope of the selection and session; the shared channel does not guarantee that one client's `Variables` and `Enable` stay together. | +| Command queue fills up | WebSocket uses `try_send`: it logs rejection and keeps the socket open. Agree on reporting and preventing a start with an outdated selection if only one of the two messages is accepted. | +| Command channel closes | Decide whether to stop just the session or the service. Do not automatically equate this with a frontend disconnection. | +| Stop timestamp | `LoggerCommand` carries no timestamp. Define whether the cutoff is taken at WebSocket reception or when logging processes the command. | + +### Frontend Disconnection + +The WebSocket branch returns `FrontendDisconnected` when the last frontend is +lost, according to its heartbeat and reconnection policy. With the documented +three-second timeout, the last client's heartbeat expiration ends supervision +immediately; other closures allow a reconnection window. The timeout is +configurable. + +Disconnection does not arrive as a `LoggerCommand`. The supervisor must connect +it to emergency stop and, when appropriate, backend shutdown. Confirm whether +logging stops when any frontend closes or when the last one is lost after that +window; the reviewed branch uses the latter policy to detect frontend loss. + +If a session is tied to a specific client, the current contract needs additional +identity information. + +## 9. Settled Contracts and Independent Pending Work + +Orders arrive from `event` as `ToLogging::OrderSent`. The CSV columns are +`instant,from,to,id,name,parameters,timestamp`. Its `at` supplies `instant` and +`timestamp`. `Index::packet(order.id)` supplies the order `name` and parameter +metadata. `parameters` is directly a JSON array: +`[{"id":4000,"alias":"enabled_command","value":true}]`. Each object has only +measurement `id`, `alias` and confirmed `value`; order ID/name are not repeated +inside it. An order without parameters uses `[]`. `from` is `backend`; `to` is +the board's name or `all` for the reserved fault broadcast, whose name is `Fault`. + +This is already implemented in logging and tested with the event router. +Do not require the original frontend JSON or frontend reception time again. + +Protection CSVs record the resolved ADJ definition's `Protection.time`: `0` +for a zero duration, otherwise a duration with units such as `500ms`. This is +a property of the protection; logging does not calculate an accumulation or +require a new field in `ProtectionPacket`. Nonzero durations follow the HTTP +catalog's precision-preserving `ms`/`us`/`ns` formatting rule. + +Elapsed `instant` uses the event's `Notification.at` or `OrderSent.at` minus +the session's startup time, converted to `time_unit`. Both use `SystemTime`. +Calendar-clock adjustments can affect the result; this is an accepted +limitation. Unused monotonic session helpers have been removed, and the +WebSocket merge does not need to add monotonic timestamps to `event`. + +The JSONL trace and validator output in `others/` remain pending independently +of the WebSocket merge. + +## 10. Implementation Checks + +- [ ] Startup without a session: service alive, state `false`, no session CSVs. +- [ ] `Variables` followed by `Enable(true)`: correct selection and metadata. +- [ ] Start without a selection, with an empty selection and with an invalid + selection: agreed behavior. +- [ ] Selection changes while recording: affect only the next session. +- [ ] Repeated starts and stops: no accidental truncation, and a response is sent. +- [ ] Stop with pending data and active producers: finite drain and flush. +- [ ] New session after stop: no old events or files for unselected variables. +- [ ] Full command queue: observable rejection and consistent selection. +- [ ] Write failure: session stopped, state `false`, reason retained and event + input still available. +- [ ] Disconnection, reconnection and multiple frontends: agreed policy. +- [ ] Backend shutdown with a full command queue: independent signal, pending data + processed and writer finished. +- [ ] Slow or closed broker: the writer does not wait for the frontend. +- [ ] Confirmed orders: name column, parameters array in one cell, and timing from `OrderSent.at`. +- [ ] Update tests, README examples and callers of the previous API. + +Integration is complete when the backend uses the real service and these paths +have been tested together. Having the types in both branches does not replace +connecting them at startup. diff --git a/backend/crates/station/src/logging/catalog.rs b/backend/crates/station/src/logging/catalog.rs new file mode 100644 index 000000000..329cf44b7 --- /dev/null +++ b/backend/crates/station/src/logging/catalog.rs @@ -0,0 +1,234 @@ +//! Read-only ADJ lookups for input validation and CSV writing. +//! +//! Notifications carry board/packet IDs and decoded values. This catalog +//! resolves the labels and definitions needed to validate those notifications +//! and write CSV rows. The supplied `PodData` and protocol Index must describe +//! the same ADJ checkout that networking used to decode the packets. + +use std::{collections::HashMap, sync::Arc}; + +use software_core::{ + model::{ + AdjId, Board, BoardId, Measurement, MessageLevel, OrderPacket, Packet, PacketDef, + PacketType, PodData, Protection, Value, + }, + net::Event, + protocol::Index, +}; + +use crate::event::ToLogging; + +use super::Error; + +/// Keep ADJ labels to a single filename component on supported platforms. +pub(super) fn validate_name(name: &str) -> Result<(), Error> { + if name.is_empty() + || matches!(name, "." | "..") + || name.ends_with(['.', ' ']) + || name + .chars() + .any(|c| c.is_control() || "/\\:*?\"<>|".contains(c)) + { + return Err(Error::InvalidName(name.to_owned())); + } + Ok(()) +} + +/// Keeps the writer's definitions shared with the rest of the application. +/// Returned references borrow existing ADJ/Index entries; no packet metadata +/// needs to be copied into a separate logging record for every event. +#[derive(Debug)] +pub(super) struct Catalog { + /// Vehicle boards and their display/filesystem names, shared with `net` + /// and `event`. + pod_data: Arc, + /// Packet definitions, including the synthesized shared message severities. + index: Arc, + /// (Board ID, measurement ID) -> (data packet ID, position in that packet). + /// Store locators instead of self-references into the shared Index. + measurements: HashMap<(BoardId, AdjId), (AdjId, usize)>, +} + +impl Catalog { + /// Build measurement locators once when the logging service is constructed. + /// Only data measurements are eligible for the selected telemetry files; + /// order parameters and protection definitions are resolved through Index. + pub fn new(pod_data: Arc, index: Arc) -> Self { + let mut measurements = HashMap::new(); + for board in pod_data.boards.values() { + for packet in board.packets.values() { + if let PacketType::Data(fields) = &packet.packet_type { + for (position, measurement) in fields.iter().enumerate() { + // Decoded data values use the same positional ordering + // as this ADJ measurement list. + measurements.insert((board.id, measurement.id), (packet.id, position)); + } + } + } + } + Self { + pod_data, + index, + measurements, + } + } + + /// Resolve a notification's numeric board ID to its ADJ board definition. + pub fn board(&self, id: BoardId) -> Result<&Board, Error> { + self.pod_data.boards.get(&id).ok_or(Error::UnknownBoard(id)) + } + + /// Find a selectable measurement without scanning all boards and packets. + /// The definition includes the textual alias used to name its CSV file. + pub fn measurement(&self, board: BoardId, id: AdjId) -> Result<&Measurement, Error> { + let &(packet, position) = self + .measurements + .get(&(board, id)) + .ok_or(Error::UnknownMeasurement { board, id })?; + // Resolve through the same Index used for incoming data. A missing or + // inconsistent locator is an error before session files are created. + self.data(board, packet)? + .get(position) + .ok_or(Error::UnknownMeasurement { board, id }) + } + + /// Centralize packet existence and ownership checks for all typed lookups. + fn definition(&self, board: BoardId, id: AdjId) -> Result<&PacketType, Error> { + self.board(board)?; + let packet = self.index.packet(id).ok_or(Error::UnknownPacket(id))?; + // Message severities are shared by all boards (reserved BoardId(0)), + // so their synthetic owner must not be compared with the sender board. + // Every other packet must belong to the board named by its notification. + if !matches!(packet.packet_type, PacketType::Message(_)) && packet.board != board { + return Err(Error::PacketBoardMismatch { board, id }); + } + Ok(&packet.packet_type) + } + + /// Return the ordered definitions to zip with a decoded DataPacket's values. + /// A known ID of another packet kind must not be interpreted as telemetry. + pub fn data(&self, board: BoardId, id: AdjId) -> Result<&[Measurement], Error> { + match self.definition(board, id)? { + PacketType::Data(measurements) => Ok(measurements), + _ => Err(Error::UnexpectedPacketType(id)), + } + } + + /// Resolve the watched measurement and the particular protection that fired. + /// The CSV writer uses their static metadata alongside the packet's actual + /// triggered value; the catalog does not recompute the board's decision. + pub fn protection( + &self, + board: BoardId, + id: AdjId, + ) -> Result<(&Measurement, &Protection), Error> { + let PacketType::Protection(measurement) = self.definition(board, id)? else { + return Err(Error::UnexpectedPacketType(id)); + }; + // The wire ID combines the measurement ID with a protection position + // in its high bits. Protection::id stores that position, not the full + // compound ID, so compare against the extracted position. + let protection = measurement + .protections + .iter() + .find(|protection| protection.id.0 == u16::from(id.protection_position())) + .ok_or(Error::UnknownPacket(id))?; + Ok((measurement, protection)) + } + + /// Interpret a message's wire ID through its synthesized Index definition. + /// The notification supplies the real sender board; the ID supplies severity. + pub fn message_level(&self, board: BoardId, id: AdjId) -> Result { + match self.definition(board, id)? { + PacketType::Message(level) => Ok(*level), + _ => Err(Error::UnexpectedPacketType(id)), + } + } + + /// Resolve confirmed orders through the same Index as networking. Only the + /// reserved broadcast fault has no ADJ definition. + pub fn order( + &self, + board: Option, + order: &OrderPacket, + ) -> Result, Error> { + if board.is_none() && order.id == AdjId(0) { + if !order.values.is_empty() { + return Err(Error::MeasurementCount(order.id)); + } + return Ok(None); + } + let definition = self + .index + .packet(order.id) + .ok_or(Error::UnknownPacket(order.id))?; + let PacketType::Order(fields) = &definition.packet_type else { + return Err(Error::UnexpectedPacketType(order.id)); + }; + let board = board.unwrap_or(BoardId(0)); + self.board(board)?; + if definition.board != board { + return Err(Error::PacketBoardMismatch { + board, + id: order.id, + }); + } + if fields.len() != order.values.len() { + return Err(Error::MeasurementCount(order.id)); + } + // JSON has no NaN or infinity, so the parameters cell could not hold + // it. A bad order is discarded; it is not a reason to stop recording. + if order + .values + .iter() + .any(|value| matches!(value, Value::Number(number) if !number.is_finite())) + { + return Err(Error::NonFiniteValue(order.id)); + } + Ok(Some(definition)) + } + + /// Validate a received packet before writing any of its CSV rows. + /// Connection notifications have no CSV row. + /// `true` means the packet is structurally eligible for writing; measurement + /// selection is applied separately by the CSV writer. + pub fn validate(&self, incoming: &ToLogging) -> Result { + let notification = match incoming { + ToLogging::OrderSent { board, order, .. } => { + // Event confirms the packet was sent. Resolve its destination; + // the broadcast fault has no single owner or ADJ packet entry. + if let Some(board) = board { + validate_name(&self.board(*board)?.name)?; + } + self.order(*board, order)?; + return Ok(true); + } + ToLogging::Received(notification) => notification, + }; + // Board labels become directories or filenames, so validate the label + // from the ADJ before it can reach a file writer. + validate_name(&self.board(notification.board)?.name)?; + match ¬ification.event { + Event::Connected | Event::Disconnected => return Ok(false), + Event::Received(Packet::Data(packet)) => { + // Positional values must match the complete schema, even when + // only some measurements are selected. Reject mismatches before + // any rows from this packet can be written. + if self.data(notification.board, packet.id)?.len() != packet.values.len() { + return Err(Error::MeasurementCount(packet.id)); + } + } + Event::Received(Packet::Protection(packet)) => { + // Confirm both the measurement definition and protection slot. + self.protection(notification.board, packet.id)?; + } + Event::Received(Packet::Message(packet)) => { + self.message_level(notification.board, packet.id)?; + } + // Only OrderSent records outgoing orders; network reception is + // not a confirmation that this backend sent an order. + Event::Received(Packet::Order(_)) => return Ok(false), + } + Ok(true) + } +} diff --git a/backend/crates/station/src/logging/commands.rs b/backend/crates/station/src/logging/commands.rs new file mode 100644 index 000000000..d674ffb86 --- /dev/null +++ b/backend/crates/station/src/logging/commands.rs @@ -0,0 +1,157 @@ +//! Turns the frontend's logger commands into recording sessions. +//! +//! `websocket` queues `logger/variables` and `logger/enable` as +//! [`LoggerCommand`]s. This task applies them to [`Logging`] and answers on +//! `logger/response` with the actual recording state: +//! +//! - `logger/variables` replaces the selection for the next start, as +//! `"/"` entries. A session that is already +//! recording keeps its own. Unknown entries are skipped with a warning. +//! - Until a selection arrives, a start records every data measurement of +//! every board: competition-view only sends `logger/enable`. +//! - Every `logger/enable` is answered, even when nothing changes, because +//! the frontend waits for the answer. +//! - A session that ends on its own (a write error) is answered with `false` +//! too; the reason reaches the front as a notice from the writer. +//! +//! Protection files are prepared for every board, whatever the selection. + +use std::{ + collections::{HashMap, HashSet}, + sync::Arc, +}; + +use software_core::model::{BoardId, PacketType, PodData}; +use tokio::sync::mpsc; + +use crate::{ + payload::LoggerResponse, + websocket::{LoggerCommand, broker::BrokerClient}, +}; + +use super::{Logging, MeasurementKey, Phase, SessionSelection}; + +/// Every recordable measurement, by its `"/"` name. +#[derive(Debug)] +struct Names { + keys: HashMap, + /// Every name, sorted: the selection until the front sends one. + all: Vec, + boards: Vec, +} + +impl Names { + fn new(pod_data: &PodData) -> Self { + let mut keys = HashMap::new(); + for board in pod_data.boards.values() { + for packet in board.packets.values() { + if let PacketType::Data(measurements) = &packet.packet_type { + for measurement in measurements { + keys.insert( + format!("{}/{}", board.name, measurement.alias), + MeasurementKey { + board: board.id, + measurement_id: measurement.id, + }, + ); + } + } + } + } + let mut all: Vec = keys.keys().cloned().collect(); + all.sort(); + Self { + keys, + all, + boards: pod_data.boards.keys().copied().collect(), + } + } + + /// The session for `requested`, or for every measurement if the front + /// has not sent a selection yet. + fn selection(&self, requested: Option<&[String]>) -> SessionSelection { + let requested = requested.unwrap_or(&self.all); + let mut seen = HashSet::new(); + let mut measurements = Vec::new(); + let mut accepted = Vec::new(); + for name in requested { + match self.keys.get(name) { + Some(&key) if seen.insert(key) => { + measurements.push(key); + accepted.push(name.clone()); + } + Some(_) => {} + None => tracing::warn!(%name, "unknown logger variable skipped"), + } + } + SessionSelection { + measurements, + connected_boards: self.boards.clone(), + selected_variables: serde_json::Value::from(accepted), + } + } +} + +/// Applies the frontend's logger commands until `websocket` drops its end of +/// `commands` or the writer closes. +/// +/// It holds a [`BrokerClient`], so it must end for the broker to stop: when +/// `event` stops, the writer closes and this task ends with it. +pub async fn serve_commands( + logging: Arc, + mut commands: mpsc::Receiver, + broker: BrokerClient, + pod_data: Arc, +) { + let names = Names::new(&pod_data); + let mut requested: Option> = None; + let mut status = logging.subscribe(); + let mut recording = false; + if broker.publish_logger(LoggerResponse(false)).await.is_err() { + return; + } + loop { + tokio::select! { + command = commands.recv() => { + let Some(command) = command else { break }; + match command { + LoggerCommand::Variables(list) => { + requested = Some(list); + continue; + } + LoggerCommand::Enable(true) => { + let selection = names.selection(requested.as_deref()); + if let Err(error) = logging.play(selection).await { + tracing::warn!(%error, "logger start from the front failed"); + } + } + LoggerCommand::Enable(false) => { + if let Err(error) = logging.stop().await { + tracing::warn!(%error, "logger stop from the front reported errors"); + } + } + } + recording = logging.status().phase == Phase::Recording; + if broker.publish_logger(LoggerResponse(recording)).await.is_err() { + break; + } + } + changed = status.changed() => { + let Ok(status) = changed else { break }; + // Starting and Stopping keep the previous answer. + if matches!(status.phase, Phase::Recording | Phase::Inactive | Phase::Closed) { + let now = status.phase == Phase::Recording; + if now != recording { + recording = now; + if broker.publish_logger(LoggerResponse(recording)).await.is_err() { + break; + } + } + } + } + } + } +} + +#[cfg(test)] +mod tests; diff --git a/backend/crates/station/src/logging/commands/tests.rs b/backend/crates/station/src/logging/commands/tests.rs new file mode 100644 index 000000000..d427afcc3 --- /dev/null +++ b/backend/crates/station/src/logging/commands/tests.rs @@ -0,0 +1,126 @@ +use std::{fs, time::SystemTime}; + +use tokio::{sync::watch, time::timeout}; + +use super::*; +use crate::{ + logging::{BackendRun, Config, WriterOptions, test_support::*}, + websocket::broker::Broker, +}; + +#[test] +fn without_a_selection_every_data_measurement_of_every_board_is_recorded() { + let (pod_data, _) = definitions(); + let selection = Names::new(&pod_data).selection(None); + let mut measurements = selection.measurements.clone(); + measurements.sort_by_key(|key| key.measurement_id.0); + assert_eq!( + measurements, + [ + MeasurementKey { + board: LCU, + measurement_id: SPEED + }, + MeasurementKey { + board: LCU, + measurement_id: UNSELECTED + }, + ] + ); + let mut boards = selection.connected_boards.clone(); + boards.sort_by_key(|board| board.0); + assert_eq!(boards, [LCU, PCU]); + assert_eq!( + selection.selected_variables, + serde_json::json!(["LCU/speed", "LCU/unselected"]) + ); +} + +#[test] +fn unknown_and_repeated_names_are_skipped() { + let (pod_data, _) = definitions(); + let requested = ["LCU/speed", "LCU/nope", "PCU/speed", "LCU/speed"].map(String::from); + let selection = Names::new(&pod_data).selection(Some(&requested)); + assert_eq!( + selection.measurements, + [MeasurementKey { + board: LCU, + measurement_id: SPEED + }] + ); + assert_eq!( + selection.selected_variables, + serde_json::json!(["LCU/speed"]) + ); + // An empty selection is a choice: no measurement files. + assert!( + Names::new(&pod_data) + .selection(Some(&[])) + .measurements + .is_empty() + ); +} + +async fn answer( + logger: &mut watch::Receiver, +) -> Result> { + timeout(WAIT, logger.changed()).await??; + Ok(logger.borrow_and_update().0) +} + +#[tokio::test] +async fn the_front_starts_and_stops_sessions_and_every_enable_is_answered() -> TestResult { + let temp = tempfile::tempdir()?; + let (pod_data, index) = definitions(); + let run = BackendRun::new( + Config { + logging_path: temp.path().into(), + ..Config::default() + }, + "adj", + )?; + let (input, receiver) = mpsc::channel(16); + let (notices, _notices) = mpsc::channel(4); + let logging = Arc::new(Logging::new( + run, + pod_data.clone(), + index, + receiver, + notices, + WriterOptions::default(), + )?); + let (broker, client) = Broker::new(); + let broker = tokio::spawn(broker.run()); + let mut logger = client.subscriber().subscribe_logger(); + let (commands, rx) = mpsc::channel(4); + let task = tokio::spawn(serve_commands(logging.clone(), rx, client, pod_data)); + assert!(!answer(&mut logger).await?); + + commands + .send(LoggerCommand::Variables(vec!["LCU/speed".into()])) + .await?; + commands.send(LoggerCommand::Enable(true)).await?; + assert!(answer(&mut logger).await?); + let session = logging.status().session.ok_or("no session")?; + input.send(data(SystemTime::now(), 3.0)).await?; + + commands.send(LoggerCommand::Enable(false)).await?; + assert!(!answer(&mut logger).await?); + // The front waits for an answer even when nothing changes. + commands.send(LoggerCommand::Enable(false)).await?; + assert!(!answer(&mut logger).await?); + assert_eq!( + fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? + .lines() + .count(), + 1 + ); + assert!(!session.directory.join("data/LCU/unselected.csv").exists()); + + // event stopping closes the writer, which ends the task and the broker. + drop(input); + timeout(WAIT, task).await??; + timeout(WAIT, broker).await??; + logging.shutdown().await?; + Ok(()) +} diff --git a/backend/crates/station/src/logging/control.rs b/backend/crates/station/src/logging/control.rs new file mode 100644 index 000000000..f1f59992e --- /dev/null +++ b/backend/crates/station/src/logging/control.rs @@ -0,0 +1,25 @@ +//! Private lifecycle requests, independent of the event data channel. +//! The frontend control-channel contract remains the application's concern. + +use std::time::SystemTime; + +use tokio::sync::oneshot; + +use super::{Error, SessionInfo, SessionSelection, StopReason, StopReport}; + +#[derive(Debug)] +pub(super) enum Control { + Play { + selection: SessionSelection, + reply: oneshot::Sender>, + }, + Stop { + reason: StopReason, + at: SystemTime, + reply: oneshot::Sender, Error>>, + }, + Shutdown { + at: SystemTime, + reply: Option>, + }, +} diff --git a/backend/crates/station/src/logging/data.rs b/backend/crates/station/src/logging/data.rs new file mode 100644 index 000000000..a42f1b083 --- /dev/null +++ b/backend/crates/station/src/logging/data.rs @@ -0,0 +1,88 @@ +//! Selected measurement CSVs. IDs stay numeric internally; filenames use ADJ aliases. + +use std::{collections::HashMap, path::Path}; + +use software_core::{ + logger::CsvFile, + model::{AdjId, Board, BoardId, DataPacket, Measurement}, +}; + +use super::{ + Error, + catalog::Catalog, + output::{flush_if_due, value_field}, + session::MeasurementKey, +}; + +#[derive(Debug)] +pub(super) struct DataLogger { + files: HashMap>, +} + +impl DataLogger { + /// Open only the selected measurement files, resolving labels once from ADJ. + pub fn open( + directory: &Path, + selected: &[MeasurementKey], + catalog: &Catalog, + ) -> Result { + let mut files = HashMap::>::new(); + for variable in selected { + let measurements = files.entry(variable.board).or_default(); + if let std::collections::hash_map::Entry::Vacant(entry) = + measurements.entry(variable.measurement_id) + { + let board = catalog.board(variable.board)?; + let measurement = catalog.measurement(variable.board, variable.measurement_id)?; + let path = directory + .join("data") + .join(&board.name) + .join(format!("{}.csv", measurement.alias)); + entry.insert(CsvFile::create(path, &[])?); + } + } + Ok(Self { files }) + } + + /// Positional packet values are matched with their ADJ measurement definitions. + pub fn write( + &mut self, + instant: u128, + board: &Board, + packet: &DataPacket, + measurements: &[Measurement], + threshold: u64, + ) -> Result<(), Error> { + if measurements.len() != packet.values.len() { + return Err(Error::MeasurementCount(packet.id)); + } + if let Some(files) = self.files.get_mut(&board.id) { + for (measurement, value) in measurements.iter().zip(&packet.values) { + if let Some(file) = files.get_mut(&measurement.id) { + value_field( + file.row() + .instant(instant) + .text(&board.name) + .text("backend"), + value, + ) + .end()?; + flush_if_due(file, threshold)?; + } + } + } + Ok(()) + } + + pub fn files_mut(&mut self) -> impl Iterator { + self.files + .values_mut() + .flat_map(|measurements| measurements.values_mut()) + } + + pub fn into_files(self) -> impl Iterator { + self.files + .into_values() + .flat_map(|measurements| measurements.into_values()) + } +} diff --git a/backend/crates/station/src/logging/error.rs b/backend/crates/station/src/logging/error.rs new file mode 100644 index 000000000..e7a6e7c10 --- /dev/null +++ b/backend/crates/station/src/logging/error.rs @@ -0,0 +1,62 @@ +//! Errors for recording setup, lifecycle transitions and the writer. +//! +//! Errors preserve file context from `software_core::logger` and report setup +//! or writer failures. +//! Shutdown attempts every file close and returns write failures to the caller. + +use software_core::model::{AdjId, BoardId}; +use std::{io, path::PathBuf}; + +/// Errors preparing logging settings, directories and sessions. +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("board {0:?} is not declared in the logging ADJ")] + UnknownBoard(BoardId), + #[error("measurement {id:?} is not declared as data for board {board:?}")] + UnknownMeasurement { board: BoardId, id: AdjId }, + #[error("packet {0:?} is not declared in the logging ADJ")] + UnknownPacket(AdjId), + #[error("packet {id:?} does not belong to board {board:?}")] + PacketBoardMismatch { board: BoardId, id: AdjId }, + #[error("packet {0:?} has an unexpected ADJ type")] + UnexpectedPacketType(AdjId), + #[error("packet {0:?} value count differs from its ADJ measurement count")] + MeasurementCount(AdjId), + #[error("order {0:?} has a value that is not a finite number")] + NonFiniteValue(AdjId), + #[error("couldn't serialize the logged order parameters: {0}")] + OrderPayload(#[source] serde_json::Error), + #[error("invalid logging file component: {0:?}")] + InvalidName(String), + #[error("flush interval and flush byte threshold must be positive")] + InvalidWriterOptions, + #[error("the logging writer is closed or exited unexpectedly")] + WorkerClosed, + #[error("logging session ID space exhausted")] + SessionIdExhausted, + #[error("the logging session stopped with errors: {0:?}")] + RecordingFailed(Vec), + /// A filesystem operation failed. The path identifies its destination. + #[error("couldn't {operation} at {path:?}: {source}")] + Io { + /// Operation being attempted. + operation: &'static str, + /// Destination of the operation. + path: PathBuf, + /// Underlying filesystem error. + #[source] + source: io::Error, + }, + /// A session destination is a file or symlink rather than a directory. + #[error("refusing to replace a session path that is not a directory: {0:?}")] + InvalidSessionPath(PathBuf), + /// The session selection could not be represented as JSON. + #[error("couldn't serialize the logging selection: {0}")] + Selection(#[from] serde_json::Error), + /// A date could not be converted to the recording timezone. + #[error("couldn't determine the logging date in Europe/Madrid: {0}")] + Date(#[from] jiff::Error), + /// The shared logger could not write the metadata file. + #[error(transparent)] + Logger(#[from] software_core::logger::Error), +} diff --git a/backend/crates/station/src/logging/messages.rs b/backend/crates/station/src/logging/messages.rs new file mode 100644 index 000000000..1f3e7fcbe --- /dev/null +++ b/backend/crates/station/src/logging/messages.rs @@ -0,0 +1,54 @@ +//! Message recording in the session's single `messages/messages.csv` file. +//! +//! Columns, in order: `instant,from,to,board,source,severity,message`. +//! There is no header. +//! `board` identifies the board that emitted the message; `source` preserves +//! the received TCP message's `origin`, including file and line when present. +//! +//! This component owns a `software_core::logger::CsvFile` and formats rows. + +use std::path::Path; + +use software_core::{ + logger::CsvFile, + model::{Board, MessageLevel, MessagePacket}, +}; + +use super::{Error, output::flush_if_due}; + +#[derive(Debug)] +pub(super) struct MessagesLogger { + pub file: CsvFile, +} + +impl MessagesLogger { + /// Creates and/or opens messages.csv without a header. + pub fn open(directory: &Path) -> Result { + Ok(Self { + file: CsvFile::create(directory.join("messages/messages.csv"), &[])?, + }) + } + + /// `origin` and text are borrowed directly from the received model packet. + pub fn write( + &mut self, + instant: u128, + board: &Board, + packet: &MessagePacket, + severity: MessageLevel, + threshold: u64, + ) -> Result<(), Error> { + self.file + .row() + .instant(instant) + .text(&board.name) + .text("backend") + .text(&board.name) + .text(&packet.origin) + .text(severity.name()) + .text(&packet.message) + .end()?; + flush_if_due(&mut self.file, threshold)?; + Ok(()) + } +} diff --git a/backend/crates/station/src/logging/order.rs b/backend/crates/station/src/logging/order.rs new file mode 100644 index 000000000..190e8fb7f --- /dev/null +++ b/backend/crates/station/src/logging/order.rs @@ -0,0 +1,122 @@ +//! Order recording in the session's single `order/order.csv` file. +//! +//! Columns, in order: `instant,from,to,id,name,parameters,timestamp`. +//! `timestamp` is the order's wall-clock time formatted as +//! `YYYY-MM-DDTHH-MM-SS` followed by the applicable `Europe/Madrid` UTC offset +//! (`+01:00` for CET or `+02:00` for CEST). +//! Orders come from event's `OrderSent`, using its TCP confirmation time. +//! `name` comes from the ADJ. `parameters` is a compact JSON array of +//! measurement IDs, aliases and values in one CSV cell. No header. +//! +//! This component owns a `software_core::logger::CsvFile` and formats rows. + +use std::path::Path; + +use serde::{Serialize, Serializer, ser::SerializeSeq}; +use software_core::{ + logger::CsvFile, + model::{AdjId, Measurement, OrderPacket, PacketDef, PacketType, Value}, +}; + +use super::{Error, output::flush_if_due, session::RecordTime}; + +#[derive(Debug)] +pub(super) struct OrderLogger { + pub file: CsvFile, +} + +impl OrderLogger { + /// Creates and/or opens the order.csv file + pub fn open(directory: &Path) -> Result { + Ok(Self { + file: CsvFile::create(directory.join("order/order.csv"), &[])?, + }) + } + + /// Serialize the confirmed packet before starting a row, so a parameters serialization + /// failure cannot leave a partial CSV record. ADJ parameters retain their order. + pub fn write( + &mut self, + time: RecordTime, + order: &OrderPacket, + to: &str, + definition: Option<&PacketDef>, + threshold: u64, + ) -> Result<(), Error> { + let (name, fields) = match definition { + Some(PacketDef { + id, + name, + packet_type: PacketType::Order(fields), + .. + }) if *id == order.id => (name.as_str(), fields.as_slice()), + None if order.id == AdjId(0) => ("Fault", &[][..]), + _ => return Err(Error::UnexpectedPacketType(order.id)), + }; + if fields.len() != order.values.len() { + return Err(Error::MeasurementCount(order.id)); + } + let parameters = serde_json::to_string(&Parameters { + fields, + values: &order.values, + }) + .map_err(Error::OrderPayload)?; + let timestamp = time + .wall_time + .in_tz("Europe/Madrid")? + .strftime("%Y-%m-%dT%H-%M-%S%:z") + .to_string(); + self.file + .row() // new row + .instant(time.instant) + .text("backend") // orders will always come from the backend and never from the boards + .text(to) + .int(i64::from(order.id.0)) + .text(name) + .text(¶meters) + .text(×tamp) + .end()?; // validates row and ends it + flush_if_due(&mut self.file, threshold)?; + Ok(()) + } +} + +/// A borrowed JSON view keeps logging's representation out of core's model +/// and avoids copying packet values or building an intermediate JSON tree. +struct Parameters<'a> { + fields: &'a [Measurement], + values: &'a [Value], +} + +impl Serialize for Parameters<'_> { + fn serialize(&self, serializer: S) -> Result { + let mut sequence = serializer.serialize_seq(Some(self.fields.len()))?; + for (field, value) in self.fields.iter().zip(self.values) { + sequence.serialize_element(&Parameter { + id: field.id.0, + alias: &field.alias, + value, + })?; + } + sequence.end() + } +} + +#[derive(Serialize)] +struct Parameter<'a> { + id: u16, + alias: &'a str, + #[serde(serialize_with = "serialize_value")] + value: &'a Value, +} + +fn serialize_value(value: &Value, serializer: S) -> Result { + match value { + Value::Number(value) if !value.is_finite() => { + Err(serde::ser::Error::custom("non-finite order value")) + } + Value::Number(value) => serializer.serialize_f64(*value), + Value::Bool(value) => serializer.serialize_bool(*value), + Value::Enum(value) => serializer.serialize_str(value), + } +} diff --git a/backend/crates/station/src/logging/output.rs b/backend/crates/station/src/logging/output.rs new file mode 100644 index 000000000..bd47df893 --- /dev/null +++ b/backend/crates/station/src/logging/output.rs @@ -0,0 +1,50 @@ +//! Shared CSV field formatting and explicit close/flush discipline. + +use std::io::Write; + +use software_core::{ + logger::{CsvFile, Row}, + model::Value, +}; + +use super::Error; + +pub(super) fn flush_if_due(file: &mut CsvFile, threshold: u64) -> Result<(), Error> { + if file.bytes_since_flush() >= threshold { + file.flush()?; + } + Ok(()) +} + +pub(super) fn value_field<'a, W: Write>(row: Row<'a, W>, value: &Value) -> Row<'a, W> { + match value { + Value::Number(value) => row.num(*value), + Value::Bool(value) => row.bool(*value), + Value::Enum(value) => row.text(value), + } +} + +pub(super) fn flush_files<'a, W: Write + 'a>( + files: impl Iterator>, + threshold: u64, +) -> Vec { + let mut errors = Vec::new(); + for file in files { + if file.bytes_since_flush() >= threshold + && let Err(error) = file.flush() + { + errors.push(error.into()); + } + } + errors +} + +pub(super) fn close_files(files: impl Iterator>) -> Vec { + let mut errors = Vec::new(); + for file in files { + if let Err(error) = file.close() { + errors.push(error.into()); + } + } + errors +} diff --git a/backend/crates/station/src/logging/protections.rs b/backend/crates/station/src/logging/protections.rs new file mode 100644 index 000000000..cc672fcc0 --- /dev/null +++ b/backend/crates/station/src/logging/protections.rs @@ -0,0 +1,114 @@ +//! Protection rows resolved from a received packet and the ADJ definition. +//! The final time field preserves the duration in the ADJ protection definition. + +use std::{ + collections::HashMap, + path::{Path, PathBuf}, + time::Duration, +}; + +use software_core::{ + logger::CsvFile, + model::{Board, BoardId, Measurement, Protection, ProtectionKind, ProtectionPacket, Severity}, +}; + +use super::{ + Error, + catalog::Catalog, + output::{flush_if_due, value_field}, +}; + +#[derive(Debug)] +pub(super) struct ProtectionsLogger { + directory: PathBuf, + files: HashMap, +} + +impl ProtectionsLogger { + pub fn open(directory: &Path, boards: &[BoardId], catalog: &Catalog) -> Result { + let mut logger = Self { + directory: directory.join("protections"), + files: HashMap::new(), + }; + for &board in boards { + logger.file(catalog.board(board)?)?; + } + Ok(logger) + } + + fn file(&mut self, board: &Board) -> Result<&mut CsvFile, Error> { + if let std::collections::hash_map::Entry::Vacant(entry) = self.files.entry(board.id) { + entry.insert(CsvFile::create( + self.directory.join(format!("{}.csv", board.name)), + &[], + )?); + } + self.files.get_mut(&board.id).ok_or(Error::WorkerClosed) + } + + pub fn write( + &mut self, + instant: u128, + board: &Board, + packet: &ProtectionPacket, + measurement: &Measurement, + protection: &Protection, + threshold: u64, + ) -> Result<(), Error> { + let (kind, first, second) = match protection.kind { + ProtectionKind::Above { limit } => ("above", limit, None), + ProtectionKind::Below { limit } => ("below", limit, None), + ProtectionKind::Equal { target } => ("equal", target, None), + ProtectionKind::NotEqual { target } => ("not_equal", target, None), + ProtectionKind::Range { min, max } => ("range", min, Some(max)), + }; + let severity = match protection.severity { + Severity::Fault => "fault", + Severity::Warning => "warning", + }; + let file = self.file(board)?; + let row = file + .row() + .instant(instant) + .text(&board.name) + .text("backend") + .int(i64::from(packet.id.0)) + .text(severity) + .text(kind) + .num(first); + let row = match second { + Some(value) => row.num(value), + None => row.text(""), + }; + let row = value_field(row.int(i64::from(measurement.id.0)), &packet.value); + // This is a property of the protection, independent of the session + // clock and the board's timestamp in the received packet. + row.text(&format_time(protection.time)).end()?; + flush_if_due(file, threshold)?; + Ok(()) + } + + pub fn files_mut(&mut self) -> impl Iterator { + self.files.values_mut() + } + pub fn into_files(self) -> impl Iterator { + self.files.into_values() + } +} + +/// Match the HTTP catalog's units without losing fractional milliseconds. +/// CSVs explicitly write zero where the catalog omits the optional property. +fn format_time(time: Duration) -> String { + if time.is_zero() { + return "0".into(); + } + let ns = time.as_nanos(); + let (value, unit) = if ns.is_multiple_of(1_000_000) { + (ns / 1_000_000, "ms") + } else if ns.is_multiple_of(1_000) { + (ns / 1_000, "us") + } else { + (ns, "ns") + }; + format!("{value}{unit}") +} diff --git a/backend/crates/station/src/logging/service.rs b/backend/crates/station/src/logging/service.rs new file mode 100644 index 000000000..b5b24678b --- /dev/null +++ b/backend/crates/station/src/logging/service.rs @@ -0,0 +1,163 @@ +//! Lifecycle handle for the writer that owns event's data receiver. + +use std::{ + sync::{Arc, Mutex}, + thread::JoinHandle, + time::SystemTime, +}; + +use software_core::{model::PodData, protocol::Index}; +use tokio::sync::{mpsc, oneshot, watch}; + +use crate::event::Notice; + +use super::{ + BackendRun, Error, Phase, SessionInfo, SessionSelection, Status, StatusReceiver, StopReason, + StopReport, ToLogging, WriterOptions, catalog::Catalog, control::Control, + status::checked_report, writer, +}; + +/// The writer serializes controls and owns all session state. The independent +/// control channel remains usable even when event's data channel is full. +#[derive(Debug)] +pub struct Logging { + controls: mpsc::UnboundedSender, + status: watch::Receiver, + worker: Mutex>>, +} + +impl Logging { + /// Move event's existing receiver directly into the dedicated writer. + /// No additional data channel or forwarding task is created. + /// + /// `notices` is a clone of event's ② sender: a session that stops on a + /// write error sends a warning there, so the operator learns about it. + pub fn new( + run: BackendRun, + pod_data: Arc, + index: Arc, + input: mpsc::Receiver, + notices: mpsc::Sender, + options: WriterOptions, + ) -> Result { + if let Err(error) = options.validate() { + tracing::warn!(%error, "logging configuration rejected"); + return Err(error); + } + let directory = run.directory().to_path_buf(); + let catalog = Catalog::new(pod_data, index); + let (controls, control_rx) = mpsc::unbounded_channel(); + let (status_tx, status) = watch::channel(Status::default()); + let worker = std::thread::Builder::new() + .name("logging-writer".into()) + .spawn(move || { + writer::run(run, input, control_rx, notices, status_tx, catalog, options) + }) + .map_err(|source| { + tracing::error!(directory = %directory.display(), error = %source, "could not spawn logging writer"); + Error::Io { + operation: "spawn the logging writer", + path: directory, + source, + } + })?; + Ok(Self { + controls, + status, + worker: Mutex::new(Some(worker)), + }) + } + + pub fn status(&self) -> Status { + self.status.borrow().clone() + } + pub fn subscribe(&self) -> StatusReceiver { + StatusReceiver::new(self.status.clone()) + } + + /// Wait until files are ready; repeated play returns the existing session. + /// Cancelling a caller's wait does not retract its already sent request. + pub async fn play(&self, selection: SessionSelection) -> Result { + let (reply, response) = oneshot::channel(); + self.controls + .send(Control::Play { selection, reply }) + .map_err(|_| Error::WorkerClosed)?; + response.await.map_err(|_| Error::WorkerClosed)? + } + + pub async fn stop(&self) -> Result, Error> { + self.stop_with_reason(StopReason::Requested).await + } + + /// Stop the session while retaining event's receiver for a later restart. + pub async fn emergency_stop(&self) -> Result, Error> { + self.stop_with_reason(StopReason::Emergency).await + } + + async fn stop_with_reason(&self, reason: StopReason) -> Result, Error> { + let (reply, response) = oneshot::channel(); + self.controls + .send(Control::Stop { + reason, + at: SystemTime::now(), + reply, + }) + .map_err(|_| Error::WorkerClosed)?; + response.await.map_err(|_| Error::WorkerClosed)? + } + + /// Close event input, drain accepted records, close files and join the writer. + pub async fn shutdown(&self) -> Result<(), Error> { + if self.status().phase != Phase::Closed { + let (reply, response) = oneshot::channel(); + if self + .controls + .send(Control::Shutdown { + at: SystemTime::now(), + reply: Some(reply), + }) + .is_ok() + { + // Input may have closed independently; still join and inspect + // final status even if that race drops the acknowledgement. + let _ = response.await; + } + } + let worker = self.worker.lock().unwrap_or_else(|e| e.into_inner()).take(); + if let Some(worker) = worker { + tokio::task::spawn_blocking(move || worker.join()) + .await + .map_err(|_| Error::WorkerClosed)? + .map_err(|_| Error::WorkerClosed)?; + } + let status = self.status(); + checked_report(status.last_stop)?; + if let Some(error) = status.last_error { + return Err(Error::RecordingFailed(vec![error])); + } + Ok(()) + } +} + +impl Drop for Logging { + fn drop(&mut self) { + // Bounded draining makes this fallback independent of producers that + // would otherwise keep filling the data channel indefinitely. + let _ = self.controls.send(Control::Shutdown { + at: SystemTime::now(), + reply: None, + }); + if let Some(worker) = self + .worker + .get_mut() + .unwrap_or_else(|e| e.into_inner()) + .take() + { + // The writer's exit guard traces an unexpected exit at its source. + let _ = worker.join(); + } + } +} + +#[cfg(test)] +mod tests; diff --git a/backend/crates/station/src/logging/service/tests.rs b/backend/crates/station/src/logging/service/tests.rs new file mode 100644 index 000000000..df6da52ae --- /dev/null +++ b/backend/crates/station/src/logging/service/tests.rs @@ -0,0 +1,598 @@ +//! Lifecycle tests using the real ToLogging channel, ADJ and protocol index. + +use std::{ + fs, + path::Path, + time::{Duration, SystemTime}, +}; +use tokio::time::{sleep, timeout}; + +use super::*; +use crate::event::NoticeKind; +use crate::logging::{Config, MeasurementKey, TimeUnit, test_support::*}; +use software_core::{ + model::{AdjId, DataPacket, OrderPacket, Packet}, + net::Event, +}; + +type Fixture = ( + tempfile::TempDir, + Logging, + mpsc::Sender, + mpsc::Receiver, +); + +fn logging(options: WriterOptions) -> Result> { + logging_with_capacity(options, 1024) +} + +fn logging_with_capacity( + options: WriterOptions, + capacity: usize, +) -> Result> { + let temp = tempfile::tempdir()?; + let (pod_data, index) = definitions(); + let run = BackendRun::new_at( + Config { + logging_path: temp.path().into(), + time_unit: TimeUnit::Microseconds, + }, + "adj", + "2026-11-27T14:30:00Z".parse()?, + )?; + let (sender, receiver) = mpsc::channel(capacity); + let (notices, notices_rx) = mpsc::channel(16); + let logger = Logging::new(run, pod_data, index, receiver, notices, options)?; + Ok((temp, logger, sender, notices_rx)) +} + +async fn visible(path: &Path) -> TestResult { + timeout(WAIT, async { + loop { + if !fs::read_to_string(path)?.is_empty() { + return Ok::<(), std::io::Error>(()); + } + sleep(Duration::from_millis(5)).await; + } + }) + .await??; + Ok(()) +} + +#[tokio::test] +async fn stop_drains_records_filters_selection_and_is_idempotent() -> TestResult { + let (_temp, logger, sender, mut notices) = logging(WriterOptions::default())?; + let session = logger.play(selection()).await?; + for n in 0..200 { + sender.send(data(SystemTime::now(), f64::from(n))).await?; + } + let first_stop = timeout(WAIT, logger.stop()).await??; + assert_eq!( + first_stop.as_ref().map(|r| r.reason), + Some(StopReason::Requested) + ); + assert_eq!(first_stop, logger.stop().await?); + let text = fs::read_to_string(session.directory.join("data/LCU/speed.csv"))?; + assert_eq!(text.lines().count(), 200); + assert!(text.ends_with(",LCU,backend,199\n")); + assert!(!session.directory.join("data/LCU/unselected.csv").exists()); + // Inactive logging must keep event's receiver alive. + sender.send(data(SystemTime::now(), 999.0)).await?; + logger.shutdown().await?; + assert_eq!( + fs::read_to_string(session.directory.join("data/LCU/speed.csv"))?, + text + ); + // Requested stops are not news for the operator. + assert!(notices.try_recv().is_err()); + Ok(()) +} + +#[tokio::test] +async fn double_play_preserves_session_and_old_receptions_cannot_enter_a_new_one() -> TestResult { + let (_temp, logger, sender, _notices) = logging(WriterOptions::default())?; + let first = logger.play(selection()).await?; + let old_reception = SystemTime::now(); + sender.send(data(old_reception, 1.0)).await?; + assert_eq!( + first, + logger + .play(SessionSelection { + measurements: vec![], + connected_boards: vec![], + selected_variables: serde_json::json!([]) + }) + .await? + ); + assert_eq!( + logger.emergency_stop().await?.map(|r| r.reason), + Some(StopReason::Emergency) + ); + let second = logger.play(selection()).await?; + assert_ne!(first.id, second.id); + sender.send(data(old_reception, 99.0)).await?; + sender.send(data(SystemTime::now(), 2.0)).await?; + logger.stop().await?; + let text = fs::read_to_string(second.directory.join("data/LCU/speed.csv"))?; + assert_eq!(text.lines().count(), 1); + assert!(text.ends_with(",LCU,backend,2\n")); + logger.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn selection_can_change_between_sessions() -> TestResult { + let (_temp, logger, sender, _notices) = logging(WriterOptions::default())?; + logger.play(selection()).await?; + sender.send(data(SystemTime::now(), 1.0)).await?; + logger.stop().await?; + let mut next = selection(); + next.measurements = vec![MeasurementKey { + board: LCU, + measurement_id: UNSELECTED, + }]; + next.selected_variables = serde_json::json!({"LCU": ["unselected"]}); + let session = logger.play(next).await?; + sender.send(data(SystemTime::now(), 2.0)).await?; + logger.stop().await?; + let data_dir = session.directory.join("data/LCU"); + assert_eq!( + fs::read_to_string(data_dir.join("unselected.csv"))? + .lines() + .count(), + 1 + ); + let metadata: serde_json::Value = + software_core::logger::read_json(session.directory.join("logger_settings.json"))?; + assert_eq!( + metadata["selected_variables"], + serde_json::json!({"LCU": ["unselected"]}) + ); + assert_eq!(metadata["date"], session.date); + logger.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn stopping_a_one_slot_data_channel_never_needs_an_extra_data_slot() -> TestResult { + let (_temp, logger, sender, _notices) = logging_with_capacity(WriterOptions::default(), 1)?; + let session = logger.play(selection()).await?; + sender.try_send(data(SystemTime::now(), 1.0))?; + let report = timeout(WAIT, logger.stop()).await??; + assert_eq!(report.map(|r| r.reason), Some(StopReason::Requested)); + assert_eq!( + fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? + .lines() + .count(), + 1 + ); + assert!(!sender.is_closed()); + logger.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn periodic_flush_persists_a_buffered_tail_without_stopping() -> TestResult { + let (_temp, logger, sender, _notices) = logging(WriterOptions { + flush_interval: Duration::from_millis(20), + flush_bytes: u64::MAX, + })?; + let session = logger.play(selection()).await?; + sender.send(data(SystemTime::now(), 1.0)).await?; + visible(&session.directory.join("data/LCU/speed.csv")).await?; + assert_eq!(logger.status().phase, Phase::Recording); + logger.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn byte_threshold_flushes_without_waiting_for_the_timer() -> TestResult { + let (_temp, logger, sender, _notices) = logging(WriterOptions { + flush_interval: Duration::from_secs(60), + flush_bytes: 1, + })?; + let session = logger.play(selection()).await?; + sender.send(data(SystemTime::now(), 1.0)).await?; + visible(&session.directory.join("data/LCU/speed.csv")).await?; + assert_eq!(logger.status().phase, Phase::Recording); + logger.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn concurrent_producers_are_drained_before_shutdown() -> TestResult { + let (_temp, logger, sender, _notices) = logging(WriterOptions::default())?; + let session = logger.play(selection()).await?; + let mut producers = tokio::task::JoinSet::new(); + for producer in 0..8 { + let sender = sender.clone(); + producers.spawn(async move { + for n in 0..100 { + sender + .send(data(SystemTime::now(), f64::from(producer * 100 + n))) + .await?; + } + Ok::<(), mpsc::error::SendError>(()) + }); + } + while let Some(result) = producers.join_next().await { + result??; + } + timeout(WAIT, logger.shutdown()).await??; + assert_eq!(logger.status().phase, Phase::Closed); + let text = fs::read_to_string(session.directory.join("data/LCU/speed.csv"))?; + assert_eq!(text.lines().count(), 800); + let unique: std::collections::HashSet<_> = text + .lines() + .filter_map(|line| line.rsplit(',').next()) + .collect(); + assert_eq!(unique.len(), 800); + assert!(matches!( + logger.play(selection()).await, + Err(Error::WorkerClosed) + )); + Ok(()) +} + +#[tokio::test] +async fn write_failure_stops_with_an_error_and_closes_the_other_files() -> TestResult { + let (_temp, logger, sender, mut notices) = logging(WriterOptions::default())?; + let mut selected = selection(); + selected.connected_boards.clear(); // Keep protection files unopened until the event. + let session = logger.play(selected).await?; + let protections = session.directory.join("protections"); + fs::remove_dir(&protections)?; + fs::write(&protections, "not a directory")?; + sender.send(data(SystemTime::now(), 7.0)).await?; + sender + .send(protection(PCU, AdjId((1 << 13) | 3003), 55.0)) + .await?; + assert!(matches!( + timeout(WAIT, logger.stop()).await?, + Err(Error::RecordingFailed(_)) + )); + assert_eq!( + logger.status().last_stop.map(|r| r.reason), + Some(StopReason::WriteError) + ); + assert!( + fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? + .ends_with(",LCU,backend,7\n") + ); + // The operator is told, once, and the backend keeps running. + let notice = notices.try_recv()?; + assert_eq!(notice.kind, NoticeKind::Warning); + assert!(notice.text.starts_with("recording stopped")); + // Remove the obstruction even if the next session has a different second. + fs::remove_file(protections)?; + logger.play(selection()).await?; + sender.send(data(SystemTime::now(), 8.0)).await?; + logger.shutdown().await?; + assert!(notices.try_recv().is_err()); + Ok(()) +} + +#[tokio::test] +async fn invalid_selection_is_rejected_before_replacing_existing_files() -> TestResult { + let (_temp, logger, sender, _notices) = logging(WriterOptions::default())?; + let session = logger.play(selection()).await?; + sender.send(data(SystemTime::now(), 1.0)).await?; + logger.stop().await?; + let file = session.directory.join("data/LCU/speed.csv"); + let before = fs::read(&file)?; + let mut invalid = selection(); + invalid.measurements[0].measurement_id = AdjId(7000); + assert!(matches!( + logger.play(invalid).await, + Err(Error::UnknownMeasurement { .. }) + )); + assert_eq!(fs::read(file)?, before); + assert_eq!(logger.status().phase, Phase::Inactive); + logger.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn an_abandoned_start_reply_does_not_prevent_emergency_stop_or_restart() -> TestResult { + let (_temp, logger, _sender, _notices) = logging(WriterOptions::default())?; + let (reply, response) = oneshot::channel(); + drop(response); + logger.controls.send(Control::Play { + selection: selection(), + reply, + })?; + let report = timeout(WAIT, logger.emergency_stop()).await??; + let first_id = report.as_ref().ok_or("start was not processed")?.session.id; + assert_eq!(report.map(|r| r.reason), Some(StopReason::Emergency)); + assert!(logger.play(selection()).await?.id.get() > first_id.get()); + logger.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn drop_is_a_fallback_drain_when_explicit_shutdown_was_missed() -> TestResult { + let (_temp, logger, sender, _notices) = logging(WriterOptions::default())?; + let session = logger.play(selection()).await?; + for n in 0..100 { + sender.send(data(SystemTime::now(), f64::from(n))).await?; + } + drop(logger); + assert_eq!( + fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? + .lines() + .count(), + 100 + ); + assert!(sender.is_closed()); + Ok(()) +} + +#[tokio::test] +async fn controls_can_run_in_spawned_application_tasks() -> TestResult { + let (_temp, logger, sender, _notices) = logging(WriterOptions::default())?; + let logger = Arc::new(logger); + let controller = logger.clone(); + let session = tokio::spawn(async move { controller.play(selection()).await }).await??; + sender.send(data(SystemTime::now(), 1.0)).await?; + let controller = logger.clone(); + tokio::spawn(async move { controller.emergency_stop().await }).await??; + assert!( + fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? + .ends_with(",LCU,backend,1\n") + ); + let controller = logger.clone(); + tokio::spawn(async move { controller.shutdown().await }).await??; + Ok(()) +} + +#[tokio::test] +async fn stop_drains_a_finite_prefix_while_the_producer_keeps_sending() -> TestResult { + use std::{ + future::{Future, poll_fn}, + task::Poll, + }; + let (_temp, logger, sender, _notices) = logging(WriterOptions::default())?; + let session = logger.play(selection()).await?; + for n in 0..128 { + sender.send(data(SystemTime::now(), f64::from(n))).await?; + } + let mut stopping = Box::pin(logger.stop()); + let completed = poll_fn(|cx| { + Poll::Ready(match stopping.as_mut().poll(cx) { + Poll::Ready(result) => Some(result), + Poll::Pending => None, + }) + }) + .await; + for _ in 0..1024 { + sender.send(data(SystemTime::now(), 999.0)).await?; + } + let report = match completed { + Some(result) => result?, + None => timeout(WAIT, stopping).await??, + }; + assert_eq!(report.map(|r| r.reason), Some(StopReason::Requested)); + assert_eq!( + fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? + .lines() + .count(), + 128 + ); + assert!(!sender.is_closed()); + logger.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn input_closure_flushes_the_session_and_releases_the_worker() -> TestResult { + let (_temp, logger, sender, _notices) = logging(WriterOptions::default())?; + let session = logger.play(selection()).await?; + let mut updates = logger.subscribe(); + for n in 0..128 { + sender.send(data(SystemTime::now(), f64::from(n))).await?; + } + drop(sender); + timeout(WAIT, async { + while logger.status().phase != Phase::Closed { + if updates.changed().await.is_err() { + break; + } + } + Ok::<(), Error>(()) + }) + .await??; + logger.shutdown().await?; + assert_eq!( + fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? + .lines() + .count(), + 128 + ); + Ok(()) +} + +#[tokio::test] +async fn invalid_packets_and_received_orders_do_not_write_partial_or_duplicate_rows() -> TestResult +{ + let (_temp, logger, sender, _notices) = logging(WriterOptions::default())?; + let session = logger.play(selection()).await?; + sender + .send(received( + LCU, + SystemTime::now(), + Event::Received(Packet::Data(DataPacket::new(TELEMETRY, vec![]))), + )) + .await?; + sender + .send(received( + PCU, + SystemTime::now(), + Event::Received(Packet::Data(DataPacket::new(TELEMETRY, vec![]))), + )) + .await?; + sender + .send(received(LCU, SystemTime::now(), Event::Connected)) + .await?; + sender + .send(received( + LCU, + SystemTime::now(), + Event::Received(Packet::Order(OrderPacket::new(AdjId(2000), vec![]))), + )) + .await?; + sender.send(data(SystemTime::now(), 42.0)).await?; + logger.stop().await?; + assert_eq!( + fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? + .lines() + .count(), + 1 + ); + assert!(fs::read(session.directory.join("order/order.csv"))?.is_empty()); + logger.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn event_routes_to_the_real_logger_across_session_stop_and_restart() -> TestResult { + use crate::event::{self, ToPipeline}; + + let temp = tempfile::tempdir()?; + let (pod_data, index) = definitions(); + let config = event::EventConfig::default(); + let event::Channels { + udp, + tcp, + event: ends, + orders, + notices, + logging: input, + mut pipeline, + mut pipeline_data, + } = event::channels(&config); + let run = BackendRun::new( + Config { + logging_path: temp.path().into(), + ..Config::default() + }, + "adj", + )?; + let logger = Logging::new( + run, + pod_data.clone(), + index.clone(), + input, + notices.clone(), + WriterOptions::default(), + )?; + struct Tcp; + impl event::TcpLink for Tcp { + fn send( + &self, + _order: OrderPacket, + ) -> event::BoxFuture<'_, Result> { + Box::pin(async { Ok(LCU) }) + } + fn send_fault( + &self, + ) -> event::BoxFuture<'_, Result<(), Vec>> { + Box::pin(async { Ok(()) }) + } + } + let event_task = event::spawn(config, ends, pod_data, index, Some(Arc::new(Tcp))); + + for recording in [true, false, true] { + let session = if recording { + Some(logger.play(selection()).await?) + } else { + None + }; + for n in 0..4 { + udp.notify( + LCU, + Event::Received(Packet::Data(DataPacket::new( + TELEMETRY, + vec![ + software_core::model::Value::Number(f64::from(n)), + software_core::model::Value::Number(999.0), + ], + ))), + ) + .await?; + } + // Router sends to logging before pipeline, whose telemetry copy goes + // on ⑨. Receiving these four proves that all four passed through + // event's real logging sender. + for _ in 0..4 { + assert!(timeout(WAIT, pipeline_data.recv()).await?.is_some()); + } + if let Some(session) = session { + logger.stop().await?; + assert_eq!( + fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? + .lines() + .count(), + 4 + ); + } + assert!(!event_task.is_finished()); + } + let session = logger.play(selection()).await?; + orders + .send(OrderPacket::new( + AdjId(2000), + vec![software_core::model::Value::Bool(true)], + )) + .await?; + let confirmed_at = match timeout(WAIT, pipeline.recv()).await? { + Some(ToPipeline::OrderSent { at, .. }) => at, + other => return Err(format!("expected a confirmed order, got {other:?}").into()), + }; + logger.stop().await?; + let timestamp = jiff::Timestamp::try_from(confirmed_at)? + .in_tz("Europe/Madrid")? + .strftime("%Y-%m-%dT%H-%M-%S%:z") + .to_string(); + let contents = fs::read_to_string(session.directory.join("order/order.csv"))?; + assert_eq!(contents.lines().count(), 1); + assert!(contents.ends_with(&format!( + ",backend,LCU,2000,Enable,\"[{{\"\"id\"\":4000,\"\"alias\"\":\"\"enabled_command\"\",\"\"value\"\":true}}]\",{timestamp}\n" + ))); + drop((udp, tcp, orders, notices)); + assert!(matches!( + timeout(WAIT, event_task).await??, + event::Stop::NetGone + )); + timeout(WAIT, logger.shutdown()).await??; + assert_eq!(logger.status().phase, Phase::Closed); + Ok(()) +} + +#[tokio::test] +async fn a_non_finite_order_is_discarded_and_recording_continues() -> TestResult { + let (_temp, logger, sender, mut notices) = logging(WriterOptions::default())?; + let session = logger.play(selection()).await?; + sender.send(data(SystemTime::now(), 7.0)).await?; + for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + sender + .send(ToLogging::OrderSent { + at: SystemTime::now(), + board: Some(LCU), + order: OrderPacket::new( + AdjId(2002), + vec![software_core::model::Value::Number(value)], + ), + }) + .await?; + } + sender.send(data(SystemTime::now(), 8.0)).await?; + let report = timeout(WAIT, logger.stop()).await??; + assert_eq!(report.map(|r| r.reason), Some(StopReason::Requested)); + assert!(fs::read(session.directory.join("order/order.csv"))?.is_empty()); + let speed = fs::read_to_string(session.directory.join("data/LCU/speed.csv"))?; + assert_eq!(speed.lines().count(), 2); + assert!(speed.ends_with(",LCU,backend,8\n")); + logger.shutdown().await?; + assert!(notices.try_recv().is_err()); + Ok(()) +} diff --git a/backend/crates/station/src/logging/session.rs b/backend/crates/station/src/logging/session.rs new file mode 100644 index 000000000..ba60cb170 --- /dev/null +++ b/backend/crates/station/src/logging/session.rs @@ -0,0 +1,268 @@ +//! Recording session paths, identity, clock and lifecycle state. +//! +//! Every successful `play` starts a separate session directory named +//! `YYYY-MM-DDTHH-MM-SS` below the backend startup directory. Each session has +//! `logger_settings.json` and `data/`, `protections/`, `order/`, `messages/`. +//! +//! The session's SystemTime origin is subtracted from event's reception or +//! order-confirmation time to obtain elapsed instants in the configured unit. +//! These follow the machine's calendar clock, including any clock adjustments. +//! The first event need not occur at zero. A new session with an existing +//! directory name overwrites it without retaining files from its old selection. +//! +//! Planned states: inactive, starting, recording and stopping. A normal stop +//! preserves the backend-wide `others/` files for subsequent sessions. + +use std::{ + fs, io, + path::{Path, PathBuf}, + time::SystemTime, +}; + +use jiff::Timestamp; +use serde::Serialize; +use serde_json::Value; +use software_core::logger::write_json; +use software_core::model::{AdjId, BoardId}; + +use super::{ + Config, Error, Settings, + catalog::{Catalog, validate_name}, +}; + +/// Selected measurements use native ADJ IDs; file labels are resolved separately. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct MeasurementKey { + pub board: BoardId, + pub measurement_id: AdjId, +} + +/// Resolved session selection, independent of the pending control-channel schema. +#[derive(Debug, Clone)] +pub struct SessionSelection { + pub measurements: Vec, + pub connected_boards: Vec, + pub selected_variables: Value, +} + +impl SessionSelection { + pub(super) fn validate(&self, catalog: &Catalog) -> Result<(), Error> { + for variable in &self.measurements { + validate_name(&catalog.board(variable.board)?.name)?; + validate_name( + &catalog + .measurement(variable.board, variable.measurement_id)? + .alias, + )?; + } + for &board in &self.connected_boards { + validate_name(&catalog.board(board)?.name)?; + } + Ok(()) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct SessionId(pub(super) u64); + +impl SessionId { + pub fn get(self) -> u64 { + self.0 + } +} + +/// Writer-private stamp derived from notification reception or OrderSent's +/// TCP confirmation time, as supplied by event. +#[derive(Debug, Clone, Copy)] +pub(super) struct RecordTime { + pub instant: u128, + pub wall_time: Timestamp, +} + +const SETTINGS_FILE: &str = "logger_settings.json"; + +/// Directory and metadata for one backend execution. +/// +/// This is filesystem preparation, not the recording service: it does not +/// start a writer, open CSVs or implement `play`/`stop`. The recording service +/// must close the previous session before preparing a replacement. +#[derive(Debug)] +pub struct BackendRun { + directory: PathBuf, + settings: Settings, +} + +impl BackendRun { + /// Creates a run directory with the current date and backend metadata. + /// + /// Blocking: call during startup or on the writer thread. + pub fn new(config: Config, adj_commit_hash: impl Into) -> Result { + Self::new_at(config, adj_commit_hash, Timestamp::now()) + } + + /// Uses a startup time captured by the caller, before ADJ acquisition. + /// + /// Dates use `Europe/Madrid`, including its daylight-saving rules. A run + /// directory that already exists is an error rather than a shared run. + pub fn new_at( + config: Config, + adj_commit_hash: impl Into, + started_at: Timestamp, + ) -> Result { + let date = directory_date(started_at)?; + let root = if config.logging_path.is_absolute() { + config.logging_path + } else { + let cwd = std::env::current_dir().map_err(|source| Error::Io { + operation: "resolve the working directory", + path: config.logging_path.clone(), + source, + })?; + cwd.join(config.logging_path) + } + .join("logger"); + + create_directories(&root)?; + let directory = root.join(&date); + fs::create_dir(&directory).map_err(|source| Error::Io { + operation: "create the backend run directory", + path: directory.clone(), + source, + })?; + + let settings = Settings { + adj_commit_hash: adj_commit_hash.into(), + time_unit: config.time_unit, + date, + }; + write_json(directory.join("others").join(SETTINGS_FILE), &settings)?; + Ok(Self { + directory, + settings, + }) + } + + /// Absolute path of `logger//`. + pub fn directory(&self) -> &Path { + &self.directory + } + + /// Metadata written in `others/logger_settings.json`. + pub fn settings(&self) -> &Settings { + &self.settings + } + + /// Prepares session directories and settings using the current time. + /// + /// `selected_variables` is serialized unchanged, leaving its schema to + /// the application layer. No WebSocket event or payload type is required. + /// This performs blocking filesystem work and overwrites a previous + /// session with the same timestamp. The caller must finish that session + /// and close all of its files first. + pub fn prepare_session( + &mut self, + selected_variables: impl Serialize, + ) -> Result { + self.prepare_session_at(selected_variables, Timestamp::now()) + } + + /// Use the same startup timestamp for the directory, metadata and time origin. + fn prepare_session_at( + &mut self, + selected_variables: impl Serialize, + started_at: Timestamp, + ) -> Result { + // Validate serialization before removing any existing session. + let selected_variables = serde_json::to_value(selected_variables)?; + let mut settings = self.settings.clone(); + settings.date = directory_date(started_at)?; + let directory = self.directory.join(&settings.date); + + match fs::symlink_metadata(&directory) { + Ok(metadata) if metadata.is_dir() => { + fs::remove_dir_all(&directory).map_err(|source| Error::Io { + operation: "replace the previous session directory", + path: directory.clone(), + source, + })?; + } + Ok(_) => return Err(Error::InvalidSessionPath(directory)), + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(source) => { + return Err(Error::Io { + operation: "inspect the session directory", + path: directory, + source, + }); + } + } + + for name in ["data", "protections", "order", "messages"] { + create_directories(&directory.join(name))?; + } + let metadata = SessionSettings { + settings, + selected_variables, + }; + write_json(directory.join(SETTINGS_FILE), &metadata)?; + + Ok(Session { + directory, + metadata, + wall_origin: started_at.into(), + }) + } +} + +/// Prepared session metadata and calendar time origin; no CSVs are open yet. +#[derive(Debug)] +pub struct Session { + directory: PathBuf, + metadata: SessionSettings, + wall_origin: SystemTime, +} + +#[derive(Debug, Serialize)] +struct SessionSettings { + #[serde(flatten)] + settings: Settings, + selected_variables: Value, +} + +impl Session { + pub(super) fn wall_origin(&self) -> SystemTime { + self.wall_origin + } + /// Absolute path of the session directory. + pub fn directory(&self) -> &Path { + &self.directory + } + + /// Common metadata, with the session's start date. + pub fn settings(&self) -> &Settings { + &self.metadata.settings + } + + /// Selection serialized unchanged into this session's metadata. + pub fn selected_variables(&self) -> &Value { + &self.metadata.selected_variables + } +} + +fn directory_date(timestamp: Timestamp) -> Result { + Ok(timestamp + .in_tz("Europe/Madrid")? + .strftime("%Y-%m-%dT%H-%M-%S") + .to_string()) +} + +fn create_directories(path: &Path) -> Result<(), Error> { + fs::create_dir_all(path).map_err(|source| Error::Io { + operation: "create logging directories", + path: path.to_path_buf(), + source, + }) +} + +#[cfg(test)] +mod tests; diff --git a/backend/crates/station/src/logging/session/tests.rs b/backend/crates/station/src/logging/session/tests.rs new file mode 100644 index 000000000..a3b109fa9 --- /dev/null +++ b/backend/crates/station/src/logging/session/tests.rs @@ -0,0 +1,157 @@ +use std::fs; + +use serde_json::json; +use software_core::logger::read_json; + +use super::*; +use crate::logging::TimeUnit; + +type TestResult = Result<(), Box>; + +fn config(directory: &Path) -> Config { + Config { + logging_path: directory.to_path_buf(), + time_unit: TimeUnit::Microseconds, + } +} + +#[test] +fn backend_and_session_settings_have_their_own_dates_and_selection() -> TestResult { + let temp = tempfile::tempdir()?; + let mut run = BackendRun::new_at( + config(temp.path()), + "adj-commit", + "2026-11-27T14:30:00Z".parse()?, + )?; + let backend_directory = temp.path().join("logger/2026-11-27T15-30-00"); + assert_eq!(run.directory(), backend_directory); + assert!(backend_directory.join("others").is_dir()); + + let selected = json!({"LCU": ["speed", "temperature"]}); + let session = run.prepare_session_at(&selected, "2026-11-27T14:31:05Z".parse()?)?; + let backend_settings: Value = read_json(backend_directory.join("others").join(SETTINGS_FILE))?; + let session_settings: Value = read_json(session.directory().join(SETTINGS_FILE))?; + assert_eq!( + backend_settings, + json!({ + "adj_commit_hash": "adj-commit", "time_unit": "us", "date": "2026-11-27T15-30-00" + }) + ); + assert_eq!( + session_settings, + json!({ + "adj_commit_hash": "adj-commit", "time_unit": "us", "date": "2026-11-27T15-31-05", + "selected_variables": selected + }) + ); + assert_eq!(session.selected_variables(), &selected); + assert_eq!(session.settings().date, "2026-11-27T15-31-05"); + for name in ["data", "protections", "order", "messages"] { + assert!(session.directory().join(name).is_dir()); + assert_eq!(fs::read_dir(session.directory().join(name))?.count(), 0); + } + let started_at: Timestamp = "2026-11-27T14:31:05Z".parse()?; + assert_eq!(session.wall_origin(), SystemTime::from(started_at)); + Ok(()) +} + +#[test] +fn session_replacement_removes_stale_files_and_keeps_backend_files() -> TestResult { + let temp = tempfile::tempdir()?; + let mut run = BackendRun::new_at(config(temp.path()), "adj", "2026-07-15T13:30:00Z".parse()?)?; + // Both calls fall in the same named second, despite different subsecond times. + let first = run.prepare_session_at(json!(["LCU/old"]), "2026-07-15T13:31:00.100Z".parse()?)?; + assert_eq!(first.settings().date, "2026-07-15T15-31-00"); + fs::create_dir(first.directory().join("data/LCU"))?; + fs::write(first.directory().join("data/LCU/old.csv"), "old data")?; + let previous_directory = first.directory().to_path_buf(); + drop(first); + let trace = run.directory().join("others/existing-trace.jsonl"); + fs::write(&trace, "preserve this")?; + + let replacement = + run.prepare_session_at(json!(["PCU/new"]), "2026-07-15T13:31:00.900Z".parse()?)?; + assert_eq!(replacement.directory(), previous_directory); + assert!(!replacement.directory().join("data/LCU").exists()); + let settings: Value = read_json(replacement.directory().join(SETTINGS_FILE))?; + assert_eq!(settings["selected_variables"], json!(["PCU/new"])); + assert_eq!(fs::read_to_string(trace)?, "preserve this"); + Ok(()) +} + +#[test] +fn colliding_backend_startups_do_not_share_or_overwrite_a_run() -> TestResult { + let temp = tempfile::tempdir()?; + let timestamp: Timestamp = "2026-11-27T14:30:00Z".parse()?; + let first = BackendRun::new_at(config(temp.path()), "first", timestamp)?; + let result = BackendRun::new_at(config(temp.path()), "second", timestamp); + assert!( + matches!(result, Err(Error::Io { source, .. }) if source.kind() == io::ErrorKind::AlreadyExists) + ); + let settings: Settings = read_json(first.directory().join("others").join(SETTINGS_FILE))?; + assert_eq!(settings.adj_commit_hash, "first"); + Ok(()) +} + +#[test] +fn relative_logging_paths_are_resolved_against_the_working_directory() -> TestResult { + let cwd = std::env::current_dir()?; + let temp = tempfile::tempdir_in(&cwd)?; + let relative = temp.path().strip_prefix(&cwd)?; + let run = BackendRun::new_at(config(relative), "adj", "2026-11-27T14:30:00Z".parse()?)?; + assert_eq!( + run.directory(), + temp.path().join("logger/2026-11-27T15-30-00") + ); + Ok(()) +} + +#[test] +fn invalid_selection_does_not_delete_an_existing_session() -> TestResult { + let temp = tempfile::tempdir()?; + let mut run = BackendRun::new_at(config(temp.path()), "adj", "2026-11-27T14:30:00Z".parse()?)?; + let timestamp: Timestamp = "2026-11-27T14:31:00Z".parse()?; + let session = run.prepare_session_at(json!(["speed"]), timestamp)?; + let settings_file = session.directory().join(SETTINGS_FILE); + let before = fs::read(&settings_file)?; + drop(session); + // A JSON object cannot have an array as a key. + let invalid = std::collections::BTreeMap::from([(vec![1, 2], "invalid")]); + assert!(matches!( + run.prepare_session_at(invalid, timestamp), + Err(Error::Selection(_)) + )); + assert_eq!(fs::read(settings_file)?, before); + Ok(()) +} + +#[cfg(unix)] +#[test] +fn session_replacement_does_not_follow_symlinks() -> TestResult { + let temp = tempfile::tempdir()?; + let mut run = BackendRun::new_at(config(temp.path()), "adj", "2026-11-27T14:30:00Z".parse()?)?; + let outside = temp.path().join("outside"); + fs::create_dir(&outside)?; + fs::write(outside.join("keep.txt"), "keep")?; + std::os::unix::fs::symlink(&outside, run.directory().join("2026-11-27T15-31-00"))?; + assert!(matches!( + run.prepare_session_at(json!([]), "2026-11-27T14:31:00Z".parse()?), + Err(Error::InvalidSessionPath(_)) + )); + assert_eq!(fs::read_to_string(outside.join("keep.txt"))?, "keep"); + Ok(()) +} + +#[test] +fn directory_errors_include_the_destination() -> TestResult { + let temp = tempfile::tempdir()?; + fs::write( + temp.path().join("logger"), + "a file cannot contain run directories", + )?; + assert!(matches!( + BackendRun::new_at(config(temp.path()), "adj", "2026-11-27T14:30:00Z".parse()?), + Err(Error::Io { path, .. }) if path == temp.path().join("logger") + )); + Ok(()) +} diff --git a/backend/crates/station/src/logging/settings.rs b/backend/crates/station/src/logging/settings.rs new file mode 100644 index 000000000..9162897b0 --- /dev/null +++ b/backend/crates/station/src/logging/settings.rs @@ -0,0 +1,79 @@ +//! Backend and recording-session `logger_settings.json` metadata. +//! +//! Backend settings in `others/` contain `adj_commit_hash`, `time_unit` and +//! `date`, where `date` matches the backend startup directory name. +//! Time units match the frontend: `ns`, `us`, `ms`, `s`; its default is `us`. +//! CSV instants are integers in the chosen unit. +//! Session settings preserve that metadata, replace `date` with the session +//! directory name and add `selected_variables`. The representation of that +//! selection remains to be defined. +//! +//! Settings are written through `software_core::logger::write_json`. +//! The metadata schema can grow independently of the frontend integration. + +use std::{path::PathBuf, time::Duration}; + +use serde::{Deserialize, Serialize}; + +/// Fields of the application's `[logging]` configuration section. +/// +/// Relative and empty paths are resolved against the backend's working +/// directory, matching the old backend. `logger/` is added to this path. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Config { + /// Unit of all elapsed instants recorded during a session. + pub time_unit: TimeUnit, + /// Directory that will contain `logger//`. + pub logging_path: PathBuf, +} + +impl Default for Config { + fn default() -> Self { + Self { + time_unit: TimeUnit::default(), + logging_path: PathBuf::from("."), + } + } +} + +/// Time units supported by the frontend. Sub-unit fractions are truncated. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum TimeUnit { + /// Nanoseconds. + #[serde(rename = "ns")] + Nanoseconds, + /// Microseconds, the frontend's default. + #[default] + #[serde(rename = "us")] + Microseconds, + /// Milliseconds. + #[serde(rename = "ms")] + Milliseconds, + /// Seconds. + #[serde(rename = "s")] + Seconds, +} + +impl TimeUnit { + /// Converts elapsed time to an integer without narrowing or floating point. + pub fn convert(self, elapsed: Duration) -> u128 { + match self { + Self::Nanoseconds => elapsed.as_nanos(), + Self::Microseconds => elapsed.as_micros(), + Self::Milliseconds => elapsed.as_millis(), + Self::Seconds => u128::from(elapsed.as_secs()), + } + } +} + +/// Metadata common to backend runs and logging sessions. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Settings { + /// Commit of the ADJ used by the backend. + pub adj_commit_hash: String, + /// Unit for the CSV `instant` fields. + pub time_unit: TimeUnit, + /// Start date, matching the owning directory's name. + pub date: String, +} diff --git a/backend/crates/station/src/logging/status.rs b/backend/crates/station/src/logging/status.rs new file mode 100644 index 000000000..1b6f98ff9 --- /dev/null +++ b/backend/crates/station/src/logging/status.rs @@ -0,0 +1,97 @@ +//! Public lifecycle snapshots; observers never borrow the writer's file handles. + +use std::path::PathBuf; + +use tokio::sync::watch; + +use super::{Error, SessionId, TimeUnit}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Phase { + Inactive, + Starting, + Recording, + Stopping, + Closed, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SessionInfo { + /// Unique even if a later session replaces the same directory. + pub id: SessionId, + pub directory: PathBuf, + pub date: String, + pub time_unit: TimeUnit, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum StopReason { + Requested, + Emergency, + WriteError, + Shutdown, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StopReport { + pub session: SessionInfo, + pub reason: StopReason, + /// Every file close was attempted; nonempty means the drain failed. + pub errors: Vec, +} + +#[derive(Debug, Clone)] +pub struct Status { + pub phase: Phase, + pub session: Option, + /// Retained across starts and replaced by the next completed stop. + pub last_stop: Option, + pub last_error: Option, +} + +impl Default for Status { + fn default() -> Self { + Self { + phase: Phase::Inactive, + session: None, + last_stop: None, + last_error: None, + } + } +} + +/// Notifications may coalesce; use `current` for the latest complete snapshot. +#[derive(Debug)] +pub struct StatusReceiver { + changes: watch::Receiver, +} + +impl StatusReceiver { + pub(super) fn new(changes: watch::Receiver) -> Self { + Self { changes } + } + + pub fn current(&self) -> Status { + self.changes.borrow().clone() + } + + pub async fn changed(&mut self) -> Result { + if self.current().phase == Phase::Closed { + return Err(Error::WorkerClosed); + } + self.changes + .changed() + .await + .map_err(|_| Error::WorkerClosed)?; + Ok(self.current()) + } +} + +pub(super) fn checked_report(report: Option) -> Result, Error> { + if let Some(report) = &report + && !report.errors.is_empty() + { + return Err(Error::RecordingFailed(report.errors.clone())); + } + Ok(report) +} diff --git a/backend/crates/station/src/logging/test_support.rs b/backend/crates/station/src/logging/test_support.rs new file mode 100644 index 000000000..eb0d4d586 --- /dev/null +++ b/backend/crates/station/src/logging/test_support.rs @@ -0,0 +1,192 @@ +//! Native ADJ and event fixtures shared by the logging tests. + +use std::{ + collections::HashMap, + sync::Arc, + time::{Duration, SystemTime}, +}; + +use serde_json::json; +use software_core::{ + model::{ + AdjId, Board, BoardId, DataPacket, MacAddress, Measurement, MeasurementKind, MessageLevel, + NumericKind, Packet, PacketDef, PacketType, PodData, Protection, ProtectionKind, + ProtectionPacket, Severity, ShortTimestamp, Value, + }, + net::{Event, Notification}, + protocol::Index, +}; + +use super::{MeasurementKey, SessionSelection, ToLogging}; + +pub(super) type TestResult = Result<(), Box>; +pub(super) const LCU: BoardId = BoardId(1); +pub(super) const PCU: BoardId = BoardId(2); +pub(super) const TELEMETRY: AdjId = AdjId(1000); +pub(super) const SPEED: AdjId = AdjId(3000); +pub(super) const UNSELECTED: AdjId = AdjId(3001); +pub(super) const TEMPERATURE: AdjId = AdjId(3002); +pub(super) const ABOVE: AdjId = AdjId((1 << 13) | TEMPERATURE.0); +pub(super) const RANGE: AdjId = AdjId((2 << 13) | TEMPERATURE.0); +pub(super) const FAULT_MESSAGE: AdjId = AdjId(2); +pub(super) const WAIT: Duration = Duration::from_secs(3); + +pub(super) fn definitions() -> (Arc, Arc) { + let measurement = |id, alias: &str| Measurement { + id, + alias: alias.into(), + name: alias.into(), + display_units: String::new(), + kind: MeasurementKind::Numeric { + wire_type: NumericKind::F64, + }, + protections: vec![], + }; + let mut temperature = measurement(TEMPERATURE, "temperature"); + temperature.protections = vec![ + Protection { + id: AdjId(1), + kind: ProtectionKind::Above { limit: 50.0 }, + severity: Severity::Fault, + time: Duration::from_millis(500), + }, + Protection { + id: AdjId(2), + kind: ProtectionKind::Range { + min: 0.0, + max: 100.0, + }, + severity: Severity::Warning, + time: Duration::ZERO, + }, + ]; + let telemetry = PacketDef { + id: TELEMETRY, + board: LCU, + name: "telemetry".into(), + packet_type: PacketType::Data(vec![ + measurement(SPEED, "speed"), + measurement(UNSELECTED, "unselected"), + ]), + }; + let protection = |board, id| PacketDef { + id, + board, + name: "temperature protection".into(), + packet_type: PacketType::Protection(temperature.clone()), + }; + let board = |id, name: &str, packets: Vec| Board { + id, + name: name.into(), + ip: std::net::IpAddr::from([127, 0, 0, id.0 as u8]), + mac: MacAddress([0; 6]), + packets: packets + .into_iter() + .map(|packet| (packet.id, packet)) + .collect(), + }; + // PCU has its own compound ID, so Index ownership checks remain meaningful. + let pcu_protection = PacketDef { + id: AdjId((1 << 13) | 3003), + board: PCU, + name: "PCU protection".into(), + packet_type: PacketType::Protection(Measurement { + id: AdjId(3003), + ..temperature.clone() + }), + }; + let command = |id, alias, kind| Measurement { + kind, + ..measurement(AdjId(id), alias) + }; + let enabled = command(4000, "enabled_command", MeasurementKind::Boolean); + let speed = command( + 4001, + "speed_command", + MeasurementKind::Numeric { + wire_type: NumericKind::F64, + }, + ); + let mode = command( + 4002, + "mode_command", + MeasurementKind::Enum { + options: vec!["Idle".into(), "run, \"fast\"\nnext".into()], + }, + ); + let order = |id, name: &str, fields| PacketDef { + id: AdjId(id), + board: LCU, + name: name.into(), + packet_type: PacketType::Order(fields), + }; + let boards = [ + board( + LCU, + "LCU", + vec![ + telemetry, + protection(LCU, ABOVE), + protection(LCU, RANGE), + order(2000, "Enable", vec![enabled.clone()]), + order(2001, "Brake", vec![]), + order(2002, "Set speed", vec![speed.clone()]), + order(2003, "Configure, \"drive\"", vec![speed, enabled, mode]), + ], + ), + board(PCU, "PCU", vec![pcu_protection]), + ]; + let pod_data = PodData { + boards: boards.into_iter().map(|board| (board.id, board)).collect(), + }; + let message_levels = HashMap::from([(FAULT_MESSAGE, MessageLevel::Fault)]); + let index = Arc::new(Index::new(&pod_data, Some(&message_levels))); + (Arc::new(pod_data), index) +} + +pub(super) fn selection() -> SessionSelection { + SessionSelection { + measurements: vec![MeasurementKey { + board: LCU, + measurement_id: SPEED, + }], + connected_boards: vec![LCU], + selected_variables: json!({"LCU": ["speed"]}), + } +} + +pub(super) fn received(board: BoardId, at: SystemTime, event: Event) -> ToLogging { + ToLogging::Received(Arc::new(Notification { board, at, event })) +} + +pub(super) fn data(at: SystemTime, value: f64) -> ToLogging { + received( + LCU, + at, + Event::Received(Packet::Data(DataPacket::new( + TELEMETRY, + vec![Value::Number(value), Value::Number(999.0)], + ))), + ) +} + +pub(super) fn short_timestamp() -> ShortTimestamp { + ShortTimestamp { + hour: 12, + minute: 30, + second: 0, + subsecond: 0, + } +} + +pub(super) fn protection(board: BoardId, id: AdjId, value: f64) -> ToLogging { + received( + board, + SystemTime::now(), + Event::Received(Packet::Protection(ProtectionPacket { + id, + timestamp: short_timestamp(), + value: Value::Number(value), + })), + ) +} diff --git a/backend/crates/station/src/logging/writer.rs b/backend/crates/station/src/logging/writer.rs new file mode 100644 index 000000000..5cd404283 --- /dev/null +++ b/backend/crates/station/src/logging/writer.rs @@ -0,0 +1,526 @@ +//! Single data-channel consumer and owner of all session files. +//! +//! This runs on a dedicated OS thread with a private Tokio timer runtime. Disk +//! operations never run on the application's async workers. Lifecycle controls +//! have their own channel and do not need a free slot in event's data channel. +//! +//! A stop snapshots the number of queued events and drains that finite prefix, +//! excluding reception timestamps after its cutoff. Producers can keep running; +//! new traffic is consumed without recording once the session is inactive. + +use std::{ + path::Path, + time::{Duration, SystemTime}, +}; + +use software_core::{logger::CsvFile, model::Packet, net::Event}; +use tokio::sync::{mpsc, watch}; + +use crate::event::{Notice, NoticeKind}; + +use super::{ + BackendRun, Error, Phase, Session, SessionId, SessionInfo, SessionSelection, Status, + StopReason, StopReport, ToLogging, + catalog::Catalog, + control::Control, + data::DataLogger, + messages::MessagesLogger, + order::OrderLogger, + output::{close_files, flush_files}, + protections::ProtectionsLogger, + session::RecordTime, + status::checked_report, +}; + +/// Flush limits. Event owns the sole data channel and configures its capacity. +#[derive(Debug, Clone)] +pub struct WriterOptions { + /// Maximum interval between flush attempts while a session is active. + /// A slow filesystem operation can delay the next attempt. + pub flush_interval: Duration, + /// Per-file threshold. Only the file touched by a row is checked. + pub flush_bytes: u64, +} + +impl Default for WriterOptions { + fn default() -> Self { + Self { + flush_interval: Duration::from_millis(250), + flush_bytes: 64 * 1024, + } + } +} + +impl WriterOptions { + /// A zero timer would spin; a zero byte threshold would flush every row. + pub(super) fn validate(&self) -> Result<(), Error> { + if self.flush_interval.is_zero() || self.flush_bytes == 0 { + return Err(Error::InvalidWriterOptions); + } + Ok(()) + } +} + +/// Owns every CSV handle for one session, grouped by the row format it writes. +/// Sharing these handles with producers would require locking around disk I/O. +#[derive(Debug)] +pub(super) struct SessionFiles { + data: DataLogger, + protections: ProtectionsLogger, + orders: OrderLogger, + messages: MessagesLogger, +} + +impl SessionFiles { + /// Opens selected measurement files, connected boards' protection files, + /// and the two shared order/message files. Metadata is already prepared. + /// A session is not published as recording until all of these opens succeed. + pub fn open( + directory: &Path, + selection: &SessionSelection, + catalog: &Catalog, + ) -> Result { + Ok(Self { + data: DataLogger::open(directory, &selection.measurements, catalog)?, + protections: ProtectionsLogger::open(directory, &selection.connected_boards, catalog)?, + orders: OrderLogger::open(directory)?, + messages: MessagesLogger::open(directory)?, + }) + } + + /// Dispatches a decoded event without copying its packet values. + /// The catalog supplies board labels and packet definitions from the ADJ; + /// each format writer also checks the touched file's byte flush threshold. + pub fn write( + &mut self, + time: RecordTime, + record: &ToLogging, + threshold: u64, + catalog: &Catalog, + ) -> Result<(), Error> { + let notification = match record { + ToLogging::OrderSent { board, order, .. } => { + let to = match board { + Some(board) => catalog.board(*board)?.name.as_str(), + None => "all", + }; + return self.orders.write( + time, + order, + to, + catalog.order(*board, order)?, + threshold, + ); + } + ToLogging::Received(notification) => notification, + }; + let board = catalog.board(notification.board)?; + match ¬ification.event { + // Connection events have no row in the agreed CSV layouts. + Event::Connected | Event::Disconnected => Ok(()), + Event::Received(Packet::Data(packet)) => self.data.write( + time.instant, + board, + packet, + catalog.data(notification.board, packet.id)?, + threshold, + ), + Event::Received(Packet::Protection(packet)) => { + // The packet carries the triggered value and compound ID; + // its severity, limits and measurement come from the ADJ. + let (measurement, protection) = + catalog.protection(notification.board, packet.id)?; + self.protections.write( + time.instant, + board, + packet, + measurement, + protection, + threshold, + ) + } + Event::Received(Packet::Message(packet)) => self.messages.write( + time.instant, + board, + packet, + catalog.message_level(notification.board, packet.id)?, + threshold, + ), + Event::Received(Packet::Order(_)) => Ok(()), + } + } + + fn files_mut(&mut self) -> impl Iterator { + // Flatten the different registries so flushing has one error policy. + self.data + .files_mut() + .chain(self.protections.files_mut()) + .chain(std::iter::once(&mut self.orders.file)) + .chain(std::iter::once(&mut self.messages.file)) + } + + fn flush(&mut self) -> Vec { + // A threshold of one skips clean files while flushing every dirty one. + flush_files(self.files_mut(), 1) + } + + fn close(self) -> Vec { + // Consuming ownership prevents later writes. The helper attempts every + // close even when one fails, returning all errors rather than stopping + // at the first poisoned or unwritable file. + close_files( + self.data + .into_files() + .chain(self.protections.into_files()) + .chain(std::iter::once(self.orders.file)) + .chain(std::iter::once(self.messages.file)), + ) + } +} + +/// All recording state is local to this writer; observers receive snapshots. +struct Recording { + session: Session, + info: SessionInfo, + files: SessionFiles, + errors: Vec, +} + +impl Recording { + fn remember(&mut self, errors: impl IntoIterator) { + for error in errors { + let text = error_chain(&error); + if !self.errors.contains(&text) { + tracing::error!(session_id = self.info.id.get(), directory = %self.info.directory.display(), error = %text, "logging file operation failed"); + self.errors.push(text); + } + } + } +} + +struct Writer { + run: BackendRun, + input: mpsc::Receiver, + controls: mpsc::UnboundedReceiver, + /// event's ②: tells the operator when a session stops on its own. + notices: mpsc::Sender, + updates: watch::Sender, + status: Status, + catalog: Catalog, + options: WriterOptions, + active: Option, + next_id: u64, +} + +enum Step { + Control(Option), + Input(Option), + Flush, +} + +/// The runtime is created and dropped on this OS thread. Its timer and channel +/// waits stay asynchronous, while synchronous file operations stay off the +/// application's Tokio worker threads. +pub(super) fn run( + run: BackendRun, + input: mpsc::Receiver, + controls: mpsc::UnboundedReceiver, + notices: mpsc::Sender, + updates: watch::Sender, + catalog: Catalog, + options: WriterOptions, +) { + let _exit = ExitGuard(updates.clone()); + match tokio::runtime::Builder::new_current_thread() + .enable_time() + .build() + { + Ok(runtime) => runtime.block_on( + Writer { + run, + input, + controls, + notices, + updates, + catalog, + options, + status: Status::default(), + active: None, + next_id: 0, + } + .run(), + ), + Err(error) => { + tracing::error!(directory = %run.directory().display(), error = %error_chain(&error), "could not start logging writer runtime"); + updates.send_replace(Status { + phase: Phase::Closed, + last_error: Some(format!("couldn't start the logging timer runtime: {error}")), + ..Status::default() + }); + } + } +} + +impl Writer { + async fn run(mut self) { + let mut timer = tokio::time::interval(self.options.flush_interval); + timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + timer.tick().await; // Consume the interval's immediate first tick. + tracing::info!(directory = %self.run.directory().display(), queue_capacity = self.input.max_capacity(), flush_interval = ?self.options.flush_interval, flush_bytes = self.options.flush_bytes, "logging service ready"); + loop { + // Controls win over data, including when input is full. recv is + // cancellation-safe: an unselected branch does not steal a record. + let step = tokio::select! { + biased; + command = self.controls.recv() => Step::Control(command), + _ = timer.tick(), if self.active.is_some() => Step::Flush, + incoming = self.input.recv() => Step::Input(incoming), + }; + match step { + Step::Control(Some(Control::Play { selection, reply })) => { + let result = self.start(selection).await; + // Invalid selections never enter Starting and must not + // turn a rejected request into a recording failure. + if let Err(error) = &result + && self.status.phase == Phase::Starting + { + tracing::error!(directory = %self.run.directory().display(), error = %error_chain(error), "could not start logging session"); + self.status.phase = Phase::Inactive; + self.status.last_error = Some(error_chain(error)); + self.publish(); + } + let _ = reply.send(result); + } + Step::Control(Some(Control::Stop { reason, at, reply })) => { + let report = self.stop(reason, at).await; + let _ = reply.send(checked_report(report)); + } + Step::Control(Some(Control::Shutdown { at, reply })) => { + self.shutdown(at).await; + if let Some(reply) = reply { + let _ = reply.send(()); + } + break; + } + Step::Control(None) | Step::Input(None) => { + self.shutdown(SystemTime::now()).await; + break; + } + Step::Flush => { + if let Some(recording) = &mut self.active { + let errors = recording.files.flush(); + if !errors.is_empty() { + recording.remember(errors); + self.stop(StopReason::WriteError, SystemTime::now()).await; + } + } + } + Step::Input(Some(incoming)) => { + if self.write(&incoming, None) { + self.stop(StopReason::WriteError, SystemTime::now()).await; + } + } + } + } + } + + async fn start(&mut self, selection: SessionSelection) -> Result { + if let Some(recording) = &self.active { + return Ok(recording.info.clone()); + } + if let Err(error) = selection.validate(&self.catalog) { + tracing::warn!(error = %error_chain(&error), "logging session selection rejected"); + return Err(error); + } + let id = SessionId(self.next_id.checked_add(1).ok_or_else(|| { + tracing::error!("could not start logging session: session IDs exhausted"); + Error::SessionIdExhausted + })?); + self.next_id = id.0; + // Clear only the finite inactive backlog. New arrivals are not allowed + // to keep a start waiting forever, and older timestamps are also filtered. + let pending = self.input.len(); + for _ in 0..pending { + if self.input.recv().await.is_none() { + break; + } + } + self.status.phase = Phase::Starting; + self.status.last_error = None; + self.publish(); + let session = self.run.prepare_session(&selection.selected_variables)?; + let files = SessionFiles::open(session.directory(), &selection, &self.catalog)?; + let info = SessionInfo { + id, + directory: session.directory().to_path_buf(), + date: session.settings().date.clone(), + time_unit: session.settings().time_unit, + }; + self.active = Some(Recording { + session, + info: info.clone(), + files, + errors: Vec::new(), + }); + self.status.phase = Phase::Recording; + self.status.session = Some(info.clone()); + self.publish(); + tracing::info!(session_id = info.id.get(), directory = %info.directory.display(), measurements = selection.measurements.len(), boards = selection.connected_boards.len(), time_unit = ?info.time_unit, "logging session started"); + Ok(info) + } + + /// Returns true only for a write failure that requires an ordered stop. + fn write(&mut self, incoming: &ToLogging, cutoff: Option) -> bool { + let Some(recording) = &mut self.active else { + return false; + }; + let at = match incoming { + ToLogging::Received(notification) => notification.at, + ToLogging::OrderSent { at, .. } => *at, + }; + if cutoff.is_some_and(|cutoff| at > cutoff) { + return false; + } + let Ok(elapsed) = at.duration_since(recording.session.wall_origin()) else { + return false; + }; + match self.catalog.validate(incoming) { + Ok(false) => return false, + Err(error) => { + tracing::warn!(session_id = recording.info.id.get(), error = %error_chain(&error), "logging input discarded"); + return false; + } + Ok(true) => {} + } + let result = jiff::Timestamp::try_from(at) + .map_err(Error::from) + .and_then(|wall_time| { + recording.files.write( + RecordTime { + instant: recording.info.time_unit.convert(elapsed), + wall_time, + }, + incoming, + self.options.flush_bytes, + &self.catalog, + ) + }); + if let Err(error) = result { + recording.remember([error]); + return true; + } + false + } + + /// Drain the ready prefix observed at the stop boundary, never the + /// continuously growing tail. Reception timestamps after the caller's + /// cutoff are excluded from this session even if already queued. + async fn stop(&mut self, reason: StopReason, cutoff: SystemTime) -> Option { + if self.active.is_none() { + return self.status.last_stop.clone(); + } + self.status.phase = Phase::Stopping; + self.publish(); + let pending = self.input.len(); + for _ in 0..pending { + let Some(incoming) = self.input.recv().await else { + break; + }; + self.write(&incoming, Some(cutoff)); + } + if let Some(Recording { + info, + files, + mut errors, + .. + }) = self.active.take() + { + for error in files.close() { + let text = error_chain(&error); + if !errors.contains(&text) { + tracing::error!(session_id = info.id.get(), directory = %info.directory.display(), error = %text, "logging file close failed"); + errors.push(text); + } + } + let reason = if errors.is_empty() { + reason + } else { + StopReason::WriteError + }; + if let Some(error) = errors.first() { + self.status.last_error = Some(error.clone()); + if reason == StopReason::WriteError { + self.report_write_error(&info, error); + } + } + tracing::info!(session_id = info.id.get(), directory = %info.directory.display(), ?reason, errors = errors.len(), "logging session stopped after draining and closing files"); + self.status.last_stop = Some(StopReport { + session: info, + reason, + errors, + }); + self.status.phase = Phase::Inactive; + self.status.session = None; + self.publish(); + } + self.status.last_stop.clone() + } + + async fn shutdown(&mut self, cutoff: SystemTime) { + // Closing prevents new sends. Existing ready records are still drained; + // a normal session stop never closes this receiver. + self.input.close(); + self.controls.close(); + self.stop(StopReason::Shutdown, cutoff).await; + self.status.phase = Phase::Closed; + self.publish(); + tracing::info!(directory = %self.run.directory().display(), failed = self.status.last_error.is_some(), "logging service closed"); + } + + fn publish(&self) { + self.updates.send_replace(self.status.clone()); + } + + /// Tells the operator, through event's ②, that a session stopped on its + /// own. Never waits for room: event's router may be waiting for room in + /// this writer's input at the same time, and then neither would move. + fn report_write_error(&self, session: &SessionInfo, error: &str) { + let text = format!("recording stopped, its files may be incomplete: {error}"); + if let Err(failed) = self + .notices + .try_send(Notice::now(NoticeKind::Warning, None, text)) + { + tracing::warn!(session_id = session.id.get(), reason = %failed, "could not tell the front that recording stopped"); + } + } +} + +fn error_chain(error: &dyn std::error::Error) -> String { + let mut text = error.to_string(); + let mut source = error.source(); + while let Some(error) = source { + text.push_str(": "); + text.push_str(&error.to_string()); + source = error.source(); + } + text +} + +/// Dropping pending control replies releases their callers on an unexpected +/// exit. The status signal records failure rather than claiming a clean drain. +struct ExitGuard(watch::Sender); + +impl Drop for ExitGuard { + fn drop(&mut self) { + let mut status = self.0.borrow().clone(); + if status.phase != Phase::Closed { + tracing::error!(session_id = status.session.as_ref().map(|session| session.id.get()), phase = ?status.phase, "logging writer exited unexpectedly"); + status.phase = Phase::Closed; + status.last_error = Some("logging writer exited unexpectedly".into()); + self.0.send_replace(status); + } + } +} + +#[cfg(test)] +mod tests; diff --git a/backend/crates/station/src/logging/writer/tests.rs b/backend/crates/station/src/logging/writer/tests.rs new file mode 100644 index 000000000..437e899e0 --- /dev/null +++ b/backend/crates/station/src/logging/writer/tests.rs @@ -0,0 +1,409 @@ +use std::{ + fs, + io::{self, Write}, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, +}; + +use software_core::{ + logger::CsvFile, + model::{AdjId, MessagePacket, OrderPacket, Protection, ProtectionPacket, Value}, + net::Event, +}; +use tokio::sync::oneshot; + +use super::*; +use crate::logging::{Config, test_support::*}; + +fn time(wall_time: &str) -> Result { + Ok(RecordTime { + instant: u128::MAX, + wall_time: wall_time.parse()?, + }) +} + +#[test] +fn native_csv_formats_preserve_fields_without_headers() -> TestResult { + let temp = tempfile::tempdir()?; + let (pod_data, index) = definitions(); + let catalog = Catalog::new(pod_data, index); + let mut files = SessionFiles::open(temp.path(), &selection(), &catalog)?; + let mut stamp = time("2026-07-15T13:30:05Z")?; + stamp.instant = 35000; + files.write(stamp, &data(SystemTime::now(), 12.5), u64::MAX, &catalog)?; + files.write(stamp, &protection(LCU, ABOVE, 55.0), u64::MAX, &catalog)?; + files.write(stamp, &protection(LCU, RANGE, 105.0), u64::MAX, &catalog)?; + files.write( + stamp, + &received( + LCU, + SystemTime::now(), + Event::Received(Packet::Message(MessagePacket { + id: FAULT_MESSAGE, + timestamp: short_timestamp(), + origin: "control.cpp:123".into(), + message: "failed, \"overload\"\nagain".into(), + })), + ), + u64::MAX, + &catalog, + )?; + assert!(files.close().is_empty()); + assert_eq!( + fs::read_to_string(temp.path().join("data/LCU/speed.csv"))?, + "35000,LCU,backend,12.5\n" + ); + assert!(!temp.path().join("data/LCU/unselected.csv").exists()); + // These notifications contain no confirmed outgoing order. + assert!(fs::read(temp.path().join("order/order.csv"))?.is_empty()); + assert_eq!( + fs::read_to_string(temp.path().join("protections/LCU.csv"))?, + format!( + "35000,LCU,backend,{},fault,above,50,,3002,55,500ms\n35000,LCU,backend,{},warning,range,0,100,3002,105,0\n", + ABOVE.0, RANGE.0 + ) + ); + assert_eq!( + fs::read_to_string(temp.path().join("messages/messages.csv"))?, + "35000,LCU,backend,LCU,control.cpp:123,fault,\"failed, \"\"overload\"\"\nagain\"\n" + ); + Ok(()) +} + +#[test] +fn order_payload_offsets_and_large_instants_are_preserved() -> TestResult { + let temp = tempfile::tempdir()?; + let mut orders = OrderLogger::open(temp.path())?; + let (_, index) = definitions(); + let mut summer = time("2026-07-15T13:30:05Z")?; + summer.instant = 35000; + let order = OrderPacket::new( + AdjId(2003), + vec![ + Value::Number(1.5), + Value::Bool(true), + Value::Enum("run, \"fast\"\nnext".into()), + ], + ); + orders.write(summer, &order, "LCU", index.packet(order.id), u64::MAX)?; + orders.write( + time("2026-11-27T14:30:05Z")?, + &OrderPacket::new(AdjId(2001), vec![]), + "LCU", + index.packet(AdjId(2001)), + u64::MAX, + )?; + orders.file.close()?; + let parameters = serde_json::json!([ + {"id":4001,"alias":"speed_command","value":1.5}, + {"id":4000,"alias":"enabled_command","value":true}, + {"id":4002,"alias":"mode_command","value":"run, \"fast\"\nnext"} + ]); + let contents = fs::read_to_string(temp.path().join("order/order.csv"))?; + let lines: Vec<_> = contents.lines().collect(); + assert_eq!(lines.len(), 2); + // Extract the seven-column layout independently: verify the name's CSV + // quoting, decode the array cell, and check the timestamp separately. + let prefix = "35000,backend,LCU,2003,\"Configure, \"\"drive\"\"\",\""; + let suffix = "\",2026-07-15T15-30-05+02:00"; + let cell = lines[0] + .strip_prefix(prefix) + .ok_or("incorrect order/name columns")? + .strip_suffix(suffix) + .ok_or("incorrect timestamp column")?; + let decoded: serde_json::Value = serde_json::from_str(&cell.replace("\"\"", "\""))?; + assert_eq!(decoded, parameters); + assert_eq!( + lines[1], + format!( + "{},backend,LCU,2001,Brake,[],2026-11-27T15-30-05+01:00", + u128::MAX + ) + ); + Ok(()) +} + +#[test] +fn confirmed_broadcast_orders_use_all_as_destination() -> TestResult { + let temp = tempfile::tempdir()?; + let (pod_data, index) = definitions(); + let catalog = Catalog::new(pod_data, index); + let mut files = SessionFiles::open(temp.path(), &selection(), &catalog)?; + let order = ToLogging::OrderSent { + at: SystemTime::now(), + board: None, + order: OrderPacket::new(AdjId(0), vec![]), + }; + assert!(catalog.validate(&order)?); + files.write(time("2026-11-27T14:30:05Z")?, &order, u64::MAX, &catalog)?; + assert!(files.close().is_empty()); + assert_eq!( + fs::read_to_string(temp.path().join("order/order.csv"))?, + format!( + "{},backend,all,0,Fault,[],2026-11-27T15-30-05+01:00\n", + u128::MAX + ) + ); + Ok(()) +} + +#[test] +fn non_finite_order_values_are_rejected_before_starting_a_csv_row() -> TestResult { + let temp = tempfile::tempdir()?; + let mut orders = OrderLogger::open(temp.path())?; + let (_, index) = definitions(); + for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + assert!(matches!( + orders.write( + time("2026-11-27T14:30:05Z")?, + &OrderPacket::new(AdjId(2002), vec![Value::Number(value)]), + "LCU", + index.packet(AdjId(2002)), + u64::MAX + ), + Err(Error::OrderPayload(_)) + )); + } + orders.file.close()?; + assert!(fs::read(temp.path().join("order/order.csv"))?.is_empty()); + Ok(()) +} + +#[test] +fn close_attempts_every_file_even_when_one_flush_fails() -> TestResult { + struct Destination { + flushed: Arc, + fail: bool, + } + impl Write for Destination { + fn write(&mut self, bytes: &[u8]) -> io::Result { + Ok(bytes.len()) + } + fn flush(&mut self) -> io::Result<()> { + self.flushed.store(true, Ordering::SeqCst); + if self.fail { + Err(io::Error::other("disk full")) + } else { + Ok(()) + } + } + } + let first = Arc::new(AtomicBool::new(false)); + let second = Arc::new(AtomicBool::new(false)); + let files = [ + CsvFile::new( + Destination { + flushed: first.clone(), + fail: true, + }, + "first", + &[], + )?, + CsvFile::new( + Destination { + flushed: second.clone(), + fail: false, + }, + "second", + &[], + )?, + ]; + assert_eq!(close_files(files.into_iter()).len(), 1); + assert!(first.load(Ordering::SeqCst)); + assert!(second.load(Ordering::SeqCst)); + Ok(()) +} + +#[test] +fn unexpected_exit_publishes_failure() { + let (updates, status) = watch::channel(Status { + phase: Phase::Starting, + ..Status::default() + }); + drop(ExitGuard(updates)); + assert_eq!(status.borrow().phase, Phase::Closed); + assert!( + status + .borrow() + .last_error + .as_deref() + .is_some_and(|error| error.contains("unexpectedly")) + ); +} + +#[test] +fn dropping_pending_controls_releases_start_replies() -> TestResult { + let (sender, receiver) = mpsc::unbounded_channel(); + let (reply, mut response) = oneshot::channel(); + sender.send(Control::Play { + selection: selection(), + reply, + })?; + drop(receiver); + assert!(matches!( + response.try_recv(), + Err(oneshot::error::TryRecvError::Closed) + )); + Ok(()) +} + +#[tokio::test] +async fn events_use_at_for_elapsed_and_order_wall_timestamps() -> TestResult { + let temp = tempfile::tempdir()?; + let run = BackendRun::new( + Config { + logging_path: temp.path().into(), + ..Config::default() + }, + "adj", + )?; + let (pod_data, index) = definitions(); + let (_sender, input) = mpsc::channel(16); + let (_controls, controls) = mpsc::unbounded_channel(); + let (notices, _notices) = mpsc::channel(1); + let (updates, _status) = watch::channel(Status::default()); + let mut writer = Writer { + run, + input, + controls, + notices, + updates, + status: Status::default(), + catalog: Catalog::new(pod_data, index), + options: WriterOptions::default(), + active: None, + next_id: 0, + }; + let session = writer.start(selection()).await?; + let origin = writer + .active + .as_ref() + .ok_or("session was not opened")? + .session + .wall_origin(); + let at = origin + Duration::from_millis(35); + let order = |at| ToLogging::OrderSent { + at, + board: Some(LCU), + order: OrderPacket::new(AdjId(2001), vec![]), + }; + // An old confirmation cannot leak into this session. A later one must + // use its own stamp, even if the writer processes it immediately. + assert!(!writer.write(&order(origin - Duration::from_secs(1)), None)); + assert!(!writer.write(&order(at), None)); + assert!(!writer.write(&data(origin - Duration::from_secs(1), 999.0), None)); + assert!(!writer.write(&data(at, 42.0), None)); + writer.stop(StopReason::Requested, at).await; + assert_eq!( + fs::read_to_string(session.directory.join("data/LCU/speed.csv"))?, + "35000,LCU,backend,42\n" + ); + let timestamp = jiff::Timestamp::try_from(at)? + .in_tz("Europe/Madrid")? + .strftime("%Y-%m-%dT%H-%M-%S%:z") + .to_string(); + assert_eq!( + fs::read_to_string(session.directory.join("order/order.csv"))?, + format!("35000,backend,LCU,2001,Brake,[],{timestamp}\n") + ); + Ok(()) +} + +#[test] +fn protection_time_preserves_the_adj_duration_and_its_precision() -> TestResult { + let temp = tempfile::tempdir()?; + let (pod_data, index) = definitions(); + let catalog = Catalog::new(pod_data, index); + let mut logger = ProtectionsLogger::open(temp.path(), &[LCU], &catalog)?; + let (measurement, definition) = catalog.protection(LCU, ABOVE)?; + let packet = ProtectionPacket { + id: ABOVE, + timestamp: short_timestamp(), + value: Value::Number(55.0), + }; + let cases = [ + (Duration::ZERO, "0"), + (Duration::from_millis(500), "500ms"), + (Duration::from_secs(1), "1000ms"), + (Duration::from_micros(1500), "1500us"), + (Duration::from_nanos(1501), "1501ns"), + (Duration::from_nanos(1), "1ns"), + ]; + for (time, _) in cases { + // Changing the definition's duration must change the final CSV cell; + // the instant and timestamp in the received event stay unchanged. + let protection = Protection { + time, + ..*definition + }; + logger.write( + 35000, + catalog.board(LCU)?, + &packet, + measurement, + &protection, + u64::MAX, + )?; + } + assert!(close_files(logger.into_files()).is_empty()); + let contents = fs::read_to_string(temp.path().join("protections/LCU.csv"))?; + assert_eq!(contents.lines().count(), cases.len()); + for (row, (_, expected)) in contents.lines().zip(cases) { + assert_eq!(row.split(',').count(), 11); + assert!(row.starts_with("35000,LCU,backend,")); + assert_eq!(row.rsplit(',').next(), Some(expected)); + } + Ok(()) +} + +#[test] +fn orders_require_matching_index_metadata_before_writing() -> TestResult { + let temp = tempfile::tempdir()?; + let (pod_data, index) = definitions(); + let catalog = Catalog::new(pod_data, index); + let mut files = SessionFiles::open(temp.path(), &selection(), &catalog)?; + let sent = |board, id, values| ToLogging::OrderSent { + at: SystemTime::now(), + board, + order: OrderPacket::new(AdjId(id), values), + }; + assert!(matches!( + catalog.validate(&sent(Some(LCU), 999, vec![])), + Err(Error::UnknownPacket(_)) + )); + assert!(matches!( + catalog.validate(&sent(Some(LCU), TELEMETRY.0, vec![])), + Err(Error::UnexpectedPacketType(_)) + )); + assert!(matches!( + catalog.validate(&sent(Some(PCU), 2000, vec![Value::Bool(true)])), + Err(Error::PacketBoardMismatch { .. }) + )); + assert!( + catalog + .validate(&sent(None, 2000, vec![Value::Bool(true)])) + .is_err() + ); + assert!(matches!( + catalog.validate(&sent(None, 0, vec![Value::Bool(true)])), + Err(Error::MeasurementCount(_)) + )); + // Too few and too many values must fail before zip could silently drop a + // parameter or its value, including at the file writer's own boundary. + for values in [vec![], vec![Value::Bool(true), Value::Bool(false)]] { + let incoming = sent(Some(LCU), 2000, values); + assert!(matches!( + catalog.validate(&incoming), + Err(Error::MeasurementCount(_)) + )); + assert!(matches!( + files.write(time("2026-07-15T13:30:05Z")?, &incoming, u64::MAX, &catalog), + Err(Error::MeasurementCount(_)) + )); + } + assert!(files.close().is_empty()); + assert!(fs::read(temp.path().join("order/order.csv"))?.is_empty()); + Ok(()) +} diff --git a/backend/crates/station/src/websocket.rs b/backend/crates/station/src/websocket.rs index 2d49ed89f..0ad1907fb 100644 --- a/backend/crates/station/src/websocket.rs +++ b/backend/crates/station/src/websocket.rs @@ -18,7 +18,7 @@ use tokio::{ use self::broker::Subscriber; use self::handler::SessionEnd; -pub(crate) use self::order::OrderForwarder; +pub use self::order::OrderForwarder; pub mod broker; mod error; @@ -39,8 +39,11 @@ 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 { +pub enum LoggerCommand { + /// `logger/enable`: start (`true`) or stop (`false`) recording. Enable(LoggerEnable), + /// `logger/variables`: the measurements for the next session, as + /// `"/"`. Variables(LoggerVariables), } @@ -48,9 +51,9 @@ pub(crate) enum LoggerCommand { #[derive(Debug, Clone, Default)] pub struct Commands { /// Validates frontend orders before queuing them for the vehicle. - pub(crate) orders: Option, + pub orders: Option, /// Queues recording and variable selection requests for the logger. - pub(crate) logger: Option>, + pub logger: Option>, } /// Topics a frontend can subscribe to. Commands and heartbeats are routed by the reader. diff --git a/backend/crates/station/src/websocket/order.rs b/backend/crates/station/src/websocket/order.rs index c1805ec4d..fdc9eac3d 100644 --- a/backend/crates/station/src/websocket/order.rs +++ b/backend/crates/station/src/websocket/order.rs @@ -11,13 +11,14 @@ use crate::payload::{OrderField, OrderSend}; /// Validates frontend requests against the ADJ and forwards them to the vehicle. #[derive(Debug, Clone)] -pub(crate) struct OrderForwarder { +pub struct OrderForwarder { index: Arc, orders: mpsc::Sender, } impl OrderForwarder { - pub(crate) fn new(index: Arc, orders: mpsc::Sender) -> Self { + /// Validates against `index` and queues on `orders` (event's ⑦). + pub fn new(index: Arc, orders: mpsc::Sender) -> Self { Self { index, orders } }