From ceb77c3add29e2b449575fe93f5b702fcfcd9bec Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 27 Nov 2026 01:41:57 +0100 Subject: [PATCH 01/19] feat(backend, logging): logging module initial structure --- backend/crates/station/Cargo.toml | 2 +- backend/crates/station/src/logging.rs | 27 +++++++++++++++++++ backend/crates/station/src/logging/data.rs | 9 +++++++ backend/crates/station/src/logging/error.rs | 6 +++++ backend/crates/station/src/logging/event.rs | 8 ++++++ .../crates/station/src/logging/messages.rs | 8 ++++++ backend/crates/station/src/logging/order.rs | 9 +++++++ .../crates/station/src/logging/protections.rs | 11 ++++++++ backend/crates/station/src/logging/session.rs | 14 ++++++++++ .../crates/station/src/logging/settings.rs | 10 +++++++ backend/crates/station/src/logging/writer.rs | 14 ++++++++++ 11 files changed, 117 insertions(+), 1 deletion(-) create mode 100644 backend/crates/station/src/logging.rs create mode 100644 backend/crates/station/src/logging/data.rs create mode 100644 backend/crates/station/src/logging/error.rs create mode 100644 backend/crates/station/src/logging/event.rs create mode 100644 backend/crates/station/src/logging/messages.rs create mode 100644 backend/crates/station/src/logging/order.rs create mode 100644 backend/crates/station/src/logging/protections.rs create mode 100644 backend/crates/station/src/logging/session.rs create mode 100644 backend/crates/station/src/logging/settings.rs create mode 100644 backend/crates/station/src/logging/writer.rs diff --git a/backend/crates/station/Cargo.toml b/backend/crates/station/Cargo.toml index 9eed62cbe..3dc8f145c 100644 --- a/backend/crates/station/Cargo.toml +++ b/backend/crates/station/Cargo.toml @@ -9,7 +9,7 @@ authors.workspace = true repository.workspace = true [dependencies] -software-core = { workspace = true, features = ["net", "git", "http"] } +software-core = { workspace = true, features = ["net", "git", "http", "logger"] } serde.workspace = true thiserror.workspace = true tokio.workspace = true diff --git a/backend/crates/station/src/logging.rs b/backend/crates/station/src/logging.rs new file mode 100644 index 000000000..816819c9d --- /dev/null +++ b/backend/crates/station/src/logging.rs @@ -0,0 +1,27 @@ +//! Backend recording policy, built on `software_core::logger`. +//! +//! This is the module scaffold; recording and frontend integration are not +//! implemented yet. The file writers stay in `software_core::logger`; this +//! module will decide what to record, where it belongs and when to flush it. +//! +//! Planned 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 and enables event admission. +//! - `stop` stops admission, drains accepted events and closes session files. +//! - `emergency_stop` performs the same drain during backend shutdown, then +//! finishes the writer and flushes the backend trace. +//! +//! Session state, event admission and stop ordering must be coordinated so +//! that an accepted event cannot leak into a later session. The frontend +//! receives success only after the requested transition has completed. + +mod data; +mod error; +mod event; +mod messages; +mod order; +mod protections; +mod session; +mod settings; +mod writer; diff --git a/backend/crates/station/src/logging/data.rs b/backend/crates/station/src/logging/data.rs new file mode 100644 index 000000000..d3b3dcfa8 --- /dev/null +++ b/backend/crates/station/src/logging/data.rs @@ -0,0 +1,9 @@ +//! Measurement recording under `data//.csv`. +//! +//! One directory per connected board and one CSV per selected measurement, +//! named with its textual identifier. Files have no header. Columns, in order: +//! `instant,from,to,value`. +//! +//! This component will own the measurement `software_core::logger::CsvFile` +//! handles and translate typed events into rows, reusing the logger's CSV +//! escaping, buffering and explicit flush/close operations. diff --git a/backend/crates/station/src/logging/error.rs b/backend/crates/station/src/logging/error.rs new file mode 100644 index 000000000..adf643342 --- /dev/null +++ b/backend/crates/station/src/logging/error.rs @@ -0,0 +1,6 @@ +//! Errors for recording setup, lifecycle transitions and the writer. +//! +//! Errors will preserve file context from `software_core::logger` and report +//! queue saturation, writer failure and invalid session transitions. Shutdown +//! must attempt to close all files even if closing one of them fails, and +//! return failures to the caller rather than report a successful stop. diff --git a/backend/crates/station/src/logging/event.rs b/backend/crates/station/src/logging/event.rs new file mode 100644 index 000000000..2d00ab80e --- /dev/null +++ b/backend/crates/station/src/logging/event.rs @@ -0,0 +1,8 @@ +//! Typed recording events for measurements, orders, protections and messages. +//! +//! Events will carry their recording session identity and the elapsed time +//! captured at reception or order execution, before entering the writer queue. +//! Queue latency must not become part of the recorded `instant`. +//! +//! Order events also capture wall-clock time for the timestamp column. Event +//! types and the concrete producer API remain to be implemented. diff --git a/backend/crates/station/src/logging/messages.rs b/backend/crates/station/src/logging/messages.rs new file mode 100644 index 000000000..a35de950e --- /dev/null +++ b/backend/crates/station/src/logging/messages.rs @@ -0,0 +1,8 @@ +//! Message recording in the session's single `messages/messages.csv` file. +//! +//! Columns, in order: `instant,from,to,board,source,severity`. +//! `board` identifies the board that emitted the message; `source` combines +//! file and line in one field when applicable to the message type. +//! +//! This component will own a `software_core::logger::CsvFile` and format rows. +//! Header policy and the exact representation of `source` remain to be defined. diff --git a/backend/crates/station/src/logging/order.rs b/backend/crates/station/src/logging/order.rs new file mode 100644 index 000000000..e39a6d8f6 --- /dev/null +++ b/backend/crates/station/src/logging/order.rs @@ -0,0 +1,9 @@ +//! Order recording in the session's single `order/order.csv` file. +//! +//! Columns, in order: `instant,from,to,id,payload,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). +//! +//! This component will own a `software_core::logger::CsvFile` and format rows. +//! Header policy and the exact payload representation remain to be defined. diff --git a/backend/crates/station/src/logging/protections.rs b/backend/crates/station/src/logging/protections.rs new file mode 100644 index 000000000..7b476e47e --- /dev/null +++ b/backend/crates/station/src/logging/protections.rs @@ -0,0 +1,11 @@ +//! Protection recording in `protections/.csv`, one per board. +//! +//! Columns, in order: +//! `instant,from,to,protection_id,severity,protection_type,threshold_1,threshold_2,measurement_id,value,time`. +//! The second threshold is empty unless the protection is a range. `value` +//! is the measurement value that triggered the protection. For a +//! `timeacumulation` protection, `time` is a string containing time and units; +//! for other protection types it is `0`. +//! +//! This component will own the `software_core::logger::CsvFile` handles and +//! format rows. Header policy remains to be defined. diff --git a/backend/crates/station/src/logging/session.rs b/backend/crates/station/src/logging/session.rs new file mode 100644 index 000000000..a7bef0f8a --- /dev/null +++ b/backend/crates/station/src/logging/session.rs @@ -0,0 +1,14 @@ +//! 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/`. +//! +//! A monotonic `std::time::Instant` will establish the session's zero point. +//! Recorded elapsed times use the configured time unit; the first event need +//! not occur at zero. Wall-clock time is used separately for directory names +//! and order timestamps. Directory creation must never overwrite an earlier +//! session when two starts fall in the same second. +//! +//! Planned states: inactive, starting, recording and stopping. A normal stop +//! preserves the backend-wide `others/` files for subsequent sessions. diff --git a/backend/crates/station/src/logging/settings.rs b/backend/crates/station/src/logging/settings.rs new file mode 100644 index 000000000..369e82d32 --- /dev/null +++ b/backend/crates/station/src/logging/settings.rs @@ -0,0 +1,10 @@ +//! 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. +//! 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 will be written through `software_core::logger::write_json` or +//! `software_core::logger::JsonDocument`, allowing the metadata to grow later. diff --git a/backend/crates/station/src/logging/writer.rs b/backend/crates/station/src/logging/writer.rs new file mode 100644 index 000000000..bf9c898e8 --- /dev/null +++ b/backend/crates/station/src/logging/writer.rs @@ -0,0 +1,14 @@ +//! Dedicated synchronous writer and its bounded event queue. +//! +//! One writer thread will own the session's four recording components and +//! perform their blocking `software_core::logger` operations away from the +//! async network tasks. Keep files open for the session and reuse their +//! existing buffers; flush periodically and according to bytes_since_flush. +//! +//! Admission and control commands must establish a session boundary: stop +//! rejects new events for that session, drains every accepted event, attempts +//! to close every session file and acknowledges completion. Queue saturation +//! must be reported explicitly rather than silently dropping events. +//! +//! Backend trace output has a separate lifetime from recording sessions. It +//! remains active between sessions and is flushed at the end of shutdown. From 667b6609eb7168e1b19bf5055c43752779954fbd Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 27 Nov 2026 14:46:00 +0100 Subject: [PATCH 02/19] docs(backend, logging): create README.md and explanation of module workflow --- backend/crates/station/src/logging/README.md | 396 +++++++++++++++++++ 1 file changed, 396 insertions(+) create mode 100644 backend/crates/station/src/logging/README.md diff --git a/backend/crates/station/src/logging/README.md b/backend/crates/station/src/logging/README.md new file mode 100644 index 000000000..ac3a61966 --- /dev/null +++ b/backend/crates/station/src/logging/README.md @@ -0,0 +1,396 @@ +# 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). + +## Current Status + +The module currently consists of a scaffold with documented responsibilities. +It is declared in `main.rs`, and `station` enables the `logger` feature of +`software-core`. + +The logging service, control functions, writer, event formats, and integration +with the frontend and backend startup are not implemented yet. The following +sections describe the agreed requirements and planned design, rather than +features that are already operational. + +## 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 +/ +└── 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. + +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. Handling another `play()` while a session is active +remains undecided; ignoring it has been proposed to prevent a double click +from truncating an ongoing session. + +## 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 will be written using `logger::write_json` or `logger::JsonDocument`. + +## 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"`. + +A monotonic clock (`std::time::Instant`) is planned as the session's time +origin. The instant must be captured when the event is received, before +queuing it, so that writing delays do not change the recorded time. + +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 connected board, using its name. It contains +one CSV per selected measurement, named after its string ID: + +```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,payload,timestamp +``` + +| Field | Content | +| --- | --- | +| `instant` | Time since the session started, in `time_unit`. | +| `from` | Order source. | +| `to` | Order destination. | +| `id` | Order ID. | +| `payload` | JSON received from the frontend over WebSocket, preserved as text. | +| `timestamp` | Order date and time, using the format and offset described above. | + +An order is recorded **when it is received from the frontend**. Recording does +not wait for it to be sent to the board or for execution confirmation. Its +times are captured at that point of reception. + +### 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` | Timing result sent by the board for `timeacumulation`, as a string containing time and units; `0` for other types. | + +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 `timeacumulation` data comes from the board. It is not calculated from the +session clock or `time_unit`; its extraction remains to be specified when +integrating the received packet with recording. + +### 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 planned functions are `play()`, `stop()`, and `emergency_stop()`. Their +signatures are not implemented yet, and no WebSocket control protocol has +been defined. + +### play() + +Prepares a new session's directory, settings, variable selection, and files. +Establishes the time origin and starts accepting records once the session +is ready. + +The planned states are: + +```text +Inactive -> Starting -> Recording -> Stopping -> Inactive +``` + +### stop() + +Stops the session in this order: + +1. Stops accepting new records for that session. +2. Processes all events already accepted into the queue. +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. + +### 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. + +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 planned design uses a dedicated thread for synchronous +`software_core::logger` writes, separate from asynchronous network tasks: + +```text +Event reception + | + v +Capture instant and associate with session + | + v +Queue with limited capacity + | + v +Writer thread and format components + | + v +software_core::logger + | + v +Buffered files +``` + +The writer will own the files. It will keep them open throughout the session +and reuse the buffers already provided by `logger`, avoiding opening, writing, +and closing a file for every record. + +Buffers are planned to be flushed periodically and when a byte threshold is +reached, using `bytes_since_flush()`. Exact capacities and intervals will be +chosen during implementation. Stopping must explicitly call +`flush()`/`close()` and report errors, rather than relying solely on `Drop`. + +### Queue Saturation + +If records arrive faster than they can be written for long enough to fill +the queue, the agreed behavior is to **stop logging and notify the frontend**: + +1. Stop accepting new records. +2. Write records that have already been accepted. +3. Flush and close the session files. +4. Indicate that the session ended because of saturation. + +The backend continues running. Records must not keep being silently dropped +while the session is presented as active. + +A write error must be reported and cannot be treated as a successful stop. +The exact policy for disk failures and frontend status messages remains +undecided. + +## 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 | Planned responsibility | +| --- | --- | +| `../logging.rs` | Logging service, coordination, and control API. | +| `session.rs` | Identity, paths, clock, and state of each session. | +| `settings.rs` | Backend run and session metadata. | +| `event.rs` | Typed events with their instant and target session. | +| `writer.rs` | Bounded queue, writer thread, flushing, and orderly shutdown. | +| `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, queue, 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 frontend control. +- Final position of the text column in `messages.csv`. +- Behavior of repeated `play()` calls during an active session. +- Disconnection stop rule when multiple frontends are connected. +- Write error policy and frontend notification format. +- Queue/buffer capacities, flush intervals, and configuration parameters. From db6d981fe7354a2b4e9c44bb6239321ce0c0f6fc Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 27 Nov 2026 15:15:04 +0100 Subject: [PATCH 03/19] feat(backend, logging): create directories when the backend is started and when a logging session is started --- backend/Cargo.lock | 3 + backend/Cargo.toml | 1 + backend/crates/station/Cargo.toml | 4 + backend/crates/station/src/lib.rs | 2 + backend/crates/station/src/logging.rs | 20 +- backend/crates/station/src/logging/error.rs | 30 +++ backend/crates/station/src/logging/session.rs | 225 +++++++++++++++++- .../crates/station/src/logging/settings.rs | 75 +++++- 8 files changed, 348 insertions(+), 12 deletions(-) diff --git a/backend/Cargo.lock b/backend/Cargo.lock index e09a599b4..ef89cdfbe 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", @@ -2959,9 +2960,11 @@ name = "station" version = "0.1.0" dependencies = [ "axum", + "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/station/Cargo.toml b/backend/crates/station/Cargo.toml index 3dc8f145c..05d29efb8 100644 --- a/backend/crates/station/Cargo.toml +++ b/backend/crates/station/Cargo.toml @@ -10,6 +10,7 @@ repository.workspace = true [dependencies] software-core = { workspace = true, features = ["net", "git", "http", "logger"] } +jiff.workspace = true serde.workspace = true thiserror.workspace = true tokio.workspace = true @@ -21,5 +22,8 @@ tower = "0.5.3" axum = { version = "0.8.9", features = ["ws", "http1", "http2"] } tower-http = { version = "0.6.11", features = ["cors", "set-header"] } +[dev-dependencies] +tempfile = "3.27" + [lints] workspace = true diff --git a/backend/crates/station/src/lib.rs b/backend/crates/station/src/lib.rs index 9eb696501..380d13823 100644 --- a/backend/crates/station/src/lib.rs +++ b/backend/crates/station/src/lib.rs @@ -7,6 +7,8 @@ //! - [`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. pub mod event; pub mod http; +pub mod logging; diff --git a/backend/crates/station/src/logging.rs b/backend/crates/station/src/logging.rs index 816819c9d..902d90cb3 100644 --- a/backend/crates/station/src/logging.rs +++ b/backend/crates/station/src/logging.rs @@ -1,16 +1,19 @@ //! Backend recording policy, built on `software_core::logger`. //! -//! This is the module scaffold; recording and frontend integration are not -//! implemented yet. The file writers stay in `software_core::logger`; this -//! module will decide what to record, where it belongs and when to flush it. +//! Configuration, run directories, session metadata and clocks are implemented. +//! Recording, the writer and frontend integration are not implemented yet. +//! 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`. //! //! Planned 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 and enables event admission. //! - `stop` stops admission, drains accepted events and closes session files. -//! - `emergency_stop` performs the same drain during backend shutdown, then -//! finishes the writer and flushes the backend trace. +//! - `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. //! //! Session state, event admission and stop ordering must be coordinated so //! that an accepted event cannot leak into a later session. The frontend @@ -25,3 +28,10 @@ mod protections; mod session; mod settings; mod writer; + +pub use error::Error; +pub use session::{BackendRun, Session}; +pub use settings::{Config, Settings, TimeUnit}; + +#[cfg(test)] +mod tests; diff --git a/backend/crates/station/src/logging/error.rs b/backend/crates/station/src/logging/error.rs index adf643342..52700c64e 100644 --- a/backend/crates/station/src/logging/error.rs +++ b/backend/crates/station/src/logging/error.rs @@ -4,3 +4,33 @@ //! queue saturation, writer failure and invalid session transitions. Shutdown //! must attempt to close all files even if closing one of them fails, and //! return failures to the caller rather than report a successful stop. + +use std::{io, path::PathBuf}; + +/// Errors preparing logging settings, directories and sessions. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// 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/session.rs b/backend/crates/station/src/logging/session.rs index a7bef0f8a..060bd068e 100644 --- a/backend/crates/station/src/logging/session.rs +++ b/backend/crates/station/src/logging/session.rs @@ -2,13 +2,230 @@ //! //! 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/`. +//! `logger_settings.json` and `data/`, `protections/`, `order/`, `messages/`. //! -//! A monotonic `std::time::Instant` will establish the session's zero point. +//! A monotonic `std::time::Instant` establishes the session's zero point. //! Recorded elapsed times use the configured time unit; the first event need //! not occur at zero. Wall-clock time is used separately for directory names -//! and order timestamps. Directory creation must never overwrite an earlier -//! session when two starts fall in the same second. +//! and order timestamps. A new session with an existing directory name +//! overwrites that session, 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::Instant, +}; + +use jiff::Timestamp; +use serde::Serialize; +use serde_json::Value; +use software_core::logger::write_json; + +use super::{Config, Error, Settings}; + +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 future 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 future 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(), Instant::now()) + } + + /// Captures the wall and monotonic clocks at the same session boundary. + fn prepare_session_at( + &mut self, + selected_variables: impl Serialize, + started_at: Timestamp, + clock_origin: Instant, + ) -> 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, + clock_origin, + }) + } +} + +/// Prepared session metadata and its monotonic clock; no CSVs are open yet. +#[derive(Debug)] +pub struct Session { + directory: PathBuf, + metadata: SessionSettings, + clock_origin: Instant, +} + +#[derive(Debug, Serialize)] +struct SessionSettings { + #[serde(flatten)] + settings: Settings, + selected_variables: Value, +} + +impl Session { + /// 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 + } + + /// Elapsed time for an event captured before it enters the writer queue. + /// + /// An event predating this session returns `None`, not a fabricated zero. + /// The future service must also check the event's session identity. + pub fn instant_at(&self, received_at: Instant) -> Option { + received_at + .checked_duration_since(self.clock_origin) + .map(|elapsed| self.metadata.settings.time_unit.convert(elapsed)) + } + + /// Current elapsed session time in the configured unit. + pub fn elapsed(&self) -> u128 { + self.metadata + .settings + .time_unit + .convert(self.clock_origin.elapsed()) + } +} + +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/settings.rs b/backend/crates/station/src/logging/settings.rs index 369e82d32..9162897b0 100644 --- a/backend/crates/station/src/logging/settings.rs +++ b/backend/crates/station/src/logging/settings.rs @@ -1,10 +1,79 @@ -//! Backend and recording-session `logger-settings.json` metadata. +//! 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 will be written through `software_core::logger::write_json` or -//! `software_core::logger::JsonDocument`, allowing the metadata to grow later. +//! 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, +} From bd934c3b84a1704e3335d673c74ec34eed3bec5d Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Wed, 2 Dec 2026 20:09:47 +0100 Subject: [PATCH 04/19] refactor(backend, logging): adapt event input --- backend/crates/core/src/logger/csv.rs | 6 + backend/crates/station/src/logging.rs | 73 ++- backend/crates/station/src/logging/README.md | 305 +++++++++-- backend/crates/station/src/logging/catalog.rs | 184 +++++++ backend/crates/station/src/logging/control.rs | 25 + backend/crates/station/src/logging/data.rs | 97 +++- backend/crates/station/src/logging/error.rs | 32 +- backend/crates/station/src/logging/event.rs | 8 - .../crates/station/src/logging/messages.rs | 56 +- backend/crates/station/src/logging/order.rs | 56 +- backend/crates/station/src/logging/output.rs | 50 ++ .../crates/station/src/logging/protections.rs | 108 +++- backend/crates/station/src/logging/service.rs | 149 +++++ .../station/src/logging/service/tests.rs | 382 +++++++++++++ backend/crates/station/src/logging/session.rs | 69 ++- .../station/src/logging/session/tests.rs | 172 ++++++ backend/crates/station/src/logging/status.rs | 98 ++++ backend/crates/station/src/logging/writer.rs | 509 +++++++++++++++++- .../station/src/logging/writer/tests.rs | 218 ++++++++ 19 files changed, 2471 insertions(+), 126 deletions(-) create mode 100644 backend/crates/station/src/logging/catalog.rs create mode 100644 backend/crates/station/src/logging/control.rs delete mode 100644 backend/crates/station/src/logging/event.rs create mode 100644 backend/crates/station/src/logging/output.rs create mode 100644 backend/crates/station/src/logging/service.rs create mode 100644 backend/crates/station/src/logging/service/tests.rs create mode 100644 backend/crates/station/src/logging/session/tests.rs create mode 100644 backend/crates/station/src/logging/status.rs create mode 100644 backend/crates/station/src/logging/writer/tests.rs diff --git a/backend/crates/core/src/logger/csv.rs b/backend/crates/core/src/logger/csv.rs index 8c2fbd723..16cdfca1c 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/src/logging.rs b/backend/crates/station/src/logging.rs index 902d90cb3..4643787c1 100644 --- a/backend/crates/station/src/logging.rs +++ b/backend/crates/station/src/logging.rs @@ -1,37 +1,88 @@ //! Backend recording policy, built on `software_core::logger`. //! -//! Configuration, run directories, session metadata and clocks are implemented. -//! Recording, the writer and frontend integration are not implemented yet. +//! 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`. //! -//! Planned lifecycle: +//! 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 and enables event admission. -//! - `stop` stops admission, drains accepted events and closes session files. +//! - `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. //! -//! Session state, event admission and stop ordering must be coordinated so -//! that an accepted event cannot leak into a later session. The frontend -//! receives success only after the requested transition has completed. +//! 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 control; +mod output; mod data; mod error; -mod event; mod messages; mod order; mod protections; +mod service; mod session; mod settings; +mod status; mod writer; +pub use crate::event::ToLogging; pub use error::Error; -pub use session::{BackendRun, Session}; +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; +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 index ac3a61966..62cefe79d 100644 --- a/backend/crates/station/src/logging/README.md +++ b/backend/crates/station/src/logging/README.md @@ -7,14 +7,141 @@ Write operations use ## Current Status -The module currently consists of a scaffold with documented responsibilities. -It is declared in `main.rs`, and `station` enables the `logger` feature of -`software-core`. +This is a work-in-progress adaptation to `event` on `backend/net`, reviewed +against the local `origin/backend/net` commit `99a31ba6`. -The logging service, control functions, writer, event formats, and integration -with the frontend and backend startup are not implemented yet. The following -sections describe the agreed requirements and planned design, rather than -features that are already operational. +The input contract is `tokio::sync::mpsc::Receiver`. The +application passes a shared `Arc` and `Arc` 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. + +**This branch does not yet contain `station::event` or `core::net`.** The +references to those modules intentionally target their real types from +`backend/net`. No duplicate contracts or temporary stubs have been added. +Compilation in this branch and migration of the existing tests are deferred +until the incoming changes have been merged. The production library has also +been checked in a temporary combination with that branch, outside this checkout. + +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. + +`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 `Adj::pod_data`. +- 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, adj, index, receiver, options)` starts the writer thread and +moves event's receiver into it. +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::{adj::Adj, protocol::Index}; +use station::{event::ToLogging, logging::{BackendRun, Error, Logging, WriterOptions}}; +use tokio::sync::mpsc; + +fn start_logging_consumer( + run: BackendRun, + adj: Arc, + index: Arc, + receiver: mpsc::Receiver, +) -> Result, Error> { + Ok(Arc::new(Logging::new( + run, adj, index, receiver, WriterOptions::default(), + )?)) +} +``` + +### Contract Follow-ups + +These are deliberately not filled in with reconstructed or guessed data: + +- **Orders:** `OrderSent` is later than frontend reception and contains no + original JSON text. The consumer reports this pending contract once and + keeps draining. It does not write misleading order rows. The order file + and formatter are retained for the eventual original-payload input. +- **Accumulated protection timing:** the current `ProtectionPacket` has no + separate accumulated-time result. Untimed protections write `0`; timed + protections temporarily leave that cell empty to mean unavailable. The + configured ADJ duration is not presented as a result sent by the board. +- **Reception clock:** upstream supplies `SystemTime`, not a monotonic stamp. + The event path calculates elapsed time from the supplied reception time and + the session's wall-clock origin. Events older than the session are rejected. + This preserves queue delay correctly but inherits wall-clock adjustments; + adding monotonic reception time remains an event-contract follow-up. +- **Saturation:** the writer stops recording when it observes event's data + channel at full capacity. Event currently uses awaited sends with + backpressure: a transient full condition can clear before the writer observes + it. Detecting every producer-side full condition would require a change to + that input contract. +- **Controls:** the session-control channel and multi-frontend disconnect rule + remain pending. ## File Structure for a Backend Run @@ -26,7 +153,7 @@ 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 @@ -51,12 +178,14 @@ directory uses the same format, but with the session's start date and time. 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. Handling another `play()` while a session is active -remains undecided; ignoring it has been proposed to prevent a double click -from truncating an ongoing session. +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 @@ -96,7 +225,7 @@ 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 will be written using `logger::write_json` or `logger::JsonDocument`. +Metadata is written using `logger::write_json`. ## Record Timing @@ -111,9 +240,11 @@ 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"`. -A monotonic clock (`std::time::Instant`) is planned as the session's time -origin. The instant must be captured when the event is received, before -queuing it, so that writing delays do not change the recorded time. +The low-level session retains its monotonic clock for elapsed-time helpers. The +`ToLogging` path uses the upstream `Notification::at` (`SystemTime`) against +the session's wall-clock origin, so queue delays are not added to `instant`. +A monotonic timestamp at original reception is not available in the current +event contract; immunity to wall-clock changes therefore remains pending. The units verified in the frontend are: @@ -190,9 +321,10 @@ instant,from,to,id,payload,timestamp | `payload` | JSON received from the frontend over WebSocket, preserved as text. | | `timestamp` | Order date and time, using the format and offset described above. | -An order is recorded **when it is received from the frontend**. Recording does -not wait for it to be sent to the board or for execution confirmation. Its -times are captured at that point of reception. +The required behavior is to record an order **when received from the frontend**, +with the original JSON. The current `ToLogging::OrderSent` cannot satisfy that +contract, so writing order rows is deferred rather than substituting a later +timestamp or reconstructed payload. ### Protections: protections/ @@ -225,9 +357,10 @@ instant,from,to,protection_id,severity,protection_type,threshold_1,threshold_2,m 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 `timeacumulation` data comes from the board. It is not calculated from the -session clock or `time_unit`; its extraction remains to be specified when -integrating the received packet with recording. +The required `timeacumulation` result must come from the board, not the session +clock, `time_unit`, or the configured ADJ duration. The current model lacks +that result: for now a timed protection's cell is empty (unavailable), while +an untimed protection still writes `0`. Completing this field remains pending. ### Messages: messages/messages.csv @@ -255,17 +388,19 @@ another column or reconstructing its format. ## Frontend Control and Shutdown -The planned functions are `play()`, `stop()`, and `emergency_stop()`. Their -signatures are not implemented yet, and no WebSocket control protocol has -been defined. +The internal functions are `play()`, `stop()`, and `emergency_stop()`. +The `websocket`, `event`, and `payload` +modules in the PR under review will connect this internal API to the frontend; +this module does not define a separate WebSocket control protocol. ### play() Prepares a new session's directory, settings, variable selection, and files. -Establishes the time origin and starts accepting records once the session -is ready. +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 planned states are: +The states are: ```text Inactive -> Starting -> Recording -> Stopping -> Inactive @@ -275,8 +410,9 @@ Inactive -> Starting -> Recording -> Stopping -> Inactive Stops the session in this order: -1. Stops accepting new records for that session. -2. Processes all events already accepted into the queue. +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. @@ -284,6 +420,14 @@ 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 @@ -294,23 +438,28 @@ 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 planned design uses a dedicated thread for synchronous +The service uses a dedicated thread for synchronous `software_core::logger` writes, separate from asynchronous network tasks: ```text Event reception | v -Capture instant and associate with session +Attach reception timestamp | v -Queue with limited capacity +Event's existing bounded mpsc channel | v Writer thread and format components @@ -322,31 +471,51 @@ software_core::logger Buffered files ``` -The writer will own the files. It will keep them open throughout the session -and reuse the buffers already provided by `logger`, avoiding opening, writing, +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 planned to be flushed periodically and when a byte threshold is -reached, using `bytes_since_flush()`. Exact capacities and intervals will be -chosen during implementation. Stopping must explicitly call -`flush()`/`close()` and report errors, rather than relying solely on `Drop`. +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. ### Queue Saturation If records arrive faster than they can be written for long enough to fill -the queue, the agreed behavior is to **stop logging and notify the frontend**: +the channel, the writer stops logging when it observes that full condition: -1. Stop accepting new records. -2. Write records that have already been accepted. +1. Begin stopping the session. +2. Write the ready input prefix at the stop boundary. 3. Flush and close the session files. 4. Indicate that the session ended because of saturation. -The backend continues running. Records must not keep being silently dropped -while the session is presented as active. +The backend continues running and the receiver remains open. `status` and +`subscribe` expose `StopReason::Saturation` for the application to notify the +frontend. As noted above, transient producer-side full conditions can escape +observation with the current input contract. -A write error must be reported and cannot be treated as a successful stop. -The exact policy for disk failures and frontend status messages remains -undecided. +A write or flush error also 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 frontend notification format remains the application adapter's concern. ## Files in others/ @@ -366,18 +535,22 @@ were left undecided**. This flow has not been implemented in the new backend. ## Responsibilities of Module Files -| File | Planned responsibility | +| File | Responsibility | | --- | --- | -| `../logging.rs` | Logging service, coordination, and control API. | -| `session.rs` | Identity, paths, clock, and state of each session. | +| `../logging.rs` | Public API exports. | +| `catalog.rs` | Shared ADJ/Index lookups and measurement locators. | +| `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. | -| `event.rs` | Typed events with their instant and target session. | -| `writer.rs` | Bounded queue, writer thread, flushing, and orderly shutdown. | +| `writer.rs` | Event consumer, session state, CSV ownership, flushing, and shutdown. | +| `csv.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, queue, and write errors. | +| `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, @@ -388,9 +561,27 @@ buffers, and explicit flush and close operations. - 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 frontend control. -- Final position of the text column in `messages.csv`. -- Behavior of repeated `play()` calls during an active session. +- Exact schema of `selected_variables` in JSON and the session-control channel. +- Original order JSON and frontend reception time in the input contract. +- Board-supplied accumulated timing and monotonic reception timestamps. - Disconnection stop rule when multiple frontends are connected. -- Write error policy and frontend notification format. -- Queue/buffer capacities, flush intervals, and configuration parameters. +- Frontend notification format and integration through the application modules. +- Wiring `WriterOptions` into application configuration if these defaults need UI controls. + +## Verification During This Adaptation + +`rustfmt` and `git diff --check` validate syntax formatting and whitespace. +The production library is also checked in a temporary workspace combining +these changes with the reviewed `backend/net` source, without merging it into +this checkout. + +The old logging tests still use the former DTO-based API. Their migration and +full test execution are intentionally deferred until the branches are joined. +Do not treat this WIP commit as a passing standalone build before `event` and +`core::net` are brought in. + +`cargo test -p station --test logging_service --offline` checks the native event +API in a workspace that includes those dependencies. It covers session restart, +old reception timestamps, invalid selections, pending-record drains and +controls awaited from spawned Tokio tasks. It also checks stopping while the +producer keeps sending, a one-slot data channel, and input-closure flushing. diff --git a/backend/crates/station/src/logging/catalog.rs b/backend/crates/station/src/logging/catalog.rs new file mode 100644 index 000000000..09ab9cc26 --- /dev/null +++ b/backend/crates/station/src/logging/catalog.rs @@ -0,0 +1,184 @@ +//! 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 ADJ and protocol Index must describe the +//! same checkout that networking used to decode the packets. + +use std::{collections::HashMap, sync::Arc}; + +use software_core::{ + adj::Adj, + model::{AdjId, Board, BoardId, Measurement, MessageLevel, Packet, PacketType, Protection}, + 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. + adj: 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(adj: Arc, index: Arc) -> Self { + let mut measurements = HashMap::new(); + for board in adj.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 { + adj, + index, + measurements, + } + } + + /// Resolve a notification's numeric board ID to its ADJ board definition. + pub fn board(&self, id: BoardId) -> Result<&Board, Error> { + self.adj + .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)), + } + } + + /// 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 ToLogging::Received(notification) = incoming else { + // OrderSent has neither the original JSON nor frontend reception time. + return Err(Error::OrderContractPending); + }; + // 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)?; + } + // Receiving a decoded order does not restore the missing original + // frontend JSON or establish its frontend reception timestamp. + Event::Received(Packet::Order(_)) => return Err(Error::OrderContractPending), + } + Ok(true) + } +} 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 index d3b3dcfa8..a42f1b083 100644 --- a/backend/crates/station/src/logging/data.rs +++ b/backend/crates/station/src/logging/data.rs @@ -1,9 +1,88 @@ -//! Measurement recording under `data//.csv`. -//! -//! One directory per connected board and one CSV per selected measurement, -//! named with its textual identifier. Files have no header. Columns, in order: -//! `instant,from,to,value`. -//! -//! This component will own the measurement `software_core::logger::CsvFile` -//! handles and translate typed events into rows, reusing the logger's CSV -//! escaping, buffering and explicit flush/close operations. +//! 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 index 52700c64e..2083a9524 100644 --- a/backend/crates/station/src/logging/error.rs +++ b/backend/crates/station/src/logging/error.rs @@ -1,15 +1,39 @@ //! Errors for recording setup, lifecycle transitions and the writer. //! -//! Errors will preserve file context from `software_core::logger` and report -//! queue saturation, writer failure and invalid session transitions. Shutdown -//! must attempt to close all files even if closing one of them fails, and -//! return failures to the caller rather than report a successful stop. +//! Errors preserve file context from `software_core::logger` and report setup +//! or writer failures. Saturation is exposed through `StopReason` instead. +//! 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 logging awaits original frontend JSON and reception time in the event contract")] + OrderContractPending, + #[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 { diff --git a/backend/crates/station/src/logging/event.rs b/backend/crates/station/src/logging/event.rs deleted file mode 100644 index 2d00ab80e..000000000 --- a/backend/crates/station/src/logging/event.rs +++ /dev/null @@ -1,8 +0,0 @@ -//! Typed recording events for measurements, orders, protections and messages. -//! -//! Events will carry their recording session identity and the elapsed time -//! captured at reception or order execution, before entering the writer queue. -//! Queue latency must not become part of the recorded `instant`. -//! -//! Order events also capture wall-clock time for the timestamp column. Event -//! types and the concrete producer API remain to be implemented. diff --git a/backend/crates/station/src/logging/messages.rs b/backend/crates/station/src/logging/messages.rs index a35de950e..1f3e7fcbe 100644 --- a/backend/crates/station/src/logging/messages.rs +++ b/backend/crates/station/src/logging/messages.rs @@ -1,8 +1,54 @@ //! Message recording in the session's single `messages/messages.csv` file. //! -//! Columns, in order: `instant,from,to,board,source,severity`. -//! `board` identifies the board that emitted the message; `source` combines -//! file and line in one field when applicable to the message type. +//! 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 will own a `software_core::logger::CsvFile` and format rows. -//! Header policy and the exact representation of `source` remain to be defined. +//! 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 index e39a6d8f6..078b06b59 100644 --- a/backend/crates/station/src/logging/order.rs +++ b/backend/crates/station/src/logging/order.rs @@ -1,9 +1,59 @@ //! Order recording in the session's single `order/order.csv` file. //! -//! Columns, in order: `instant,from,to,id,payload,timestamp`. +//! Columns, in order: `instant,from,to,order_id,payload,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 are recorded when received from the frontend over WebSocket; +//! `payload` preserves the received JSON as text. There is no header. //! -//! This component will own a `software_core::logger::CsvFile` and format rows. -//! Header policy and the exact payload representation remain to be defined. +//! This component owns a `software_core::logger::CsvFile` and formats rows. + +use std::path::Path; + +use software_core::{logger::CsvFile, model::AdjId}; + +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"), &[])?, + }) + } + + /// Pending input contract: only call with the original frontend JSON. + /// Writes a complete row in the order.csv file, following this order per columns + /// instant,from,to,order_id,payload,timestamp + pub fn write( + &mut self, + time: RecordTime, + id: AdjId, + to: &str, + payload: &str, + threshold: u64, + ) -> Result<(), Error> { + 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(id.0)) + .text(payload) + .text(×tamp) + .end()?; // validates row and ends it + flush_if_due(&mut self.file, threshold)?; + Ok(()) + } +} 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 index 7b476e47e..22136e351 100644 --- a/backend/crates/station/src/logging/protections.rs +++ b/backend/crates/station/src/logging/protections.rs @@ -1,11 +1,97 @@ -//! Protection recording in `protections/.csv`, one per board. -//! -//! Columns, in order: -//! `instant,from,to,protection_id,severity,protection_type,threshold_1,threshold_2,measurement_id,value,time`. -//! The second threshold is empty unless the protection is a range. `value` -//! is the measurement value that triggered the protection. For a -//! `timeacumulation` protection, `time` is a string containing time and units; -//! for other protection types it is `0`. -//! -//! This component will own the `software_core::logger::CsvFile` handles and -//! format rows. Header policy remains to be defined. +//! Protection rows resolved from a received packet and the ADJ definition. +//! Board-supplied accumulated timing is not present in the current packet model. + +use std::{ + collections::HashMap, + path::{Path, PathBuf}, +}; + +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); + // Never substitute the ADJ's configured duration for a board result. + // An empty timed-protection cell explicitly means unavailable for now. + row.text(if protection.time.is_zero() { "0" } else { "" }) + .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() + } +} diff --git a/backend/crates/station/src/logging/service.rs b/backend/crates/station/src/logging/service.rs new file mode 100644 index 000000000..02275e411 --- /dev/null +++ b/backend/crates/station/src/logging/service.rs @@ -0,0 +1,149 @@ +//! Lifecycle handle for the writer that owns event's data receiver. + +use std::{ + sync::{Arc, Mutex}, + thread::JoinHandle, + time::SystemTime, +}; + +use software_core::{adj::Adj, protocol::Index}; +use tokio::sync::{mpsc, oneshot, watch}; + +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. + pub fn new( + run: BackendRun, + adj: Arc, + index: Arc, + input: mpsc::Receiver, + options: WriterOptions, + ) -> Result { + options.validate()?; + let directory = run.directory().to_path_buf(); + let catalog = Catalog::new(adj, 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, status_tx, catalog, options)) + .map_err(|source| 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() + && worker.join().is_err() + { + tracing::error!("logging writer exited unexpectedly during close"); + } + } +} + +#[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..36d3fa4d1 --- /dev/null +++ b/backend/crates/station/src/logging/service/tests.rs @@ -0,0 +1,382 @@ +use std::{fs, path::Path}; + +use serde_json::json; +use software_core::model::Value; +use tokio::time::{sleep, timeout}; + +use super::*; +use crate::logging::{Config, DataRecord, MeasurementKey, ProtectionRecord, Thresholds}; + +type TestResult = Result<(), Box>; + +fn selection() -> SessionSelection { + SessionSelection { + measurements: vec![MeasurementKey { + board: "LCU".into(), + measurement_id: "speed".into(), + }], + connected_boards: Vec::new(), + selected_variables: json!({"LCU": ["speed"]}), + } +} + +fn data(value: f64) -> Record { + Record::Data(DataRecord { + from: "LCU".into(), + to: "backend".into(), + measurement_id: "speed".into(), + value: Value::Number(value), + }) +} + +fn logging( + options: WriterOptions, +) -> Result<(tempfile::TempDir, Logging), Box> { + let temp = tempfile::tempdir()?; + let run = BackendRun::new_at( + Config { + logging_path: temp.path().to_path_buf(), + time_unit: TimeUnit::Microseconds, + }, + "adj", + "2026-11-27T14:30:00Z".parse()?, + )?; + let logger = Logging::new(run, options)?; + Ok((temp, logger)) +} + +async fn visible(path: &Path) -> TestResult { + timeout(Duration::from_secs(3), 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) = logging(WriterOptions::default())?; + let session = logger.play(selection()).await?; + let stamp = logger.capture()?; + for n in 0..200 { + assert_eq!( + logger.record_at(stamp, data(f64::from(n)))?, + RecordOutcome::Accepted + ); + } + assert_eq!( + logger.record_at( + stamp, + Record::Data(DataRecord { + from: "LCU".into(), + to: "backend".into(), + measurement_id: "unselected".into(), + value: Value::Bool(true), + }) + )?, + RecordOutcome::Filtered + ); + let first_stop = timeout(Duration::from_secs(3), 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()); + assert!(matches!(logger.record(data(1.0)), Err(Error::NotRecording))); + logger.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn double_play_preserves_session_and_old_tokens_cannot_enter_a_new_one() -> TestResult { + let (_temp, logger) = logging(WriterOptions::default())?; + let first = logger.play(selection()).await?; + let stamp = logger.capture()?; + logger.record_at(stamp, data(1.0))?; + assert_eq!( + first, + logger + .play(SessionSelection { + measurements: Vec::new(), + connected_boards: Vec::new(), + selected_variables: json!([]), + }) + .await? + ); + logger.emergency_stop().await?; + assert_eq!( + logger.status().last_stop.map(|r| r.reason), + Some(StopReason::Emergency) + ); + let second = logger.play(selection()).await?; + assert_ne!(first.id, second.id); + assert!(matches!( + logger.record_at(stamp, data(99.0)), + Err(Error::SessionChanged) + )); + logger.record(data(2.0))?; + 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 full_queue_reserves_stop_admission_and_drains_every_accepted_record() -> TestResult { + let (_temp, logger) = logging(WriterOptions { + queue_capacity: 2, + ..WriterOptions::default() + })?; + let session = logger.play(selection()).await?; + let stamp = logger.capture()?; + let mut notifications = logger.subscribe(); + { + // Hold the admission lock so the writer cannot consume the test queue. + let mut state = logger.shared.lock(); + assert_eq!( + logger.shared.admit(&mut state, stamp, data(1.0))?, + RecordOutcome::Accepted + ); + assert_eq!( + logger.shared.admit(&mut state, stamp, data(2.0))?, + RecordOutcome::Accepted + ); + assert!(matches!( + logger.shared.admit(&mut state, stamp, data(3.0)), + Err(Error::QueueFull) + )); + assert_eq!(state.phase, Phase::Stopping); + assert_eq!(state.queued_records, 2); + assert!(matches!(state.queue.back(), Some(Command::Stop))); + } + let report = timeout(Duration::from_secs(3), logger.stop()).await??; + assert_eq!( + report.as_ref().map(|r| r.reason), + Some(StopReason::Saturation) + ); + let status = timeout(Duration::from_secs(3), notifications.changed()).await??; + assert_eq!( + status.last_stop.map(|r| r.reason), + Some(StopReason::Saturation) + ); + assert_eq!( + fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? + .lines() + .count(), + 2 + ); + logger.play(selection()).await?; + assert_eq!( + logger.status().last_stop.map(|r| r.reason), + Some(StopReason::Saturation) + ); + logger.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn periodic_flush_persists_a_buffered_tail_without_stopping() -> TestResult { + let (_temp, logger) = logging(WriterOptions { + flush_interval: Duration::from_millis(20), + flush_bytes: u64::MAX, + ..WriterOptions::default() + })?; + let session = logger.play(selection()).await?; + logger.record(data(1.0))?; + 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) = logging(WriterOptions { + flush_interval: Duration::from_secs(60), + flush_bytes: 1, + ..WriterOptions::default() + })?; + let session = logger.play(selection()).await?; + logger.record(data(1.0))?; + visible(&session.directory.join("data/LCU/speed.csv")).await?; + logger.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn concurrent_producers_are_drained_before_shutdown() -> TestResult { + let (_temp, logger) = logging(WriterOptions { + queue_capacity: 1024, + ..WriterOptions::default() + })?; + let session = logger.play(selection()).await?; + std::thread::scope(|scope| -> TestResult { + let workers: Vec<_> = (0..8) + .map(|producer| { + let logger = &logger; + scope.spawn(move || -> Result<(), Error> { + for n in 0..100 { + logger.record(data(f64::from(producer * 100 + n)))?; + } + Ok(()) + }) + }) + .collect(); + for worker in workers { + worker.join().map_err(|_| "producer panicked")??; + } + Ok(()) + })?; + timeout(Duration::from_secs(3), 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) = logging(WriterOptions::default())?; + let session = logger.play(selection()).await?; + let protections = session.directory.join("protections"); + fs::remove_dir(&protections)?; + fs::write(&protections, "not a directory")?; + let stamp = logger.capture()?; + { + let mut state = logger.shared.lock(); + logger.shared.admit( + &mut state, + stamp, + Record::Protection(ProtectionRecord { + board: "PCU".into(), + from: "PCU".into(), + to: "backend".into(), + protection_id: "1".into(), + severity: "fault".into(), + protection_type: "above".into(), + thresholds: Thresholds::Single(Value::Number(1.0)), + measurement_id: "temperature".into(), + value: Value::Number(2.0), + accumulated_time: None, + }), + )?; + logger.shared.admit(&mut state, stamp, data(7.0))?; + } + assert!(matches!( + timeout(Duration::from_secs(3), 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") + ); + // A later session can recover; its replacement removes the blocking file. + logger.play(selection()).await?; + logger.record(data(8.0))?; + logger.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn invalid_selection_is_rejected_before_replacing_existing_files() -> TestResult { + let (_temp, logger) = logging(WriterOptions::default())?; + let session = logger.play(selection()).await?; + logger.record(data(1.0))?; + logger.stop().await?; + let before = fs::read(session.directory.join("data/LCU/speed.csv"))?; + let mut invalid = selection(); + invalid.measurements[0].measurement_id = "../escape".into(); + assert!(matches!( + logger.play(invalid).await, + Err(Error::InvalidName(_)) + )); + assert_eq!( + fs::read(session.directory.join("data/LCU/speed.csv"))?, + before + ); + logger.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn an_abandoned_start_reply_does_not_prevent_emergency_stop_or_restart() -> TestResult { + let (_temp, logger) = logging(WriterOptions::default())?; + let (reply, response) = oneshot::channel(); + drop(response); + { + let mut state = logger.shared.lock(); + state.phase = Phase::Starting; + state.next_id = 1; + state.queue.push_back(Command::Start { + id: SessionId(1), + selection: selection(), + reply, + }); + logger.shared.publish(); + logger.shared.ready.notify_one(); + } + let report = timeout(Duration::from_secs(3), logger.emergency_stop()).await??; + assert_eq!(report.map(|r| r.reason), Some(StopReason::Emergency)); + assert_eq!(logger.play(selection()).await?.id, SessionId(2)); + logger.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn drop_is_a_fallback_drain_when_explicit_shutdown_was_missed() -> TestResult { + let (_temp, logger) = logging(WriterOptions::default())?; + let session = logger.play(selection()).await?; + for n in 0..100 { + logger.record(data(f64::from(n)))?; + } + drop(logger); + assert_eq!( + fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? + .lines() + .count(), + 100 + ); + Ok(()) +} + +#[tokio::test] +async fn controls_can_run_in_spawned_application_tasks() -> TestResult { + let (_temp, logger) = logging(WriterOptions::default())?; + let logger = Arc::new(logger); + let controller = logger.clone(); + let session = tokio::spawn(async move { controller.play(selection()).await }).await??; + logger.record(data(1.0))?; + 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(()) +} diff --git a/backend/crates/station/src/logging/session.rs b/backend/crates/station/src/logging/session.rs index 060bd068e..3c7826b6e 100644 --- a/backend/crates/station/src/logging/session.rs +++ b/backend/crates/station/src/logging/session.rs @@ -16,22 +16,74 @@ use std::{ fs, io, path::{Path, PathBuf}, - time::Instant, + time::{Instant, 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}; +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, always derived from the incoming event's reception time. +#[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 future service +/// 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 { @@ -42,7 +94,7 @@ pub struct BackendRun { impl BackendRun { /// Creates a run directory with the current date and backend metadata. /// - /// Blocking: call during startup or on the future writer thread. + /// 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()) } @@ -158,6 +210,7 @@ impl BackendRun { directory, metadata, clock_origin, + wall_origin: started_at.into(), }) } } @@ -168,6 +221,7 @@ pub struct Session { directory: PathBuf, metadata: SessionSettings, clock_origin: Instant, + wall_origin: SystemTime, } #[derive(Debug, Serialize)] @@ -178,6 +232,9 @@ struct SessionSettings { } 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 @@ -193,10 +250,10 @@ impl Session { &self.metadata.selected_variables } - /// Elapsed time for an event captured before it enters the writer queue. + /// Elapsed time for an externally supplied monotonic reception timestamp. /// /// An event predating this session returns `None`, not a fabricated zero. - /// The future service must also check the event's session identity. + /// The current ToLogging input supplies SystemTime instead of Instant. pub fn instant_at(&self, received_at: Instant) -> Option { received_at .checked_duration_since(self.clock_origin) 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..d63345c62 --- /dev/null +++ b/backend/crates/station/src/logging/session/tests.rs @@ -0,0 +1,172 @@ +use std::{fs, time::Duration}; + +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 clock_origin = Instant::now(); + let session = + run.prepare_session_at(&selected, "2026-11-27T14:31:05Z".parse()?, clock_origin)?; + 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); + } + assert_eq!(session.instant_at(clock_origin), Some(0)); + assert_eq!( + session.instant_at(clock_origin + Duration::from_millis(35)), + Some(35000) + ); + if let Some(earlier) = clock_origin.checked_sub(Duration::from_millis(1)) { + assert_eq!(session.instant_at(earlier), None); + } + 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()?, + Instant::now(), + )?; + 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()?, + Instant::now(), + )?; + 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, Instant::now())?; + 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, Instant::now()), + 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()?, Instant::now()), + 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/status.rs b/backend/crates/station/src/logging/status.rs new file mode 100644 index 000000000..f193414d5 --- /dev/null +++ b/backend/crates/station/src/logging/status.rs @@ -0,0 +1,98 @@ +//! 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, + Saturation, + 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/writer.rs b/backend/crates/station/src/logging/writer.rs index bf9c898e8..0ecb9ef0a 100644 --- a/backend/crates/station/src/logging/writer.rs +++ b/backend/crates/station/src/logging/writer.rs @@ -1,14 +1,499 @@ -//! Dedicated synchronous writer and its bounded event queue. +//! Single data-channel consumer and owner of all session files. //! -//! One writer thread will own the session's four recording components and -//! perform their blocking `software_core::logger` operations away from the -//! async network tasks. Keep files open for the session and reuse their -//! existing buffers; flush periodically and according to bytes_since_flush. +//! 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. //! -//! Admission and control commands must establish a session boundary: stop -//! rejects new events for that session, drains every accepted event, attempts -//! to close every session file and acknowledges completion. Queue saturation -//! must be reported explicitly rather than silently dropping events. -//! -//! Backend trace output has a separate lifetime from recording sessions. It -//! remains active between sessions and is flushed at the end of shutdown. +//! 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 super::{ + BackendRun, Error, Phase, Session, SessionId, SessionInfo, SessionSelection, Status, + StopReason, StopReport, ToLogging, + catalog::Catalog, + control::Control, + output::{close_files, flush_files}, + data::DataLogger, + messages::MessagesLogger, + order::OrderLogger, + 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 ToLogging::Received(notification) = record else { + // OrderSent lacks the original frontend JSON and reception time. + // Keep that contract pending instead of inventing an order row. + return Err(Error::OrderContractPending); + }; + 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(_)) => Err(Error::OrderContractPending), + } + } + + 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) { + self.errors.push(text); + } + } + } +} + +struct Writer { + run: BackendRun, + input: mpsc::Receiver, + controls: mpsc::UnboundedReceiver, + updates: watch::Sender, + status: Status, + catalog: Catalog, + options: WriterOptions, + active: Option, + next_id: u64, + order_contract_reported: bool, +} + +enum Step { + Control(Option), + Input(Option), + Flush, + Saturated, +} + +/// 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, + 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, + updates, + catalog, + options, + status: Status::default(), + active: None, + next_id: 0, + order_contract_reported: false, + } + .run(), + ), + Err(error) => { + 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. + loop { + let saturated = self.active.is_some() && self.input.len() == self.input.max_capacity(); + // 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), + _ = std::future::ready(()), if saturated => Step::Saturated, + _ = 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 + { + 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::Saturated => { + self.stop(StopReason::Saturation, SystemTime::now()).await; + } + 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()); + } + selection.validate(&self.catalog)?; + let id = SessionId( + self.next_id + .checked_add(1) + .ok_or(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(); + 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::OrderContractPending) => { + if !self.order_contract_reported { + tracing::warn!( + "OrderSent logging pending: original frontend JSON and reception time are unavailable" + ); + self.order_contract_reported = true; + } + return false; + } + Err(error) => { + tracing::warn!(%error, "logging input could not be recorded"); + 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) { + 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()); + } + 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(); + } + + fn publish(&self) { + self.updates.send_replace(self.status.clone()); + } +} + +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 { + 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..bc856b203 --- /dev/null +++ b/backend/crates/station/src/logging/writer/tests.rs @@ -0,0 +1,218 @@ +use std::{ + fs, + io::{self, Write}, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, +}; + +use serde_json::json; +use software_core::{logger::CsvFile, model::Value}; + +use super::*; +use crate::logging::{ + DataRecord, MeasurementKey, MessageRecord, OrderRecord, ProtectionRecord, Thresholds, +}; + +type TestResult = Result<(), Box>; + +fn selection() -> SessionSelection { + SessionSelection { + measurements: vec![MeasurementKey { + board: "LCU".into(), + measurement_id: "speed".into(), + }], + connected_boards: vec!["LCU".into()], + selected_variables: json!({"LCU": ["speed"]}), + } +} + +fn time(wall_time: &str) -> Result { + Ok(RecordTime { + session_id: SessionId(1), + instant: u128::MAX, + wall_time: wall_time.parse()?, + }) +} + +#[test] +fn all_csv_formats_preserve_fields_without_headers() -> TestResult { + let temp = tempfile::tempdir()?; + let mut files = SessionFiles::open(temp.path(), &selection())?; + let mut stamp = time("2026-07-15T13:30:05Z")?; + stamp.instant = 35000; + files.write( + stamp, + &Record::Data(DataRecord { + from: "LCU".into(), + to: "backend".into(), + measurement_id: "speed".into(), + value: Value::Number(12.5), + }), + u64::MAX, + )?; + files.write( + stamp, + &Record::Data(DataRecord { + from: "LCU".into(), + to: "backend".into(), + measurement_id: "unselected".into(), + value: Value::Bool(true), + }), + u64::MAX, + )?; + files.write( + stamp, + &Record::Order(OrderRecord { + from: "backend".into(), + to: "LCU".into(), + id: "start".into(), + payload: "{ \"mode\": \"run\" }".into(), + }), + u64::MAX, + )?; + let mut protection = ProtectionRecord { + board: "LCU".into(), + from: "LCU".into(), + to: "backend".into(), + protection_id: "42".into(), + severity: "fault".into(), + protection_type: "above".into(), + thresholds: Thresholds::Single(Value::Number(50.0)), + measurement_id: "temperature".into(), + value: Value::Number(55.0), + accumulated_time: Some("500ms".into()), + }; + files.write(stamp, &Record::Protection(protection.clone()), u64::MAX)?; + protection.protection_type = "range".into(); + protection.thresholds = Thresholds::Range { + min: Value::Number(0.0), + max: Value::Number(100.0), + }; + protection.accumulated_time = None; + files.write(stamp, &Record::Protection(protection), u64::MAX)?; + files.write( + stamp, + &Record::Message(MessageRecord { + from: "LCU".into(), + to: "backend".into(), + board: "LCU".into(), + source: "control.cpp:123".into(), + severity: "fault".into(), + message: "failed, \"overload\"\nagain".into(), + }), + u64::MAX, + )?; + 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()); + assert_eq!( + fs::read_to_string(temp.path().join("order/order.csv"))?, + "35000,backend,LCU,start,\"{ \"\"mode\"\": \"\"run\"\" }\",2026-07-15T15-30-05+02:00\n" + ); + assert_eq!( + fs::read_to_string(temp.path().join("protections/LCU.csv"))?, + "35000,LCU,backend,42,fault,above,50,,temperature,55,500ms\n35000,LCU,backend,42,fault,range,0,100,temperature,55,0\n" + ); + 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 winter_order_offset_and_large_integer_instants_are_preserved() -> TestResult { + let temp = tempfile::tempdir()?; + let mut files = SessionFiles::open(temp.path(), &selection())?; + files.write( + time("2026-11-27T14:30:05Z")?, + &Record::Order(OrderRecord { + from: "backend".into(), + to: "LCU".into(), + id: "off".into(), + payload: "{}".into(), + }), + u64::MAX, + )?; + assert!(files.close().is_empty()); + assert_eq!( + fs::read_to_string(temp.path().join("order/order.csv"))?, + format!( + "{},backend,LCU,off,{{}},2026-11-27T15-30-05+01:00\n", + u128::MAX + ) + ); + 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", + &[], + )?, + ]; + let errors = close_files(files.into_iter()); + assert_eq!(errors.len(), 1); + assert!(first.load(Ordering::SeqCst)); + assert!(second.load(Ordering::SeqCst)); + Ok(()) +} + +#[test] +fn unexpected_exit_releases_queued_start_replies() { + let shared = Arc::new(Shared::new(2)); + let (reply, mut response) = tokio::sync::oneshot::channel(); + { + let mut state = shared.lock(); + state.phase = Phase::Starting; + state.queue.push_back(Command::Start { + id: SessionId(1), + selection: selection(), + reply, + }); + } + drop(ExitGuard(shared.clone())); + assert_eq!(shared.lock().phase, Phase::Closed); + assert!(matches!( + response.try_recv(), + Err(tokio::sync::oneshot::error::TryRecvError::Closed) + )); +} From 822606a5128dc72a772e6d74f57dea4a98303f82 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Thu, 3 Dec 2026 12:51:27 +0100 Subject: [PATCH 05/19] test(backend, logging): correct tests --- backend/crates/station/src/logging.rs | 3 + backend/crates/station/src/logging/README.md | 46 +- .../station/src/logging/service/tests.rs | 505 +++++++++++------- .../station/src/logging/test_support.rs | 163 ++++++ .../station/src/logging/writer/tests.rs | 295 ++++++---- 5 files changed, 693 insertions(+), 319 deletions(-) create mode 100644 backend/crates/station/src/logging/test_support.rs diff --git a/backend/crates/station/src/logging.rs b/backend/crates/station/src/logging.rs index 4643787c1..3c1650a59 100644 --- a/backend/crates/station/src/logging.rs +++ b/backend/crates/station/src/logging.rs @@ -36,6 +36,9 @@ mod settings; mod status; mod writer; +#[cfg(test)] +mod test_support; + pub use crate::event::ToLogging; pub use error::Error; pub use service::Logging; diff --git a/backend/crates/station/src/logging/README.md b/backend/crates/station/src/logging/README.md index 62cefe79d..4748a9c69 100644 --- a/backend/crates/station/src/logging/README.md +++ b/backend/crates/station/src/logging/README.md @@ -7,8 +7,8 @@ Write operations use ## Current Status -This is a work-in-progress adaptation to `event` on `backend/net`, reviewed -against the local `origin/backend/net` commit `99a31ba6`. +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 a shared `Arc` and `Arc` to `Logging`. @@ -16,12 +16,9 @@ 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. -**This branch does not yet contain `station::event` or `core::net`.** The -references to those modules intentionally target their real types from -`backend/net`. No duplicate contracts or temporary stubs have been added. -Compilation in this branch and migration of the existing tests are deferred -until the incoming changes have been merged. The production library has also -been checked in a temporary combination with that branch, outside this checkout. +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 @@ -545,7 +542,7 @@ were left undecided**. This flow has not been implemented in the new backend. | `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. | -| `csv.rs` | Shared value formatting and flush/close error handling. | +| `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. | @@ -568,20 +565,23 @@ buffers, and explicit flush and close operations. - Frontend notification format and integration through the application modules. - Wiring `WriterOptions` into application configuration if these defaults need UI controls. -## Verification During This Adaptation +## Verification -`rustfmt` and `git diff --check` validate syntax formatting and whitespace. -The production library is also checked in a temporary workspace combining -these changes with the reviewed `backend/net` source, without merging it into -this checkout. +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. -The old logging tests still use the former DTO-based API. Their migration and -full test execution are intentionally deferred until the branches are joined. -Do not treat this WIP commit as a passing standalone build before `event` and -`core::net` are brought in. +`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. -`cargo test -p station --test logging_service --offline` checks the native event -API in a workspace that includes those dependencies. It covers session restart, -old reception timestamps, invalid selections, pending-record drains and -controls awaited from spawned Tokio tasks. It also checks stopping while the -producer keeps sending, a one-slot data channel, and input-closure flushing. +Writer tests check headerless CSVs, escaping, protection metadata, missing +board timing, the order formatter's original JSON and timezone offsets, +large integer instants, deterministic full-channel handling and failed closes. +Pending `OrderSent` input is explicitly checked to leave the order CSV empty; +testing the formatter directly does not imply that order reception is wired. + +`rustfmt` and `git diff --check` validate formatting and whitespace. diff --git a/backend/crates/station/src/logging/service/tests.rs b/backend/crates/station/src/logging/service/tests.rs index 36d3fa4d1..ad7bbd6b5 100644 --- a/backend/crates/station/src/logging/service/tests.rs +++ b/backend/crates/station/src/logging/service/tests.rs @@ -1,52 +1,46 @@ -use std::{fs, path::Path}; +//! Lifecycle tests using the real ToLogging channel, ADJ and protocol index. -use serde_json::json; -use software_core::model::Value; +use std::{ + fs, + path::Path, + time::{Duration, SystemTime}, +}; use tokio::time::{sleep, timeout}; use super::*; -use crate::logging::{Config, DataRecord, MeasurementKey, ProtectionRecord, Thresholds}; +use crate::logging::{Config, MeasurementKey, TimeUnit, test_support::*}; +use software_core::{ + model::{AdjId, DataPacket, OrderPacket, Packet}, + net::Event, +}; -type TestResult = Result<(), Box>; +type Fixture = (tempfile::TempDir, Logging, mpsc::Sender); -fn selection() -> SessionSelection { - SessionSelection { - measurements: vec![MeasurementKey { - board: "LCU".into(), - measurement_id: "speed".into(), - }], - connected_boards: Vec::new(), - selected_variables: json!({"LCU": ["speed"]}), - } -} - -fn data(value: f64) -> Record { - Record::Data(DataRecord { - from: "LCU".into(), - to: "backend".into(), - measurement_id: "speed".into(), - value: Value::Number(value), - }) +fn logging(options: WriterOptions) -> Result> { + logging_with_capacity(options, 1024) } -fn logging( +fn logging_with_capacity( options: WriterOptions, -) -> Result<(tempfile::TempDir, Logging), Box> { + capacity: usize, +) -> Result> { let temp = tempfile::tempdir()?; + let (adj, index) = definitions(); let run = BackendRun::new_at( Config { - logging_path: temp.path().to_path_buf(), + logging_path: temp.path().into(), time_unit: TimeUnit::Microseconds, }, "adj", "2026-11-27T14:30:00Z".parse()?, )?; - let logger = Logging::new(run, options)?; - Ok((temp, logger)) + let (sender, receiver) = mpsc::channel(capacity); + let logger = Logging::new(run, adj, index, receiver, options)?; + Ok((temp, logger, sender)) } async fn visible(path: &Path) -> TestResult { - timeout(Duration::from_secs(3), async { + timeout(WAIT, async { loop { if !fs::read_to_string(path)?.is_empty() { return Ok::<(), std::io::Error>(()); @@ -60,28 +54,12 @@ async fn visible(path: &Path) -> TestResult { #[tokio::test] async fn stop_drains_records_filters_selection_and_is_idempotent() -> TestResult { - let (_temp, logger) = logging(WriterOptions::default())?; + let (_temp, logger, sender) = logging(WriterOptions::default())?; let session = logger.play(selection()).await?; - let stamp = logger.capture()?; for n in 0..200 { - assert_eq!( - logger.record_at(stamp, data(f64::from(n)))?, - RecordOutcome::Accepted - ); + sender.send(data(SystemTime::now(), f64::from(n))).await?; } - assert_eq!( - logger.record_at( - stamp, - Record::Data(DataRecord { - from: "LCU".into(), - to: "backend".into(), - measurement_id: "unselected".into(), - value: Value::Bool(true), - }) - )?, - RecordOutcome::Filtered - ); - let first_stop = timeout(Duration::from_secs(3), logger.stop()).await??; + let first_stop = timeout(WAIT, logger.stop()).await??; assert_eq!( first_stop.as_ref().map(|r| r.reason), Some(StopReason::Requested) @@ -91,39 +69,40 @@ async fn stop_drains_records_filters_selection_and_is_idempotent() -> TestResult assert_eq!(text.lines().count(), 200); assert!(text.ends_with(",LCU,backend,199\n")); assert!(!session.directory.join("data/LCU/unselected.csv").exists()); - assert!(matches!(logger.record(data(1.0)), Err(Error::NotRecording))); + // 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 + ); Ok(()) } #[tokio::test] -async fn double_play_preserves_session_and_old_tokens_cannot_enter_a_new_one() -> TestResult { - let (_temp, logger) = logging(WriterOptions::default())?; +async fn double_play_preserves_session_and_old_receptions_cannot_enter_a_new_one() -> TestResult { + let (_temp, logger, sender) = logging(WriterOptions::default())?; let first = logger.play(selection()).await?; - let stamp = logger.capture()?; - logger.record_at(stamp, data(1.0))?; + let old_reception = SystemTime::now(); + sender.send(data(old_reception, 1.0)).await?; assert_eq!( first, logger .play(SessionSelection { - measurements: Vec::new(), - connected_boards: Vec::new(), - selected_variables: json!([]), + measurements: vec![], + connected_boards: vec![], + selected_variables: serde_json::json!([]) }) .await? ); - logger.emergency_stop().await?; assert_eq!( - logger.status().last_stop.map(|r| r.reason), + logger.emergency_stop().await?.map(|r| r.reason), Some(StopReason::Emergency) ); let second = logger.play(selection()).await?; assert_ne!(first.id, second.id); - assert!(matches!( - logger.record_at(stamp, data(99.0)), - Err(Error::SessionChanged) - )); - logger.record(data(2.0))?; + 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); @@ -133,67 +112,68 @@ async fn double_play_preserves_session_and_old_tokens_cannot_enter_a_new_one() - } #[tokio::test] -async fn full_queue_reserves_stop_admission_and_drains_every_accepted_record() -> TestResult { - let (_temp, logger) = logging(WriterOptions { - queue_capacity: 2, - ..WriterOptions::default() - })?; - let session = logger.play(selection()).await?; - let stamp = logger.capture()?; - let mut notifications = logger.subscribe(); - { - // Hold the admission lock so the writer cannot consume the test queue. - let mut state = logger.shared.lock(); - assert_eq!( - logger.shared.admit(&mut state, stamp, data(1.0))?, - RecordOutcome::Accepted - ); - assert_eq!( - logger.shared.admit(&mut state, stamp, data(2.0))?, - RecordOutcome::Accepted - ); - assert!(matches!( - logger.shared.admit(&mut state, stamp, data(3.0)), - Err(Error::QueueFull) - )); - assert_eq!(state.phase, Phase::Stopping); - assert_eq!(state.queued_records, 2); - assert!(matches!(state.queue.back(), Some(Command::Stop))); - } - let report = timeout(Duration::from_secs(3), logger.stop()).await??; +async fn selection_can_change_between_sessions() -> TestResult { + let (_temp, logger, sender) = 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!( - report.as_ref().map(|r| r.reason), - Some(StopReason::Saturation) + fs::read_to_string(data_dir.join("unselected.csv"))? + .lines() + .count(), + 1 ); - let status = timeout(Duration::from_secs(3), notifications.changed()).await??; + let metadata: serde_json::Value = + software_core::logger::read_json(session.directory.join("logger_settings.json"))?; assert_eq!( - status.last_stop.map(|r| r.reason), - Some(StopReason::Saturation) + 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) = 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??; + // Either the control or the full-channel observation may win this race. + assert!(matches!( + report.map(|r| r.reason), + Some(StopReason::Requested | StopReason::Saturation) + )); assert_eq!( fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? .lines() .count(), - 2 - ); - logger.play(selection()).await?; - assert_eq!( - logger.status().last_stop.map(|r| r.reason), - Some(StopReason::Saturation) + 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) = logging(WriterOptions { + let (_temp, logger, sender) = logging(WriterOptions { flush_interval: Duration::from_millis(20), flush_bytes: u64::MAX, - ..WriterOptions::default() })?; let session = logger.play(selection()).await?; - logger.record(data(1.0))?; + 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?; @@ -202,43 +182,38 @@ async fn periodic_flush_persists_a_buffered_tail_without_stopping() -> TestResul #[tokio::test] async fn byte_threshold_flushes_without_waiting_for_the_timer() -> TestResult { - let (_temp, logger) = logging(WriterOptions { + let (_temp, logger, sender) = logging(WriterOptions { flush_interval: Duration::from_secs(60), flush_bytes: 1, - ..WriterOptions::default() })?; let session = logger.play(selection()).await?; - logger.record(data(1.0))?; + 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) = logging(WriterOptions { - queue_capacity: 1024, - ..WriterOptions::default() - })?; + let (_temp, logger, sender) = logging(WriterOptions::default())?; let session = logger.play(selection()).await?; - std::thread::scope(|scope| -> TestResult { - let workers: Vec<_> = (0..8) - .map(|producer| { - let logger = &logger; - scope.spawn(move || -> Result<(), Error> { - for n in 0..100 { - logger.record(data(f64::from(producer * 100 + n)))?; - } - Ok(()) - }) - }) - .collect(); - for worker in workers { - worker.join().map_err(|_| "producer panicked")??; - } - Ok(()) - })?; - timeout(Duration::from_secs(3), logger.shutdown()).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); @@ -256,34 +231,19 @@ async fn concurrent_producers_are_drained_before_shutdown() -> TestResult { #[tokio::test] async fn write_failure_stops_with_an_error_and_closes_the_other_files() -> TestResult { - let (_temp, logger) = logging(WriterOptions::default())?; - let session = logger.play(selection()).await?; + let (_temp, logger, sender) = 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")?; - let stamp = logger.capture()?; - { - let mut state = logger.shared.lock(); - logger.shared.admit( - &mut state, - stamp, - Record::Protection(ProtectionRecord { - board: "PCU".into(), - from: "PCU".into(), - to: "backend".into(), - protection_id: "1".into(), - severity: "fault".into(), - protection_type: "above".into(), - thresholds: Thresholds::Single(Value::Number(1.0)), - measurement_id: "temperature".into(), - value: Value::Number(2.0), - accumulated_time: None, - }), - )?; - logger.shared.admit(&mut state, stamp, data(7.0))?; - } + sender.send(data(SystemTime::now(), 7.0)).await?; + sender + .send(protection(PCU, AdjId((1 << 13) | 3003), 55.0)) + .await?; assert!(matches!( - timeout(Duration::from_secs(3), logger.stop()).await?, + timeout(WAIT, logger.stop()).await?, Err(Error::RecordingFailed(_)) )); assert_eq!( @@ -294,64 +254,57 @@ async fn write_failure_stops_with_an_error_and_closes_the_other_files() -> TestR fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? .ends_with(",LCU,backend,7\n") ); - // A later session can recover; its replacement removes the blocking file. + // Remove the obstruction even if the next session has a different second. + fs::remove_file(protections)?; logger.play(selection()).await?; - logger.record(data(8.0))?; + sender.send(data(SystemTime::now(), 8.0)).await?; logger.shutdown().await?; Ok(()) } #[tokio::test] async fn invalid_selection_is_rejected_before_replacing_existing_files() -> TestResult { - let (_temp, logger) = logging(WriterOptions::default())?; + let (_temp, logger, sender) = logging(WriterOptions::default())?; let session = logger.play(selection()).await?; - logger.record(data(1.0))?; + sender.send(data(SystemTime::now(), 1.0)).await?; logger.stop().await?; - let before = fs::read(session.directory.join("data/LCU/speed.csv"))?; + let file = session.directory.join("data/LCU/speed.csv"); + let before = fs::read(&file)?; let mut invalid = selection(); - invalid.measurements[0].measurement_id = "../escape".into(); + invalid.measurements[0].measurement_id = AdjId(7000); assert!(matches!( logger.play(invalid).await, - Err(Error::InvalidName(_)) + Err(Error::UnknownMeasurement { .. }) )); - assert_eq!( - fs::read(session.directory.join("data/LCU/speed.csv"))?, - before - ); + 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) = logging(WriterOptions::default())?; + let (_temp, logger, _sender) = logging(WriterOptions::default())?; let (reply, response) = oneshot::channel(); drop(response); - { - let mut state = logger.shared.lock(); - state.phase = Phase::Starting; - state.next_id = 1; - state.queue.push_back(Command::Start { - id: SessionId(1), - selection: selection(), - reply, - }); - logger.shared.publish(); - logger.shared.ready.notify_one(); - } - let report = timeout(Duration::from_secs(3), logger.emergency_stop()).await??; + 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_eq!(logger.play(selection()).await?.id, SessionId(2)); + 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) = logging(WriterOptions::default())?; + let (_temp, logger, sender) = logging(WriterOptions::default())?; let session = logger.play(selection()).await?; for n in 0..100 { - logger.record(data(f64::from(n)))?; + sender.send(data(SystemTime::now(), f64::from(n))).await?; } drop(logger); assert_eq!( @@ -360,16 +313,17 @@ async fn drop_is_a_fallback_drain_when_explicit_shutdown_was_missed() -> TestRes .count(), 100 ); + assert!(sender.is_closed()); Ok(()) } #[tokio::test] async fn controls_can_run_in_spawned_application_tasks() -> TestResult { - let (_temp, logger) = logging(WriterOptions::default())?; + let (_temp, logger, sender) = logging(WriterOptions::default())?; let logger = Arc::new(logger); let controller = logger.clone(); let session = tokio::spawn(async move { controller.play(selection()).await }).await??; - logger.record(data(1.0))?; + sender.send(data(SystemTime::now(), 1.0)).await?; let controller = logger.clone(); tokio::spawn(async move { controller.emergency_stop().await }).await??; assert!( @@ -380,3 +334,186 @@ async fn controls_can_run_in_spawned_application_tasks() -> TestResult { 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) = 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) = 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_pending_orders_do_not_write_partial_or_fabricated_rows() -> TestResult +{ + let (_temp, logger, sender) = 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(ToLogging::OrderSent { + at: SystemTime::now(), + board: Some(LCU), + 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 (adj, index) = definitions(); + let pod_data = Arc::new(adj.pod_data.clone()); + let config = event::EventConfig::default(); + let event::Channels { + udp, + tcp, + event: ends, + orders, + problems, + logging: input, + mut pipeline, + } = event::channels(&config); + let run = BackendRun::new( + Config { + logging_path: temp.path().into(), + ..Config::default() + }, + "adj", + )?; + let logger = Logging::new(run, adj, index.clone(), input, WriterOptions::default())?; + let event_task = event::spawn(config, ends, pod_data, index, None); + + 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. Receiving these four proves + // that all four passed through event's real logging sender. + for _ in 0..4 { + assert!(matches!( + timeout(WAIT, pipeline.recv()).await?, + Some(ToPipeline::Received(_)) + )); + } + 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()); + } + drop((udp, tcp, orders, problems)); + assert!(matches!( + timeout(WAIT, event_task).await??, + event::Stop::NetGone + )); + timeout(WAIT, logger.shutdown()).await??; + assert_eq!(logger.status().phase, Phase::Closed); + Ok(()) +} 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..47d4d6cbe --- /dev/null +++ b/backend/crates/station/src/logging/test_support.rs @@ -0,0 +1,163 @@ +//! 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::{ + adj::Adj, + 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 boards = [ + board( + LCU, + "LCU", + vec![telemetry, protection(LCU, ABOVE), protection(LCU, RANGE)], + ), + board(PCU, "PCU", vec![pcu_protection]), + ]; + let mut adj = Adj { + pod_data: PodData { + boards: boards.into_iter().map(|board| (board.id, board)).collect(), + }, + info: Default::default(), + }; + adj.info.message_levels = HashMap::from([(FAULT_MESSAGE, MessageLevel::Fault)]); + let index = Arc::new(Index::new(&adj.pod_data, Some(&adj.info.message_levels))); + (Arc::new(adj), 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/tests.rs b/backend/crates/station/src/logging/writer/tests.rs index bc856b203..0cb5b50cb 100644 --- a/backend/crates/station/src/logging/writer/tests.rs +++ b/backend/crates/station/src/logging/writer/tests.rs @@ -7,102 +7,49 @@ use std::{ }, }; -use serde_json::json; -use software_core::{logger::CsvFile, model::Value}; - -use super::*; -use crate::logging::{ - DataRecord, MeasurementKey, MessageRecord, OrderRecord, ProtectionRecord, Thresholds, +use software_core::{ + logger::CsvFile, + model::{AdjId, MessagePacket, OrderPacket}, + net::Event, }; +use tokio::sync::oneshot; +use tokio::time::timeout; -type TestResult = Result<(), Box>; - -fn selection() -> SessionSelection { - SessionSelection { - measurements: vec![MeasurementKey { - board: "LCU".into(), - measurement_id: "speed".into(), - }], - connected_boards: vec!["LCU".into()], - selected_variables: json!({"LCU": ["speed"]}), - } -} +use super::*; +use crate::logging::{Config, test_support::*}; fn time(wall_time: &str) -> Result { Ok(RecordTime { - session_id: SessionId(1), instant: u128::MAX, wall_time: wall_time.parse()?, }) } #[test] -fn all_csv_formats_preserve_fields_without_headers() -> TestResult { +fn native_csv_formats_preserve_fields_without_headers() -> TestResult { let temp = tempfile::tempdir()?; - let mut files = SessionFiles::open(temp.path(), &selection())?; + let (adj, index) = definitions(); + let catalog = Catalog::new(adj, 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, - &Record::Data(DataRecord { - from: "LCU".into(), - to: "backend".into(), - measurement_id: "speed".into(), - value: Value::Number(12.5), - }), - u64::MAX, - )?; - files.write( - stamp, - &Record::Data(DataRecord { - from: "LCU".into(), - to: "backend".into(), - measurement_id: "unselected".into(), - value: Value::Bool(true), - }), - u64::MAX, - )?; - files.write( - stamp, - &Record::Order(OrderRecord { - from: "backend".into(), - to: "LCU".into(), - id: "start".into(), - payload: "{ \"mode\": \"run\" }".into(), - }), - u64::MAX, - )?; - let mut protection = ProtectionRecord { - board: "LCU".into(), - from: "LCU".into(), - to: "backend".into(), - protection_id: "42".into(), - severity: "fault".into(), - protection_type: "above".into(), - thresholds: Thresholds::Single(Value::Number(50.0)), - measurement_id: "temperature".into(), - value: Value::Number(55.0), - accumulated_time: Some("500ms".into()), - }; - files.write(stamp, &Record::Protection(protection.clone()), u64::MAX)?; - protection.protection_type = "range".into(); - protection.thresholds = Thresholds::Range { - min: Value::Number(0.0), - max: Value::Number(100.0), - }; - protection.accumulated_time = None; - files.write(stamp, &Record::Protection(protection), u64::MAX)?; - files.write( - stamp, - &Record::Message(MessageRecord { - from: "LCU".into(), - to: "backend".into(), - board: "LCU".into(), - source: "control.cpp:123".into(), - severity: "fault".into(), - message: "failed, \"overload\"\nagain".into(), - }), + &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!( @@ -110,13 +57,14 @@ fn all_csv_formats_preserve_fields_without_headers() -> TestResult { "35000,LCU,backend,12.5\n" ); assert!(!temp.path().join("data/LCU/unselected.csv").exists()); - assert_eq!( - fs::read_to_string(temp.path().join("order/order.csv"))?, - "35000,backend,LCU,start,\"{ \"\"mode\"\": \"\"run\"\" }\",2026-07-15T15-30-05+02:00\n" - ); + // The current event contract cannot supply the original frontend JSON. + assert!(fs::read(temp.path().join("order/order.csv"))?.is_empty()); assert_eq!( fs::read_to_string(temp.path().join("protections/LCU.csv"))?, - "35000,LCU,backend,42,fault,above,50,,temperature,55,500ms\n35000,LCU,backend,42,fault,range,0,100,temperature,55,0\n" + format!( + "35000,LCU,backend,{},fault,above,50,,3002,55,\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"))?, @@ -126,30 +74,58 @@ fn all_csv_formats_preserve_fields_without_headers() -> TestResult { } #[test] -fn winter_order_offset_and_large_integer_instants_are_preserved() -> TestResult { +fn order_formatter_preserves_original_json_summer_and_winter_offsets_and_large_instants() +-> TestResult { let temp = tempfile::tempdir()?; - let mut files = SessionFiles::open(temp.path(), &selection())?; - files.write( + let mut orders = OrderLogger::open(temp.path())?; + let mut summer = time("2026-07-15T13:30:05Z")?; + summer.instant = 35000; + // Exercise the formatter directly; OrderSent cannot yet supply this JSON. + orders.write( + summer, + AdjId(2000), + "LCU", + "{ \"mode\": \"run\" }", + u64::MAX, + )?; + orders.write( time("2026-11-27T14:30:05Z")?, - &Record::Order(OrderRecord { - from: "backend".into(), - to: "LCU".into(), - id: "off".into(), - payload: "{}".into(), - }), + AdjId(2001), + "LCU", + "{}", u64::MAX, )?; - assert!(files.close().is_empty()); + orders.file.close()?; assert_eq!( fs::read_to_string(temp.path().join("order/order.csv"))?, format!( - "{},backend,LCU,off,{{}},2026-11-27T15-30-05+01:00\n", + "35000,backend,LCU,2000,\"{{ \"\"mode\"\": \"\"run\"\" }}\",2026-07-15T15-30-05+02:00\n{},backend,LCU,2001,{{}},2026-11-27T15-30-05+01:00\n", u128::MAX ) ); Ok(()) } +#[test] +fn pending_order_contract_is_reported_without_writing_a_row() -> TestResult { + let temp = tempfile::tempdir()?; + let (adj, index) = definitions(); + let catalog = Catalog::new(adj, index); + let mut files = SessionFiles::open(temp.path(), &selection(), &catalog)?; + let order = ToLogging::OrderSent { + at: SystemTime::now(), + board: Some(LCU), + order: OrderPacket::new(AdjId(2000), vec![]), + }; + assert!(matches!( + files.write(time("2026-11-27T14:30:05Z")?, &order, u64::MAX, &catalog), + Err(Error::OrderContractPending) + )); + assert!(files.close().is_empty()); + 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 { @@ -189,30 +165,125 @@ fn close_attempts_every_file_even_when_one_flush_fails() -> TestResult { &[], )?, ]; - let errors = close_files(files.into_iter()); - assert_eq!(errors.len(), 1); + assert_eq!(close_files(files.into_iter()).len(), 1); assert!(first.load(Ordering::SeqCst)); assert!(second.load(Ordering::SeqCst)); Ok(()) } +#[tokio::test] +async fn observed_full_input_stops_notifies_drains_and_keeps_the_receiver_alive() -> TestResult { + let temp = tempfile::tempdir()?; + let run = BackendRun::new( + Config { + logging_path: temp.path().into(), + ..Config::default() + }, + "adj", + )?; + let (adj, index) = definitions(); + let (sender, input) = mpsc::channel(2); + let (controls, control_rx) = mpsc::unbounded_channel(); + let (updates, mut status) = watch::channel(Status::default()); + let mut writer = Writer { + run, + input, + controls: control_rx, + updates, + status: Status::default(), + catalog: Catalog::new(adj, index), + options: WriterOptions::default(), + active: None, + next_id: 0, + order_contract_reported: false, + }; + let session = writer.start(selection()).await?; + // Fill the real channel before the consumer runs, so saturation is + // deterministic rather than dependent on OS thread scheduling. + sender.try_send(data(SystemTime::now(), 1.0))?; + sender.try_send(data(SystemTime::now(), 2.0))?; + let worker = tokio::spawn(writer.run()); + timeout(WAIT, async { + loop { + if status.borrow().last_stop.is_some() { + break; + } + status.changed().await?; + } + Ok::<(), watch::error::RecvError>(()) + }) + .await??; + assert_eq!(status.borrow().phase, Phase::Inactive); + assert_eq!( + status + .borrow() + .last_stop + .as_ref() + .map(|report| report.reason), + Some(StopReason::Saturation) + ); + assert_eq!( + fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? + .lines() + .count(), + 2 + ); + assert!(!sender.is_closed()); + let (reply, response) = oneshot::channel(); + controls.send(Control::Play { + selection: selection(), + reply, + })?; + let next = timeout(WAIT, response).await???; + assert_ne!(session.id, next.id); + assert_eq!( + status + .borrow() + .last_stop + .as_ref() + .map(|report| report.reason), + Some(StopReason::Saturation) + ); + let (reply, response) = oneshot::channel(); + controls.send(Control::Shutdown { + at: SystemTime::now(), + reply: Some(reply), + })?; + timeout(WAIT, response).await??; + timeout(WAIT, worker).await??; + assert_eq!(status.borrow().phase, Phase::Closed); + Ok(()) +} + #[test] -fn unexpected_exit_releases_queued_start_replies() { - let shared = Arc::new(Shared::new(2)); - let (reply, mut response) = tokio::sync::oneshot::channel(); - { - let mut state = shared.lock(); - state.phase = Phase::Starting; - state.queue.push_back(Command::Start { - id: SessionId(1), - selection: selection(), - reply, - }); - } - drop(ExitGuard(shared.clone())); - assert_eq!(shared.lock().phase, Phase::Closed); +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(tokio::sync::oneshot::error::TryRecvError::Closed) + Err(oneshot::error::TryRecvError::Closed) )); + Ok(()) } From 0026070eed8371fcd8c217d30deea197d14765da Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Thu, 3 Dec 2026 13:31:38 +0100 Subject: [PATCH 06/19] fix(backent, logging): correct order logging to match OrderPacket --- backend/crates/station/src/logging/README.md | 47 ++++--- backend/crates/station/src/logging/catalog.rs | 19 ++- backend/crates/station/src/logging/error.rs | 4 +- backend/crates/station/src/logging/order.rs | 55 ++++++-- .../station/src/logging/service/tests.rs | 85 +++++++++++- backend/crates/station/src/logging/session.rs | 3 +- backend/crates/station/src/logging/writer.rs | 28 ++-- .../station/src/logging/writer/tests.rs | 122 ++++++++++++++---- 8 files changed, 280 insertions(+), 83 deletions(-) diff --git a/backend/crates/station/src/logging/README.md b/backend/crates/station/src/logging/README.md index 4748a9c69..381669ce8 100644 --- a/backend/crates/station/src/logging/README.md +++ b/backend/crates/station/src/logging/README.md @@ -49,6 +49,8 @@ internal controls. - `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 + as compact JSON in the order CSV's payload cell. `Catalog` keeps the supplied ADJ and protocol index shared. It builds a small measurement locator once, using `(BoardId, AdjId)` as keys. It resolves: @@ -119,10 +121,6 @@ fn start_logging_consumer( These are deliberately not filled in with reconstructed or guessed data: -- **Orders:** `OrderSent` is later than frontend reception and contains no - original JSON text. The consumer reports this pending contract once and - keeps draining. It does not write misleading order rows. The order file - and formatter are retained for the eventual original-payload input. - **Accumulated protection timing:** the current `ProtectionPacket` has no separate accumulated-time result. Untimed protections write `0`; timed protections temporarily leave that cell empty to mean unavailable. The @@ -238,8 +236,9 @@ startup, its `instant` will be `35` with `time_unit = "ms"`, or `35000` with `"us"`. The low-level session retains its monotonic clock for elapsed-time helpers. The -`ToLogging` path uses the upstream `Notification::at` (`SystemTime`) against -the session's wall-clock origin, so queue delays are not added to `instant`. +`ToLogging` path uses the upstream `Notification::at` or `OrderSent::at` +(`SystemTime`) against the session's wall-clock origin, so queue delays are +not added to `instant`. A monotonic timestamp at original reception is not available in the current event contract; immunity to wall-clock changes therefore remains pending. @@ -312,16 +311,28 @@ instant,from,to,id,payload,timestamp | Field | Content | | --- | --- | | `instant` | Time since the session started, in `time_unit`. | -| `from` | Order source. | -| `to` | Order destination. | +| `from` | `backend`. | +| `to` | ADJ board name, or `all` when `OrderSent.board` is `None`. | | `id` | Order ID. | -| `payload` | JSON received from the frontend over WebSocket, preserved as text. | -| `timestamp` | Order date and time, using the format and offset described above. | +| `payload` | The confirmed `OrderPacket` as compact JSON: numeric `id` and positional `values`. | +| `timestamp` | TCP confirmation date and time from `OrderSent.at`, using the format and offset described above. | -The required behavior is to record an order **when received from the frontend**, -with the original JSON. The current `ToLogging::OrderSent` cannot satisfy that -contract, so writing order rows is deferred rather than substituting a later -timestamp or reconstructed payload. +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. + +Each payload is a single-line JSON object inside the CSV cell, for example: + +```json +{"id":2000,"values":[1.5,true,"run"]} +``` + +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 for the CSV cell. There is no separate +JSONL file or extra newline within this cell. Non-finite numeric values cannot +be represented as JSON and stop recording with an error before writing a row. ### Protections: protections/ @@ -559,7 +570,6 @@ buffers, and explicit flush and close operations. - 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. -- Original order JSON and frontend reception time in the input contract. - Board-supplied accumulated timing and monotonic reception timestamps. - Disconnection stop rule when multiple frontends are connected. - Frontend notification format and integration through the application modules. @@ -579,9 +589,10 @@ replies, fallback drop and input closure. An integration scenario connects sessions, then checks the persisted CSVs and orderly shutdown. Writer tests check headerless CSVs, escaping, protection metadata, missing -board timing, the order formatter's original JSON and timezone offsets, +board timing, serialized OrderPacket values and timezone offsets, large integer instants, deterministic full-channel handling and failed closes. -Pending `OrderSent` input is explicitly checked to leave the order CSV empty; -testing the formatter directly does not imply that order reception is wired. +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/catalog.rs b/backend/crates/station/src/logging/catalog.rs index 09ab9cc26..abca260a7 100644 --- a/backend/crates/station/src/logging/catalog.rs +++ b/backend/crates/station/src/logging/catalog.rs @@ -151,9 +151,16 @@ impl Catalog { /// `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 ToLogging::Received(notification) = incoming else { - // OrderSent has neither the original JSON nor frontend reception time. - return Err(Error::OrderContractPending); + let notification = match incoming { + ToLogging::OrderSent { board, .. } => { + // 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)?; + } + 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. @@ -175,9 +182,9 @@ impl Catalog { Event::Received(Packet::Message(packet)) => { self.message_level(notification.board, packet.id)?; } - // Receiving a decoded order does not restore the missing original - // frontend JSON or establish its frontend reception timestamp. - Event::Received(Packet::Order(_)) => return Err(Error::OrderContractPending), + // 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/error.rs b/backend/crates/station/src/logging/error.rs index 2083a9524..7896f8465 100644 --- a/backend/crates/station/src/logging/error.rs +++ b/backend/crates/station/src/logging/error.rs @@ -22,8 +22,8 @@ pub enum Error { UnexpectedPacketType(AdjId), #[error("packet {0:?} value count differs from its ADJ measurement count")] MeasurementCount(AdjId), - #[error("order logging awaits original frontend JSON and reception time in the event contract")] - OrderContractPending, + #[error("couldn't serialize the logged OrderPacket: {0}")] + OrderPayload(#[source] serde_json::Error), #[error("invalid logging file component: {0:?}")] InvalidName(String), #[error("flush interval and flush byte threshold must be positive")] diff --git a/backend/crates/station/src/logging/order.rs b/backend/crates/station/src/logging/order.rs index 078b06b59..b7d85d634 100644 --- a/backend/crates/station/src/logging/order.rs +++ b/backend/crates/station/src/logging/order.rs @@ -4,14 +4,18 @@ //! `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 are recorded when received from the frontend over WebSocket; -//! `payload` preserves the received JSON as text. There is no header. +//! Orders come from event's `OrderSent`, using its TCP confirmation time. +//! `payload` is the OrderPacket as compact JSON in one CSV cell. No header. //! //! This component owns a `software_core::logger::CsvFile` and formats rows. use std::path::Path; -use software_core::{logger::CsvFile, model::AdjId}; +use serde::{Serialize, Serializer, ser::SerializeSeq}; +use software_core::{ + logger::CsvFile, + model::{OrderPacket, Value}, +}; use super::{Error, output::flush_if_due, session::RecordTime}; @@ -28,17 +32,20 @@ impl OrderLogger { }) } - /// Pending input contract: only call with the original frontend JSON. - /// Writes a complete row in the order.csv file, following this order per columns - /// instant,from,to,order_id,payload,timestamp + /// Serialize the confirmed packet before starting a row, so a payload + /// failure cannot leave a partial CSV record. Values remain positional. pub fn write( &mut self, time: RecordTime, - id: AdjId, + order: &OrderPacket, to: &str, - payload: &str, threshold: u64, ) -> Result<(), Error> { + let payload = serde_json::to_string(&Payload { + id: order.id.0, + values: &order.values, + }) + .map_err(Error::OrderPayload)?; let timestamp = time .wall_time .in_tz("Europe/Madrid")? @@ -49,11 +56,39 @@ impl OrderLogger { .instant(time.instant) .text("backend") // orders will always come from the backend and never from the boards .text(to) - .int(i64::from(id.0)) - .text(payload) + .int(i64::from(order.id.0)) + .text(&payload) .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. +#[derive(Serialize)] +struct Payload<'a> { + id: u16, + #[serde(serialize_with = "serialize_values")] + values: &'a [Value], +} + +fn serialize_values(values: &[Value], serializer: S) -> Result { + let mut sequence = serializer.serialize_seq(Some(values.len()))?; + for value in values { + match value { + Value::Number(value) => { + // JSON has no NaN/infinity; never silently replace a value + // with null and present that as the packet that was sent. + if !value.is_finite() { + return Err(serde::ser::Error::custom("non-finite order value")); + } + sequence.serialize_element(value)?; + } + Value::Bool(value) => sequence.serialize_element(value)?, + Value::Enum(value) => sequence.serialize_element(value)?, + } + } + sequence.end() +} diff --git a/backend/crates/station/src/logging/service/tests.rs b/backend/crates/station/src/logging/service/tests.rs index ad7bbd6b5..0f5cfb25e 100644 --- a/backend/crates/station/src/logging/service/tests.rs +++ b/backend/crates/station/src/logging/service/tests.rs @@ -402,7 +402,7 @@ async fn input_closure_flushes_the_session_and_releases_the_worker() -> TestResu } #[tokio::test] -async fn invalid_packets_and_pending_orders_do_not_write_partial_or_fabricated_rows() -> TestResult +async fn invalid_packets_and_received_orders_do_not_write_partial_or_duplicate_rows() -> TestResult { let (_temp, logger, sender) = logging(WriterOptions::default())?; let session = logger.play(selection()).await?; @@ -424,11 +424,11 @@ async fn invalid_packets_and_pending_orders_do_not_write_partial_or_fabricated_r .send(received(LCU, SystemTime::now(), Event::Connected)) .await?; sender - .send(ToLogging::OrderSent { - at: SystemTime::now(), - board: Some(LCU), - order: OrderPacket::new(AdjId(2000), vec![]), - }) + .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?; @@ -468,7 +468,21 @@ async fn event_routes_to_the_real_logger_across_session_stop_and_restart() -> Te "adj", )?; let logger = Logging::new(run, adj, index.clone(), input, WriterOptions::default())?; - let event_task = event::spawn(config, ends, pod_data, index, None); + 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 { @@ -508,6 +522,27 @@ async fn event_routes_to_the_real_logger_across_session_stop_and_restart() -> Te } 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,\"{{\"\"id\"\":2000,\"\"values\"\":[true]}}\",{timestamp}\n" + ))); drop((udp, tcp, orders, problems)); assert!(matches!( timeout(WAIT, event_task).await??, @@ -517,3 +552,39 @@ async fn event_routes_to_the_real_logger_across_session_stop_and_restart() -> Te assert_eq!(logger.status().phase, Phase::Closed); Ok(()) } + +#[tokio::test] +async fn an_unrepresentable_order_payload_stops_recording_and_flushes_healthy_files() -> TestResult +{ + let (_temp, logger, sender) = logging(WriterOptions::default())?; + let session = logger.play(selection()).await?; + sender.send(data(SystemTime::now(), 7.0)).await?; + sender + .send(ToLogging::OrderSent { + at: SystemTime::now(), + board: Some(LCU), + order: OrderPacket::new( + AdjId(2000), + vec![software_core::model::Value::Number(f64::NAN)], + ), + }) + .await?; + assert!(matches!( + timeout(WAIT, logger.stop()).await?, + Err(Error::RecordingFailed(_)) + )); + assert_eq!( + logger.status().last_stop.map(|report| report.reason), + Some(StopReason::WriteError) + ); + assert!(fs::read(session.directory.join("order/order.csv"))?.is_empty()); + assert!( + fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? + .ends_with(",LCU,backend,7\n") + ); + assert!(matches!( + logger.shutdown().await, + Err(Error::RecordingFailed(_)) + )); + Ok(()) +} diff --git a/backend/crates/station/src/logging/session.rs b/backend/crates/station/src/logging/session.rs index 3c7826b6e..3e8c703b8 100644 --- a/backend/crates/station/src/logging/session.rs +++ b/backend/crates/station/src/logging/session.rs @@ -71,7 +71,8 @@ impl SessionId { } } -/// Writer-private stamp, always derived from the incoming event's reception time. +/// 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, diff --git a/backend/crates/station/src/logging/writer.rs b/backend/crates/station/src/logging/writer.rs index 0ecb9ef0a..e7ba54a68 100644 --- a/backend/crates/station/src/logging/writer.rs +++ b/backend/crates/station/src/logging/writer.rs @@ -21,10 +21,10 @@ use super::{ StopReason, StopReport, ToLogging, catalog::Catalog, control::Control, - output::{close_files, flush_files}, data::DataLogger, messages::MessagesLogger, order::OrderLogger, + output::{close_files, flush_files}, protections::ProtectionsLogger, session::RecordTime, status::checked_report, @@ -96,10 +96,15 @@ impl SessionFiles { threshold: u64, catalog: &Catalog, ) -> Result<(), Error> { - let ToLogging::Received(notification) = record else { - // OrderSent lacks the original frontend JSON and reception time. - // Keep that contract pending instead of inventing an order row. - return Err(Error::OrderContractPending); + 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, threshold); + } + ToLogging::Received(notification) => notification, }; let board = catalog.board(notification.board)?; match ¬ification.event { @@ -133,7 +138,7 @@ impl SessionFiles { catalog.message_level(notification.board, packet.id)?, threshold, ), - Event::Received(Packet::Order(_)) => Err(Error::OrderContractPending), + Event::Received(Packet::Order(_)) => Ok(()), } } @@ -194,7 +199,6 @@ struct Writer { options: WriterOptions, active: Option, next_id: u64, - order_contract_reported: bool, } enum Step { @@ -231,7 +235,6 @@ pub(super) fn run( status: Status::default(), active: None, next_id: 0, - order_contract_reported: false, } .run(), ), @@ -370,15 +373,6 @@ impl Writer { }; match self.catalog.validate(incoming) { Ok(false) => return false, - Err(Error::OrderContractPending) => { - if !self.order_contract_reported { - tracing::warn!( - "OrderSent logging pending: original frontend JSON and reception time are unavailable" - ); - self.order_contract_reported = true; - } - return false; - } Err(error) => { tracing::warn!(%error, "logging input could not be recorded"); return false; diff --git a/backend/crates/station/src/logging/writer/tests.rs b/backend/crates/station/src/logging/writer/tests.rs index 0cb5b50cb..69992eb94 100644 --- a/backend/crates/station/src/logging/writer/tests.rs +++ b/backend/crates/station/src/logging/writer/tests.rs @@ -9,7 +9,7 @@ use std::{ use software_core::{ logger::CsvFile, - model::{AdjId, MessagePacket, OrderPacket}, + model::{AdjId, MessagePacket, OrderPacket, Value}, net::Event, }; use tokio::sync::oneshot; @@ -57,7 +57,7 @@ fn native_csv_formats_preserve_fields_without_headers() -> TestResult { "35000,LCU,backend,12.5\n" ); assert!(!temp.path().join("data/LCU/unselected.csv").exists()); - // The current event contract cannot supply the original frontend JSON. + // 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"))?, @@ -74,32 +74,33 @@ fn native_csv_formats_preserve_fields_without_headers() -> TestResult { } #[test] -fn order_formatter_preserves_original_json_summer_and_winter_offsets_and_large_instants() --> TestResult { +fn order_payload_offsets_and_large_instants_are_preserved() -> TestResult { let temp = tempfile::tempdir()?; let mut orders = OrderLogger::open(temp.path())?; let mut summer = time("2026-07-15T13:30:05Z")?; summer.instant = 35000; - // Exercise the formatter directly; OrderSent cannot yet supply this JSON. - orders.write( - summer, + let order = OrderPacket::new( AdjId(2000), - "LCU", - "{ \"mode\": \"run\" }", - u64::MAX, - )?; + vec![ + Value::Number(1.5), + Value::Bool(true), + Value::Enum("run, \"fast\"\nnext".into()), + ], + ); + orders.write(summer, &order, "LCU", u64::MAX)?; orders.write( time("2026-11-27T14:30:05Z")?, - AdjId(2001), + &OrderPacket::new(AdjId(2001), vec![]), "LCU", - "{}", u64::MAX, )?; orders.file.close()?; + let payload = r#"{"id":2000,"values":[1.5,true,"run, \"fast\"\nnext"]}"#; assert_eq!( fs::read_to_string(temp.path().join("order/order.csv"))?, format!( - "35000,backend,LCU,2000,\"{{ \"\"mode\"\": \"\"run\"\" }}\",2026-07-15T15-30-05+02:00\n{},backend,LCU,2001,{{}},2026-11-27T15-30-05+01:00\n", + "35000,backend,LCU,2000,\"{}\",2026-07-15T15-30-05+02:00\n{},backend,LCU,2001,\"{{\"\"id\"\":2001,\"\"values\"\":[]}}\",2026-11-27T15-30-05+01:00\n", + payload.replace('"', "\"\""), u128::MAX ) ); @@ -107,21 +108,45 @@ fn order_formatter_preserves_original_json_summer_and_winter_offsets_and_large_i } #[test] -fn pending_order_contract_is_reported_without_writing_a_row() -> TestResult { +fn confirmed_broadcast_orders_use_all_as_destination() -> TestResult { let temp = tempfile::tempdir()?; let (adj, index) = definitions(); let catalog = Catalog::new(adj, index); let mut files = SessionFiles::open(temp.path(), &selection(), &catalog)?; let order = ToLogging::OrderSent { at: SystemTime::now(), - board: Some(LCU), - order: OrderPacket::new(AdjId(2000), vec![]), + board: None, + order: OrderPacket::new(AdjId(0), vec![]), }; - assert!(matches!( - files.write(time("2026-11-27T14:30:05Z")?, &order, u64::MAX, &catalog), - Err(Error::OrderContractPending) - )); + 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,\"{{\"\"id\"\":0,\"\"values\"\":[]}}\",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())?; + for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + assert!(matches!( + orders.write( + time("2026-11-27T14:30:05Z")?, + &OrderPacket::new(AdjId(2000), vec![Value::Number(value)]), + "LCU", + u64::MAX + ), + Err(Error::OrderPayload(_)) + )); + } + orders.file.close()?; assert!(fs::read(temp.path().join("order/order.csv"))?.is_empty()); Ok(()) } @@ -195,7 +220,6 @@ async fn observed_full_input_stops_notifies_drains_and_keeps_the_receiver_alive( options: WriterOptions::default(), active: None, next_id: 0, - order_contract_reported: false, }; let session = writer.start(selection()).await?; // Fill the real channel before the consumer runs, so saturation is @@ -287,3 +311,57 @@ fn dropping_pending_controls_releases_start_replies() -> TestResult { )); Ok(()) } + +#[tokio::test] +async fn orders_use_confirmation_time_for_elapsed_and_wall_timestamps() -> TestResult { + let temp = tempfile::tempdir()?; + let run = BackendRun::new( + Config { + logging_path: temp.path().into(), + ..Config::default() + }, + "adj", + )?; + let (adj, index) = definitions(); + let (_sender, input) = mpsc::channel(16); + let (_controls, controls) = mpsc::unbounded_channel(); + let (updates, _status) = watch::channel(Status::default()); + let mut writer = Writer { + run, + input, + controls, + updates, + status: Status::default(), + catalog: Catalog::new(adj, 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(2000), 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)); + writer.stop(StopReason::Requested, at).await; + 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,2000,\"{{\"\"id\"\":2000,\"\"values\"\":[]}}\",{timestamp}\n") + ); + Ok(()) +} From 7e2ab8a46a544bb7dcbcf7f11c2b140d470acf4f Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Thu, 3 Dec 2026 15:03:47 +0100 Subject: [PATCH 07/19] fix(backend, logging): log protection durations and simplify session timing --- .../crates/station/src/logging/protections.rs | 27 +++++++-- backend/crates/station/src/logging/session.rs | 39 +++--------- .../station/src/logging/session/tests.rs | 35 ++++------- .../station/src/logging/writer/tests.rs | 59 ++++++++++++++++++- 4 files changed, 97 insertions(+), 63 deletions(-) diff --git a/backend/crates/station/src/logging/protections.rs b/backend/crates/station/src/logging/protections.rs index 22136e351..cc672fcc0 100644 --- a/backend/crates/station/src/logging/protections.rs +++ b/backend/crates/station/src/logging/protections.rs @@ -1,9 +1,10 @@ //! Protection rows resolved from a received packet and the ADJ definition. -//! Board-supplied accumulated timing is not present in the current packet model. +//! The final time field preserves the duration in the ADJ protection definition. use std::{ collections::HashMap, path::{Path, PathBuf}, + time::Duration, }; use software_core::{ @@ -80,10 +81,9 @@ impl ProtectionsLogger { None => row.text(""), }; let row = value_field(row.int(i64::from(measurement.id.0)), &packet.value); - // Never substitute the ADJ's configured duration for a board result. - // An empty timed-protection cell explicitly means unavailable for now. - row.text(if protection.time.is_zero() { "0" } else { "" }) - .end()?; + // 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(()) } @@ -95,3 +95,20 @@ impl ProtectionsLogger { 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/session.rs b/backend/crates/station/src/logging/session.rs index 3e8c703b8..ba60cb170 100644 --- a/backend/crates/station/src/logging/session.rs +++ b/backend/crates/station/src/logging/session.rs @@ -4,11 +4,11 @@ //! `YYYY-MM-DDTHH-MM-SS` below the backend startup directory. Each session has //! `logger_settings.json` and `data/`, `protections/`, `order/`, `messages/`. //! -//! A monotonic `std::time::Instant` establishes the session's zero point. -//! Recorded elapsed times use the configured time unit; the first event need -//! not occur at zero. Wall-clock time is used separately for directory names -//! and order timestamps. A new session with an existing directory name -//! overwrites that session, without retaining files from its old selection. +//! 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. @@ -16,7 +16,7 @@ use std::{ fs, io, path::{Path, PathBuf}, - time::{Instant, SystemTime}, + time::SystemTime, }; use jiff::Timestamp; @@ -163,15 +163,14 @@ impl BackendRun { &mut self, selected_variables: impl Serialize, ) -> Result { - self.prepare_session_at(selected_variables, Timestamp::now(), Instant::now()) + self.prepare_session_at(selected_variables, Timestamp::now()) } - /// Captures the wall and monotonic clocks at the same session boundary. + /// 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, - clock_origin: Instant, ) -> Result { // Validate serialization before removing any existing session. let selected_variables = serde_json::to_value(selected_variables)?; @@ -210,18 +209,16 @@ impl BackendRun { Ok(Session { directory, metadata, - clock_origin, wall_origin: started_at.into(), }) } } -/// Prepared session metadata and its monotonic clock; no CSVs are open yet. +/// Prepared session metadata and calendar time origin; no CSVs are open yet. #[derive(Debug)] pub struct Session { directory: PathBuf, metadata: SessionSettings, - clock_origin: Instant, wall_origin: SystemTime, } @@ -250,24 +247,6 @@ impl Session { pub fn selected_variables(&self) -> &Value { &self.metadata.selected_variables } - - /// Elapsed time for an externally supplied monotonic reception timestamp. - /// - /// An event predating this session returns `None`, not a fabricated zero. - /// The current ToLogging input supplies SystemTime instead of Instant. - pub fn instant_at(&self, received_at: Instant) -> Option { - received_at - .checked_duration_since(self.clock_origin) - .map(|elapsed| self.metadata.settings.time_unit.convert(elapsed)) - } - - /// Current elapsed session time in the configured unit. - pub fn elapsed(&self) -> u128 { - self.metadata - .settings - .time_unit - .convert(self.clock_origin.elapsed()) - } } fn directory_date(timestamp: Timestamp) -> Result { diff --git a/backend/crates/station/src/logging/session/tests.rs b/backend/crates/station/src/logging/session/tests.rs index d63345c62..a3b109fa9 100644 --- a/backend/crates/station/src/logging/session/tests.rs +++ b/backend/crates/station/src/logging/session/tests.rs @@ -1,4 +1,4 @@ -use std::{fs, time::Duration}; +use std::fs; use serde_json::json; use software_core::logger::read_json; @@ -28,9 +28,7 @@ fn backend_and_session_settings_have_their_own_dates_and_selection() -> TestResu assert!(backend_directory.join("others").is_dir()); let selected = json!({"LCU": ["speed", "temperature"]}); - let clock_origin = Instant::now(); - let session = - run.prepare_session_at(&selected, "2026-11-27T14:31:05Z".parse()?, clock_origin)?; + 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!( @@ -52,14 +50,8 @@ fn backend_and_session_settings_have_their_own_dates_and_selection() -> TestResu assert!(session.directory().join(name).is_dir()); assert_eq!(fs::read_dir(session.directory().join(name))?.count(), 0); } - assert_eq!(session.instant_at(clock_origin), Some(0)); - assert_eq!( - session.instant_at(clock_origin + Duration::from_millis(35)), - Some(35000) - ); - if let Some(earlier) = clock_origin.checked_sub(Duration::from_millis(1)) { - assert_eq!(session.instant_at(earlier), None); - } + let started_at: Timestamp = "2026-11-27T14:31:05Z".parse()?; + assert_eq!(session.wall_origin(), SystemTime::from(started_at)); Ok(()) } @@ -68,11 +60,7 @@ fn session_replacement_removes_stale_files_and_keeps_backend_files() -> TestResu 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()?, - Instant::now(), - )?; + 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")?; @@ -81,11 +69,8 @@ fn session_replacement_removes_stale_files_and_keeps_backend_files() -> TestResu 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()?, - Instant::now(), - )?; + 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))?; @@ -126,14 +111,14 @@ 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, Instant::now())?; + 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, Instant::now()), + run.prepare_session_at(invalid, timestamp), Err(Error::Selection(_)) )); assert_eq!(fs::read(settings_file)?, before); @@ -150,7 +135,7 @@ fn session_replacement_does_not_follow_symlinks() -> TestResult { 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()?, Instant::now()), + 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"); diff --git a/backend/crates/station/src/logging/writer/tests.rs b/backend/crates/station/src/logging/writer/tests.rs index 69992eb94..bea32d8b1 100644 --- a/backend/crates/station/src/logging/writer/tests.rs +++ b/backend/crates/station/src/logging/writer/tests.rs @@ -9,7 +9,7 @@ use std::{ use software_core::{ logger::CsvFile, - model::{AdjId, MessagePacket, OrderPacket, Value}, + model::{AdjId, MessagePacket, OrderPacket, Protection, ProtectionPacket, Value}, net::Event, }; use tokio::sync::oneshot; @@ -62,7 +62,7 @@ fn native_csv_formats_preserve_fields_without_headers() -> TestResult { assert_eq!( fs::read_to_string(temp.path().join("protections/LCU.csv"))?, format!( - "35000,LCU,backend,{},fault,above,50,,3002,55,\n35000,LCU,backend,{},warning,range,0,100,3002,105,0\n", + "35000,LCU,backend,{},fault,above,50,,3002,55,500ms\n35000,LCU,backend,{},warning,range,0,100,3002,105,0\n", ABOVE.0, RANGE.0 ) ); @@ -313,7 +313,7 @@ fn dropping_pending_controls_releases_start_replies() -> TestResult { } #[tokio::test] -async fn orders_use_confirmation_time_for_elapsed_and_wall_timestamps() -> TestResult { +async fn events_use_at_for_elapsed_and_order_wall_timestamps() -> TestResult { let temp = tempfile::tempdir()?; let run = BackendRun::new( Config { @@ -354,7 +354,13 @@ async fn orders_use_confirmation_time_for_elapsed_and_wall_timestamps() -> TestR // 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") @@ -365,3 +371,50 @@ async fn orders_use_confirmation_time_for_elapsed_and_wall_timestamps() -> TestR ); Ok(()) } + +#[test] +fn protection_time_preserves_the_adj_duration_and_its_precision() -> TestResult { + let temp = tempfile::tempdir()?; + let (adj, index) = definitions(); + let catalog = Catalog::new(adj, 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(()) +} From ada1427d4c05ca116b1bd23e6633aac521fab98f Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Thu, 3 Dec 2026 15:04:00 +0100 Subject: [PATCH 08/19] docs(backend, logging): document WebSocket integration plan --- backend/crates/station/src/logging/README.md | 49 ++-- .../src/logging/WEBSOCKET_INTEGRATION.md | 273 ++++++++++++++++++ 2 files changed, 299 insertions(+), 23 deletions(-) create mode 100644 backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md diff --git a/backend/crates/station/src/logging/README.md b/backend/crates/station/src/logging/README.md index 381669ce8..3d1f1ede1 100644 --- a/backend/crates/station/src/logging/README.md +++ b/backend/crates/station/src/logging/README.md @@ -5,6 +5,9 @@ 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 @@ -121,15 +124,6 @@ fn start_logging_consumer( These are deliberately not filled in with reconstructed or guessed data: -- **Accumulated protection timing:** the current `ProtectionPacket` has no - separate accumulated-time result. Untimed protections write `0`; timed - protections temporarily leave that cell empty to mean unavailable. The - configured ADJ duration is not presented as a result sent by the board. -- **Reception clock:** upstream supplies `SystemTime`, not a monotonic stamp. - The event path calculates elapsed time from the supplied reception time and - the session's wall-clock origin. Events older than the session are rejected. - This preserves queue delay correctly but inherits wall-clock adjustments; - adding monotonic reception time remains an event-contract follow-up. - **Saturation:** the writer stops recording when it observes event's data channel at full capacity. Event currently uses awaited sends with backpressure: a transient full condition can clear before the writer observes @@ -235,12 +229,16 @@ 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 low-level session retains its monotonic clock for elapsed-time helpers. The -`ToLogging` path uses the upstream `Notification::at` or `OrderSent::at` -(`SystemTime`) against the session's wall-clock origin, so queue delays are -not added to `instant`. -A monotonic timestamp at original reception is not available in the current -event contract; immunity to wall-clock changes therefore remains pending. +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: @@ -360,15 +358,21 @@ instant,from,to,protection_id,severity,protection_type,threshold_1,threshold_2,m | `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` | Timing result sent by the board for `timeacumulation`, as a string containing time and units; `0` for other types. | +| `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 required `timeacumulation` result must come from the board, not the session -clock, `time_unit`, or the configured ADJ duration. The current model lacks -that result: for now a timed protection's cell is empty (unavailable), while -an untimed protection still writes `0`. Completing this field remains pending. +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 @@ -570,7 +574,6 @@ buffers, and explicit flush and close operations. - 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. -- Board-supplied accumulated timing and monotonic reception timestamps. - 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. @@ -588,8 +591,8 @@ 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, missing -board timing, serialized OrderPacket values and timezone offsets, +Writer tests check headerless CSVs, escaping, protection metadata and duration +precision, event-supplied reception times, serialized OrderPacket values and timezone offsets, large integer instants, deterministic full-channel handling and failed closes. Order tests also cover event routing, confirmation timestamps, broadcast destinations and rejected non-finite numbers. Connecting the real logging 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..3fc6e7b01 --- /dev/null +++ b/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md @@ -0,0 +1,273 @@ +# 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), +} +``` + +In the reviewed branch, `Commands.logger` holds an +`Option>`. Logging must consume the corresponding +receiver. `LoggerCommand` and that field have `pub(crate)` visibility, so other +`station` modules can use them. + +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 +``` + +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 + +- [ ] Retain and share the complete `Arc` and its `Arc`, consistent + with networking. The current `main` moves `adj.pod_data` out of the ADJ. +- [ ] 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, +saturation 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 an error or saturation | `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. Define how those details are reported through +the existing problem/message mechanisms. + +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. + +### Data-Channel Saturation + +The `event → logging` channel is separate from the command channel. Currently, +`event` waits with `send().await`, and the writer stops the session when it +observes a full input. A transient full condition can escape that check. + +To guarantee “channel fills → stop logging and notify”, agree on detection at +the producer and signaling to the writer while keeping the receiver alive and +draining pending data. Avoid letting logging's wait unnecessarily block delivery +to pipeline. Distinguish this saturation from rejecting frontend commands. + +## 9. Settled Contracts and Independent Pending Work + +Orders arrive from `event` as `ToLogging::OrderSent`. The CSV uses its `at` for +`instant` and `timestamp`, and the `OrderPacket` as compact JSON in the `payload` +cell: `{"id":2000,"values":[...]}`. `from` is `backend`; `to` is the board's name +or `all` when the destination is `None`. + +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. +- [ ] Saturation or 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: JSON 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. From 204e9b034a070d43a70d438ae828b9523c4106b6 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Thu, 3 Dec 2026 20:02:17 +0100 Subject: [PATCH 09/19] feat(backend, logging): add lifecycle and error tracing --- backend/crates/station/src/logging/README.md | 27 ++++++++++++++++ backend/crates/station/src/logging/service.rs | 20 +++++++----- backend/crates/station/src/logging/writer.rs | 31 ++++++++++++++----- 3 files changed, 64 insertions(+), 14 deletions(-) diff --git a/backend/crates/station/src/logging/README.md b/backend/crates/station/src/logging/README.md index 3d1f1ede1..beb11a275 100644 --- a/backend/crates/station/src/logging/README.md +++ b/backend/crates/station/src/logging/README.md @@ -132,6 +132,33 @@ 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 observed queue saturation that stops a session. | +| `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. Saturation includes queue occupancy and capacity. 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, diff --git a/backend/crates/station/src/logging/service.rs b/backend/crates/station/src/logging/service.rs index 02275e411..56455e3d9 100644 --- a/backend/crates/station/src/logging/service.rs +++ b/backend/crates/station/src/logging/service.rs @@ -34,7 +34,10 @@ impl Logging { input: mpsc::Receiver, options: WriterOptions, ) -> Result { - options.validate()?; + 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(adj, index); let (controls, control_rx) = mpsc::unbounded_channel(); @@ -42,10 +45,13 @@ impl Logging { let worker = std::thread::Builder::new() .name("logging-writer".into()) .spawn(move || writer::run(run, input, control_rx, status_tx, catalog, options)) - .map_err(|source| Error::Io { - operation: "spawn the logging writer", - path: directory, - source, + .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, @@ -138,9 +144,9 @@ impl Drop for Logging { .get_mut() .unwrap_or_else(|e| e.into_inner()) .take() - && worker.join().is_err() { - tracing::error!("logging writer exited unexpectedly during close"); + // The writer's exit guard traces an unexpected exit at its source. + let _ = worker.join(); } } } diff --git a/backend/crates/station/src/logging/writer.rs b/backend/crates/station/src/logging/writer.rs index e7ba54a68..98e389436 100644 --- a/backend/crates/station/src/logging/writer.rs +++ b/backend/crates/station/src/logging/writer.rs @@ -183,6 +183,7 @@ impl Recording { 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); } } @@ -239,6 +240,7 @@ pub(super) fn run( .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}")), @@ -253,6 +255,7 @@ impl Writer { 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 { let saturated = self.active.is_some() && self.input.len() == self.input.max_capacity(); // Controls win over data, including when input is full. recv is @@ -272,6 +275,7 @@ impl Writer { 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(); @@ -294,6 +298,12 @@ impl Writer { break; } Step::Saturated => { + tracing::warn!( + session_id = self.status.session.as_ref().map(|session| session.id.get()), + queue_len = self.input.len(), + queue_capacity = self.input.max_capacity(), + "logging input saturated; stopping session" + ); self.stop(StopReason::Saturation, SystemTime::now()).await; } Step::Flush => { @@ -318,12 +328,14 @@ impl Writer { if let Some(recording) = &self.active { return Ok(recording.info.clone()); } - selection.validate(&self.catalog)?; - let id = SessionId( - self.next_id - .checked_add(1) - .ok_or(Error::SessionIdExhausted)?, - ); + 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. @@ -353,6 +365,7 @@ impl Writer { 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) } @@ -374,7 +387,7 @@ impl Writer { match self.catalog.validate(incoming) { Ok(false) => return false, Err(error) => { - tracing::warn!(%error, "logging input could not be recorded"); + tracing::warn!(session_id = recording.info.id.get(), error = %error_chain(&error), "logging input discarded"); return false; } Ok(true) => {} @@ -425,6 +438,7 @@ impl Writer { 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); } } @@ -436,6 +450,7 @@ impl Writer { if let Some(error) = errors.first() { self.status.last_error = Some(error.clone()); } + 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, @@ -456,6 +471,7 @@ impl Writer { 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) { @@ -482,6 +498,7 @@ 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); From 3a3baebac5f279f5c90053062b948927b567e352 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Thu, 3 Dec 2026 20:48:04 +0100 Subject: [PATCH 10/19] fix(backend, logging): orders payload enriched with Index metadata --- backend/crates/station/src/logging/README.md | 19 +++- .../src/logging/WEBSOCKET_INTEGRATION.md | 5 +- backend/crates/station/src/logging/catalog.rs | 42 ++++++- backend/crates/station/src/logging/order.rs | 102 +++++++++++++---- .../station/src/logging/service/tests.rs | 4 +- .../station/src/logging/test_support.rs | 35 +++++- backend/crates/station/src/logging/writer.rs | 8 +- .../station/src/logging/writer/tests.rs | 103 +++++++++++++++--- 8 files changed, 274 insertions(+), 44 deletions(-) diff --git a/backend/crates/station/src/logging/README.md b/backend/crates/station/src/logging/README.md index beb11a275..e269a45fa 100644 --- a/backend/crates/station/src/logging/README.md +++ b/backend/crates/station/src/logging/README.md @@ -53,7 +53,7 @@ internal controls. 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 - as compact JSON in the order CSV's payload cell. + as compact JSON enriched with Index metadata in the order CSV's payload cell. `Catalog` keeps the supplied ADJ and protocol index shared. It builds a small measurement locator once, using `(BoardId, AdjId)` as keys. It resolves: @@ -339,7 +339,7 @@ instant,from,to,id,payload,timestamp | `from` | `backend`. | | `to` | ADJ board name, or `all` when `OrderSent.board` is `None`. | | `id` | Order ID. | -| `payload` | The confirmed `OrderPacket` as compact JSON: numeric `id` and positional `values`. | +| `payload` | Compact JSON with order `id`, ADJ `name`, and ordered `parameters`, each containing `id`, `alias`, `type` and `value`. | | `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 @@ -350,9 +350,22 @@ produce no order row. Logger controls arrive separately from WebSocket. Each payload is a single-line JSON object inside the CSV cell, for example: ```json -{"id":2000,"values":[1.5,true,"run"]} +{"id":1002,"name":"Duty","parameters":[{"id":3032,"alias":"duty_command","type":"uint32","value":75}]} ``` +Names and parameter definitions are resolved with `Index::packet(order.id)`; +parameter values are paired positionally with `PacketType::Order` fields. +The CSV's existing columns remain unchanged. The payload replaces the former +`values` array, so readers of that JSON must use `parameters[*].value` instead. +Types use ADJ names (`uint8` through `uint64`, `int8` through `int64`, `float32`, +`float64`, `bool`, `enum`). Metadata is borrowed from the shared Index rather +than copied into core's OrderPacket or a second per-event JSON tree. + +Unknown orders, wrong packet kinds, mismatched destinations and incorrect +parameter counts are discarded with a warning before writing. The reserved +broadcast fault (ID 0, destination `all`) requires no Index entry and is recorded +as `{"id":0,"name":"Fault","parameters":[]}`; 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 for the CSV cell. There is no separate diff --git a/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md b/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md index 3fc6e7b01..05cc07c67 100644 --- a/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md +++ b/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md @@ -226,8 +226,9 @@ to pipeline. Distinguish this saturation from rejecting frontend commands. ## 9. Settled Contracts and Independent Pending Work Orders arrive from `event` as `ToLogging::OrderSent`. The CSV uses its `at` for -`instant` and `timestamp`, and the `OrderPacket` as compact JSON in the `payload` -cell: `{"id":2000,"values":[...]}`. `from` is `backend`; `to` is the board's name +`instant` and `timestamp`, and enriches the `OrderPacket` using `Index::packet(order.id)` for the JSON +`payload` cell: `{"id":2000,"name":"Enable","parameters":[...]}`. Each parameter +has its measurement `id`, `alias`, ADJ `type` and confirmed `value`. `from` is `backend`; `to` is the board's name or `all` when the destination is `None`. This is already implemented in logging and tested with the event router. diff --git a/backend/crates/station/src/logging/catalog.rs b/backend/crates/station/src/logging/catalog.rs index abca260a7..e91a3b191 100644 --- a/backend/crates/station/src/logging/catalog.rs +++ b/backend/crates/station/src/logging/catalog.rs @@ -9,7 +9,10 @@ use std::{collections::HashMap, sync::Arc}; use software_core::{ adj::Adj, - model::{AdjId, Board, BoardId, Measurement, MessageLevel, Packet, PacketType, Protection}, + model::{ + AdjId, Board, BoardId, Measurement, MessageLevel, OrderPacket, Packet, PacketDef, + PacketType, Protection, + }, net::Event, protocol::Index, }; @@ -146,18 +149,53 @@ impl Catalog { } } + /// 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)); + } + 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, .. } => { + 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, diff --git a/backend/crates/station/src/logging/order.rs b/backend/crates/station/src/logging/order.rs index b7d85d634..923ff8f3c 100644 --- a/backend/crates/station/src/logging/order.rs +++ b/backend/crates/station/src/logging/order.rs @@ -5,7 +5,8 @@ //! `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. -//! `payload` is the OrderPacket as compact JSON in one CSV cell. No header. +//! `payload` contains the order ID/name and ADJ parameter metadata with values, +//! as compact JSON in one CSV cell. No header. //! //! This component owns a `software_core::logger::CsvFile` and formats rows. @@ -14,7 +15,9 @@ use std::path::Path; use serde::{Serialize, Serializer, ser::SerializeSeq}; use software_core::{ logger::CsvFile, - model::{OrderPacket, Value}, + model::{ + AdjId, Measurement, MeasurementKind, NumericKind, OrderPacket, PacketDef, PacketType, Value, + }, }; use super::{Error, output::flush_if_due, session::RecordTime}; @@ -33,17 +36,35 @@ impl OrderLogger { } /// Serialize the confirmed packet before starting a row, so a payload - /// failure cannot leave a partial CSV record. Values remain positional. + /// 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 payload = serde_json::to_string(&Payload { id: order.id.0, - values: &order.values, + name, + parameters: Parameters { + fields, + values: &order.values, + }, }) .map_err(Error::OrderPayload)?; let timestamp = time @@ -70,25 +91,66 @@ impl OrderLogger { #[derive(Serialize)] struct Payload<'a> { id: u16, - #[serde(serialize_with = "serialize_values")] + name: &'a str, + parameters: Parameters<'a>, +} + +struct Parameters<'a> { + fields: &'a [Measurement], values: &'a [Value], } -fn serialize_values(values: &[Value], serializer: S) -> Result { - let mut sequence = serializer.serialize_seq(Some(values.len()))?; - for value in values { - match value { - Value::Number(value) => { - // JSON has no NaN/infinity; never silently replace a value - // with null and present that as the packet that was sent. - if !value.is_finite() { - return Err(serde::ser::Error::custom("non-finite order value")); - } - sequence.serialize_element(value)?; - } - Value::Bool(value) => sequence.serialize_element(value)?, - Value::Enum(value) => sequence.serialize_element(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, + kind: type_name(&field.kind), + value, + })?; + } + sequence.end() + } +} + +#[derive(Serialize)] +struct Parameter<'a> { + id: u16, + alias: &'a str, + #[serde(rename = "type")] + kind: &'static 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), + } +} + +fn type_name(kind: &MeasurementKind) -> &'static str { + match kind { + MeasurementKind::Boolean => "bool", + MeasurementKind::Enum { .. } => "enum", + MeasurementKind::Numeric { wire_type } => match wire_type { + NumericKind::U8 => "uint8", + NumericKind::U16 => "uint16", + NumericKind::U32 => "uint32", + NumericKind::U64 => "uint64", + NumericKind::I8 => "int8", + NumericKind::I16 => "int16", + NumericKind::I32 => "int32", + NumericKind::I64 => "int64", + NumericKind::F32 => "float32", + NumericKind::F64 => "float64", + }, } - sequence.end() } diff --git a/backend/crates/station/src/logging/service/tests.rs b/backend/crates/station/src/logging/service/tests.rs index 0f5cfb25e..cda69f9f4 100644 --- a/backend/crates/station/src/logging/service/tests.rs +++ b/backend/crates/station/src/logging/service/tests.rs @@ -541,7 +541,7 @@ async fn event_routes_to_the_real_logger_across_session_stop_and_restart() -> Te 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,\"{{\"\"id\"\":2000,\"\"values\"\":[true]}}\",{timestamp}\n" + ",backend,LCU,2000,\"{{\"\"id\"\":2000,\"\"name\"\":\"\"Enable\"\",\"\"parameters\"\":[{{\"\"id\"\":4000,\"\"alias\"\":\"\"enabled_command\"\",\"\"type\"\":\"\"bool\"\",\"\"value\"\":true}}]}}\",{timestamp}\n" ))); drop((udp, tcp, orders, problems)); assert!(matches!( @@ -564,7 +564,7 @@ async fn an_unrepresentable_order_payload_stops_recording_and_flushes_healthy_fi at: SystemTime::now(), board: Some(LCU), order: OrderPacket::new( - AdjId(2000), + AdjId(2002), vec![software_core::model::Value::Number(f64::NAN)], ), }) diff --git a/backend/crates/station/src/logging/test_support.rs b/backend/crates/station/src/logging/test_support.rs index 47d4d6cbe..789663172 100644 --- a/backend/crates/station/src/logging/test_support.rs +++ b/backend/crates/station/src/logging/test_support.rs @@ -96,11 +96,44 @@ pub(super) fn definitions() -> (Arc, Arc) { ..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)], + 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]), ]; diff --git a/backend/crates/station/src/logging/writer.rs b/backend/crates/station/src/logging/writer.rs index 98e389436..ec6a5eebf 100644 --- a/backend/crates/station/src/logging/writer.rs +++ b/backend/crates/station/src/logging/writer.rs @@ -102,7 +102,13 @@ impl SessionFiles { Some(board) => catalog.board(*board)?.name.as_str(), None => "all", }; - return self.orders.write(time, order, to, threshold); + return self.orders.write( + time, + order, + to, + catalog.order(*board, order)?, + threshold, + ); } ToLogging::Received(notification) => notification, }; diff --git a/backend/crates/station/src/logging/writer/tests.rs b/backend/crates/station/src/logging/writer/tests.rs index bea32d8b1..404a78130 100644 --- a/backend/crates/station/src/logging/writer/tests.rs +++ b/backend/crates/station/src/logging/writer/tests.rs @@ -77,33 +77,56 @@ fn native_csv_formats_preserve_fields_without_headers() -> TestResult { 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(2000), + AdjId(2003), vec![ Value::Number(1.5), Value::Bool(true), Value::Enum("run, \"fast\"\nnext".into()), ], ); - orders.write(summer, &order, "LCU", u64::MAX)?; + 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 payload = r#"{"id":2000,"values":[1.5,true,"run, \"fast\"\nnext"]}"#; + let payload = serde_json::json!({"id":2003,"name":"Configure, \"drive\"","parameters":[ + {"id":4001,"alias":"speed_command","type":"float64","value":1.5}, + {"id":4000,"alias":"enabled_command","type":"bool","value":true}, + {"id":4002,"alias":"mode_command","type":"enum","value":"run, \"fast\"\nnext"} + ]}); + // Decode the JSON cell and verify CSV escaping of + // commas, quotes and JSON-escaped newlines in both names and values. + let contents = fs::read_to_string(temp.path().join("order/order.csv"))?; + let lines: Vec<_> = contents.lines().collect(); + assert_eq!(lines.len(), 2); + let read_payload = + |line: &str| -> Result> { + let escaped = line + .split_once(",\"") + .ok_or("missing CSV payload")? + .1 + .rsplit_once("\",") + .ok_or("missing CSV timestamp")? + .0; + Ok(serde_json::from_str(&escaped.replace("\"\"", "\""))?) + }; + assert_eq!(read_payload(lines[0])?, payload); + assert!(lines[0].starts_with("35000,backend,LCU,2003,")); + assert!(lines[0].ends_with(",2026-07-15T15-30-05+02:00")); assert_eq!( - fs::read_to_string(temp.path().join("order/order.csv"))?, - format!( - "35000,backend,LCU,2000,\"{}\",2026-07-15T15-30-05+02:00\n{},backend,LCU,2001,\"{{\"\"id\"\":2001,\"\"values\"\":[]}}\",2026-11-27T15-30-05+01:00\n", - payload.replace('"', "\"\""), - u128::MAX - ) + read_payload(lines[1])?, + serde_json::json!({"id":2001,"name":"Brake","parameters":[]}) ); + assert!(lines[1].starts_with(&format!("{},backend,LCU,2001,", u128::MAX))); + assert!(lines[1].ends_with(",2026-11-27T15-30-05+01:00")); Ok(()) } @@ -124,7 +147,7 @@ fn confirmed_broadcast_orders_use_all_as_destination() -> TestResult { assert_eq!( fs::read_to_string(temp.path().join("order/order.csv"))?, format!( - "{},backend,all,0,\"{{\"\"id\"\":0,\"\"values\"\":[]}}\",2026-11-27T15-30-05+01:00\n", + "{},backend,all,0,\"{{\"\"id\"\":0,\"\"name\"\":\"\"Fault\"\",\"\"parameters\"\":[]}}\",2026-11-27T15-30-05+01:00\n", u128::MAX ) ); @@ -135,12 +158,14 @@ fn confirmed_broadcast_orders_use_all_as_destination() -> TestResult { 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(2000), vec![Value::Number(value)]), + &OrderPacket::new(AdjId(2002), vec![Value::Number(value)]), "LCU", + index.packet(AdjId(2002)), u64::MAX ), Err(Error::OrderPayload(_)) @@ -348,7 +373,7 @@ async fn events_use_at_for_elapsed_and_order_wall_timestamps() -> TestResult { let order = |at| ToLogging::OrderSent { at, board: Some(LCU), - order: OrderPacket::new(AdjId(2000), vec![]), + 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. @@ -367,7 +392,9 @@ async fn events_use_at_for_elapsed_and_order_wall_timestamps() -> TestResult { .to_string(); assert_eq!( fs::read_to_string(session.directory.join("order/order.csv"))?, - format!("35000,backend,LCU,2000,\"{{\"\"id\"\":2000,\"\"values\"\":[]}}\",{timestamp}\n") + format!( + "35000,backend,LCU,2001,\"{{\"\"id\"\":2001,\"\"name\"\":\"\"Brake\"\",\"\"parameters\"\":[]}}\",{timestamp}\n" + ) ); Ok(()) } @@ -418,3 +445,53 @@ fn protection_time_preserves_the_adj_duration_and_its_precision() -> TestResult } Ok(()) } + +#[test] +fn orders_require_matching_index_metadata_before_writing() -> TestResult { + let temp = tempfile::tempdir()?; + let (adj, index) = definitions(); + let catalog = Catalog::new(adj, 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(()) +} From b0c3126dde0c9e294d7d842aa57dd7d970d8110c Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Thu, 3 Dec 2026 21:10:21 +0100 Subject: [PATCH 11/19] fix(backend, logging): add order name field and rethink of payload (now parameters) --- backend/crates/station/src/logging/README.md | 31 ++++++----- .../src/logging/WEBSOCKET_INTEGRATION.md | 15 +++--- backend/crates/station/src/logging/error.rs | 2 +- backend/crates/station/src/logging/order.rs | 54 ++++--------------- .../station/src/logging/service/tests.rs | 2 +- .../station/src/logging/writer/tests.rs | 52 ++++++++---------- 6 files changed, 61 insertions(+), 95 deletions(-) diff --git a/backend/crates/station/src/logging/README.md b/backend/crates/station/src/logging/README.md index e269a45fa..ed2181713 100644 --- a/backend/crates/station/src/logging/README.md +++ b/backend/crates/station/src/logging/README.md @@ -53,7 +53,7 @@ internal controls. 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 - as compact JSON enriched with Index metadata in the order CSV's payload cell. + 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: @@ -330,7 +330,7 @@ There is a single `order.csv` file inside `order/`. Columns, in order: ```text -instant,from,to,id,payload,timestamp +instant,from,to,id,name,parameters,timestamp ``` | Field | Content | @@ -339,7 +339,8 @@ instant,from,to,id,payload,timestamp | `from` | `backend`. | | `to` | ADJ board name, or `all` when `OrderSent.board` is `None`. | | `id` | Order ID. | -| `payload` | Compact JSON with order `id`, ADJ `name`, and ordered `parameters`, each containing `id`, `alias`, `type` and `value`. | +| `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 @@ -347,30 +348,32 @@ 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. -Each payload is a single-line JSON object inside the CSV cell, for example: +The `parameters` cell is directly a JSON array, for example: ```json -{"id":1002,"name":"Duty","parameters":[{"id":3032,"alias":"duty_command","type":"uint32","value":75}]} +[{"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 CSV's existing columns remain unchanged. The payload replaces the former -`values` array, so readers of that JSON must use `parameters[*].value` instead. -Types use ADJ names (`uint8` through `uint64`, `int8` through `int64`, `float32`, -`float64`, `bool`, `enum`). Metadata is borrowed from the shared Index rather -than copied into core's OrderPacket or a second per-event JSON tree. +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 and incorrect parameter counts are discarded with a warning before writing. The reserved broadcast fault (ID 0, destination `all`) requires no Index entry and is recorded -as `{"id":0,"name":"Fault","parameters":[]}`; it must have no values. +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 for the CSV cell. There is no separate -JSONL file or extra newline within this cell. Non-finite numeric values cannot -be represented as JSON and stop recording with an error before writing a row. +`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. +Non-finite numeric values stop recording with an error before writing a row. ### Protections: protections/ diff --git a/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md b/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md index 05cc07c67..445943e20 100644 --- a/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md +++ b/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md @@ -225,11 +225,14 @@ to pipeline. Distinguish this saturation from rejecting frontend commands. ## 9. Settled Contracts and Independent Pending Work -Orders arrive from `event` as `ToLogging::OrderSent`. The CSV uses its `at` for -`instant` and `timestamp`, and enriches the `OrderPacket` using `Index::packet(order.id)` for the JSON -`payload` cell: `{"id":2000,"name":"Enable","parameters":[...]}`. Each parameter -has its measurement `id`, `alias`, ADJ `type` and confirmed `value`. `from` is `backend`; `to` is the board's name -or `all` when the destination is `None`. +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. @@ -266,7 +269,7 @@ of the WebSocket merge. - [ ] 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: JSON in one cell and timing from `OrderSent.at`. +- [ ] 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 diff --git a/backend/crates/station/src/logging/error.rs b/backend/crates/station/src/logging/error.rs index 7896f8465..f47f3cee2 100644 --- a/backend/crates/station/src/logging/error.rs +++ b/backend/crates/station/src/logging/error.rs @@ -22,7 +22,7 @@ pub enum Error { UnexpectedPacketType(AdjId), #[error("packet {0:?} value count differs from its ADJ measurement count")] MeasurementCount(AdjId), - #[error("couldn't serialize the logged OrderPacket: {0}")] + #[error("couldn't serialize the logged order parameters: {0}")] OrderPayload(#[source] serde_json::Error), #[error("invalid logging file component: {0:?}")] InvalidName(String), diff --git a/backend/crates/station/src/logging/order.rs b/backend/crates/station/src/logging/order.rs index 923ff8f3c..190e8fb7f 100644 --- a/backend/crates/station/src/logging/order.rs +++ b/backend/crates/station/src/logging/order.rs @@ -1,12 +1,12 @@ //! Order recording in the session's single `order/order.csv` file. //! -//! Columns, in order: `instant,from,to,order_id,payload,timestamp`. +//! 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. -//! `payload` contains the order ID/name and ADJ parameter metadata with values, -//! as compact JSON in one CSV cell. No header. +//! `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. @@ -15,9 +15,7 @@ use std::path::Path; use serde::{Serialize, Serializer, ser::SerializeSeq}; use software_core::{ logger::CsvFile, - model::{ - AdjId, Measurement, MeasurementKind, NumericKind, OrderPacket, PacketDef, PacketType, Value, - }, + model::{AdjId, Measurement, OrderPacket, PacketDef, PacketType, Value}, }; use super::{Error, output::flush_if_due, session::RecordTime}; @@ -35,7 +33,7 @@ impl OrderLogger { }) } - /// Serialize the confirmed packet before starting a row, so a payload + /// 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, @@ -58,13 +56,9 @@ impl OrderLogger { if fields.len() != order.values.len() { return Err(Error::MeasurementCount(order.id)); } - let payload = serde_json::to_string(&Payload { - id: order.id.0, - name, - parameters: Parameters { - fields, - values: &order.values, - }, + let parameters = serde_json::to_string(&Parameters { + fields, + values: &order.values, }) .map_err(Error::OrderPayload)?; let timestamp = time @@ -78,7 +72,8 @@ impl OrderLogger { .text("backend") // orders will always come from the backend and never from the boards .text(to) .int(i64::from(order.id.0)) - .text(&payload) + .text(name) + .text(¶meters) .text(×tamp) .end()?; // validates row and ends it flush_if_due(&mut self.file, threshold)?; @@ -88,13 +83,6 @@ impl OrderLogger { /// A borrowed JSON view keeps logging's representation out of core's model /// and avoids copying packet values or building an intermediate JSON tree. -#[derive(Serialize)] -struct Payload<'a> { - id: u16, - name: &'a str, - parameters: Parameters<'a>, -} - struct Parameters<'a> { fields: &'a [Measurement], values: &'a [Value], @@ -107,7 +95,6 @@ impl Serialize for Parameters<'_> { sequence.serialize_element(&Parameter { id: field.id.0, alias: &field.alias, - kind: type_name(&field.kind), value, })?; } @@ -119,8 +106,6 @@ impl Serialize for Parameters<'_> { struct Parameter<'a> { id: u16, alias: &'a str, - #[serde(rename = "type")] - kind: &'static str, #[serde(serialize_with = "serialize_value")] value: &'a Value, } @@ -135,22 +120,3 @@ fn serialize_value(value: &Value, serializer: S) -> Result serializer.serialize_str(value), } } - -fn type_name(kind: &MeasurementKind) -> &'static str { - match kind { - MeasurementKind::Boolean => "bool", - MeasurementKind::Enum { .. } => "enum", - MeasurementKind::Numeric { wire_type } => match wire_type { - NumericKind::U8 => "uint8", - NumericKind::U16 => "uint16", - NumericKind::U32 => "uint32", - NumericKind::U64 => "uint64", - NumericKind::I8 => "int8", - NumericKind::I16 => "int16", - NumericKind::I32 => "int32", - NumericKind::I64 => "int64", - NumericKind::F32 => "float32", - NumericKind::F64 => "float64", - }, - } -} diff --git a/backend/crates/station/src/logging/service/tests.rs b/backend/crates/station/src/logging/service/tests.rs index cda69f9f4..e4cd64206 100644 --- a/backend/crates/station/src/logging/service/tests.rs +++ b/backend/crates/station/src/logging/service/tests.rs @@ -541,7 +541,7 @@ async fn event_routes_to_the_real_logger_across_session_stop_and_restart() -> Te 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,\"{{\"\"id\"\":2000,\"\"name\"\":\"\"Enable\"\",\"\"parameters\"\":[{{\"\"id\"\":4000,\"\"alias\"\":\"\"enabled_command\"\",\"\"type\"\":\"\"bool\"\",\"\"value\"\":true}}]}}\",{timestamp}\n" + ",backend,LCU,2000,Enable,\"[{{\"\"id\"\":4000,\"\"alias\"\":\"\"enabled_command\"\",\"\"value\"\":true}}]\",{timestamp}\n" ))); drop((udp, tcp, orders, problems)); assert!(matches!( diff --git a/backend/crates/station/src/logging/writer/tests.rs b/backend/crates/station/src/logging/writer/tests.rs index 404a78130..83e4ae4f4 100644 --- a/backend/crates/station/src/logging/writer/tests.rs +++ b/backend/crates/station/src/logging/writer/tests.rs @@ -97,36 +97,32 @@ fn order_payload_offsets_and_large_instants_are_preserved() -> TestResult { u64::MAX, )?; orders.file.close()?; - let payload = serde_json::json!({"id":2003,"name":"Configure, \"drive\"","parameters":[ - {"id":4001,"alias":"speed_command","type":"float64","value":1.5}, - {"id":4000,"alias":"enabled_command","type":"bool","value":true}, - {"id":4002,"alias":"mode_command","type":"enum","value":"run, \"fast\"\nnext"} - ]}); - // Decode the JSON cell and verify CSV escaping of - // commas, quotes and JSON-escaped newlines in both names and values. + 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); - let read_payload = - |line: &str| -> Result> { - let escaped = line - .split_once(",\"") - .ok_or("missing CSV payload")? - .1 - .rsplit_once("\",") - .ok_or("missing CSV timestamp")? - .0; - Ok(serde_json::from_str(&escaped.replace("\"\"", "\""))?) - }; - assert_eq!(read_payload(lines[0])?, payload); - assert!(lines[0].starts_with("35000,backend,LCU,2003,")); - assert!(lines[0].ends_with(",2026-07-15T15-30-05+02:00")); + // 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!( - read_payload(lines[1])?, - serde_json::json!({"id":2001,"name":"Brake","parameters":[]}) + lines[1], + format!( + "{},backend,LCU,2001,Brake,[],2026-11-27T15-30-05+01:00", + u128::MAX + ) ); - assert!(lines[1].starts_with(&format!("{},backend,LCU,2001,", u128::MAX))); - assert!(lines[1].ends_with(",2026-11-27T15-30-05+01:00")); Ok(()) } @@ -147,7 +143,7 @@ fn confirmed_broadcast_orders_use_all_as_destination() -> TestResult { assert_eq!( fs::read_to_string(temp.path().join("order/order.csv"))?, format!( - "{},backend,all,0,\"{{\"\"id\"\":0,\"\"name\"\":\"\"Fault\"\",\"\"parameters\"\":[]}}\",2026-11-27T15-30-05+01:00\n", + "{},backend,all,0,Fault,[],2026-11-27T15-30-05+01:00\n", u128::MAX ) ); @@ -392,9 +388,7 @@ async fn events_use_at_for_elapsed_and_order_wall_timestamps() -> TestResult { .to_string(); assert_eq!( fs::read_to_string(session.directory.join("order/order.csv"))?, - format!( - "35000,backend,LCU,2001,\"{{\"\"id\"\":2001,\"\"name\"\":\"\"Brake\"\",\"\"parameters\"\":[]}}\",{timestamp}\n" - ) + format!("35000,backend,LCU,2001,Brake,[],{timestamp}\n") ); Ok(()) } From aa0ab8f14811ae2beb13e3199ac0069000ec0840 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sun, 6 Dec 2026 10:55:44 +0100 Subject: [PATCH 12/19] fix(backend, logging): adapt tests to the merged event channels event::Channels renamed problems to notices and telemetry now reaches pipeline on its own queue (pipeline_data), so the event integration test waits there. Also formats the two files this branch touches and commits the Cargo.lock order left by the merge. --- backend/Cargo.lock | 2 +- backend/crates/core/src/logger/csv.rs | 2 +- backend/crates/station/src/logging.rs | 2 +- .../crates/station/src/logging/service/tests.rs | 15 +++++++-------- 4 files changed, 10 insertions(+), 11 deletions(-) diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 8c0325c4d..51ba1dae3 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -2960,8 +2960,8 @@ name = "station" version = "0.1.0" dependencies = [ "axum", - "jiff", "futures-util", + "jiff", "serde", "serde_json", "software-core", diff --git a/backend/crates/core/src/logger/csv.rs b/backend/crates/core/src/logger/csv.rs index 16cdfca1c..57638eda2 100644 --- a/backend/crates/core/src/logger/csv.rs +++ b/backend/crates/core/src/logger/csv.rs @@ -255,7 +255,7 @@ impl Row<'_, W> { self.number(format_args!("{value}")) } - /// Appends the instant field. Cannot use `Self::int()`, + /// 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}")) diff --git a/backend/crates/station/src/logging.rs b/backend/crates/station/src/logging.rs index 3c1650a59..d24806280 100644 --- a/backend/crates/station/src/logging.rs +++ b/backend/crates/station/src/logging.rs @@ -24,11 +24,11 @@ mod catalog; mod control; -mod output; mod data; mod error; mod messages; mod order; +mod output; mod protections; mod service; mod session; diff --git a/backend/crates/station/src/logging/service/tests.rs b/backend/crates/station/src/logging/service/tests.rs index e4cd64206..07c5e6ad5 100644 --- a/backend/crates/station/src/logging/service/tests.rs +++ b/backend/crates/station/src/logging/service/tests.rs @@ -456,9 +456,10 @@ async fn event_routes_to_the_real_logger_across_session_stop_and_restart() -> Te tcp, event: ends, orders, - problems, + notices, logging: input, mut pipeline, + mut pipeline_data, } = event::channels(&config); let run = BackendRun::new( Config { @@ -503,13 +504,11 @@ async fn event_routes_to_the_real_logger_across_session_stop_and_restart() -> Te ) .await?; } - // Router sends to logging before pipeline. Receiving these four proves - // that all four passed through event's real logging sender. + // 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!(matches!( - timeout(WAIT, pipeline.recv()).await?, - Some(ToPipeline::Received(_)) - )); + assert!(timeout(WAIT, pipeline_data.recv()).await?.is_some()); } if let Some(session) = session { logger.stop().await?; @@ -543,7 +542,7 @@ async fn event_routes_to_the_real_logger_across_session_stop_and_restart() -> Te assert!(contents.ends_with(&format!( ",backend,LCU,2000,Enable,\"[{{\"\"id\"\":4000,\"\"alias\"\":\"\"enabled_command\"\",\"\"value\"\":true}}]\",{timestamp}\n" ))); - drop((udp, tcp, orders, problems)); + drop((udp, tcp, orders, notices)); assert!(matches!( timeout(WAIT, event_task).await??, event::Stop::NetGone From 45341f7f92f75dc763389692743691e4db1b2b22 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sun, 6 Dec 2026 10:56:42 +0100 Subject: [PATCH 13/19] refactor(backend, logging): remove the saturation stop A full input queue is backpressure: event waits for a slot and logging keeps recording. Stopping the session on it lost every later record, and right after a start that opens many files it could stop the session that had just begun. Only write errors stop a session now. --- backend/crates/station/src/logging/README.md | 31 +++---- .../src/logging/WEBSOCKET_INTEGRATION.md | 21 ++--- backend/crates/station/src/logging/error.rs | 2 +- .../station/src/logging/service/tests.rs | 6 +- backend/crates/station/src/logging/status.rs | 1 - backend/crates/station/src/logging/writer.rs | 12 --- .../station/src/logging/writer/tests.rs | 84 ------------------- 7 files changed, 17 insertions(+), 140 deletions(-) diff --git a/backend/crates/station/src/logging/README.md b/backend/crates/station/src/logging/README.md index ed2181713..69f80e4d8 100644 --- a/backend/crates/station/src/logging/README.md +++ b/backend/crates/station/src/logging/README.md @@ -124,11 +124,6 @@ fn start_logging_consumer( These are deliberately not filled in with reconstructed or guessed data: -- **Saturation:** the writer stops recording when it observes event's data - channel at full capacity. Event currently uses awaited sends with - backpressure: a transient full condition can clear before the writer observes - it. Detecting every producer-side full condition would require a change to - that input contract. - **Controls:** the session-control channel and multi-frontend disconnect rule remain pending. @@ -139,11 +134,11 @@ 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 observed queue saturation that stops a session. | +| `WARN` | Rejected configuration or selection, and discarded invalid input. | | `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. Saturation includes queue occupancy and capacity. Identical +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 @@ -550,22 +545,16 @@ 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. -### Queue Saturation +### A Full Input Queue -If records arrive faster than they can be written for long enough to fill -the channel, the writer stops logging when it observes that full condition: +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. -1. Begin stopping the session. -2. Write the ready input prefix at the stop boundary. -3. Flush and close the session files. -4. Indicate that the session ended because of saturation. +### Write Errors -The backend continues running and the receiver remains open. `status` and -`subscribe` expose `StopReason::Saturation` for the application to notify the -frontend. As noted above, transient producer-side full conditions can escape -observation with the current input contract. - -A write or flush error also stops recording. The writer attempts the ready +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 @@ -636,7 +625,7 @@ 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, deterministic full-channel handling and failed closes. +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. diff --git a/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md b/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md index 445943e20..67832545d 100644 --- a/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md +++ b/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md @@ -137,8 +137,8 @@ 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, -saturation or write failure. `event` treats losing the logging consumer as fatal. +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. @@ -167,7 +167,7 @@ The writer must keep draining data without waiting for frontend network I/O. | Session preparation completed | `true`. | | Start rejected while inactive | `false`, retaining the error. | | Stop completed | `false`. | -| Session stopped by an error or saturation | `false`, retaining the reason. | +| 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 @@ -212,17 +212,6 @@ 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. -### Data-Channel Saturation - -The `event → logging` channel is separate from the command channel. Currently, -`event` waits with `send().await`, and the writer stops the session when it -observes a full input. A transient full condition can escape that check. - -To guarantee “channel fills → stop logging and notify”, agree on detection at -the producer and signaling to the writer while keeping the receiver alive and -draining pending data. Avoid letting logging's wait unnecessarily block delivery -to pipeline. Distinguish this saturation from rejecting frontend commands. - ## 9. Settled Contracts and Independent Pending Work Orders arrive from `event` as `ToLogging::OrderSent`. The CSV columns are @@ -263,8 +252,8 @@ of the WebSocket merge. - [ ] 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. -- [ ] Saturation or write failure: session stopped, state `false`, reason retained - and event input still available. +- [ ] 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. diff --git a/backend/crates/station/src/logging/error.rs b/backend/crates/station/src/logging/error.rs index f47f3cee2..3f0d1ad21 100644 --- a/backend/crates/station/src/logging/error.rs +++ b/backend/crates/station/src/logging/error.rs @@ -1,7 +1,7 @@ //! Errors for recording setup, lifecycle transitions and the writer. //! //! Errors preserve file context from `software_core::logger` and report setup -//! or writer failures. Saturation is exposed through `StopReason` instead. +//! or writer failures. //! Shutdown attempts every file close and returns write failures to the caller. use software_core::model::{AdjId, BoardId}; diff --git a/backend/crates/station/src/logging/service/tests.rs b/backend/crates/station/src/logging/service/tests.rs index 07c5e6ad5..240a40e08 100644 --- a/backend/crates/station/src/logging/service/tests.rs +++ b/backend/crates/station/src/logging/service/tests.rs @@ -150,11 +150,7 @@ async fn stopping_a_one_slot_data_channel_never_needs_an_extra_data_slot() -> Te let session = logger.play(selection()).await?; sender.try_send(data(SystemTime::now(), 1.0))?; let report = timeout(WAIT, logger.stop()).await??; - // Either the control or the full-channel observation may win this race. - assert!(matches!( - report.map(|r| r.reason), - Some(StopReason::Requested | StopReason::Saturation) - )); + assert_eq!(report.map(|r| r.reason), Some(StopReason::Requested)); assert_eq!( fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? .lines() diff --git a/backend/crates/station/src/logging/status.rs b/backend/crates/station/src/logging/status.rs index f193414d5..1b6f98ff9 100644 --- a/backend/crates/station/src/logging/status.rs +++ b/backend/crates/station/src/logging/status.rs @@ -28,7 +28,6 @@ pub struct SessionInfo { pub enum StopReason { Requested, Emergency, - Saturation, WriteError, Shutdown, } diff --git a/backend/crates/station/src/logging/writer.rs b/backend/crates/station/src/logging/writer.rs index ec6a5eebf..0bffc7763 100644 --- a/backend/crates/station/src/logging/writer.rs +++ b/backend/crates/station/src/logging/writer.rs @@ -212,7 +212,6 @@ enum Step { Control(Option), Input(Option), Flush, - Saturated, } /// The runtime is created and dropped on this OS thread. Its timer and channel @@ -263,13 +262,11 @@ impl Writer { 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 { - let saturated = self.active.is_some() && self.input.len() == self.input.max_capacity(); // 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), - _ = std::future::ready(()), if saturated => Step::Saturated, _ = timer.tick(), if self.active.is_some() => Step::Flush, incoming = self.input.recv() => Step::Input(incoming), }; @@ -303,15 +300,6 @@ impl Writer { self.shutdown(SystemTime::now()).await; break; } - Step::Saturated => { - tracing::warn!( - session_id = self.status.session.as_ref().map(|session| session.id.get()), - queue_len = self.input.len(), - queue_capacity = self.input.max_capacity(), - "logging input saturated; stopping session" - ); - self.stop(StopReason::Saturation, SystemTime::now()).await; - } Step::Flush => { if let Some(recording) = &mut self.active { let errors = recording.files.flush(); diff --git a/backend/crates/station/src/logging/writer/tests.rs b/backend/crates/station/src/logging/writer/tests.rs index 83e4ae4f4..ee6926a3b 100644 --- a/backend/crates/station/src/logging/writer/tests.rs +++ b/backend/crates/station/src/logging/writer/tests.rs @@ -13,7 +13,6 @@ use software_core::{ net::Event, }; use tokio::sync::oneshot; -use tokio::time::timeout; use super::*; use crate::logging::{Config, test_support::*}; @@ -217,89 +216,6 @@ fn close_attempts_every_file_even_when_one_flush_fails() -> TestResult { Ok(()) } -#[tokio::test] -async fn observed_full_input_stops_notifies_drains_and_keeps_the_receiver_alive() -> TestResult { - let temp = tempfile::tempdir()?; - let run = BackendRun::new( - Config { - logging_path: temp.path().into(), - ..Config::default() - }, - "adj", - )?; - let (adj, index) = definitions(); - let (sender, input) = mpsc::channel(2); - let (controls, control_rx) = mpsc::unbounded_channel(); - let (updates, mut status) = watch::channel(Status::default()); - let mut writer = Writer { - run, - input, - controls: control_rx, - updates, - status: Status::default(), - catalog: Catalog::new(adj, index), - options: WriterOptions::default(), - active: None, - next_id: 0, - }; - let session = writer.start(selection()).await?; - // Fill the real channel before the consumer runs, so saturation is - // deterministic rather than dependent on OS thread scheduling. - sender.try_send(data(SystemTime::now(), 1.0))?; - sender.try_send(data(SystemTime::now(), 2.0))?; - let worker = tokio::spawn(writer.run()); - timeout(WAIT, async { - loop { - if status.borrow().last_stop.is_some() { - break; - } - status.changed().await?; - } - Ok::<(), watch::error::RecvError>(()) - }) - .await??; - assert_eq!(status.borrow().phase, Phase::Inactive); - assert_eq!( - status - .borrow() - .last_stop - .as_ref() - .map(|report| report.reason), - Some(StopReason::Saturation) - ); - assert_eq!( - fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? - .lines() - .count(), - 2 - ); - assert!(!sender.is_closed()); - let (reply, response) = oneshot::channel(); - controls.send(Control::Play { - selection: selection(), - reply, - })?; - let next = timeout(WAIT, response).await???; - assert_ne!(session.id, next.id); - assert_eq!( - status - .borrow() - .last_stop - .as_ref() - .map(|report| report.reason), - Some(StopReason::Saturation) - ); - let (reply, response) = oneshot::channel(); - controls.send(Control::Shutdown { - at: SystemTime::now(), - reply: Some(reply), - })?; - timeout(WAIT, response).await??; - timeout(WAIT, worker).await??; - assert_eq!(status.borrow().phase, Phase::Closed); - Ok(()) -} - #[test] fn unexpected_exit_publishes_failure() { let (updates, status) = watch::channel(Status { From 7b4e407fa0d037a408e1fffc36cd863e88248460 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sun, 6 Dec 2026 10:57:44 +0100 Subject: [PATCH 14/19] refactor(backend, logging): take Arc instead of Arc The catalog only reads the boards. main already shares Arc with net and event (and moves pod_data out of the Adj), so logging can take that same Arc instead of a separate copy of the whole ADJ. --- backend/crates/station/src/logging/README.md | 13 +++++----- .../src/logging/WEBSOCKET_INTEGRATION.md | 4 ++-- backend/crates/station/src/logging/catalog.rs | 24 ++++++++----------- backend/crates/station/src/logging/service.rs | 6 ++--- .../station/src/logging/service/tests.rs | 15 ++++++++---- .../station/src/logging/test_support.rs | 16 +++++-------- .../station/src/logging/writer/tests.rs | 20 ++++++++-------- 7 files changed, 48 insertions(+), 50 deletions(-) diff --git a/backend/crates/station/src/logging/README.md b/backend/crates/station/src/logging/README.md index 69f80e4d8..b12fb2d8b 100644 --- a/backend/crates/station/src/logging/README.md +++ b/backend/crates/station/src/logging/README.md @@ -14,7 +14,8 @@ 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 a shared `Arc` and `Arc` to `Logging`. +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. @@ -58,7 +59,7 @@ internal controls. `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 `Adj::pod_data`. +- 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. @@ -80,7 +81,7 @@ row; they do not define a session-control protocol. 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, adj, index, receiver, options)` starts the writer thread and +`Logging::new(run, pod_data, index, receiver, options)` starts the writer thread and moves event's receiver into it. Share the service through `Arc`. @@ -104,18 +105,18 @@ The consumer can already run and drain notifications while inactive. ```rust use std::sync::Arc; -use software_core::{adj::Adj, protocol::Index}; +use software_core::{model::PodData, protocol::Index}; use station::{event::ToLogging, logging::{BackendRun, Error, Logging, WriterOptions}}; use tokio::sync::mpsc; fn start_logging_consumer( run: BackendRun, - adj: Arc, + pod_data: Arc, index: Arc, receiver: mpsc::Receiver, ) -> Result, Error> { Ok(Arc::new(Logging::new( - run, adj, index, receiver, WriterOptions::default(), + run, pod_data, index, receiver, WriterOptions::default(), )?)) } ``` diff --git a/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md b/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md index 67832545d..abb295482 100644 --- a/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md +++ b/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md @@ -85,8 +85,8 @@ be chosen; do not introduce another unbounded channel by default. ## 4. Backend Startup -- [ ] Retain and share the complete `Arc` and its `Arc`, consistent - with networking. The current `main` moves `adj.pod_data` out of the ADJ. +- [ ] 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 diff --git a/backend/crates/station/src/logging/catalog.rs b/backend/crates/station/src/logging/catalog.rs index e91a3b191..0dfaf3561 100644 --- a/backend/crates/station/src/logging/catalog.rs +++ b/backend/crates/station/src/logging/catalog.rs @@ -2,16 +2,15 @@ //! //! 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 ADJ and protocol Index must describe the -//! same checkout that networking used to decode the packets. +//! 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::{ - adj::Adj, model::{ AdjId, Board, BoardId, Measurement, MessageLevel, OrderPacket, Packet, PacketDef, - PacketType, Protection, + PacketType, PodData, Protection, }, net::Event, protocol::Index, @@ -40,8 +39,9 @@ pub(super) fn validate_name(name: &str) -> Result<(), Error> { /// 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. - adj: Arc, + /// 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). @@ -53,9 +53,9 @@ 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(adj: Arc, index: Arc) -> Self { + pub fn new(pod_data: Arc, index: Arc) -> Self { let mut measurements = HashMap::new(); - for board in adj.pod_data.boards.values() { + 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() { @@ -67,7 +67,7 @@ impl Catalog { } } Self { - adj, + pod_data, index, measurements, } @@ -75,11 +75,7 @@ impl Catalog { /// Resolve a notification's numeric board ID to its ADJ board definition. pub fn board(&self, id: BoardId) -> Result<&Board, Error> { - self.adj - .pod_data - .boards - .get(&id) - .ok_or(Error::UnknownBoard(id)) + self.pod_data.boards.get(&id).ok_or(Error::UnknownBoard(id)) } /// Find a selectable measurement without scanning all boards and packets. diff --git a/backend/crates/station/src/logging/service.rs b/backend/crates/station/src/logging/service.rs index 56455e3d9..1012bbe35 100644 --- a/backend/crates/station/src/logging/service.rs +++ b/backend/crates/station/src/logging/service.rs @@ -6,7 +6,7 @@ use std::{ time::SystemTime, }; -use software_core::{adj::Adj, protocol::Index}; +use software_core::{model::PodData, protocol::Index}; use tokio::sync::{mpsc, oneshot, watch}; use super::{ @@ -29,7 +29,7 @@ impl Logging { /// No additional data channel or forwarding task is created. pub fn new( run: BackendRun, - adj: Arc, + pod_data: Arc, index: Arc, input: mpsc::Receiver, options: WriterOptions, @@ -39,7 +39,7 @@ impl Logging { return Err(error); } let directory = run.directory().to_path_buf(); - let catalog = Catalog::new(adj, index); + 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() diff --git a/backend/crates/station/src/logging/service/tests.rs b/backend/crates/station/src/logging/service/tests.rs index 240a40e08..4b55877d4 100644 --- a/backend/crates/station/src/logging/service/tests.rs +++ b/backend/crates/station/src/logging/service/tests.rs @@ -25,7 +25,7 @@ fn logging_with_capacity( capacity: usize, ) -> Result> { let temp = tempfile::tempdir()?; - let (adj, index) = definitions(); + let (pod_data, index) = definitions(); let run = BackendRun::new_at( Config { logging_path: temp.path().into(), @@ -35,7 +35,7 @@ fn logging_with_capacity( "2026-11-27T14:30:00Z".parse()?, )?; let (sender, receiver) = mpsc::channel(capacity); - let logger = Logging::new(run, adj, index, receiver, options)?; + let logger = Logging::new(run, pod_data, index, receiver, options)?; Ok((temp, logger, sender)) } @@ -444,8 +444,7 @@ async fn event_routes_to_the_real_logger_across_session_stop_and_restart() -> Te use crate::event::{self, ToPipeline}; let temp = tempfile::tempdir()?; - let (adj, index) = definitions(); - let pod_data = Arc::new(adj.pod_data.clone()); + let (pod_data, index) = definitions(); let config = event::EventConfig::default(); let event::Channels { udp, @@ -464,7 +463,13 @@ async fn event_routes_to_the_real_logger_across_session_stop_and_restart() -> Te }, "adj", )?; - let logger = Logging::new(run, adj, index.clone(), input, WriterOptions::default())?; + let logger = Logging::new( + run, + pod_data.clone(), + index.clone(), + input, + WriterOptions::default(), + )?; struct Tcp; impl event::TcpLink for Tcp { fn send( diff --git a/backend/crates/station/src/logging/test_support.rs b/backend/crates/station/src/logging/test_support.rs index 789663172..eb0d4d586 100644 --- a/backend/crates/station/src/logging/test_support.rs +++ b/backend/crates/station/src/logging/test_support.rs @@ -8,7 +8,6 @@ use std::{ use serde_json::json; use software_core::{ - adj::Adj, model::{ AdjId, Board, BoardId, DataPacket, MacAddress, Measurement, MeasurementKind, MessageLevel, NumericKind, Packet, PacketDef, PacketType, PodData, Protection, ProtectionKind, @@ -32,7 +31,7 @@ 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) { +pub(super) fn definitions() -> (Arc, Arc) { let measurement = |id, alias: &str| Measurement { id, alias: alias.into(), @@ -137,15 +136,12 @@ pub(super) fn definitions() -> (Arc, Arc) { ), board(PCU, "PCU", vec![pcu_protection]), ]; - let mut adj = Adj { - pod_data: PodData { - boards: boards.into_iter().map(|board| (board.id, board)).collect(), - }, - info: Default::default(), + let pod_data = PodData { + boards: boards.into_iter().map(|board| (board.id, board)).collect(), }; - adj.info.message_levels = HashMap::from([(FAULT_MESSAGE, MessageLevel::Fault)]); - let index = Arc::new(Index::new(&adj.pod_data, Some(&adj.info.message_levels))); - (Arc::new(adj), index) + 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 { diff --git a/backend/crates/station/src/logging/writer/tests.rs b/backend/crates/station/src/logging/writer/tests.rs index ee6926a3b..3fc6140e3 100644 --- a/backend/crates/station/src/logging/writer/tests.rs +++ b/backend/crates/station/src/logging/writer/tests.rs @@ -27,8 +27,8 @@ fn time(wall_time: &str) -> Result { #[test] fn native_csv_formats_preserve_fields_without_headers() -> TestResult { let temp = tempfile::tempdir()?; - let (adj, index) = definitions(); - let catalog = Catalog::new(adj, index); + 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; @@ -128,8 +128,8 @@ fn order_payload_offsets_and_large_instants_are_preserved() -> TestResult { #[test] fn confirmed_broadcast_orders_use_all_as_destination() -> TestResult { let temp = tempfile::tempdir()?; - let (adj, index) = definitions(); - let catalog = Catalog::new(adj, index); + 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(), @@ -259,7 +259,7 @@ async fn events_use_at_for_elapsed_and_order_wall_timestamps() -> TestResult { }, "adj", )?; - let (adj, index) = definitions(); + let (pod_data, index) = definitions(); let (_sender, input) = mpsc::channel(16); let (_controls, controls) = mpsc::unbounded_channel(); let (updates, _status) = watch::channel(Status::default()); @@ -269,7 +269,7 @@ async fn events_use_at_for_elapsed_and_order_wall_timestamps() -> TestResult { controls, updates, status: Status::default(), - catalog: Catalog::new(adj, index), + catalog: Catalog::new(pod_data, index), options: WriterOptions::default(), active: None, next_id: 0, @@ -312,8 +312,8 @@ async fn events_use_at_for_elapsed_and_order_wall_timestamps() -> TestResult { #[test] fn protection_time_preserves_the_adj_duration_and_its_precision() -> TestResult { let temp = tempfile::tempdir()?; - let (adj, index) = definitions(); - let catalog = Catalog::new(adj, index); + 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 { @@ -359,8 +359,8 @@ fn protection_time_preserves_the_adj_duration_and_its_precision() -> TestResult #[test] fn orders_require_matching_index_metadata_before_writing() -> TestResult { let temp = tempfile::tempdir()?; - let (adj, index) = definitions(); - let catalog = Catalog::new(adj, index); + 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(), From 65ea1c304f0db7e392a1772d97d6cb09d1723c70 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sun, 6 Dec 2026 10:59:19 +0100 Subject: [PATCH 15/19] feat(backend, logging): warn the front when a session stops on a write error MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Logging takes a clone of event's notices sender (②) and sends a Warning when a session ends with StopReason::WriteError, so the operator learns that recording stopped. It uses try_send: the router may be waiting for room in logging's input, and waiting on ② would block both. --- backend/crates/station/src/logging/README.md | 24 ++++++--- .../src/logging/WEBSOCKET_INTEGRATION.md | 6 ++- backend/crates/station/src/logging/service.rs | 10 +++- .../station/src/logging/service/tests.rs | 53 ++++++++++++------- backend/crates/station/src/logging/writer.rs | 22 ++++++++ .../station/src/logging/writer/tests.rs | 2 + 6 files changed, 89 insertions(+), 28 deletions(-) diff --git a/backend/crates/station/src/logging/README.md b/backend/crates/station/src/logging/README.md index b12fb2d8b..8f54c9ce7 100644 --- a/backend/crates/station/src/logging/README.md +++ b/backend/crates/station/src/logging/README.md @@ -81,8 +81,9 @@ row; they do not define a session-control protocol. 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, options)` starts the writer thread and -moves event's receiver into it. +`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 @@ -106,7 +107,10 @@ 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::ToLogging, logging::{BackendRun, Error, Logging, WriterOptions}}; +use station::{ + event::{Notice, ToLogging}, + logging::{BackendRun, Error, Logging, WriterOptions}, +}; use tokio::sync::mpsc; fn start_logging_consumer( @@ -114,9 +118,10 @@ fn start_logging_consumer( pod_data: Arc, index: Arc, receiver: mpsc::Receiver, + notices: mpsc::Sender, ) -> Result, Error> { Ok(Arc::new(Logging::new( - run, pod_data, index, receiver, WriterOptions::default(), + run, pod_data, index, receiver, notices, WriterOptions::default(), )?)) } ``` @@ -135,7 +140,7 @@ 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, and discarded invalid input. | +| `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 @@ -560,7 +565,14 @@ 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 frontend notification format remains the application adapter's concern. + +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/ diff --git a/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md b/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md index abb295482..72d49ef4c 100644 --- a/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md +++ b/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md @@ -59,6 +59,7 @@ event ── bounded mpsc ────────────── 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 @@ -175,8 +176,9 @@ 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. Define how those details are reported through -the existing problem/message mechanisms. +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 diff --git a/backend/crates/station/src/logging/service.rs b/backend/crates/station/src/logging/service.rs index 1012bbe35..b5b24678b 100644 --- a/backend/crates/station/src/logging/service.rs +++ b/backend/crates/station/src/logging/service.rs @@ -9,6 +9,8 @@ use std::{ 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, @@ -27,11 +29,15 @@ pub struct Logging { 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() { @@ -44,7 +50,9 @@ impl Logging { 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, status_tx, catalog, options)) + .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 { diff --git a/backend/crates/station/src/logging/service/tests.rs b/backend/crates/station/src/logging/service/tests.rs index 4b55877d4..57350a82c 100644 --- a/backend/crates/station/src/logging/service/tests.rs +++ b/backend/crates/station/src/logging/service/tests.rs @@ -8,13 +8,19 @@ use std::{ 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); +type Fixture = ( + tempfile::TempDir, + Logging, + mpsc::Sender, + mpsc::Receiver, +); fn logging(options: WriterOptions) -> Result> { logging_with_capacity(options, 1024) @@ -35,8 +41,9 @@ fn logging_with_capacity( "2026-11-27T14:30:00Z".parse()?, )?; let (sender, receiver) = mpsc::channel(capacity); - let logger = Logging::new(run, pod_data, index, receiver, options)?; - Ok((temp, logger, sender)) + 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 { @@ -54,7 +61,7 @@ async fn visible(path: &Path) -> TestResult { #[tokio::test] async fn stop_drains_records_filters_selection_and_is_idempotent() -> TestResult { - let (_temp, logger, sender) = logging(WriterOptions::default())?; + 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?; @@ -76,12 +83,14 @@ async fn stop_drains_records_filters_selection_and_is_idempotent() -> TestResult 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) = logging(WriterOptions::default())?; + 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?; @@ -113,7 +122,7 @@ async fn double_play_preserves_session_and_old_receptions_cannot_enter_a_new_one #[tokio::test] async fn selection_can_change_between_sessions() -> TestResult { - let (_temp, logger, sender) = logging(WriterOptions::default())?; + let (_temp, logger, sender, _notices) = logging(WriterOptions::default())?; logger.play(selection()).await?; sender.send(data(SystemTime::now(), 1.0)).await?; logger.stop().await?; @@ -146,7 +155,7 @@ async fn selection_can_change_between_sessions() -> TestResult { #[tokio::test] async fn stopping_a_one_slot_data_channel_never_needs_an_extra_data_slot() -> TestResult { - let (_temp, logger, sender) = logging_with_capacity(WriterOptions::default(), 1)?; + 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??; @@ -164,7 +173,7 @@ async fn stopping_a_one_slot_data_channel_never_needs_an_extra_data_slot() -> Te #[tokio::test] async fn periodic_flush_persists_a_buffered_tail_without_stopping() -> TestResult { - let (_temp, logger, sender) = logging(WriterOptions { + let (_temp, logger, sender, _notices) = logging(WriterOptions { flush_interval: Duration::from_millis(20), flush_bytes: u64::MAX, })?; @@ -178,7 +187,7 @@ async fn periodic_flush_persists_a_buffered_tail_without_stopping() -> TestResul #[tokio::test] async fn byte_threshold_flushes_without_waiting_for_the_timer() -> TestResult { - let (_temp, logger, sender) = logging(WriterOptions { + let (_temp, logger, sender, _notices) = logging(WriterOptions { flush_interval: Duration::from_secs(60), flush_bytes: 1, })?; @@ -192,7 +201,7 @@ async fn byte_threshold_flushes_without_waiting_for_the_timer() -> TestResult { #[tokio::test] async fn concurrent_producers_are_drained_before_shutdown() -> TestResult { - let (_temp, logger, sender) = logging(WriterOptions::default())?; + 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 { @@ -227,7 +236,7 @@ async fn concurrent_producers_are_drained_before_shutdown() -> TestResult { #[tokio::test] async fn write_failure_stops_with_an_error_and_closes_the_other_files() -> TestResult { - let (_temp, logger, sender) = logging(WriterOptions::default())?; + 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?; @@ -250,17 +259,22 @@ async fn write_failure_stops_with_an_error_and_closes_the_other_files() -> TestR 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) = logging(WriterOptions::default())?; + 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?; @@ -280,7 +294,7 @@ async fn invalid_selection_is_rejected_before_replacing_existing_files() -> Test #[tokio::test] async fn an_abandoned_start_reply_does_not_prevent_emergency_stop_or_restart() -> TestResult { - let (_temp, logger, _sender) = logging(WriterOptions::default())?; + let (_temp, logger, _sender, _notices) = logging(WriterOptions::default())?; let (reply, response) = oneshot::channel(); drop(response); logger.controls.send(Control::Play { @@ -297,7 +311,7 @@ async fn an_abandoned_start_reply_does_not_prevent_emergency_stop_or_restart() - #[tokio::test] async fn drop_is_a_fallback_drain_when_explicit_shutdown_was_missed() -> TestResult { - let (_temp, logger, sender) = logging(WriterOptions::default())?; + 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?; @@ -315,7 +329,7 @@ async fn drop_is_a_fallback_drain_when_explicit_shutdown_was_missed() -> TestRes #[tokio::test] async fn controls_can_run_in_spawned_application_tasks() -> TestResult { - let (_temp, logger, sender) = logging(WriterOptions::default())?; + 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??; @@ -337,7 +351,7 @@ async fn stop_drains_a_finite_prefix_while_the_producer_keeps_sending() -> TestR future::{Future, poll_fn}, task::Poll, }; - let (_temp, logger, sender) = logging(WriterOptions::default())?; + 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?; @@ -371,7 +385,7 @@ async fn stop_drains_a_finite_prefix_while_the_producer_keeps_sending() -> TestR #[tokio::test] async fn input_closure_flushes_the_session_and_releases_the_worker() -> TestResult { - let (_temp, logger, sender) = logging(WriterOptions::default())?; + let (_temp, logger, sender, _notices) = logging(WriterOptions::default())?; let session = logger.play(selection()).await?; let mut updates = logger.subscribe(); for n in 0..128 { @@ -400,7 +414,7 @@ async fn input_closure_flushes_the_session_and_releases_the_worker() -> TestResu #[tokio::test] async fn invalid_packets_and_received_orders_do_not_write_partial_or_duplicate_rows() -> TestResult { - let (_temp, logger, sender) = logging(WriterOptions::default())?; + let (_temp, logger, sender, _notices) = logging(WriterOptions::default())?; let session = logger.play(selection()).await?; sender .send(received( @@ -468,6 +482,7 @@ async fn event_routes_to_the_real_logger_across_session_stop_and_restart() -> Te pod_data.clone(), index.clone(), input, + notices.clone(), WriterOptions::default(), )?; struct Tcp; @@ -556,7 +571,7 @@ async fn event_routes_to_the_real_logger_across_session_stop_and_restart() -> Te #[tokio::test] async fn an_unrepresentable_order_payload_stops_recording_and_flushes_healthy_files() -> TestResult { - let (_temp, logger, sender) = logging(WriterOptions::default())?; + let (_temp, logger, sender, _notices) = logging(WriterOptions::default())?; let session = logger.play(selection()).await?; sender.send(data(SystemTime::now(), 7.0)).await?; sender diff --git a/backend/crates/station/src/logging/writer.rs b/backend/crates/station/src/logging/writer.rs index 0bffc7763..5cd404283 100644 --- a/backend/crates/station/src/logging/writer.rs +++ b/backend/crates/station/src/logging/writer.rs @@ -16,6 +16,8 @@ use std::{ 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, @@ -200,6 +202,8 @@ 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, @@ -221,6 +225,7 @@ pub(super) fn run( run: BackendRun, input: mpsc::Receiver, controls: mpsc::UnboundedReceiver, + notices: mpsc::Sender, updates: watch::Sender, catalog: Catalog, options: WriterOptions, @@ -235,6 +240,7 @@ pub(super) fn run( run, input, controls, + notices, updates, catalog, options, @@ -443,6 +449,9 @@ impl Writer { }; 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 { @@ -471,6 +480,19 @@ impl Writer { 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 { diff --git a/backend/crates/station/src/logging/writer/tests.rs b/backend/crates/station/src/logging/writer/tests.rs index 3fc6140e3..437e899e0 100644 --- a/backend/crates/station/src/logging/writer/tests.rs +++ b/backend/crates/station/src/logging/writer/tests.rs @@ -262,11 +262,13 @@ async fn events_use_at_for_elapsed_and_order_wall_timestamps() -> TestResult { 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), From fa3eefe88f2558537a70ee9af043bc6218b1a7a4 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sun, 6 Dec 2026 10:59:52 +0100 Subject: [PATCH 16/19] fix(backend, logging): discard orders with non-finite values instead of stopping A NaN or infinite order parameter is bad input, not a disk failure. The catalog now rejects it like any other invalid order (warning, row not written) and the session keeps recording, instead of stopping it as a write error. --- backend/crates/station/src/logging/README.md | 7 +-- backend/crates/station/src/logging/catalog.rs | 11 +++- backend/crates/station/src/logging/error.rs | 2 + .../station/src/logging/service/tests.rs | 51 ++++++++----------- 4 files changed, 38 insertions(+), 33 deletions(-) diff --git a/backend/crates/station/src/logging/README.md b/backend/crates/station/src/logging/README.md index 8f54c9ce7..3ef45c75e 100644 --- a/backend/crates/station/src/logging/README.md +++ b/backend/crates/station/src/logging/README.md @@ -365,8 +365,10 @@ 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 and incorrect -parameter counts are discarded with a warning before writing. The reserved +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. @@ -374,7 +376,6 @@ 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. -Non-finite numeric values stop recording with an error before writing a row. ### Protections: protections/ diff --git a/backend/crates/station/src/logging/catalog.rs b/backend/crates/station/src/logging/catalog.rs index 0dfaf3561..329cf44b7 100644 --- a/backend/crates/station/src/logging/catalog.rs +++ b/backend/crates/station/src/logging/catalog.rs @@ -10,7 +10,7 @@ use std::{collections::HashMap, sync::Arc}; use software_core::{ model::{ AdjId, Board, BoardId, Measurement, MessageLevel, OrderPacket, Packet, PacketDef, - PacketType, PodData, Protection, + PacketType, PodData, Protection, Value, }, net::Event, protocol::Index, @@ -176,6 +176,15 @@ impl Catalog { 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)) } diff --git a/backend/crates/station/src/logging/error.rs b/backend/crates/station/src/logging/error.rs index 3f0d1ad21..e7a6e7c10 100644 --- a/backend/crates/station/src/logging/error.rs +++ b/backend/crates/station/src/logging/error.rs @@ -22,6 +22,8 @@ pub enum Error { 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:?}")] diff --git a/backend/crates/station/src/logging/service/tests.rs b/backend/crates/station/src/logging/service/tests.rs index 57350a82c..df6da52ae 100644 --- a/backend/crates/station/src/logging/service/tests.rs +++ b/backend/crates/station/src/logging/service/tests.rs @@ -569,37 +569,30 @@ async fn event_routes_to_the_real_logger_across_session_stop_and_restart() -> Te } #[tokio::test] -async fn an_unrepresentable_order_payload_stops_recording_and_flushes_healthy_files() -> TestResult -{ - let (_temp, logger, sender, _notices) = logging(WriterOptions::default())?; +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?; - sender - .send(ToLogging::OrderSent { - at: SystemTime::now(), - board: Some(LCU), - order: OrderPacket::new( - AdjId(2002), - vec![software_core::model::Value::Number(f64::NAN)], - ), - }) - .await?; - assert!(matches!( - timeout(WAIT, logger.stop()).await?, - Err(Error::RecordingFailed(_)) - )); - assert_eq!( - logger.status().last_stop.map(|report| report.reason), - Some(StopReason::WriteError) - ); + 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()); - assert!( - fs::read_to_string(session.directory.join("data/LCU/speed.csv"))? - .ends_with(",LCU,backend,7\n") - ); - assert!(matches!( - logger.shutdown().await, - Err(Error::RecordingFailed(_)) - )); + 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(()) } From d742e6366931cc8c3ffc87f585b1c038f925c19c Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sun, 6 Dec 2026 11:00:03 +0100 Subject: [PATCH 17/19] docs(backend, logging): data files are named after the measurement alias --- backend/crates/station/src/logging/README.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/backend/crates/station/src/logging/README.md b/backend/crates/station/src/logging/README.md index 3ef45c75e..fa570c83f 100644 --- a/backend/crates/station/src/logging/README.md +++ b/backend/crates/station/src/logging/README.md @@ -180,8 +180,8 @@ directory uses the same format, but with the session's start date and time. │ ├── logger_settings.json │ ├── data/ │ │ └── / - │ │ ├── .csv - │ │ └── .csv + │ │ ├── .csv + │ │ └── .csv │ ├── protections/ │ │ └── .csv │ ├── order/ @@ -304,11 +304,13 @@ joining fields with commas. ### Measurements: data/ -A directory is created for each connected board, using its name. It contains -one CSV per selected measurement, named after its string ID: +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 +data//.csv ``` Columns, in order: From 7937189a86e3cce7d92d5920cb955f5213072887 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sun, 6 Dec 2026 11:44:24 +0100 Subject: [PATCH 18/19] feat(backend, websocket): make the command destinations public LoggerCommand, the Commands fields and OrderForwarder::new were pub(crate), so main (a separate binary crate) could not build the Commands that connect the frontends to logging and event's orders. --- backend/crates/station/src/websocket.rs | 11 +++++++---- backend/crates/station/src/websocket/order.rs | 5 +++-- 2 files changed, 10 insertions(+), 6 deletions(-) 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 } } From 6473141ca6d2ac9d26db59521a650aa2f40fa4c5 Mon Sep 17 00:00:00 2001 From: Javier Ribal del Rio Date: Sun, 6 Dec 2026 11:44:24 +0100 Subject: [PATCH 19/19] feat(backend, logging): apply the frontend's logger commands serve_commands consumes websocket's LoggerCommand queue and drives Logging: logger/variables ("/") selects the next session, logger/enable starts or stops it, and every enable is answered on logger/response with the actual state. Without a selection every data measurement is recorded, as competition-view expects. --- backend/crates/station/src/logging.rs | 2 + backend/crates/station/src/logging/README.md | 21 ++- .../src/logging/WEBSOCKET_INTEGRATION.md | 8 +- .../crates/station/src/logging/commands.rs | 157 ++++++++++++++++++ .../station/src/logging/commands/tests.rs | 126 ++++++++++++++ 5 files changed, 307 insertions(+), 7 deletions(-) create mode 100644 backend/crates/station/src/logging/commands.rs create mode 100644 backend/crates/station/src/logging/commands/tests.rs diff --git a/backend/crates/station/src/logging.rs b/backend/crates/station/src/logging.rs index d24806280..d37b94180 100644 --- a/backend/crates/station/src/logging.rs +++ b/backend/crates/station/src/logging.rs @@ -23,6 +23,7 @@ //! status snapshots through a watch channel. Input stays open between sessions. mod catalog; +mod commands; mod control; mod data; mod error; @@ -40,6 +41,7 @@ mod writer; 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}; diff --git a/backend/crates/station/src/logging/README.md b/backend/crates/station/src/logging/README.md index fa570c83f..c1b895a03 100644 --- a/backend/crates/station/src/logging/README.md +++ b/backend/crates/station/src/logging/README.md @@ -448,9 +448,23 @@ another column or reconstructing its format. ## Frontend Control and Shutdown The internal functions are `play()`, `stop()`, and `emergency_stop()`. -The `websocket`, `event`, and `payload` -modules in the PR under review will connect this internal API to the frontend; -this module does not define a separate WebSocket control protocol. +`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() @@ -599,6 +613,7 @@ were left undecided**. This flow has not been implemented in the new backend. | --- | --- | | `../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. | diff --git a/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md b/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md index 72d49ef4c..7aadaffb8 100644 --- a/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md +++ b/backend/crates/station/src/logging/WEBSOCKET_INTEGRATION.md @@ -42,10 +42,10 @@ enum LoggerCommand { } ``` -In the reviewed branch, `Commands.logger` holds an -`Option>`. Logging must consume the corresponding -receiver. `LoggerCommand` and that field have `pub(crate)` visibility, so other -`station` modules can use them. +`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 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(()) +}