Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
4a36bb2
build(backend, http): add axum, and cargo update
pminmic Nov 13, 2026
56d4aef
feat(backend, http): add datapacket structure response
pminmic Nov 13, 2026
dfbc4a6
feat(backend, http): add orderpacket structure response and separate …
pminmic Nov 13, 2026
77dd811
feat(backend, http): add protectionpacket response structure and some…
pminmic Nov 13, 2026
56e4d73
schema(backend, http): some simple example responses to understand t…
pminmic Nov 13, 2026
86726e5
fix(backend, http): delete unimportant fields in datapackets
pminmic Nov 13, 2026
c5c3562
feat(backend, http): setup functions for responses
pminmic Nov 13, 2026
7bfb433
chore(backend, http): move response to new submodule http of module adj
pminmic Nov 13, 2026
48f4abd
chore(backend, http): move http to station, change http dependencies
pminmic Nov 13, 2026
8f3c53d
feat(backend, http): handlers for each endpoint
pminmic Nov 13, 2026
d5174f6
feat(backend, http): basic server with 3 enpoints
pminmic Nov 13, 2026
8c666f7
fix(backend, http): efficient responses for endpoint (no clone)
pminmic Nov 13, 2026
caee95d
test(backend, http): add tests to server
pminmic Nov 13, 2026
e484ad3
docs(backend, http): docs in adj module
pminmic Nov 13, 2026
05d2783
refactor(backend, http): implementation in struct Adj of setups
pminmic Nov 13, 2026
441ddf1
feat(backend, http): websocket support
pminmic Nov 13, 2026
6a3d2a8
todo(backend, http): everything related with configuration (future mo…
pminmic Nov 13, 2026
b074dd4
feat(backend, http): small test of the endpoints in main
pminmic Nov 13, 2026
69af8eb
feat(backend, http): add HTTP server configuration with CORS and cach…
pminmic Nov 13, 2026
7f8a380
docs(backend, http): docs HTTP endpoints, configuration and ws handoff
pminmic Nov 13, 2026
8896a8e
refactor(backend, http): move http to model and simplify adj.rs movin…
pminmic Nov 16, 2026
e30d059
fix(backend, http): problems with time and other minor fixes
pminmic Nov 16, 2026
9b5045e
fix(backend, http): add comments
pminmic Nov 16, 2026
2817ae7
fix(backend, http): simplification of server configuration
pminmic Nov 17, 2026
69eaf1b
docs(backend, http): update readme and correct errors
pminmic Nov 17, 2026
dbef896
fix(backend, http): update main
pminmic Nov 17, 2026
ee2e354
fix(backend, git): clippy check
pminmic Nov 17, 2026
62c9ea5
fix(backend, http): clippy warings solved
pminmic Nov 17, 2026
2fdd73d
fix(backend, http): types in all the structures
pminmic Nov 17, 2026
ad236e0
docs(backend, http): comment some more
pminmic Nov 17, 2026
f6d632d
fix(backend, http): comment little things
pminmic Nov 17, 2026
f5e9ee6
fix(backend, http): revert changes to main.rs
pminmic Nov 17, 2026
8f2b89c
fix(backend, http): fix feature imports and usage
pminmic Nov 17, 2026
eabf892
Merge branch 'new-backend' into backend/http
pminmic Nov 17, 2026
ada7456
fix(backend, Cargo.lock): fix duplicated dependencies
pminmic Nov 17, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
494 changes: 356 additions & 138 deletions backend/Cargo.lock

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions backend/crates/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ files = ["logger"]
host = ["logger", "dep:whoami", "dep:rlimit"]
# Reusable tracing/diagnostics setup (console + non-blocking file + stderr layers)
trace = ["dep:tracing-subscriber", "dep:tracing-appender"]
# Structure responses for HTTP petitions
http = []

[dependencies]
bytes.workspace = true
Expand Down
7 changes: 7 additions & 0 deletions backend/crates/core/src/adj.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,13 @@ mod error;
mod info;
mod raw;

// To activate this module the feature "http" is required
// The structures used in this module aren't used for any other reason
#[cfg(feature = "http")]
Comment thread
pminmic marked this conversation as resolved.
Resolved
/// Strctures for the responses of the HTTP requests
pub mod http;

// Imports for the "git" feature
#[cfg(feature = "git")]
use std::path::PathBuf;
Comment thread
pminmic marked this conversation as resolved.
Resolved
#[cfg(feature = "git")]
Expand Down
37 changes: 32 additions & 5 deletions backend/crates/core/src/adj/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

This module deserializes, validates, and loads ADJ JSON fixtures into the backend domain model.

With the `http` feature enabled, `adj/http.rs` adds catalog-building methods to `Adj`. The serializable response types live separately in `model::http`; routes, middleware, and server setup belong to the application (`station`). See the [HTTP response models README](../model/http/README.md) for usage, JSON types, and examples.

For schema specifications, packet/measurement ID conventions, and network requirements, refer directly to the official documentation in the **ADJ repository**.

---
Expand All @@ -21,7 +23,6 @@ pub struct Adj {
Adj
├── pod_data (PodData)
│ └── boards: HashMap<BoardId, Board>
│ ├── measurements: HashMap<String, Measurement>
│ └── packets: HashMap<AdjId, PacketDef>
│ ├── explicit (Data, Order, Message — declared in packets.json;
│ │ a "message"-type packet's own `name` must be one of
Expand All @@ -38,6 +39,11 @@ Adj
└── protection_types: HashMap<String, ProtectionTypeInfo>
```

`Board` also carries its `id`, `name`, `ip`, and `mac`. There is no persistent
`Board::measurements` map: the loader uses a temporary alias-to-measurement map
to resolve packet variables, then stores the resolved measurements inside
`PacketType::Data`, `PacketType::Order`, and `PacketType::Protection`.

`message_ids` is the ADJ's own direction: a name (e.g. `"fault"`) to its
id. Not every entry is one of `model::MessageLevel`'s four severities —
other reserved names (e.g. `add_state_order`) share this same map.
Expand All @@ -47,7 +53,7 @@ other reserved names (e.g. `add_state_order`) share this same map.
between. It's the reverse of `message_ids`, restricted to whichever of
`MessageLevel::ALL`'s four names `message_ids` declares — built once in
`adj::raw::types`'s `TryFrom<RawGeneralInfo> for AdjInfo`, right after
`message_ids` itself, so it can never drift out of sync with it:
`message_ids` itself, so the two maps agree when loaded:

```rust
let message_levels: HashMap<AdjId, MessageLevel> = MessageLevel::ALL
Expand All @@ -57,7 +63,7 @@ let message_levels: HashMap<AdjId, MessageLevel> = MessageLevel::ALL
```

Which ADJ name corresponds to which `MessageLevel` is **not** decided
here — `level.name()`/`MessageLevel::from_name` (see `model/README.md`
here — `level.name()`/`MessageLevel::from_name` (see [model](../model/README.md)
§4.4) is the one place that association is spelled out, so `adj`
doesn't hardcode `"fault"`/`"warning"`/`"info"`/`"panic"` itself.

Expand All @@ -76,6 +82,27 @@ free-text log frame can reuse the same `"fault"` id. See

---

## HTTP Catalog Builders (`http` feature)

The methods implemented in `adj/http.rs` borrow `&self`; they do not consume or
modify the loaded ADJ:

| Method | Return type (in `model::http`) | Contents |
| --- | --- | --- |
| `adj.data_response()` | `DataResponse` | Data definitions grouped by board, without protection metadata. |
| `adj.order_response()` | `OrderResponse` | Order definitions grouped by board, including parameters and their protections. |
| `adj.protection_response()` | `ProtectionResponse` | Flat catalog of synthetic protection packets, plus display metadata. |

These methods return owned response models, not JSON bytes or HTTP responses.
The application chooses when to call them and serialize the results. They do
not configure routes, CORS, or caching.

In the order and protection catalogs, protection IDs are compound IDs:
`(position << 13) | measurement_id`. The internal `Protection::id` remains the
one-based position (`1–7`) within its measurement. Empty lists are retained;
zero protection durations are omitted from JSON. See the
[HTTP contract](../model/http/README.md) for the complete serialized shapes.

## Why It Is Structured This Way

The `Adj` object enforces a clear architectural boundary between **vehicle topology** and **session configuration**:
Expand All @@ -86,7 +113,7 @@ The `Adj` object enforces a clear architectural boundary between **vehicle topol
* **Design rationale**: The vehicle itself does not know or care about backend socket configurations or display strings. Separating them prevents UI and orchestration details from polluting the core telemetry model.

### 2. Standalone Loader Submodule (`raw`)
The raw deserialization types and the loader logic live isolated inside `raw`[cite: 2]. This enables non-station tools (such as bus sniffers, test runners, or simulators) to parse and ingest ADJ directories without dragging along application-level UI or station state logic.
The raw deserialization types and the loader logic live isolated inside `raw`. This enables non-station tools (such as bus sniffers, test runners, or simulators) to parse and ingest ADJ directories without dragging along application-level UI or station state logic.

### 3. Unified Packet Map (`packets`)
Protections defined under measurements are materialized during loading as first-class `PacketType::Protection(Measurement)` packets alongside the explicit data, order and message packets declared in `packets.json`. Downstream networking layers can route and handle every wire event uniformly via `Board::packets` without needing specialized traversal logic for nested measurement alarms. `packets.json` itself never declares a `"type": "protection"` entry directly — that shape only exists synthesized, one per protection a measurement declares, never as a free-standing declaration with its own arbitrary variable list.
Protections defined under measurements are materialized during loading as first-class `PacketType::Protection(Measurement)` packets alongside the explicit data, order and message packets declared in `packets.json`. Downstream networking layers can route and handle every wire event uniformly via `Board::packets` without needing specialized traversal logic for nested measurement alarms. `packets.json` itself never declares a `"type": "protection"` entry directly — that shape only exists synthesized, one per protection a measurement declares, never as a free-standing declaration with its own arbitrary variable list.
230 changes: 230 additions & 0 deletions backend/crates/core/src/adj/http.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,230 @@
use crate::{
adj::Adj,
model::{
AdjId, MeasurementKind, PacketType,
http::{
data::{
DataBoardResponse, DataMeasurementKind, DataMeasurementResponse,
DataPacketResponse, DataResponse,
},
order::{
OrderBoardResponse, OrderMeasurementResponse, OrderPacketResponse,
OrderProtectionResponse, OrderResponse,
},
protection::{ProtectionInfoResponse, ProtectionResponse, ProtectionTypeResponse},
},
},
};

use std::time::Duration;

impl Adj {
/// Builds the data catalog without modifying or consuming the ADJ.
///
/// Boards and data packets are sorted by id. Boards without data packets are
/// retained with an empty list. Measurements keep their wire order and omit
/// protection metadata.
pub fn data_response(&self) -> DataResponse {
let mut boards: Vec<DataBoardResponse> = self
.pod_data
.boards
.values()
// For each board
.map(|board| {
let mut packets: Vec<DataPacketResponse> = board
.packets
.values()
// For each packet of this board
.filter_map(|packet| {
// If the PacketType is Data, return Some(DataPacketResponse) -> Will be a Vec<DataPacketResponse>
let PacketType::Data(measurements) = &packet.packet_type else {
return None;
};

Some(DataPacketResponse {
id: packet.id,
name: packet.name.clone(),
packet_type: "data".to_string(),
measurements: measurements
.iter()
.map(|measurement| DataMeasurementResponse {
id: measurement.id,
alias: measurement.alias.clone(),
name: measurement.name.clone(),
display_units: measurement.display_units.clone(),
kind: match_measurement_kind(&measurement.kind),
})
.collect(),
})
})
.collect();
packets.sort_unstable_by_key(|packet| packet.id.0);

// Set up each packet
DataBoardResponse {
id: board.id,
name: board.name.clone(),
packets,
}
})
// Obtain a Vec<> of all the packets
.collect();

// Sort the responses by board.id
boards.sort_unstable_by_key(|board| board.id.0);

DataResponse { boards }
}

/// Builds the order catalog without modifying or consuming the ADJ.
///
/// Boards and orders are sorted by id. Boards without orders are retained with
/// an empty list. Parameters and their protections keep their ADJ order.
pub fn order_response(&self) -> OrderResponse {
let mut boards: Vec<OrderBoardResponse> = self
.pod_data
.boards
.values()
// For each board
.map(|board| {
let mut orders: Vec<OrderPacketResponse> = board
.packets
.values()
// For each order of this board
.filter_map(|packet| {
// If the packet is an Order...
let PacketType::Order(measurements) = &packet.packet_type else {
return None;
};

// Setup of the response
Some(OrderPacketResponse {
Comment thread
pminmic marked this conversation as resolved.
Resolved
id: packet.id,
name: packet.name.clone(),
packet_type: "order".to_string(),
measurements: measurements
.iter()
// Convert each parameter into its HTTP response representation
.map(|measurement| OrderMeasurementResponse {
id: measurement.id,
alias: measurement.alias.clone(),
name: measurement.name.clone(),
display_units: measurement.display_units.clone(),
kind: match_measurement_kind(&measurement.kind),
protections: measurement
.protections
.iter()
// Convert each protection
.map(|protection| OrderProtectionResponse {
id: AdjId((protection.id.0 << 13) | measurement.id.0),
kind: protection.kind,
severity: protection.severity,
time: format_protection_time(protection.time),
})
.collect(),
})
.collect(),
})
})
// Collect all the OrderPacketResponses
.collect();
orders.sort_unstable_by_key(|order| order.id.0);

OrderBoardResponse {
id: board.id,
name: board.name.clone(),
orders,
}
})
.collect();
boards.sort_unstable_by_key(|board| board.id.0);

OrderResponse { boards }
}

/// Builds the flat protection catalog without modifying or consuming the ADJ.
///
/// Protection packet ids and names are reused from the loader. The position in
/// each compound id selects its definition within the watched measurement.
/// Packets with no definition at that position are omitted. The resulting list
/// is sorted by packet id, then board id to break ties.
pub fn protection_response(&self) -> ProtectionResponse {
let mut protections: Vec<ProtectionInfoResponse> = self
.pod_data
.boards
.values()
// For each board
.flat_map(|board| board.packets.values())
.filter_map(|packet| {
// If the packet is of type Protection...
let PacketType::Protection(measurement) = &packet.packet_type else {
return None;
};

let index = usize::from(packet.id.protection_position()).checked_sub(1)?;
let protection = measurement.protections.get(index)?;

Some(ProtectionInfoResponse {
id: packet.id,
name: packet.name.clone(),
board_id: packet.board,
measurement_id: measurement.id,
kind: protection.kind,
severity: protection.severity,
time: format_protection_time(protection.time),
})
})
.collect();
protections.sort_unstable_by_key(|protection| (protection.id.0, protection.board_id.0));

let info = self
.info
.protection_types
.iter()
.map(|(name, metadata)| {
(
name.clone(),
ProtectionTypeResponse {
is_range: metadata.is_range,
text: metadata.text.clone(),
text_time: metadata.text_time.clone(),
},
)
})
.collect();

ProtectionResponse { protections, info }
}
}

// Returns Some("(time)xs") if the time is not 0
fn format_protection_time(time: Duration) -> Option<String> {
if time == Duration::new(0, 0) {
None
} else {
// If the duration is in nanoseconds (default)
let ns = time.as_nanos();

// Adjust the result
if ns.is_multiple_of(1_000_000) {
Some(format!("{}ms", ns / 1_000_000))
} else if ns.is_multiple_of(1_000) {
Some(format!("{}us", ns / 1_000))
} else {
Some(format!("{}ns", ns))
}
}
}

// Matches the kind of measurement and returns the specific type/structure
fn match_measurement_kind(measurement: &MeasurementKind) -> DataMeasurementKind {
match measurement {
MeasurementKind::Numeric { wire_type } => DataMeasurementKind::Numeric {
wire_type: *wire_type,
},
MeasurementKind::Boolean => DataMeasurementKind::Boolean,
MeasurementKind::Enum { options } => DataMeasurementKind::Enum {
options: options.clone(),
},
}
}
5 changes: 3 additions & 2 deletions backend/crates/core/src/git/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,14 @@ const ADJ_URL: &str = "https://github.com/Hyperloop-UPV/adj.git";
pub fn update_adj(path: Option<PathBuf>, branch: &str) -> Result<String, GitError> {
let (repo, dir) = adj_exists_repo(path)?;

if check_internet_connection() && branch != "" {
if check_internet_connection() && !branch.is_empty() {
info!(path = ?dir, branch, "starting ADJ update");
// Release repository handles before moving the existing cache directory.
drop(repo);
git_replace(&dir, branch, ADJ_URL)
} else if let Some(repo) = repo {
if branch == "" {

if branch.is_empty() {
warn!(path = ?dir, requested_branch = branch,
"branch not specified; using cached ADJ with current branch");
} else {
Expand Down
2 changes: 2 additions & 0 deletions backend/crates/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ pub mod adj;
/// [`protocol::tcp`], [`protocol::udp`].
pub mod protocol;

// Utils module
pub(crate) mod utils;
/// Everything a recording needs on disk: writing CSV, text and JSON
/// files without knowing what is in them ([`logger::CsvFile`]), moving
/// those files around ([`logger::files`], feature `files`) and the
Expand Down
3 changes: 3 additions & 0 deletions backend/crates/core/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ mod packet;
mod protections;
mod value;

#[cfg(feature = "http")]
pub mod http;

pub use board::{Board, PacketDef, PacketType, PodData};
pub use id::{AdjId, BoardId, MacAddress, Port};
pub use measurement::{Measurement, MeasurementKind, NumericKind, Range};
Expand Down
Loading
Loading