From 4a36bb2d67ad0c4a1c8abbeafd019d28713a64da Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 12:54:06 +0100 Subject: [PATCH 01/34] build(backend, http): add axum, and cargo update --- backend/Cargo.lock | 507 ++++++++++++++++++++++++--------- backend/crates/core/Cargo.toml | 4 + 2 files changed, 373 insertions(+), 138 deletions(-) diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 3d6daa45d..6c129a49e 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -19,9 +19,9 @@ checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" [[package]] name = "arc-swap" -version = "1.9.2" +version = "1.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c049c0be4daef0b145cb3555416b3b8ef5b7888a38aea1a3a155801fe7b0810b" +checksum = "84a22b5d51209f6de83d37a0b33d320acb8da88823e42a94c075140708f032a5" dependencies = [ "rustversion", ] @@ -46,9 +46,9 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "aws-lc-rs" -version = "1.18.2" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "faac5829c2b74c28f830747e7818ccfb684261b5f48a1118b1e2a13d36dfab13" +checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53" dependencies = [ "aws-lc-sys", "zeroize", @@ -56,9 +56,9 @@ dependencies = [ [[package]] name = "aws-lc-sys" -version = "0.46.0" +version = "0.47.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1622d8446a2d4b2ce0c7eefc73dd43a99779028d5ee5c2dd8073a658ba8a2bc" +checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52" dependencies = [ "cc", "cmake", @@ -67,6 +67,61 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "base64 0.22.1", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sha1", + "sync_wrapper", + "tokio", + "tokio-tungstenite", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + [[package]] name = "base64" version = "0.22.1" @@ -137,9 +192,9 @@ checksum = "7354288c522e7e980fafd2075d63d1285794c3a6a16cdd492f189ea406e5f18b" [[package]] name = "cc" -version = "1.8.0" +version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" +checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155" dependencies = [ "find-msvc-tools", "jobserver", @@ -167,7 +222,7 @@ checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" dependencies = [ "cfg-if", "cpufeatures 0.3.1", - "rand_core", + "rand_core 0.10.1", ] [[package]] @@ -190,9 +245,9 @@ dependencies = [ [[package]] name = "combine" -version = "4.6.8" +version = "4.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" dependencies = [ "bytes", "memchr", @@ -240,9 +295,9 @@ dependencies = [ [[package]] name = "crc32fast" -version = "1.5.2" +version = "1.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" dependencies = [ "cfg-if", ] @@ -305,20 +360,26 @@ dependencies = [ "parking_lot_core", ] +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + [[package]] name = "defmt" -version = "0.3.100" +version = "0.3.101" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0963443817029b2024136fc4dd07a5107eb8f977eaf18fcd1fdeb11306b64ad" +checksum = "4deef977660e373c458df605a913d4ab121db0ccd18d1ad6976dff7d37cddb53" dependencies = [ - "defmt 1.1.1", + "defmt 1.2.0", ] [[package]] name = "defmt" -version = "1.1.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1" +checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" dependencies = [ "bitflags 1.3.2", "defmt-macros", @@ -326,30 +387,30 @@ dependencies = [ [[package]] name = "defmt-macros" -version = "1.1.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8" +checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" dependencies = [ "defmt-parser", "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.10", ] [[package]] name = "defmt-parser" -version = "1.0.0" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" +checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" dependencies = [ "thiserror", ] [[package]] name = "deranged" -version = "0.5.8" +version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" [[package]] name = "digest" @@ -390,7 +451,7 @@ checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -401,9 +462,9 @@ checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" [[package]] name = "encoding_rs" -version = "0.8.42" +version = "0.8.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" dependencies = [ "cfg-if", "core_detect", @@ -415,15 +476,15 @@ dependencies = [ [[package]] name = "equivalent" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" [[package]] name = "errno" -version = "0.3.14" +version = "0.3.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" dependencies = [ "libc", "windows-sys 0.61.2", @@ -436,7 +497,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04839bdf9d8c10f66806fad16b852fc72aab80873aebc3cb69d85b4fa41543ed" dependencies = [ "autocfg", - "defmt 0.3.100", + "defmt 0.3.101", "heapless", "serde", ] @@ -459,9 +520,9 @@ dependencies = [ [[package]] name = "find-msvc-tools" -version = "0.1.14" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" [[package]] name = "fnv" @@ -562,6 +623,18 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + [[package]] name = "getrandom" version = "0.4.3" @@ -571,8 +644,8 @@ dependencies = [ "cfg-if", "js-sys", "libc", - "r-efi", - "rand_core", + "r-efi 6.0.0", + "rand_core 0.10.1", "wasm-bindgen", ] @@ -1657,6 +1730,12 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + [[package]] name = "human_format" version = "1.2.1" @@ -1677,6 +1756,7 @@ dependencies = [ "http", "http-body", "httparse", + "httpdate", "itoa", "pin-project-lite", "smallvec", @@ -1725,9 +1805,9 @@ dependencies = [ [[package]] name = "icu_collections" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" dependencies = [ "displaydoc", "potential_utf", @@ -1739,9 +1819,9 @@ dependencies = [ [[package]] name = "icu_locale_core" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" dependencies = [ "displaydoc", "litemap", @@ -1752,9 +1832,9 @@ dependencies = [ [[package]] name = "icu_normalizer" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" dependencies = [ "icu_collections", "icu_normalizer_data", @@ -1766,15 +1846,15 @@ dependencies = [ [[package]] name = "icu_normalizer_data" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" [[package]] name = "icu_properties" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" dependencies = [ "displaydoc", "icu_collections", @@ -1787,15 +1867,15 @@ dependencies = [ [[package]] name = "icu_properties_data" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" [[package]] name = "icu_provider" -version = "2.3.1" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" dependencies = [ "displaydoc", "icu_locale_core", @@ -1855,17 +1935,16 @@ checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" [[package]] name = "itoa" -version = "1.0.18" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" [[package]] name = "jiff" -version = "0.2.38" +version = "0.2.43" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2b005715dcbeb0089a3c0dab99f2ff1cc3b2525323552703d648585d342a383" +checksum = "26699905cc795a23e3949585cc7ba3ee8ade090872a27e4316304a777297894a" dependencies = [ - "defmt 1.1.1", "jiff-core", "jiff-static", "jiff-tzdb-platform", @@ -1878,19 +1957,18 @@ dependencies = [ [[package]] name = "jiff-core" -version = "0.1.1" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c" +checksum = "ffe6854081f5ac0a3046a9b223729ccd7a20b1e0e8277e44dc0660eedf67dfe2" dependencies = [ - "defmt 1.1.1", "log", ] [[package]] name = "jiff-static" -version = "0.2.38" +version = "0.2.43" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2cc9817253cf7c7ee4684451bd327e88d6f3658014e54a29198625590650695c" +checksum = "4b4ff49b2887190c760b86207b55cdcaabbdecaf7a0660d68aa2ed6f652abf0a" dependencies = [ "jiff-core", "proc-macro2", @@ -1974,9 +2052,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.106" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ "cfg-if", "futures-util", @@ -1991,9 +2069,9 @@ checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" [[package]] name = "libc" -version = "0.2.190" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "libredox" @@ -2027,9 +2105,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.34" +version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] name = "lru-slab" @@ -2046,6 +2124,12 @@ dependencies = [ "regex-automata", ] +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + [[package]] name = "memchr" version = "2.8.3" @@ -2054,18 +2138,18 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] name = "memmap2" -version = "0.9.11" +version = "0.9.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" dependencies = [ "libc", ] [[package]] name = "mime" -version = "0.3.17" +version = "0.3.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" [[package]] name = "mio" @@ -2134,9 +2218,9 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" [[package]] name = "openssl-probe" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" [[package]] name = "option-ext" @@ -2215,6 +2299,15 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -2265,7 +2358,7 @@ dependencies = [ "bytes", "getrandom 0.4.3", "lru-slab", - "rand", + "rand 0.10.3", "rand_pcg", "ring", "rustc-hash", @@ -2301,12 +2394,28 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + [[package]] name = "r-efi" version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core 0.9.5", +] + [[package]] name = "rand" version = "0.10.3" @@ -2315,7 +2424,26 @@ checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" dependencies = [ "chacha20", "getrandom 0.4.3", - "rand_core", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", ] [[package]] @@ -2330,7 +2458,7 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" dependencies = [ - "rand_core", + "rand_core 0.10.1", ] [[package]] @@ -2452,9 +2580,9 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.5" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags 2.13.2", "errno", @@ -2465,9 +2593,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.45" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "aws-lc-rs", "once_cell", @@ -2479,9 +2607,9 @@ dependencies = [ [[package]] name = "rustls-native-certs" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" dependencies = [ "openssl-probe", "rustls-pki-types", @@ -2491,9 +2619,9 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.15.1" +version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" dependencies = [ "web-time", "zeroize", @@ -2528,9 +2656,9 @@ checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" [[package]] name = "rustls-webpki" -version = "0.103.15" +version = "0.103.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" dependencies = [ "aws-lc-rs", "ring", @@ -2544,6 +2672,12 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + [[package]] name = "same-file" version = "1.0.6" @@ -2555,9 +2689,9 @@ dependencies = [ [[package]] name = "schannel" -version = "0.1.29" +version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" dependencies = [ "windows-sys 0.61.2", ] @@ -2624,7 +2758,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -2640,15 +2774,38 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + [[package]] name = "serde_spanned" -version = "1.1.2" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" dependencies = [ "serde_core", ] +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + [[package]] name = "sha1" version = "0.10.7" @@ -2687,9 +2844,9 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" [[package]] name = "signal-hook" -version = "0.4.5" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b29ffa27d3d59a049bb328258de100f8012848d1b08d444e08bbc02ac468435e" +checksum = "49f7447afd772ca79ad17ae0a3972a6b0df0cb4b80990fd82707593e9e012a74" dependencies = [ "libc", "signal-hook-registry", @@ -2729,9 +2886,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.16.3" +version = "1.16.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" [[package]] name = "socket2" @@ -2747,6 +2904,7 @@ dependencies = [ name = "software-core" version = "0.1.0" dependencies = [ + "axum", "bytes", "dirs", "gix", @@ -2756,6 +2914,7 @@ dependencies = [ "tempfile", "thiserror", "tokio", + "tower", "tracing", "tracing-appender", "tracing-subscriber", @@ -2805,9 +2964,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.9" +version = "3.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" dependencies = [ "proc-macro2", "quote", @@ -2831,7 +2990,7 @@ checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -2864,7 +3023,7 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -2908,9 +3067,9 @@ dependencies = [ [[package]] name = "tinystr" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" dependencies = [ "displaydoc", "zerovec", @@ -2924,9 +3083,9 @@ checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" [[package]] name = "tokio" -version = "1.53.2" +version = "1.54.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e95f91fcc7a621e8b030f6aa23c71fe9838ae2fb4d8118b75602a328f5144044" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" dependencies = [ "bytes", "libc", @@ -2946,7 +3105,7 @@ checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -2959,6 +3118,18 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite", +] + [[package]] name = "tokio-util" version = "0.7.20" @@ -3003,14 +3174,14 @@ version = "1.1.5+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" dependencies = [ - "winnow 1.0.4", + "winnow 1.0.5", ] [[package]] name = "toml_writer" -version = "1.1.3+spec-1.1.0" +version = "1.2.0+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" [[package]] name = "tower" @@ -3025,6 +3196,7 @@ dependencies = [ "tokio", "tower-layer", "tower-service", + "tracing", ] [[package]] @@ -3151,6 +3323,22 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1", + "thiserror", +] + [[package]] name = "typenum" version = "1.20.1" @@ -3180,9 +3368,9 @@ checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" [[package]] name = "unicode-normalization" -version = "0.1.25" +version = "0.1.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" dependencies = [ "tinyvec", ] @@ -3207,9 +3395,18 @@ dependencies = [ [[package]] name = "utf8_iter" -version = "1.0.4" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" [[package]] name = "valuable" @@ -3248,14 +3445,22 @@ version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + [[package]] name = "wasm-bindgen" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if", - "once_cell", "rustversion", "wasm-bindgen-macro", "wasm-bindgen-shared", @@ -3263,9 +3468,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.79" +version = "0.4.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" dependencies = [ "js-sys", "tokio", @@ -3274,9 +3479,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -3284,31 +3489,31 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ "unicode-ident", ] [[package]] name = "web-sys" -version = "0.3.106" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" dependencies = [ "js-sys", "wasm-bindgen", @@ -3326,9 +3531,9 @@ dependencies = [ [[package]] name = "webpki-root-certs" -version = "1.0.9" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" dependencies = [ "rustls-pki-types", ] @@ -3460,9 +3665,15 @@ checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" [[package]] name = "winnow" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" [[package]] name = "writeable" @@ -3472,9 +3683,9 @@ checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" [[package]] name = "yoke" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" dependencies = [ "stable_deref_trait", "yoke-derive", @@ -3489,10 +3700,30 @@ checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", "synstructure", ] +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "zerofrom" version = "0.1.8" @@ -3510,7 +3741,7 @@ checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", "synstructure", ] @@ -3533,9 +3764,9 @@ dependencies = [ [[package]] name = "zerovec" -version = "0.11.8" +version = "0.11.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" dependencies = [ "yoke", "zerofrom", @@ -3544,13 +3775,13 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.11.6" +version = "0.11.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] diff --git a/backend/crates/core/Cargo.toml b/backend/crates/core/Cargo.toml index 83985c825..50bcde557 100644 --- a/backend/crates/core/Cargo.toml +++ b/backend/crates/core/Cargo.toml @@ -22,6 +22,8 @@ pcap = ["net"] logger = [] # Reusable tracing/diagnostics setup (console + non-blocking file + stderr layers) trace = ["dep:tracing-subscriber", "dep:tracing-appender"] +# HTTP +http = ["dep:tokio"] [dependencies] bytes.workspace = true @@ -36,6 +38,8 @@ gix = { version = "0.87.1", optional = true, features = ["blocking-http-transpor dirs = { version = "7.0.0", optional = true } tempfile = { version = "3.27", optional = true } ntp_usg-server = { version = "5.0.0", optional = true, features = ["ipv4", "tokio"] } +axum = { version = "0.8.9", features = ["ws", "http2", "http1"] } +tower = { version = "0.5.3", features = ["util"] } # `workspace = true` can't be combined with extra lints in the same table, # so the workspace list is repeated here with `missing_docs` added: this is From 56d4aeff6b3e82faafad16abb021b02cd234459a Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 12:54:46 +0100 Subject: [PATCH 02/34] feat(backend, http): add datapacket structure response --- backend/crates/core/src/http.rs | 10 ++ backend/crates/core/src/http/response.rs | 3 + backend/crates/core/src/http/response/data.rs | 112 ++++++++++++++++++ backend/crates/core/src/lib.rs | 3 + 4 files changed, 128 insertions(+) create mode 100644 backend/crates/core/src/http.rs create mode 100644 backend/crates/core/src/http/response.rs create mode 100644 backend/crates/core/src/http/response/data.rs diff --git a/backend/crates/core/src/http.rs b/backend/crates/core/src/http.rs new file mode 100644 index 000000000..ca413fc77 --- /dev/null +++ b/backend/crates/core/src/http.rs @@ -0,0 +1,10 @@ +//! HTTP server built on Axum. +//! +//! Currently exposes only `GET /health`, returning `{"status":"ok"}`. +//! This reports that HTTP is responding, not that the vehicle is ready. + +mod handlers; +pub mod response; +mod server; + +pub use server::serve; diff --git a/backend/crates/core/src/http/response.rs b/backend/crates/core/src/http/response.rs new file mode 100644 index 000000000..30fd88c3a --- /dev/null +++ b/backend/crates/core/src/http/response.rs @@ -0,0 +1,3 @@ +//! Models for HTTP response bodies. + +pub mod data; diff --git a/backend/crates/core/src/http/response/data.rs b/backend/crates/core/src/http/response/data.rs new file mode 100644 index 000000000..6bdc1cd99 --- /dev/null +++ b/backend/crates/core/src/http/response/data.rs @@ -0,0 +1,112 @@ +//! ADJ v3 data packet catalog returned by `/backend/adj/DataPackets`. + +use serde::{Serialize, Serializer}; + +use crate::model::{AdjId, BoardId, NumericKind}; + +/// Data packet definitions grouped by board. +/// +/// Serialized as a JSON object containing a `boards` array. +/// See `example/data.json` for the response shape. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct DataResponse { + /// Boards and their data packet definitions. + pub boards: Vec, +} + +/// A board and the data packets it declares. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct DataBoardResponse { + /// Numeric board id from the ADJ. + #[serde(serialize_with = "serialize_board_id")] + pub id: BoardId, + /// Human-readable board name. + pub name: String, + /// Data packet definitions, each carrying its own numeric id. + pub packets: Vec, +} + +/// A data packet's ADJ metadata, not its current telemetry values. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct DataPacketResponse { + /// Numeric packet id from the ADJ. + #[serde(serialize_with = "serialize_adj_id")] + pub id: AdjId, + /// Human-readable packet name. + pub name: String, + /// ADJ packet type: `data` for this endpoint. + #[serde(rename = "type")] + pub packet_type: String, + /// Declared transmission period, expressed in `period_type` units. + pub period: f64, + /// ADJ period unit, e.g. `ms`. + pub period_type: String, + /// Name of the socket declared by the ADJ. + pub socket: String, + /// Measurement definitions in wire order, without protections. + pub measurements: Vec, +} + +/// A measurement's definition with protection metadata deliberately omitted. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct DataMeasurementResponse { + /// Numeric measurement id, distinct from its textual alias. + #[serde(serialize_with = "serialize_adj_id")] + pub id: AdjId, + /// Textual identifier declared in the ADJ. + pub alias: String, + /// Human-readable measurement name. + pub name: String, + /// Unit label displayed to the user. + pub display_units: String, + /// Numeric, boolean or enum metadata. + pub kind: DataMeasurementKind, +} + +/// Measurement metadata tagged with an explicit `type` field in JSON. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum DataMeasurementKind { + /// Numeric measurement, including its binary representation. + Numeric { + /// Wire type, serialized with its ADJ name, e.g. `float32`. + #[serde(serialize_with = "serialize_numeric_kind")] + wire_type: NumericKind, + }, + /// Boolean measurement, serialized as `{"type":"boolean"}`. + Boolean, + /// Enumeration with variants in ADJ order. + Enum { + /// Allowed variant names. + options: Vec, + }, +} + +// Serialize domain types locally without changing the internal model. +fn serialize_board_id(id: &BoardId, serializer: S) -> Result { + serializer.serialize_u16(id.0) +} + +fn serialize_adj_id(id: &AdjId, serializer: S) -> Result { + serializer.serialize_u16(id.0) +} + +// Serialize numeric kind to match ADJv3 types +fn serialize_numeric_kind( + kind: &NumericKind, + serializer: S, +) -> Result { + let name = match kind { + NumericKind::U8 => "uint8", + NumericKind::U16 => "uint16", + NumericKind::U32 => "uint32", + NumericKind::U64 => "uint64", + NumericKind::I8 => "int8", + NumericKind::I16 => "int16", + NumericKind::I32 => "int32", + NumericKind::I64 => "int64", + NumericKind::F32 => "float32", + NumericKind::F64 => "float64", + }; + serializer.serialize_str(name) +} diff --git a/backend/crates/core/src/lib.rs b/backend/crates/core/src/lib.rs index fdf802844..23d062bf2 100644 --- a/backend/crates/core/src/lib.rs +++ b/backend/crates/core/src/lib.rs @@ -25,3 +25,6 @@ pub mod adj; /// [`adj`] declares as the schema. See [`protocol::wire`], /// [`protocol::tcp`], [`protocol::udp`]. pub mod protocol; + +#[cfg(feature = "http")] +pub mod http; \ No newline at end of file From dfbc4a6521ec42db1db99e54ccc7c21311756fd2 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 13:12:56 +0100 Subject: [PATCH 03/34] feat(backend, http): add orderpacket structure response and separate utils file for serialize specific kinds of data --- backend/crates/core/src/http/response.rs | 2 + backend/crates/core/src/http/response/data.rs | 35 +------- .../crates/core/src/http/response/order.rs | 80 +++++++++++++++++++ .../crates/core/src/http/response/utils.rs | 65 +++++++++++++++ 4 files changed, 151 insertions(+), 31 deletions(-) create mode 100644 backend/crates/core/src/http/response/order.rs create mode 100644 backend/crates/core/src/http/response/utils.rs diff --git a/backend/crates/core/src/http/response.rs b/backend/crates/core/src/http/response.rs index 30fd88c3a..0c9be06ea 100644 --- a/backend/crates/core/src/http/response.rs +++ b/backend/crates/core/src/http/response.rs @@ -1,3 +1,5 @@ //! Models for HTTP response bodies. pub mod data; +pub mod order; +mod utils; diff --git a/backend/crates/core/src/http/response/data.rs b/backend/crates/core/src/http/response/data.rs index 6bdc1cd99..922608835 100644 --- a/backend/crates/core/src/http/response/data.rs +++ b/backend/crates/core/src/http/response/data.rs @@ -1,9 +1,11 @@ //! ADJ v3 data packet catalog returned by `/backend/adj/DataPackets`. -use serde::{Serialize, Serializer}; +use serde::Serialize; use crate::model::{AdjId, BoardId, NumericKind}; +use super::utils::{serialize_adj_id, serialize_board_id, serialize_numeric_kind}; + /// Data packet definitions grouped by board. /// /// Serialized as a JSON object containing a `boards` array. @@ -80,33 +82,4 @@ pub enum DataMeasurementKind { /// Allowed variant names. options: Vec, }, -} - -// Serialize domain types locally without changing the internal model. -fn serialize_board_id(id: &BoardId, serializer: S) -> Result { - serializer.serialize_u16(id.0) -} - -fn serialize_adj_id(id: &AdjId, serializer: S) -> Result { - serializer.serialize_u16(id.0) -} - -// Serialize numeric kind to match ADJv3 types -fn serialize_numeric_kind( - kind: &NumericKind, - serializer: S, -) -> Result { - let name = match kind { - NumericKind::U8 => "uint8", - NumericKind::U16 => "uint16", - NumericKind::U32 => "uint32", - NumericKind::U64 => "uint64", - NumericKind::I8 => "int8", - NumericKind::I16 => "int16", - NumericKind::I32 => "int32", - NumericKind::I64 => "int64", - NumericKind::F32 => "float32", - NumericKind::F64 => "float64", - }; - serializer.serialize_str(name) -} +} \ No newline at end of file diff --git a/backend/crates/core/src/http/response/order.rs b/backend/crates/core/src/http/response/order.rs new file mode 100644 index 000000000..1845f0d94 --- /dev/null +++ b/backend/crates/core/src/http/response/order.rs @@ -0,0 +1,80 @@ +//! ADJ v3 order catalog returned by `/backend/adj/OrderPackets`. + +use std::time::Duration; + +use serde::Serialize; + +use crate::model::{AdjId, BoardId, ProtectionKind, Severity}; + +use super::{ + data::DataMeasurementKind, + utils::{serialize_adj_id, serialize_board_id, serialize_protection_kind, serialize_severity}, +}; + +/// Order definitions grouped by board, matching `example/order.json`. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct OrderResponse { + /// Boards and their order definitions. + pub boards: Vec, +} + +/// A board and the orders it declares. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct OrderBoardResponse { + /// Numeric board id from the ADJ. + #[serde(serialize_with = "serialize_board_id")] + pub id: BoardId, + /// Human-readable board name. + pub name: String, + /// Order definitions, each carrying its own numeric id. + pub orders: Vec, +} + +/// An order definition, not a request to execute that order. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct OrderPacketResponse { + /// Numeric order id from the ADJ. + #[serde(serialize_with = "serialize_adj_id")] + pub id: AdjId, + /// Human-readable order name. + pub name: String, + /// ADJ packet type: `order` for this endpoint. + #[serde(rename = "type")] + pub packet_type: String, + /// Parameters in wire order; empty for parameterless orders. + pub measurements: Vec, +} + +/// An order parameter's ADJ definition, including its protections. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct OrderMeasurementResponse { + /// Numeric measurement id, distinct from its textual alias. + #[serde(serialize_with = "serialize_adj_id")] + pub id: AdjId, + /// Textual identifier declared in the ADJ. + pub alias: String, + /// Human-readable parameter name. + pub name: String, + /// Unit label displayed to the user. + pub display_units: String, + /// Same numeric, boolean or enum metadata used by data measurements. + pub kind: DataMeasurementKind, + /// Protection definitions in ADJ order; empty when none are declared. + pub protections: Vec, +} + +/// A parameter protection's definition, not a triggered protection event. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct OrderProtectionResponse { + /// One-based protection position within its measurement, not a packet id. + #[serde(serialize_with = "serialize_adj_id")] + pub id: AdjId, + /// Trigger condition, serialized with its type and named bounds. + #[serde(serialize_with = "serialize_protection_kind")] + pub kind: ProtectionKind, + /// Severity serialized as `fault` or `warning`. + #[serde(serialize_with = "serialize_severity")] + pub severity: Severity, + /// Required duration, serialized as `{"secs": ..., "nanos": ...}`. + pub time: Duration, +} diff --git a/backend/crates/core/src/http/response/utils.rs b/backend/crates/core/src/http/response/utils.rs new file mode 100644 index 000000000..cd145feed --- /dev/null +++ b/backend/crates/core/src/http/response/utils.rs @@ -0,0 +1,65 @@ +use crate::model::{AdjId, BoardId, NumericKind, ProtectionKind, Severity}; +use serde::{Serialize, Serializer}; + +// Serialize domain types locally without changing the internal model. +pub(crate) fn serialize_board_id( + id: &BoardId, + serializer: S, +) -> Result { + serializer.serialize_u16(id.0) +} + +pub(crate) fn serialize_adj_id( + id: &AdjId, + serializer: S, +) -> Result { + serializer.serialize_u16(id.0) +} + +// Serialize numeric kind to match ADJv3 types. +pub(crate) fn serialize_numeric_kind( + kind: &NumericKind, + serializer: S, +) -> Result { + let name = match kind { + NumericKind::U8 => "uint8", + NumericKind::U16 => "uint16", + NumericKind::U32 => "uint32", + NumericKind::U64 => "uint64", + NumericKind::I8 => "int8", + NumericKind::I16 => "int16", + NumericKind::I32 => "int32", + NumericKind::I64 => "int64", + NumericKind::F32 => "float32", + NumericKind::F64 => "float64", + }; + serializer.serialize_str(name) +} + +// A remote derive keeps the JSON representation here, without changing model. +#[derive(Serialize)] +#[serde(remote = "ProtectionKind", tag = "type", rename_all = "snake_case")] +enum ProtectionKindDef { + Above { limit: f64 }, + Below { limit: f64 }, + Equal { target: f64 }, + NotEqual { target: f64 }, + Range { min: f64, max: f64 }, +} + +pub(crate) fn serialize_protection_kind( + kind: &ProtectionKind, + serializer: S, +) -> Result { + ProtectionKindDef::serialize(kind, serializer) +} + +pub(crate) fn serialize_severity( + severity: &Severity, + serializer: S, +) -> Result { + serializer.serialize_str(match severity { + Severity::Fault => "fault", + Severity::Warning => "warning", + }) +} From 77dd8113116aac9659926228b49411fb93544f66 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 13:41:13 +0100 Subject: [PATCH 04/34] feat(backend, http): add protectionpacket response structure and some more utils to serialize --- backend/crates/core/src/http/response.rs | 1 + .../core/src/http/response/protection.rs | 59 +++++++++++++++++++ .../crates/core/src/http/response/utils.rs | 19 ++++++ 3 files changed, 79 insertions(+) create mode 100644 backend/crates/core/src/http/response/protection.rs diff --git a/backend/crates/core/src/http/response.rs b/backend/crates/core/src/http/response.rs index 0c9be06ea..c6a8a1325 100644 --- a/backend/crates/core/src/http/response.rs +++ b/backend/crates/core/src/http/response.rs @@ -2,4 +2,5 @@ pub mod data; pub mod order; +pub mod protection; mod utils; diff --git a/backend/crates/core/src/http/response/protection.rs b/backend/crates/core/src/http/response/protection.rs new file mode 100644 index 000000000..ada304151 --- /dev/null +++ b/backend/crates/core/src/http/response/protection.rs @@ -0,0 +1,59 @@ +//! Flat ADJ v3 protection catalog returned by `/backend/adj/ProtectionPackets`. + +use std::{collections::HashMap, time::Duration}; + +use serde::Serialize; + +use crate::model::{AdjId, BoardId, ProtectionKind, Severity}; + +use super::utils::{ + serialize_adj_id, serialize_adj_protection_kind, serialize_board_id, serialize_severity, +}; + +/// Protection definitions and their display metadata, matching `example/protection.json`. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct ProtectionResponse { + /// Flat list of protections, not grouped by board or measurement. + pub protections: Vec, + /// Contents of the ADJ's `protectionTypes`, keyed by names such as `Range`. + pub info: HashMap, +} + +/// A single protection definition referencing its board and measurement by id. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct ProtectionInfoResponse { + /// Compound packet id already assigned by the ADJ loader. + /// Its low 13 bits identify the measurement and its high 3 bits the + /// one-based protection position. This is not the position alone. + #[serde(serialize_with = "serialize_adj_id")] + pub id: AdjId, + /// Name assigned to the synthesized protection packet by the loader. + pub name: String, + /// Id of the board declaring this protection. + #[serde(serialize_with = "serialize_board_id")] + pub board_id: BoardId, + /// Id of the watched measurement, also encoded in the compound packet id. + #[serde(serialize_with = "serialize_adj_id")] + pub measurement_id: AdjId, + /// Trigger condition; `type` preserves the ADJ name to index `info` directly. + #[serde(serialize_with = "serialize_adj_protection_kind")] + pub kind: ProtectionKind, + /// Severity serialized as `fault` or `warning`. + #[serde(serialize_with = "serialize_severity")] + pub severity: Severity, + /// Required duration, serialized as `{"secs": ..., "nanos": ...}`. + pub time: Duration, +} + +/// Display metadata for one entry of `general_info.json`'s `protectionTypes`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct ProtectionTypeResponse { + /// Whether the protection takes an interval instead of a single bound. + #[serde(rename = "range")] + pub is_range: bool, + /// Display template; `{}` marks bounds and `%` the measured value. + pub text: String, + /// Optional time-related display template, omitted if absent from the ADJ. + #[serde(rename = "textTime", skip_serializing_if = "Option::is_none")] + pub text_time: Option, +} diff --git a/backend/crates/core/src/http/response/utils.rs b/backend/crates/core/src/http/response/utils.rs index cd145feed..99e880cfe 100644 --- a/backend/crates/core/src/http/response/utils.rs +++ b/backend/crates/core/src/http/response/utils.rs @@ -54,6 +54,25 @@ pub(crate) fn serialize_protection_kind( ProtectionKindDef::serialize(kind, serializer) } +// This endpoint indexes general_info.json's protectionTypes by the original +// ADJ names. Keep the order response's existing snake_case format unchanged. +#[derive(Serialize)] +#[serde(remote = "ProtectionKind", tag = "type")] +enum AdjProtectionKindDef { + Above { limit: f64 }, + Below { limit: f64 }, + Equal { target: f64 }, + NotEqual { target: f64 }, + Range { min: f64, max: f64 }, +} + +pub(crate) fn serialize_adj_protection_kind( + kind: &ProtectionKind, + serializer: S, +) -> Result { + AdjProtectionKindDef::serialize(kind, serializer) +} + pub(crate) fn serialize_severity( severity: &Severity, serializer: S, From 56e4d7332952d02865b84ecb907b60b36cd651d4 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 13:42:43 +0100 Subject: [PATCH 05/34] schema(backend, http): some simple example responses to understand the structure --- .../core/src/http/response/example/data.json | 95 +++++++++++++++++++ .../core/src/http/response/example/order.json | 78 +++++++++++++++ .../src/http/response/example/protection.json | 65 +++++++++++++ 3 files changed, 238 insertions(+) create mode 100644 backend/crates/core/src/http/response/example/data.json create mode 100644 backend/crates/core/src/http/response/example/order.json create mode 100644 backend/crates/core/src/http/response/example/protection.json diff --git a/backend/crates/core/src/http/response/example/data.json b/backend/crates/core/src/http/response/example/data.json new file mode 100644 index 000000000..06482e265 --- /dev/null +++ b/backend/crates/core/src/http/response/example/data.json @@ -0,0 +1,95 @@ +{ + "boards": [ + { + "id": 1, + "name": "LCU", + "packets": [ + { + "id": 936, + "name": "Temperatures", + "type": "data", + "period": 10.0, + "period_type": "ms", + "socket": "control_station_udp", + "measurements": [ + { + "id": 3000, + "alias": "temperature_1", + "name": "Motor temperature", + "display_units": "ºC", + "kind": { + "type": "numeric", + "wire_type": "float32" + } + } + ] + }, + { + "id": 967, + "name": "Levitation distance", + "type": "data", + "period": 10.0, + "period_type": "ms", + "socket": "control_station_udp", + "measurements": [ + { + "id": 3001, + "alias": "levitation_distance", + "name": "Levitation distance", + "display_units": "mm", + "kind": { + "type": "numeric", + "wire_type": "float32" + } + } + ] + } + ] + }, + { + "id": 2, + "name": "HVBMS", + "packets": [ + { + "id": 1200, + "name": "Battery voltage", + "type": "data", + "period": 20.0, + "period_type": "ms", + "socket": "control_station_udp", + "measurements": [ + { + "id": 3100, + "alias": "pack_voltage", + "name": "Pack voltage", + "display_units": "V", + "kind": { + "type": "numeric", + "wire_type": "float32" + } + } + ] + }, + { + "id": 1201, + "name": "Contactors status", + "type": "data", + "period": 100.0, + "period_type": "ms", + "socket": "control_station_udp", + "measurements": [ + { + "id": 3101, + "alias": "contactor_closed", + "name": "Contactor closed", + "display_units": "", + "kind": { + "type": "boolean" + } + } + ] + } + ] + } + ] +} diff --git a/backend/crates/core/src/http/response/example/order.json b/backend/crates/core/src/http/response/example/order.json new file mode 100644 index 000000000..f4951532b --- /dev/null +++ b/backend/crates/core/src/http/response/example/order.json @@ -0,0 +1,78 @@ +{ + "boards": [ + { + "id": 1, + "name": "LCU", + "orders": [ + { + "id": 1001, + "name": "Set target speed", + "type": "order", + "measurements": [ + { + "id": 3001, + "alias": "target_speed", + "name": "Target speed", + "display_units": "m/s", + "kind": { + "type": "numeric", + "wire_type": "float32" + }, + "protections": [ + { + "id": 1, + "kind": { + "type": "range", + "min": 0.0, + "max": 50.0 + }, + "severity": "fault", + "time": { + "secs": 0, + "nanos": 0 + } + }, + { + "id": 2, + "kind": { + "type": "above", + "limit": 40.0 + }, + "severity": "warning", + "time": { + "secs": 0, + "nanos": 500000000 + } + } + ] + } + ] + }, + { + "id": 1002, + "name": "Stop", + "type": "order", + "measurements": [] + } + ] + }, + { + "id": 2, + "name": "HVBMS", + "orders": [ + { + "id": 2001, + "name": "Open Contactors", + "type": "order", + "measurements": [] + }, + { + "id": 2003, + "name": "Start Precharge", + "type": "order", + "measurements": [] + } + ] + } + ] +} diff --git a/backend/crates/core/src/http/response/example/protection.json b/backend/crates/core/src/http/response/example/protection.json new file mode 100644 index 000000000..3c4cf66d7 --- /dev/null +++ b/backend/crates/core/src/http/response/example/protection.json @@ -0,0 +1,65 @@ +{ + "protections": [ + { + "id": 11192, + "name": "LCU_temperature_1_protection_1", + "board_id": 1, + "measurement_id": 3000, + "kind": { + "type": "Range", + "min": 0.0, + "max": 100.0 + }, + "severity": "fault", + "time": { + "secs": 0, + "nanos": 500000000 + } + }, + { + "id": 19384, + "name": "LCU_temperature_1_protection_2", + "board_id": 1, + "measurement_id": 3000, + "kind": { + "type": "Below", + "limit": 10.0 + }, + "severity": "warning", + "time": { + "secs": 1, + "nanos": 0 + } + }, + { + "id": 11292, + "name": "HVBMS_pack_voltage_protection_1", + "board_id": 2, + "measurement_id": 3100, + "kind": { + "type": "Range", + "min": 300.0, + "max": 500.0 + }, + "severity": "fault", + "time": { + "secs": 0, + "nanos": 0 + } + } + ], + "info": { + "Equal": { + "range": false, + "text": "Value is equal to {} (measured: %)" + }, + "Range": { + "range": true, + "text": "Value out of range {} (measured: %)" + }, + "Below": { + "range": false, + "text": "Value below {} (measured: %)" + } + } +} From 86726e5da92fd85f13357ee3251e50b1716621c9 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 14:00:11 +0100 Subject: [PATCH 06/34] fix(backend, http): delete unimportant fields in datapackets --- backend/crates/core/src/http/response/data.rs | 8 +------- .../crates/core/src/http/response/example/data.json | 12 ------------ 2 files changed, 1 insertion(+), 19 deletions(-) diff --git a/backend/crates/core/src/http/response/data.rs b/backend/crates/core/src/http/response/data.rs index 922608835..c16c1867f 100644 --- a/backend/crates/core/src/http/response/data.rs +++ b/backend/crates/core/src/http/response/data.rs @@ -39,12 +39,6 @@ pub struct DataPacketResponse { /// ADJ packet type: `data` for this endpoint. #[serde(rename = "type")] pub packet_type: String, - /// Declared transmission period, expressed in `period_type` units. - pub period: f64, - /// ADJ period unit, e.g. `ms`. - pub period_type: String, - /// Name of the socket declared by the ADJ. - pub socket: String, /// Measurement definitions in wire order, without protections. pub measurements: Vec, } @@ -82,4 +76,4 @@ pub enum DataMeasurementKind { /// Allowed variant names. options: Vec, }, -} \ No newline at end of file +} diff --git a/backend/crates/core/src/http/response/example/data.json b/backend/crates/core/src/http/response/example/data.json index 06482e265..e383f07eb 100644 --- a/backend/crates/core/src/http/response/example/data.json +++ b/backend/crates/core/src/http/response/example/data.json @@ -8,9 +8,6 @@ "id": 936, "name": "Temperatures", "type": "data", - "period": 10.0, - "period_type": "ms", - "socket": "control_station_udp", "measurements": [ { "id": 3000, @@ -28,9 +25,6 @@ "id": 967, "name": "Levitation distance", "type": "data", - "period": 10.0, - "period_type": "ms", - "socket": "control_station_udp", "measurements": [ { "id": 3001, @@ -54,9 +48,6 @@ "id": 1200, "name": "Battery voltage", "type": "data", - "period": 20.0, - "period_type": "ms", - "socket": "control_station_udp", "measurements": [ { "id": 3100, @@ -74,9 +65,6 @@ "id": 1201, "name": "Contactors status", "type": "data", - "period": 100.0, - "period_type": "ms", - "socket": "control_station_udp", "measurements": [ { "id": 3101, From c5c35626d1e65964e5e2c534eb690a366b345f3e Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 14:18:36 +0100 Subject: [PATCH 07/34] feat(backend, http): setup functions for responses --- backend/crates/core/src/http/response.rs | 12 +- .../crates/core/src/http/response/setup.rs | 202 ++++++++++++++++++ 2 files changed, 211 insertions(+), 3 deletions(-) create mode 100644 backend/crates/core/src/http/response/setup.rs diff --git a/backend/crates/core/src/http/response.rs b/backend/crates/core/src/http/response.rs index c6a8a1325..c85f3ea0b 100644 --- a/backend/crates/core/src/http/response.rs +++ b/backend/crates/core/src/http/response.rs @@ -1,6 +1,12 @@ //! Models for HTTP response bodies. -pub mod data; -pub mod order; -pub mod protection; +mod data; +mod order; +mod protection; +mod setup; mod utils; + +pub use data::DataResponse; +pub use order::OrderResponse; +pub use protection::ProtectionResponse; +pub use setup::{data_response, order_response, protection_response}; diff --git a/backend/crates/core/src/http/response/setup.rs b/backend/crates/core/src/http/response/setup.rs new file mode 100644 index 000000000..d8c006e66 --- /dev/null +++ b/backend/crates/core/src/http/response/setup.rs @@ -0,0 +1,202 @@ +//! Builds HTTP response models from a loaded ADJ. + +use crate::{ + adj::Adj, + model::{MeasurementKind, PacketType}, +}; + +use super::data::{ + DataBoardResponse, DataMeasurementKind, DataMeasurementResponse, DataPacketResponse, + DataResponse, +}; +use super::order::{ + OrderBoardResponse, OrderMeasurementResponse, OrderPacketResponse, OrderProtectionResponse, + OrderResponse, +}; +use super::protection::{ProtectionInfoResponse, ProtectionResponse, ProtectionTypeResponse}; + +/// 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(adj: &Adj) -> DataResponse { + let mut boards: Vec = adj + .pod_data + .boards + .values() + .map(|board| { + let mut packets: Vec = board + .packets + .values() + .filter_map(|packet| { + 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 { + MeasurementKind::Numeric { wire_type } => { + DataMeasurementKind::Numeric { + wire_type: *wire_type, + } + } + MeasurementKind::Boolean => DataMeasurementKind::Boolean, + MeasurementKind::Enum { options } => { + DataMeasurementKind::Enum { + options: options.clone(), + } + } + }, + }) + .collect(), + }) + }) + .collect(); + packets.sort_unstable_by_key(|packet| packet.id.0); + + DataBoardResponse { + id: board.id, + name: board.name.clone(), + packets, + } + }) + .collect(); + 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; +/// protection ids remain their one-based positions within each measurement. +pub fn order_response(adj: &Adj) -> OrderResponse { + let mut boards: Vec = adj + .pod_data + .boards + .values() + .map(|board| { + let mut orders: Vec = board + .packets + .values() + .filter_map(|packet| { + let PacketType::Order(measurements) = &packet.packet_type else { + return None; + }; + + Some(OrderPacketResponse { + id: packet.id, + name: packet.name.clone(), + packet_type: "order".to_string(), + measurements: measurements + .iter() + .map(|measurement| OrderMeasurementResponse { + id: measurement.id, + alias: measurement.alias.clone(), + name: measurement.name.clone(), + display_units: measurement.display_units.clone(), + kind: match &measurement.kind { + MeasurementKind::Numeric { wire_type } => { + DataMeasurementKind::Numeric { + wire_type: *wire_type, + } + } + MeasurementKind::Boolean => DataMeasurementKind::Boolean, + MeasurementKind::Enum { options } => { + DataMeasurementKind::Enum { + options: options.clone(), + } + } + }, + protections: measurement + .protections + .iter() + .map(|protection| OrderProtectionResponse { + id: protection.id, + kind: protection.kind, + severity: protection.severity, + time: protection.time, + }) + .collect(), + }) + .collect(), + }) + }) + .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(adj: &Adj) -> ProtectionResponse { + let mut protections: Vec = adj + .pod_data + .boards + .values() + .flat_map(|board| board.packets.values()) + .filter_map(|packet| { + 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: protection.time, + }) + }) + .collect(); + protections.sort_unstable_by_key(|protection| (protection.id.0, protection.board_id.0)); + + let info = adj + .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 } +} From 7bfb4332e99d83f386b40531caf8e6ca8a7e91b5 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 15:02:24 +0100 Subject: [PATCH 08/34] chore(backend, http): move response to new submodule http of module adj --- backend/crates/core/src/adj.rs | 3 +++ backend/crates/core/src/{http/response.rs => adj/http.rs} | 0 backend/crates/core/src/{http/response => adj/http}/data.rs | 0 .../core/src/{http/response => adj/http}/example/data.json | 0 .../core/src/{http/response => adj/http}/example/order.json | 0 .../src/{http/response => adj/http}/example/protection.json | 0 backend/crates/core/src/{http/response => adj/http}/order.rs | 0 .../crates/core/src/{http/response => adj/http}/protection.rs | 0 backend/crates/core/src/{http/response => adj/http}/setup.rs | 0 backend/crates/core/src/{http/response => adj/http}/utils.rs | 0 backend/crates/core/src/http.rs | 1 - 11 files changed, 3 insertions(+), 1 deletion(-) rename backend/crates/core/src/{http/response.rs => adj/http.rs} (100%) rename backend/crates/core/src/{http/response => adj/http}/data.rs (100%) rename backend/crates/core/src/{http/response => adj/http}/example/data.json (100%) rename backend/crates/core/src/{http/response => adj/http}/example/order.json (100%) rename backend/crates/core/src/{http/response => adj/http}/example/protection.json (100%) rename backend/crates/core/src/{http/response => adj/http}/order.rs (100%) rename backend/crates/core/src/{http/response => adj/http}/protection.rs (100%) rename backend/crates/core/src/{http/response => adj/http}/setup.rs (100%) rename backend/crates/core/src/{http/response => adj/http}/utils.rs (100%) diff --git a/backend/crates/core/src/adj.rs b/backend/crates/core/src/adj.rs index ccd420add..7633fd818 100644 --- a/backend/crates/core/src/adj.rs +++ b/backend/crates/core/src/adj.rs @@ -20,6 +20,9 @@ mod error; mod info; mod raw; +#[cfg(feature = "http")] +pub mod http; + #[cfg(feature = "git")] use std::path::PathBuf; #[cfg(feature = "git")] diff --git a/backend/crates/core/src/http/response.rs b/backend/crates/core/src/adj/http.rs similarity index 100% rename from backend/crates/core/src/http/response.rs rename to backend/crates/core/src/adj/http.rs diff --git a/backend/crates/core/src/http/response/data.rs b/backend/crates/core/src/adj/http/data.rs similarity index 100% rename from backend/crates/core/src/http/response/data.rs rename to backend/crates/core/src/adj/http/data.rs diff --git a/backend/crates/core/src/http/response/example/data.json b/backend/crates/core/src/adj/http/example/data.json similarity index 100% rename from backend/crates/core/src/http/response/example/data.json rename to backend/crates/core/src/adj/http/example/data.json diff --git a/backend/crates/core/src/http/response/example/order.json b/backend/crates/core/src/adj/http/example/order.json similarity index 100% rename from backend/crates/core/src/http/response/example/order.json rename to backend/crates/core/src/adj/http/example/order.json diff --git a/backend/crates/core/src/http/response/example/protection.json b/backend/crates/core/src/adj/http/example/protection.json similarity index 100% rename from backend/crates/core/src/http/response/example/protection.json rename to backend/crates/core/src/adj/http/example/protection.json diff --git a/backend/crates/core/src/http/response/order.rs b/backend/crates/core/src/adj/http/order.rs similarity index 100% rename from backend/crates/core/src/http/response/order.rs rename to backend/crates/core/src/adj/http/order.rs diff --git a/backend/crates/core/src/http/response/protection.rs b/backend/crates/core/src/adj/http/protection.rs similarity index 100% rename from backend/crates/core/src/http/response/protection.rs rename to backend/crates/core/src/adj/http/protection.rs diff --git a/backend/crates/core/src/http/response/setup.rs b/backend/crates/core/src/adj/http/setup.rs similarity index 100% rename from backend/crates/core/src/http/response/setup.rs rename to backend/crates/core/src/adj/http/setup.rs diff --git a/backend/crates/core/src/http/response/utils.rs b/backend/crates/core/src/adj/http/utils.rs similarity index 100% rename from backend/crates/core/src/http/response/utils.rs rename to backend/crates/core/src/adj/http/utils.rs diff --git a/backend/crates/core/src/http.rs b/backend/crates/core/src/http.rs index ca413fc77..5086b05ab 100644 --- a/backend/crates/core/src/http.rs +++ b/backend/crates/core/src/http.rs @@ -4,7 +4,6 @@ //! This reports that HTTP is responding, not that the vehicle is ready. mod handlers; -pub mod response; mod server; pub use server::serve; From 48f4abd70d078ea3fcd8d12ca603b503d08a3e5d Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 15:14:07 +0100 Subject: [PATCH 09/34] chore(backend, http): move http to station, change http dependencies --- backend/Cargo.lock | 9 +++++---- backend/crates/core/Cargo.toml | 6 ++---- backend/crates/core/src/http.rs | 9 --------- backend/crates/core/src/lib.rs | 5 +---- backend/crates/station/Cargo.toml | 6 ++++-- backend/crates/station/src/http.rs | 0 backend/crates/station/src/lib.rs | 1 + 7 files changed, 13 insertions(+), 23 deletions(-) delete mode 100644 backend/crates/core/src/http.rs create mode 100644 backend/crates/station/src/http.rs create mode 100644 backend/crates/station/src/lib.rs diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 6c129a49e..ee029ddc0 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -192,9 +192,9 @@ checksum = "7354288c522e7e980fafd2075d63d1285794c3a6a16cdd492f189ea406e5f18b" [[package]] name = "cc" -version = "1.11.1" +version = "1.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" dependencies = [ "find-msvc-tools", "jobserver", @@ -2904,7 +2904,6 @@ dependencies = [ name = "software-core" version = "0.1.0" dependencies = [ - "axum", "bytes", "dirs", "gix", @@ -2914,7 +2913,6 @@ dependencies = [ "tempfile", "thiserror", "tokio", - "tower", "tracing", "tracing-appender", "tracing-subscriber", @@ -2930,11 +2928,14 @@ checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" name = "station" version = "0.1.0" dependencies = [ + "axum", "serde", + "serde_json", "software-core", "thiserror", "tokio", "toml", + "tower", "tracing", "tracing-subscriber", ] diff --git a/backend/crates/core/Cargo.toml b/backend/crates/core/Cargo.toml index 50bcde557..e9476294c 100644 --- a/backend/crates/core/Cargo.toml +++ b/backend/crates/core/Cargo.toml @@ -22,8 +22,8 @@ pcap = ["net"] logger = [] # Reusable tracing/diagnostics setup (console + non-blocking file + stderr layers) trace = ["dep:tracing-subscriber", "dep:tracing-appender"] -# HTTP -http = ["dep:tokio"] +# Structure responses for HTTP petitions +http = [] [dependencies] bytes.workspace = true @@ -38,8 +38,6 @@ gix = { version = "0.87.1", optional = true, features = ["blocking-http-transpor dirs = { version = "7.0.0", optional = true } tempfile = { version = "3.27", optional = true } ntp_usg-server = { version = "5.0.0", optional = true, features = ["ipv4", "tokio"] } -axum = { version = "0.8.9", features = ["ws", "http2", "http1"] } -tower = { version = "0.5.3", features = ["util"] } # `workspace = true` can't be combined with extra lints in the same table, # so the workspace list is repeated here with `missing_docs` added: this is diff --git a/backend/crates/core/src/http.rs b/backend/crates/core/src/http.rs deleted file mode 100644 index 5086b05ab..000000000 --- a/backend/crates/core/src/http.rs +++ /dev/null @@ -1,9 +0,0 @@ -//! HTTP server built on Axum. -//! -//! Currently exposes only `GET /health`, returning `{"status":"ok"}`. -//! This reports that HTTP is responding, not that the vehicle is ready. - -mod handlers; -mod server; - -pub use server::serve; diff --git a/backend/crates/core/src/lib.rs b/backend/crates/core/src/lib.rs index 23d062bf2..40cf80793 100644 --- a/backend/crates/core/src/lib.rs +++ b/backend/crates/core/src/lib.rs @@ -24,7 +24,4 @@ pub mod adj; /// Translates bytes into typed packets and back, using the shapes /// [`adj`] declares as the schema. See [`protocol::wire`], /// [`protocol::tcp`], [`protocol::udp`]. -pub mod protocol; - -#[cfg(feature = "http")] -pub mod http; \ No newline at end of file +pub mod protocol; \ No newline at end of file diff --git a/backend/crates/station/Cargo.toml b/backend/crates/station/Cargo.toml index 20c403657..7855005ac 100644 --- a/backend/crates/station/Cargo.toml +++ b/backend/crates/station/Cargo.toml @@ -9,14 +9,16 @@ authors.workspace = true repository.workspace = true [dependencies] -software-core = { workspace = true, features = ["net", "git"] } - +software-core = { workspace = true, features = ["net", "git", "http"] } serde.workspace = true thiserror.workspace = true tokio.workspace = true toml.workspace = true tracing.workspace = true tracing-subscriber.workspace = true +serde_json.workspace = true +tower = "0.5.3" +axum = { version = "0.8.9", features = ["ws", "http1", "http2"] } [lints] workspace = true diff --git a/backend/crates/station/src/http.rs b/backend/crates/station/src/http.rs new file mode 100644 index 000000000..e69de29bb diff --git a/backend/crates/station/src/lib.rs b/backend/crates/station/src/lib.rs new file mode 100644 index 000000000..e05256f75 --- /dev/null +++ b/backend/crates/station/src/lib.rs @@ -0,0 +1 @@ +pub mod http; \ No newline at end of file From 8f3c53da6655823354462527c0fe6f77fdd217e4 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 16:07:55 +0100 Subject: [PATCH 10/34] feat(backend, http): handlers for each endpoint --- backend/crates/station/src/http/handlers.rs | 33 +++++++++++++++++++++ backend/crates/station/src/lib.rs | 1 - 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 backend/crates/station/src/http/handlers.rs delete mode 100644 backend/crates/station/src/lib.rs diff --git a/backend/crates/station/src/http/handlers.rs b/backend/crates/station/src/http/handlers.rs new file mode 100644 index 000000000..41b48ce6b --- /dev/null +++ b/backend/crates/station/src/http/handlers.rs @@ -0,0 +1,33 @@ +use std::sync::Arc; + +use axum::{Json, extract::State}; +use software_core::{adj::{Adj, http::{DataResponse, OrderResponse, ProtectionResponse, data_response, order_response, protection_response}}}; + +pub(super) struct Responses { + pub(super) data_response: DataResponse, + pub(super) order_response: OrderResponse, + pub(super) protection_response: ProtectionResponse +} + +impl Responses { + pub fn new(adj: &Adj) -> Self { + Self { + data_response: data_response(adj), + order_response: order_response(adj), + protection_response: protection_response(adj) + } + } +} + +pub(super) async fn data_packet(State(responses): State>) -> Json { + Json(responses.data_response.clone()) +} + +pub(super) async fn order_packet(State(responses): State>) -> Json { + Json(responses.order_response.clone()) +} + +pub(super) async fn protection_packet(State(responses): State>) -> Json { + Json(responses.protection_response.clone()) +} + diff --git a/backend/crates/station/src/lib.rs b/backend/crates/station/src/lib.rs deleted file mode 100644 index e05256f75..000000000 --- a/backend/crates/station/src/lib.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod http; \ No newline at end of file From d5174f63706c80db2cb7abb3d51457e3c09a1a59 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 16:09:22 +0100 Subject: [PATCH 11/34] feat(backend, http): basic server with 3 enpoints --- backend/crates/station/src/http.rs | 4 +++ backend/crates/station/src/http/server.rs | 39 +++++++++++++++++++++++ backend/crates/station/src/main.rs | 13 +++++++- 3 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 backend/crates/station/src/http/server.rs diff --git a/backend/crates/station/src/http.rs b/backend/crates/station/src/http.rs index e69de29bb..0549b6199 100644 --- a/backend/crates/station/src/http.rs +++ b/backend/crates/station/src/http.rs @@ -0,0 +1,4 @@ +mod handlers; +mod server; + +pub use server::serve; \ No newline at end of file diff --git a/backend/crates/station/src/http/server.rs b/backend/crates/station/src/http/server.rs new file mode 100644 index 000000000..35704e3ce --- /dev/null +++ b/backend/crates/station/src/http/server.rs @@ -0,0 +1,39 @@ +use std::io; + +use axum::{Router, routing::get}; +use software_core::adj::Adj; +use tokio::{net::TcpListener}; +use std::sync::Arc; + +use crate::http::handlers::{Responses, data_packet, order_packet, protection_packet}; + +/// Serves HTTP requests on an already-bound listener. +/// +/// The caller chooses the interface and port when binding the listener. +/// This future runs until the server stops; await it or spawn it on Tokio. +/// +/// # Errors +/// +/// Returns errors reported by Axum's server. +pub async fn serve(listener: TcpListener, adj: &Adj) -> io::Result<()> { + axum::serve(listener, router(adj)).await +} + +fn router(adj: &Adj) -> Router { + let responses = Arc::new(Responses::new(adj)); + + Router::new() + .route( + "/backend/adj/DataPackets", + get(data_packet) + ) + .route( + "/backend/adj/OrderPackets", + get(order_packet) + ) + .route( + "/backend/adj/ProtectionPackets", + get(protection_packet) + ) + .with_state(responses) +} \ No newline at end of file diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index 27767e13f..b4fb5790e 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -1,8 +1,10 @@ //! Ejecutable mínimo para demostrar la integración con `software-core`. use tracing_subscriber::EnvFilter; +use tokio::net::TcpListener; -fn main() { +#[tokio::main] +async fn main() -> Result<(), std::io::Error>{ let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); tracing_subscriber::fmt().with_env_filter(filter).init(); @@ -21,5 +23,14 @@ fn main() { }; tracing::info!(boards = adj.pod_data.boards.len(), "adj de prueba cargado"); + // Just testing, not the actual address + let listener = TcpListener::bind("127.0.0.1:8080").await?; + + http::serve(listener, &adj).await?; + tracing::info!("demo finalizada"); + + Ok(()) } + +mod http; \ No newline at end of file From 8c666f7a4cf814c76ebb1747f459a1fadb1a8bd6 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 16:19:38 +0100 Subject: [PATCH 12/34] fix(backend, http): efficient responses for endpoint (no clone) --- backend/crates/station/src/http/handlers.rs | 46 +++++++++++++-------- 1 file changed, 29 insertions(+), 17 deletions(-) diff --git a/backend/crates/station/src/http/handlers.rs b/backend/crates/station/src/http/handlers.rs index 41b48ce6b..d40829702 100644 --- a/backend/crates/station/src/http/handlers.rs +++ b/backend/crates/station/src/http/handlers.rs @@ -1,33 +1,45 @@ use std::sync::Arc; -use axum::{Json, extract::State}; -use software_core::{adj::{Adj, http::{DataResponse, OrderResponse, ProtectionResponse, data_response, order_response, protection_response}}}; +use axum::{ + body::Bytes, + extract::State, + http::header, + response::{IntoResponse, Response}, +}; +use software_core::adj::{ + Adj, + http::{data_response, order_response, protection_response}, +}; pub(super) struct Responses { - pub(super) data_response: DataResponse, - pub(super) order_response: OrderResponse, - pub(super) protection_response: ProtectionResponse + data_response: Bytes, + order_response: Bytes, + protection_response: Bytes, } impl Responses { - pub fn new(adj: &Adj) -> Self { - Self { - data_response: data_response(adj), - order_response: order_response(adj), - protection_response: protection_response(adj) - } + // Serialize once at startup; Bytes clones share the existing JSON buffer. + pub(super) fn new(adj: &Adj) -> Result { + Ok(Self { + data_response: serde_json::to_vec(&data_response(adj))?.into(), + order_response: serde_json::to_vec(&order_response(adj))?.into(), + protection_response: serde_json::to_vec(&protection_response(adj))?.into(), + }) } } -pub(super) async fn data_packet(State(responses): State>) -> Json { - Json(responses.data_response.clone()) +pub(super) async fn data_packet(State(responses): State>) -> Response { + json_response(responses.data_response.clone()) } -pub(super) async fn order_packet(State(responses): State>) -> Json { - Json(responses.order_response.clone()) +pub(super) async fn order_packet(State(responses): State>) -> Response { + json_response(responses.order_response.clone()) } -pub(super) async fn protection_packet(State(responses): State>) -> Json { - Json(responses.protection_response.clone()) +pub(super) async fn protection_packet(State(responses): State>) -> Response { + json_response(responses.protection_response.clone()) } +fn json_response(body: Bytes) -> Response { + ([(header::CONTENT_TYPE, "application/json")], body).into_response() +} From caee95da0a9575b8d68b55e950fa98c8151c26cb Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 16:22:24 +0100 Subject: [PATCH 13/34] test(backend, http): add tests to server --- backend/crates/station/src/http/server.rs | 116 +++++++++++++++++----- backend/crates/station/src/main.rs | 6 +- 2 files changed, 96 insertions(+), 26 deletions(-) diff --git a/backend/crates/station/src/http/server.rs b/backend/crates/station/src/http/server.rs index 35704e3ce..43780a113 100644 --- a/backend/crates/station/src/http/server.rs +++ b/backend/crates/station/src/http/server.rs @@ -1,9 +1,8 @@ -use std::io; +use std::{io, sync::Arc}; use axum::{Router, routing::get}; use software_core::adj::Adj; -use tokio::{net::TcpListener}; -use std::sync::Arc; +use tokio::net::TcpListener; use crate::http::handlers::{Responses, data_packet, order_packet, protection_packet}; @@ -14,26 +13,97 @@ use crate::http::handlers::{Responses, data_packet, order_packet, protection_pac /// /// # Errors /// -/// Returns errors reported by Axum's server. +/// Returns errors serializing the catalogs at startup or reported by Axum's server. pub async fn serve(listener: TcpListener, adj: &Adj) -> io::Result<()> { - axum::serve(listener, router(adj)).await + axum::serve(listener, router(adj)?).await } -fn router(adj: &Adj) -> Router { - let responses = Arc::new(Responses::new(adj)); - - Router::new() - .route( - "/backend/adj/DataPackets", - get(data_packet) - ) - .route( - "/backend/adj/OrderPackets", - get(order_packet) - ) - .route( - "/backend/adj/ProtectionPackets", - get(protection_packet) - ) - .with_state(responses) -} \ No newline at end of file +fn router(adj: &Adj) -> io::Result { + let responses = Arc::new(Responses::new(adj).map_err(io::Error::other)?); + + Ok(Router::new() + .route("/backend/adj/DataPackets", get(data_packet)) + .route("/backend/adj/OrderPackets", get(order_packet)) + .route("/backend/adj/ProtectionPackets", get(protection_packet)) + .with_state(responses)) +} + +#[cfg(test)] +mod tests { + use std::path::Path; + + use axum::{ + body::{Body, to_bytes}, + http::{Request, StatusCode, header}, + }; + use software_core::adj::{ + Adj, + http::{data_response, order_response, protection_response}, + load_from_dir, + }; + use tower::ServiceExt; + + use super::router; + + const PATHS: [&str; 3] = [ + "/backend/adj/DataPackets", + "/backend/adj/OrderPackets", + "/backend/adj/ProtectionPackets", + ]; + + #[tokio::test] + async fn catalogs_return_cached_json() -> Result<(), Box> { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../core/src/adj/test/adj"); + let adj = load_from_dir(&path)?; + let expected = [ + serde_json::to_value(data_response(&adj))?, + serde_json::to_value(order_response(&adj))?, + serde_json::to_value(protection_response(&adj))?, + ]; + let app = router(&adj)?; + drop(adj); + + for (path, expected) in PATHS.into_iter().zip(expected) { + let mut previous_body = None; + for _ in 0..2 { + let response = app + .clone() + .oneshot(Request::builder().uri(path).body(Body::empty())?) + .await?; + + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response.headers()[header::CONTENT_TYPE], "application/json"); + let body = to_bytes(response.into_body(), usize::MAX).await?; + let actual: serde_json::Value = serde_json::from_slice(&body)?; + assert_eq!(actual, expected); + if let Some(previous) = previous_body { + assert_eq!(body, previous); + } + previous_body = Some(body); + } + } + Ok(()) + } + + #[tokio::test] + async fn empty_catalogs_return_json_objects() -> Result<(), Box> { + let app = router(&Adj::default())?; + let expected = [ + serde_json::json!({"boards": []}), + serde_json::json!({"boards": []}), + serde_json::json!({"protections": [], "info": {}}), + ]; + + for (path, expected) in PATHS.into_iter().zip(expected) { + let response = app + .clone() + .oneshot(Request::builder().uri(path).body(Body::empty())?) + .await?; + assert_eq!(response.status(), StatusCode::OK); + let body = to_bytes(response.into_body(), 1024).await?; + let actual: serde_json::Value = serde_json::from_slice(&body)?; + assert_eq!(actual, expected); + } + Ok(()) + } +} diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index b4fb5790e..06ce2789e 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -1,10 +1,10 @@ //! Ejecutable mínimo para demostrar la integración con `software-core`. -use tracing_subscriber::EnvFilter; use tokio::net::TcpListener; +use tracing_subscriber::EnvFilter; #[tokio::main] -async fn main() -> Result<(), std::io::Error>{ +async fn main() -> std::io::Result<()> { let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); tracing_subscriber::fmt().with_env_filter(filter).init(); @@ -33,4 +33,4 @@ async fn main() -> Result<(), std::io::Error>{ Ok(()) } -mod http; \ No newline at end of file +mod http; From e484ad3e5b1485ce46a5ac82699d5f9b4be86750 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 16:45:53 +0100 Subject: [PATCH 14/34] docs(backend, http): docs in adj module --- backend/crates/core/src/adj/README.md | 4 ++- backend/crates/core/src/adj/http/README.md | 39 ++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 backend/crates/core/src/adj/http/README.md diff --git a/backend/crates/core/src/adj/README.md b/backend/crates/core/src/adj/README.md index c167bdfbc..a468ad4de 100644 --- a/backend/crates/core/src/adj/README.md +++ b/backend/crates/core/src/adj/README.md @@ -2,6 +2,8 @@ This module deserializes, validates, and loads ADJ JSON fixtures into the backend domain model. +The `http` submodule converts a loaded `Adj` into serializable data, order, and protection catalogs for HTTP responses. It defines response bodies, not routes or a server. See the [HTTP submodule README](http/README.md) for usage and JSON examples. + For schema specifications, packet/measurement ID conventions, and network requirements, refer directly to the official documentation in the **ADJ repository**. --- @@ -89,4 +91,4 @@ The `Adj` object enforces a clear architectural boundary between **vehicle topol 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. ### 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. \ No newline at end of file +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. diff --git a/backend/crates/core/src/adj/http/README.md b/backend/crates/core/src/adj/http/README.md new file mode 100644 index 000000000..ce881f870 --- /dev/null +++ b/backend/crates/core/src/adj/http/README.md @@ -0,0 +1,39 @@ +# ADJ HTTP (`adj::http`) + +Builds serializable HTTP response bodies from a loaded `Adj`, without modifying +or consuming it. This submodule contains catalog models and builders only; +HTTP routes and server setup belong to the application. + +## Catalogs + +| Builder | Response | Contents | JSON example | +| --- | --- | --- | --- | +| `data_response(&adj)` | `DataResponse` | Data packets grouped by board, with measurement definitions but no protections. | [data.json](example/data.json) | +| `order_response(&adj)` | `OrderResponse` | Orders grouped by board, including parameters and their protections. | [order.json](example/order.json) | +| `protection_response(&adj)` | `ProtectionResponse` | Flat protection list and display metadata from the ADJ's `protectionTypes`. | [protection.json](example/protection.json) | + +These are definitions, not live telemetry, order execution requests, or triggered +protection events. Boards and their packets/orders are sorted by ID; measurement +order is preserved. The flat protection list is sorted by packet ID, then board ID. + +## Usage + +Enable the `http` feature in the application's dependency: + +```bash +cargo add software-core -F http +``` + +With an already loaded `adj`: + +```rust +use software_core::adj::http::{data_response, order_response, protection_response}; + +let data = data_response(&adj); +let orders = order_response(&adj); +let protections = protection_response(&adj); +``` + +All three responses implement `serde::Serialize`, so the application can return +them as JSON using its HTTP framework. Serialization details are kept here, +without changing the internal domain model. From 05d2783dad854ac07b0becda980ad0eb58c6acb8 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 17:21:24 +0100 Subject: [PATCH 15/34] refactor(backend, http): implementation in struct Adj of setups --- backend/crates/core/src/adj.rs | 205 ++++++++++++++++++ backend/crates/core/src/adj/http.rs | 9 +- backend/crates/core/src/adj/http/data.rs | 7 +- backend/crates/core/src/adj/http/order.rs | 12 +- .../crates/core/src/adj/http/protection.rs | 9 +- backend/crates/core/src/adj/http/setup.rs | 202 ----------------- backend/crates/core/src/lib.rs | 5 +- backend/crates/core/src/utils.rs | 2 + .../{adj/http/utils.rs => utils/serialize.rs} | 0 9 files changed, 230 insertions(+), 221 deletions(-) delete mode 100644 backend/crates/core/src/adj/http/setup.rs create mode 100644 backend/crates/core/src/utils.rs rename backend/crates/core/src/{adj/http/utils.rs => utils/serialize.rs} (100%) diff --git a/backend/crates/core/src/adj.rs b/backend/crates/core/src/adj.rs index 7633fd818..854800f4f 100644 --- a/backend/crates/core/src/adj.rs +++ b/backend/crates/core/src/adj.rs @@ -47,6 +47,211 @@ pub struct Adj { pub info: AdjInfo, } +#[cfg(feature = "http")] +use self::http::{ + data::{ + DataBoardResponse, DataMeasurementKind, DataMeasurementResponse, DataPacketResponse, + DataResponse, + }, + order::{ + OrderBoardResponse, OrderMeasurementResponse, OrderPacketResponse, OrderProtectionResponse, + OrderResponse, + }, + protection::{ProtectionInfoResponse, ProtectionResponse, ProtectionTypeResponse}, +}; + +#[cfg(feature = "http")] +use crate::model::{MeasurementKind, PacketType}; + +#[cfg(feature = "http")] +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 = self + .pod_data + .boards + .values() + .map(|board| { + let mut packets: Vec = board + .packets + .values() + .filter_map(|packet| { + 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 { + MeasurementKind::Numeric { wire_type } => { + DataMeasurementKind::Numeric { + wire_type: *wire_type, + } + } + MeasurementKind::Boolean => DataMeasurementKind::Boolean, + MeasurementKind::Enum { options } => { + DataMeasurementKind::Enum { + options: options.clone(), + } + } + }, + }) + .collect(), + }) + }) + .collect(); + packets.sort_unstable_by_key(|packet| packet.id.0); + + DataBoardResponse { + id: board.id, + name: board.name.clone(), + packets, + } + }) + .collect(); + 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; + /// protection ids remain their one-based positions within each measurement. + pub fn order_response(&self) -> OrderResponse { + let mut boards: Vec = self + .pod_data + .boards + .values() + .map(|board| { + let mut orders: Vec = board + .packets + .values() + .filter_map(|packet| { + let PacketType::Order(measurements) = &packet.packet_type else { + return None; + }; + + Some(OrderPacketResponse { + id: packet.id, + name: packet.name.clone(), + packet_type: "order".to_string(), + measurements: measurements + .iter() + .map(|measurement| OrderMeasurementResponse { + id: measurement.id, + alias: measurement.alias.clone(), + name: measurement.name.clone(), + display_units: measurement.display_units.clone(), + kind: match &measurement.kind { + MeasurementKind::Numeric { wire_type } => { + DataMeasurementKind::Numeric { + wire_type: *wire_type, + } + } + MeasurementKind::Boolean => DataMeasurementKind::Boolean, + MeasurementKind::Enum { options } => { + DataMeasurementKind::Enum { + options: options.clone(), + } + } + }, + protections: measurement + .protections + .iter() + .map(|protection| OrderProtectionResponse { + id: protection.id, + kind: protection.kind, + severity: protection.severity, + time: protection.time, + }) + .collect(), + }) + .collect(), + }) + }) + .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 = self + .pod_data + .boards + .values() + .flat_map(|board| board.packets.values()) + .filter_map(|packet| { + 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: 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 } + } +} + /// The result of [`auto_adj`]: the loaded ADJ data and the checked-out commit hash. #[cfg(feature = "git")] #[derive(Debug, Clone)] diff --git a/backend/crates/core/src/adj/http.rs b/backend/crates/core/src/adj/http.rs index c85f3ea0b..d577f026c 100644 --- a/backend/crates/core/src/adj/http.rs +++ b/backend/crates/core/src/adj/http.rs @@ -1,12 +1,9 @@ //! Models for HTTP response bodies. -mod data; -mod order; -mod protection; -mod setup; -mod utils; +pub(super) mod data; +pub(super) mod order; +pub(super) mod protection; pub use data::DataResponse; pub use order::OrderResponse; pub use protection::ProtectionResponse; -pub use setup::{data_response, order_response, protection_response}; diff --git a/backend/crates/core/src/adj/http/data.rs b/backend/crates/core/src/adj/http/data.rs index c16c1867f..dbb1778dc 100644 --- a/backend/crates/core/src/adj/http/data.rs +++ b/backend/crates/core/src/adj/http/data.rs @@ -2,9 +2,10 @@ use serde::Serialize; -use crate::model::{AdjId, BoardId, NumericKind}; - -use super::utils::{serialize_adj_id, serialize_board_id, serialize_numeric_kind}; +use crate::{ + model::{AdjId, BoardId, NumericKind}, + utils::serialize::{serialize_adj_id, serialize_board_id, serialize_numeric_kind}, +}; /// Data packet definitions grouped by board. /// diff --git a/backend/crates/core/src/adj/http/order.rs b/backend/crates/core/src/adj/http/order.rs index 1845f0d94..330615022 100644 --- a/backend/crates/core/src/adj/http/order.rs +++ b/backend/crates/core/src/adj/http/order.rs @@ -4,13 +4,15 @@ use std::time::Duration; use serde::Serialize; -use crate::model::{AdjId, BoardId, ProtectionKind, Severity}; - -use super::{ - data::DataMeasurementKind, - utils::{serialize_adj_id, serialize_board_id, serialize_protection_kind, serialize_severity}, +use crate::{ + model::{AdjId, BoardId, ProtectionKind, Severity}, + utils::serialize::{ + serialize_adj_id, serialize_board_id, serialize_protection_kind, serialize_severity, + }, }; +use super::data::DataMeasurementKind; + /// Order definitions grouped by board, matching `example/order.json`. #[derive(Debug, Clone, PartialEq, Serialize)] pub struct OrderResponse { diff --git a/backend/crates/core/src/adj/http/protection.rs b/backend/crates/core/src/adj/http/protection.rs index ada304151..a19cabde6 100644 --- a/backend/crates/core/src/adj/http/protection.rs +++ b/backend/crates/core/src/adj/http/protection.rs @@ -4,10 +4,11 @@ use std::{collections::HashMap, time::Duration}; use serde::Serialize; -use crate::model::{AdjId, BoardId, ProtectionKind, Severity}; - -use super::utils::{ - serialize_adj_id, serialize_adj_protection_kind, serialize_board_id, serialize_severity, +use crate::{ + model::{AdjId, BoardId, ProtectionKind, Severity}, + utils::serialize::{ + serialize_adj_id, serialize_adj_protection_kind, serialize_board_id, serialize_severity, + }, }; /// Protection definitions and their display metadata, matching `example/protection.json`. diff --git a/backend/crates/core/src/adj/http/setup.rs b/backend/crates/core/src/adj/http/setup.rs deleted file mode 100644 index d8c006e66..000000000 --- a/backend/crates/core/src/adj/http/setup.rs +++ /dev/null @@ -1,202 +0,0 @@ -//! Builds HTTP response models from a loaded ADJ. - -use crate::{ - adj::Adj, - model::{MeasurementKind, PacketType}, -}; - -use super::data::{ - DataBoardResponse, DataMeasurementKind, DataMeasurementResponse, DataPacketResponse, - DataResponse, -}; -use super::order::{ - OrderBoardResponse, OrderMeasurementResponse, OrderPacketResponse, OrderProtectionResponse, - OrderResponse, -}; -use super::protection::{ProtectionInfoResponse, ProtectionResponse, ProtectionTypeResponse}; - -/// 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(adj: &Adj) -> DataResponse { - let mut boards: Vec = adj - .pod_data - .boards - .values() - .map(|board| { - let mut packets: Vec = board - .packets - .values() - .filter_map(|packet| { - 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 { - MeasurementKind::Numeric { wire_type } => { - DataMeasurementKind::Numeric { - wire_type: *wire_type, - } - } - MeasurementKind::Boolean => DataMeasurementKind::Boolean, - MeasurementKind::Enum { options } => { - DataMeasurementKind::Enum { - options: options.clone(), - } - } - }, - }) - .collect(), - }) - }) - .collect(); - packets.sort_unstable_by_key(|packet| packet.id.0); - - DataBoardResponse { - id: board.id, - name: board.name.clone(), - packets, - } - }) - .collect(); - 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; -/// protection ids remain their one-based positions within each measurement. -pub fn order_response(adj: &Adj) -> OrderResponse { - let mut boards: Vec = adj - .pod_data - .boards - .values() - .map(|board| { - let mut orders: Vec = board - .packets - .values() - .filter_map(|packet| { - let PacketType::Order(measurements) = &packet.packet_type else { - return None; - }; - - Some(OrderPacketResponse { - id: packet.id, - name: packet.name.clone(), - packet_type: "order".to_string(), - measurements: measurements - .iter() - .map(|measurement| OrderMeasurementResponse { - id: measurement.id, - alias: measurement.alias.clone(), - name: measurement.name.clone(), - display_units: measurement.display_units.clone(), - kind: match &measurement.kind { - MeasurementKind::Numeric { wire_type } => { - DataMeasurementKind::Numeric { - wire_type: *wire_type, - } - } - MeasurementKind::Boolean => DataMeasurementKind::Boolean, - MeasurementKind::Enum { options } => { - DataMeasurementKind::Enum { - options: options.clone(), - } - } - }, - protections: measurement - .protections - .iter() - .map(|protection| OrderProtectionResponse { - id: protection.id, - kind: protection.kind, - severity: protection.severity, - time: protection.time, - }) - .collect(), - }) - .collect(), - }) - }) - .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(adj: &Adj) -> ProtectionResponse { - let mut protections: Vec = adj - .pod_data - .boards - .values() - .flat_map(|board| board.packets.values()) - .filter_map(|packet| { - 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: protection.time, - }) - }) - .collect(); - protections.sort_unstable_by_key(|protection| (protection.id.0, protection.board_id.0)); - - let info = adj - .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 } -} diff --git a/backend/crates/core/src/lib.rs b/backend/crates/core/src/lib.rs index 40cf80793..32595115f 100644 --- a/backend/crates/core/src/lib.rs +++ b/backend/crates/core/src/lib.rs @@ -24,4 +24,7 @@ pub mod adj; /// Translates bytes into typed packets and back, using the shapes /// [`adj`] declares as the schema. See [`protocol::wire`], /// [`protocol::tcp`], [`protocol::udp`]. -pub mod protocol; \ No newline at end of file +pub mod protocol; + +// Utils module +pub(crate) mod utils; \ No newline at end of file diff --git a/backend/crates/core/src/utils.rs b/backend/crates/core/src/utils.rs new file mode 100644 index 000000000..8e32a77ad --- /dev/null +++ b/backend/crates/core/src/utils.rs @@ -0,0 +1,2 @@ +#[cfg(feature = "http")] +pub(crate) mod serialize; \ No newline at end of file diff --git a/backend/crates/core/src/adj/http/utils.rs b/backend/crates/core/src/utils/serialize.rs similarity index 100% rename from backend/crates/core/src/adj/http/utils.rs rename to backend/crates/core/src/utils/serialize.rs From 441ddf13a7ff08f74c19e5a9bb1c307d2ef7f4f5 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 17:25:49 +0100 Subject: [PATCH 16/34] feat(backend, http): websocket support --- backend/crates/station/src/http.rs | 22 ++- backend/crates/station/src/http/handlers.rs | 83 ++++++++-- backend/crates/station/src/http/server.rs | 172 +++++++++++++++++--- 3 files changed, 237 insertions(+), 40 deletions(-) diff --git a/backend/crates/station/src/http.rs b/backend/crates/station/src/http.rs index 0549b6199..a7f23e6f2 100644 --- a/backend/crates/station/src/http.rs +++ b/backend/crates/station/src/http.rs @@ -1,4 +1,24 @@ +//! Station HTTP API: ADJ catalogs and incoming WebSocket connections. +//! +//! This module only negotiates WebSocket upgrades and hands sockets to a +//! channel. Message handling and client management belong to the future +//! WebSocket module, which will own the channel's receiver. + +use std::io; + +use software_core::adj::Adj; +use tokio::net::TcpListener; + mod handlers; mod server; -pub use server::serve; \ No newline at end of file +pub use server::serve_with_websocket; + +/// Serves the catalogs without connecting a WebSocket consumer yet. +/// +/// Preserves the entry point used by the test startup code. Upgrade requests +/// to `/backend` receive `503` until [`serve_with_websocket`] is used with a +/// channel connected to the future WebSocket module. +pub async fn serve(listener: TcpListener, adj: &Adj) -> io::Result<()> { + serve_with_websocket(listener, adj, None).await +} diff --git a/backend/crates/station/src/http/handlers.rs b/backend/crates/station/src/http/handlers.rs index d40829702..815e33385 100644 --- a/backend/crates/station/src/http/handlers.rs +++ b/backend/crates/station/src/http/handlers.rs @@ -1,45 +1,92 @@ +//! Handlers for precomputed catalogs and WebSocket upgrades. + use std::sync::Arc; use axum::{ body::Bytes, - extract::State, - http::header, + extract::{State, WebSocketUpgrade, ws::WebSocket}, + http::{StatusCode, header}, response::{IntoResponse, Response}, }; -use software_core::adj::{ - Adj, - http::{data_response, order_response, protection_response}, -}; +use software_core::adj::Adj; +use tokio::sync::mpsc; + +/// Immutable state shared by all requests without a mutex. +pub(super) struct HttpState { + responses: Responses, + websocket_connections: Option>, +} -pub(super) struct Responses { +impl HttpState { + pub(super) fn new( + adj: &Adj, + websocket_connections: Option>, + ) -> Result { + Ok(Self { + responses: Responses::new(adj)?, + websocket_connections, + }) + } +} + +/// Pre-serialized JSON. Each Bytes clone shares the same underlying content. +struct Responses { data_response: Bytes, order_response: Bytes, protection_response: Bytes, } impl Responses { - // Serialize once at startup; Bytes clones share the existing JSON buffer. - pub(super) fn new(adj: &Adj) -> Result { + // ADJ transformation and serialization happen only at startup. + fn new(adj: &Adj) -> Result { Ok(Self { - data_response: serde_json::to_vec(&data_response(adj))?.into(), - order_response: serde_json::to_vec(&order_response(adj))?.into(), - protection_response: serde_json::to_vec(&protection_response(adj))?.into(), + data_response: serde_json::to_vec(&adj.data_response())?.into(), + order_response: serde_json::to_vec(&adj.order_response())?.into(), + protection_response: serde_json::to_vec(&adj.protection_response())?.into(), }) } } -pub(super) async fn data_packet(State(responses): State>) -> Response { - json_response(responses.data_response.clone()) +pub(super) async fn data_packet(State(state): State>) -> Response { + json_response(state.responses.data_response.clone()) +} + +pub(super) async fn order_packet(State(state): State>) -> Response { + json_response(state.responses.order_response.clone()) } -pub(super) async fn order_packet(State(responses): State>) -> Response { - json_response(responses.order_response.clone()) +pub(super) async fn protection_packet(State(state): State>) -> Response { + json_response(state.responses.protection_response.clone()) } -pub(super) async fn protection_packet(State(responses): State>) -> Response { - json_response(responses.protection_response.clone()) +/// Negotiates the connection without reading messages or implementing the frontend protocol. +pub(super) async fn websocket( + State(state): State>, + upgrade: WebSocketUpgrade, +) -> Response { + let Some(connections) = &state.websocket_connections else { + return StatusCode::SERVICE_UNAVAILABLE.into_response(); + }; + + // Reserve a slot before returning 101: a closed or full channel must reject + // the request rather than accept a socket that cannot be handed off. + let permit = match connections.clone().try_reserve_owned() { + Ok(permit) => permit, + Err(_) => return StatusCode::SERVICE_UNAVAILABLE.into_response(), + }; + + upgrade + .on_failed_upgrade(|error| { + tracing::warn!(%error, "falló el upgrade WebSocket"); + }) + .on_upgrade(move |socket| async move { + // The receiver now owns the socket and manages its lifetime and + // closure. If the receiver disappears, the socket is dropped. + permit.send(socket); + }) } fn json_response(body: Bytes) -> Response { + // Do not wrap these bytes in Json: that would serialize the content again. ([(header::CONTENT_TYPE, "application/json")], body).into_response() } diff --git a/backend/crates/station/src/http/server.rs b/backend/crates/station/src/http/server.rs index 43780a113..d8226cb29 100644 --- a/backend/crates/station/src/http/server.rs +++ b/backend/crates/station/src/http/server.rs @@ -1,45 +1,60 @@ +//! Router construction and server execution using an existing listener. + use std::{io, sync::Arc}; -use axum::{Router, routing::get}; +use axum::{Router, extract::ws::WebSocket, routing::get}; use software_core::adj::Adj; -use tokio::net::TcpListener; +use tokio::{net::TcpListener, sync::mpsc}; -use crate::http::handlers::{Responses, data_packet, order_packet, protection_packet}; +use super::handlers::{HttpState, data_packet, order_packet, protection_packet, websocket}; -/// Serves HTTP requests on an already-bound listener. +/// Serves the catalogs and hands connections to the future WebSocket module. +/// +/// The caller chooses the address and port when binding the listener. To enable +/// WebSocket, pass `Some(sender)` from a bounded channel and keep its receiver +/// in the module that will manage the sockets. With `None`, a closed receiver, +/// or a full channel, upgrade requests receive `503`. /// -/// The caller chooses the interface and port when binding the listener. /// This future runs until the server stops; await it or spawn it on Tokio. /// /// # Errors /// -/// Returns errors serializing the catalogs at startup or reported by Axum's server. -pub async fn serve(listener: TcpListener, adj: &Adj) -> io::Result<()> { - axum::serve(listener, router(adj)?).await +/// Propagates errors serializing the catalogs or running the Axum server. +pub async fn serve_with_websocket( + listener: TcpListener, + adj: &Adj, + websocket_connections: Option>, +) -> io::Result<()> { + axum::serve(listener, router(adj, websocket_connections)?).await } -fn router(adj: &Adj) -> io::Result { - let responses = Arc::new(Responses::new(adj).map_err(io::Error::other)?); +fn router(adj: &Adj, websocket_connections: Option>) -> io::Result { + // Build and serialize the catalogs once, before accepting requests. The + // state retains the bytes even after the Adj is dropped. + let state = Arc::new(HttpState::new(adj, websocket_connections).map_err(io::Error::other)?); Ok(Router::new() .route("/backend/adj/DataPackets", get(data_packet)) .route("/backend/adj/OrderPackets", get(order_packet)) .route("/backend/adj/ProtectionPackets", get(protection_packet)) - .with_state(responses)) + .route("/backend", get(websocket)) + .with_state(state)) } #[cfg(test)] mod tests { - use std::path::Path; + use std::{io, path::Path, time::Duration}; use axum::{ body::{Body, to_bytes}, http::{Request, StatusCode, header}, }; - use software_core::adj::{ - Adj, - http::{data_response, order_response, protection_response}, - load_from_dir, + use software_core::adj::{Adj, load_from_dir}; + use tokio::{ + io::{AsyncBufReadExt, AsyncWriteExt, BufReader}, + net::{TcpListener, TcpStream}, + sync::{mpsc, oneshot}, + time::timeout, }; use tower::ServiceExt; @@ -56,11 +71,11 @@ mod tests { let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../core/src/adj/test/adj"); let adj = load_from_dir(&path)?; let expected = [ - serde_json::to_value(data_response(&adj))?, - serde_json::to_value(order_response(&adj))?, - serde_json::to_value(protection_response(&adj))?, + serde_json::to_value(&adj.data_response())?, + serde_json::to_value(&adj.order_response())?, + serde_json::to_value(&adj.protection_response())?, ]; - let app = router(&adj)?; + let app = router(&adj, None)?; drop(adj); for (path, expected) in PATHS.into_iter().zip(expected) { @@ -87,7 +102,7 @@ mod tests { #[tokio::test] async fn empty_catalogs_return_json_objects() -> Result<(), Box> { - let app = router(&Adj::default())?; + let app = router(&Adj::default(), None)?; let expected = [ serde_json::json!({"boards": []}), serde_json::json!({"boards": []}), @@ -106,4 +121,119 @@ mod tests { } Ok(()) } + + // Upgrades require a real HTTP connection: oneshot does not provide Hyper's + // OnUpgrade extension. The server only runs for the duration of the test. + async fn handshake( + app: axum::Router, + ) -> Result<(String, TcpStream), Box> { + let listener = TcpListener::bind("127.0.0.1:0").await?; + let address = listener.local_addr()?; + let (shutdown, stopped) = oneshot::channel(); + let server = tokio::spawn(async move { + axum::serve(listener, app) + .with_graceful_shutdown(async move { + let _ = stopped.await; + }) + .await + }); + + let response = timeout(Duration::from_secs(5), async { + let mut stream = TcpStream::connect(address).await?; + let request = format!( + "GET /backend HTTP/1.1\r\n\ + Host: {address}\r\n\ + Connection: Upgrade\r\n\ + Upgrade: websocket\r\n\ + Sec-WebSocket-Version: 13\r\n\ + Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n" + ); + stream.write_all(request.as_bytes()).await?; + + let mut reader = BufReader::new(stream); + let mut headers = String::new(); + while !headers.ends_with("\r\n\r\n") { + if reader.read_line(&mut headers).await? == 0 { + return Err(io::Error::from(io::ErrorKind::UnexpectedEof)); + } + } + Ok((headers, reader.into_inner())) + }) + .await; + + let _ = shutdown.send(()); + timeout(Duration::from_secs(5), server).await???; + Ok(response??) + } + + #[tokio::test] + async fn websocket_upgrade_delivers_the_socket() -> Result<(), Box> { + let (connections, mut receiver) = mpsc::channel(1); + let app = router(&Adj::default(), Some(connections.clone()))?; + let (headers, _client) = handshake(app).await?; + + assert!(headers.starts_with("HTTP/1.1 101 Switching Protocols\r\n")); + assert!( + headers + .to_ascii_lowercase() + .contains("sec-websocket-accept: s3pplmbitxaq9kygzzhzrbk+xoo=\r\n") + ); + let socket = timeout(Duration::from_secs(5), receiver.recv()) + .await? + .ok_or_else(|| io::Error::other("no se entregó el socket"))?; + assert_eq!(connections.capacity(), 1); + drop(socket); + Ok(()) + } + + #[tokio::test] + async fn websocket_without_a_consumer_returns_unavailable() + -> Result<(), Box> { + let app = router(&Adj::default(), None)?; + let (headers, _client) = handshake(app).await?; + assert!(headers.starts_with("HTTP/1.1 503 Service Unavailable\r\n")); + Ok(()) + } + + #[tokio::test] + async fn websocket_with_a_closed_channel_returns_unavailable() + -> Result<(), Box> { + let (connections, receiver) = mpsc::channel(1); + drop(receiver); + let app = router(&Adj::default(), Some(connections))?; + let (headers, _client) = handshake(app).await?; + assert!(headers.starts_with("HTTP/1.1 503 Service Unavailable\r\n")); + Ok(()) + } + + #[tokio::test] + async fn websocket_with_a_full_channel_returns_unavailable() + -> Result<(), Box> { + let (connections, _receiver) = mpsc::channel(1); + // Simulate an occupied slot without requiring another test socket. + let reservation = connections.clone().try_reserve_owned()?; + let app = router(&Adj::default(), Some(connections))?; + let (headers, _client) = handshake(app).await?; + assert!(headers.starts_with("HTTP/1.1 503 Service Unavailable\r\n")); + drop(reservation); + Ok(()) + } + + #[tokio::test] + async fn websocket_rejects_requests_without_upgrade_headers() + -> Result<(), Box> { + let (connections, mut receiver) = mpsc::channel(1); + let app = router(&Adj::default(), Some(connections.clone()))?; + let response = app + .oneshot(Request::builder().uri("/backend").body(Body::empty())?) + .await?; + + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert_eq!(connections.capacity(), 1); + assert!(matches!( + receiver.try_recv(), + Err(mpsc::error::TryRecvError::Empty) + )); + Ok(()) + } } From 6a3d2a85b5e0f78cc2cb6a0c57a5b3071a48e25d Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 17:42:46 +0100 Subject: [PATCH 17/34] todo(backend, http): everything related with configuration (future module config) --- backend/crates/station/src/http/server.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/backend/crates/station/src/http/server.rs b/backend/crates/station/src/http/server.rs index d8226cb29..6a8718051 100644 --- a/backend/crates/station/src/http/server.rs +++ b/backend/crates/station/src/http/server.rs @@ -8,6 +8,25 @@ use tokio::{net::TcpListener, sync::mpsc}; use super::handlers::{HttpState, data_packet, order_packet, protection_packet, websocket}; +/// Configures the HTTP server using the future application configuration. +/// +/// Once `HttpConfig` is defined, this function should translate its settings +/// into the server setup: select the listening address and port, apply the +/// allowed CORS origins, and configure cache headers for the ADJ catalogs. +/// Invalid settings should be reported before the server starts accepting +/// requests, rather than silently falling back to other values. +/// +/// It should consume configuration already loaded by the application, not read +/// configuration files or environment variables itself. ADJ loading and +/// WebSocket message handling remain outside its responsibilities. +/// +/// The parameter and return type will be finalized when the configuration +/// module is available. This placeholder is not called by the current startup. +#[expect(dead_code, reason = "Waiting for the application configuration module")] +fn configure_server(/* config: &HttpConfig */) { + todo!("Configure the HTTP server once HttpConfig is available"); +} + /// Serves the catalogs and hands connections to the future WebSocket module. /// /// The caller chooses the address and port when binding the listener. To enable From b074dd4a22c07cf6d555cb4d7fd10e9986667463 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 17:43:16 +0100 Subject: [PATCH 18/34] feat(backend, http): small test of the endpoints in main --- backend/crates/station/src/main.rs | 1 + backend/crates/station/src/vehicle.rs | 0 2 files changed, 1 insertion(+) create mode 100644 backend/crates/station/src/vehicle.rs diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index 06ce2789e..c3288c29d 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -34,3 +34,4 @@ async fn main() -> std::io::Result<()> { } mod http; +mod vehicle; \ No newline at end of file diff --git a/backend/crates/station/src/vehicle.rs b/backend/crates/station/src/vehicle.rs new file mode 100644 index 000000000..e69de29bb From 69af8ebe5c219a09667719fe851484b1adb71475 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 23:06:25 +0100 Subject: [PATCH 19/34] feat(backend, http): add HTTP server configuration with CORS and cache policies --- backend/Cargo.lock | 1 + backend/crates/station/Cargo.toml | 1 + backend/crates/station/src/http.rs | 8 + backend/crates/station/src/http/configure.rs | 381 +++++++++++++++++++ backend/crates/station/src/http/server.rs | 59 +-- 5 files changed, 424 insertions(+), 26 deletions(-) create mode 100644 backend/crates/station/src/http/configure.rs diff --git a/backend/Cargo.lock b/backend/Cargo.lock index ee029ddc0..2f7055784 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -2936,6 +2936,7 @@ dependencies = [ "tokio", "toml", "tower", + "tower-http", "tracing", "tracing-subscriber", ] diff --git a/backend/crates/station/Cargo.toml b/backend/crates/station/Cargo.toml index 7855005ac..9eed62cbe 100644 --- a/backend/crates/station/Cargo.toml +++ b/backend/crates/station/Cargo.toml @@ -19,6 +19,7 @@ tracing-subscriber.workspace = true serde_json.workspace = true tower = "0.5.3" axum = { version = "0.8.9", features = ["ws", "http1", "http2"] } +tower-http = { version = "0.6.11", features = ["cors", "set-header"] } [lints] workspace = true diff --git a/backend/crates/station/src/http.rs b/backend/crates/station/src/http.rs index a7f23e6f2..f0d2d6484 100644 --- a/backend/crates/station/src/http.rs +++ b/backend/crates/station/src/http.rs @@ -9,10 +9,18 @@ use std::io; use software_core::adj::Adj; use tokio::net::TcpListener; +mod configure; mod handlers; mod server; pub use server::serve_with_websocket; +// The test main still uses the listener-based entry point. Configuration will +// be connected by the application startup when its config module is available. +#[allow( + unused_imports, + reason = "The test startup does not use configuration yet" +)] +pub use configure::{CachePolicy, HttpConfig, configure_server}; /// Serves the catalogs without connecting a WebSocket consumer yet. /// diff --git a/backend/crates/station/src/http/configure.rs b/backend/crates/station/src/http/configure.rs new file mode 100644 index 000000000..bf6a4a38f --- /dev/null +++ b/backend/crates/station/src/http/configure.rs @@ -0,0 +1,381 @@ +//! Provisional HTTP settings, validation, and server preparation. + +use std::{io, net::SocketAddr}; + +use axum::{ + Router, + extract::ws::WebSocket, + http::{HeaderValue, Method, Uri, header}, +}; +use software_core::adj::Adj; +use tokio::{net::TcpListener, sync::mpsc}; +use tower_http::cors::{AllowOrigin, CorsLayer}; + +use super::server::router_with_cache; + +/// Provisional HTTP settings, independent of configuration files and ADJ data. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HttpConfig { + /// Address and port to bind. Port zero requests an available port from the OS. + pub bind_addr: SocketAddr, + /// Exact HTTP(S) origins permitted by CORS; an empty list grants none. + /// + /// Wildcards, credentials, paths, queries, and fragments are not accepted. + /// The opaque origin `null` can be explicitly allowed for local-file clients, + /// but it is shared by other opaque origins too, not exclusive to Electron. + /// This list does not perform WebSocket Origin validation. + pub allowed_origins: Vec, + /// Cache-Control policy for the three catalog routes, not WebSocket upgrades. + pub cache_policy: CachePolicy, +} + +impl HttpConfig { + /// Uses an explicit bind address, no allowed CORS origins, and `no-store`. + pub fn new(bind_addr: SocketAddr) -> Self { + Self { + bind_addr, + allowed_origins: Vec::new(), + cache_policy: CachePolicy::default(), + } + } +} + +/// HTTP caching is independent of the pre-serialized buffers held by the server. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum CachePolicy { + /// Do not emit an explicit Cache-Control header. + Unspecified, + /// Allow storage, but require revalidation before reuse (`no-cache`). + NoCache, + /// Prevent clients and intermediaries from storing responses (`no-store`). + #[default] + NoStore, +} + +impl CachePolicy { + pub(super) fn header_value(self) -> Option { + match self { + Self::Unspecified => None, + Self::NoCache => Some(HeaderValue::from_static("no-cache")), + Self::NoStore => Some(HeaderValue::from_static("no-store")), + } + } +} + +/// Validates settings and prepares a bound listener and router without serving. +/// +/// The returned router owns the precomputed catalogs, CORS middleware, optional +/// WebSocket sender, and catalog cache policy. The caller can then run +/// `axum::serve(listener, router)`. Configuration is validated and responses are +/// serialized before binding, so invalid input does not leave a bound listener. +/// +/// This function consumes already-loaded settings and ADJ data. It does not +/// read configuration files or implement WebSocket Origin checks or messages. +/// +/// # Errors +/// +/// Returns `InvalidInput` for invalid CORS origins, serialization errors wrapped +/// in `io::Error`, or the error from binding the configured address. +pub async fn configure_server( + config: &HttpConfig, + adj: &Adj, + websocket_connections: Option>, +) -> io::Result<(TcpListener, Router)> { + let cors = cors_layer(&config.allowed_origins)?; + let app = router_with_cache(adj, websocket_connections, config.cache_policy)?.layer(cors); + let listener = TcpListener::bind(config.bind_addr).await?; + Ok((listener, app)) +} + +/// Validates the explicit origin list and builds CORS rules for GET and HEAD. +/// Rejects malformed origins with `InvalidInput`; an empty list permits none. +/// Handles preflight requests without enabling credentials or wildcard origins. +fn cors_layer(allowed_origins: &[String]) -> io::Result { + let origins = allowed_origins + .iter() + .map(|origin| { + let invalid = || { + io::Error::new( + io::ErrorKind::InvalidInput, + format!("invalid CORS origin {origin:?}: expected an HTTP(S) origin or null"), + ) + }; + let value = origin.parse::().map_err(|_| invalid())?; + if origin == "null" { + return Ok(value); + } + + let uri = origin.parse::().map_err(|_| invalid())?; + let (Some(scheme), Some(authority)) = (uri.scheme_str(), uri.authority()) else { + return Err(invalid()); + }; + if !matches!(scheme, "http" | "https") + || origin != &format!("{scheme}://{authority}") + || authority.host().is_empty() + || authority.as_str().contains(['@', '*']) + || (authority.as_str() != authority.host() && authority.port_u16().is_none()) + { + return Err(invalid()); + } + Ok(value) + }) + .collect::>>()?; + + // CORS controls browser access, not authentication or WebSocket origins. + Ok(CorsLayer::new() + .allow_origin(AllowOrigin::list(origins)) + .allow_methods([Method::GET, Method::HEAD]) + .allow_headers([header::ACCEPT, header::CONTENT_TYPE])) +} + +#[cfg(test)] +mod tests { + use std::{io, time::Duration}; + + use axum::{ + body::Body, + http::{Request, StatusCode, header}, + }; + use software_core::adj::Adj; + use tokio::{net::TcpListener, sync::mpsc, time::timeout}; + use tower::ServiceExt; + + use super::{CachePolicy, HttpConfig, configure_server, cors_layer}; + use crate::http::server::tests::{PATHS, handshake_on}; + + #[tokio::test] + async fn configuration_binds_the_requested_address_and_defaults_to_no_store() + -> Result<(), Box> { + let config = HttpConfig::new("127.0.0.1:0".parse()?); + assert!(config.allowed_origins.is_empty()); + assert_eq!(config.cache_policy, CachePolicy::NoStore); + let (listener, app) = configure_server(&config, &Adj::default(), None).await?; + assert_eq!(listener.local_addr()?.ip(), config.bind_addr.ip()); + assert_ne!(listener.local_addr()?.port(), 0); + + for path in PATHS { + let response = app + .clone() + .oneshot(Request::builder().uri(path).body(Body::empty())?) + .await?; + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response.headers()[header::CACHE_CONTROL], "no-store"); + assert_eq!(response.headers()[header::CONTENT_TYPE], "application/json"); + assert!( + !response + .headers() + .contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN) + ); + } + Ok(()) + } + + #[tokio::test] + async fn configured_cors_allows_only_explicit_origins() -> Result<(), Box> + { + let mut config = HttpConfig::new("127.0.0.1:0".parse()?); + config.allowed_origins = vec![ + "http://localhost:9000".into(), + "https://station.example".into(), + ]; + let (_listener, app) = configure_server(&config, &Adj::default(), None).await?; + + for origin in [ + "http://localhost:9000", + "https://station.example", + "http://untrusted.example", + ] { + let response = app + .clone() + .oneshot( + Request::builder() + .uri(PATHS[0]) + .header(header::ORIGIN, origin) + .body(Body::empty())?, + ) + .await?; + // CORS restricts browser access; it is not authorization for HTTP clients. + assert_eq!(response.status(), StatusCode::OK); + if config + .allowed_origins + .iter() + .any(|allowed| allowed == origin) + { + assert_eq!( + response.headers()[header::ACCESS_CONTROL_ALLOW_ORIGIN], + origin + ); + } else { + assert!( + !response + .headers() + .contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN) + ); + } + assert!( + !response + .headers() + .contains_key(header::ACCESS_CONTROL_ALLOW_CREDENTIALS) + ); + } + Ok(()) + } + + #[tokio::test] + async fn configured_cors_handles_preflight() -> Result<(), Box> { + let mut config = HttpConfig::new("127.0.0.1:0".parse()?); + config.allowed_origins.push("http://localhost:9000".into()); + let (_listener, app) = configure_server(&config, &Adj::default(), None).await?; + + for (origin, method, expected_origin) in [ + ( + "http://localhost:9000", + "GET", + Some("http://localhost:9000"), + ), + ("http://untrusted.example", "GET", None), + ( + "http://localhost:9000", + "POST", + Some("http://localhost:9000"), + ), + ] { + let response = app + .clone() + .oneshot( + Request::builder() + .method("OPTIONS") + .uri(PATHS[0]) + .header(header::ORIGIN, origin) + .header(header::ACCESS_CONTROL_REQUEST_METHOD, method) + .header(header::ACCESS_CONTROL_REQUEST_HEADERS, "content-type") + .body(Body::empty())?, + ) + .await?; + assert!(response.status().is_success()); + assert_eq!( + response + .headers() + .get(header::ACCESS_CONTROL_ALLOW_ORIGIN) + .map(|value| value.to_str()) + .transpose()?, + expected_origin + ); + let methods = response.headers()[header::ACCESS_CONTROL_ALLOW_METHODS].to_str()?; + assert!(methods.split(',').any(|value| value.trim() == "GET")); + assert!(!methods.split(',').any(|value| value.trim() == "POST")); + assert!( + response.headers()[header::ACCESS_CONTROL_ALLOW_HEADERS] + .to_str()? + .contains("content-type") + ); + } + Ok(()) + } + + #[tokio::test] + async fn invalid_origins_are_rejected_before_binding() -> Result<(), Box> + { + let occupied = TcpListener::bind("127.0.0.1:0").await?; + for origin in [ + "*", + "", + "localhost:9000", + "ws://localhost:9000", + "http://*.example.com", + "http://localhost:9000/", + "http://localhost:9000/path", + "http://localhost?query=1", + "http://localhost#fragment", + "http://user:password@localhost", + "http://localhost:", + "http://localhost:abc", + "http://localhost:99999", + "http://localhost\r\nInjected: value", + ] { + let mut config = HttpConfig::new(occupied.local_addr()?); + config.allowed_origins = vec![origin.into()]; + let error = configure_server(&config, &Adj::default(), None) + .await + .err() + .ok_or_else(|| io::Error::other("invalid origin was accepted"))?; + assert_eq!(error.kind(), io::ErrorKind::InvalidInput, "{origin:?}"); + } + Ok(()) + } + + #[test] + fn explicit_opaque_and_ipv6_origins_are_valid() -> Result<(), Box> { + for origin in [ + "null", + "http://[::1]:9000", + "https://example.com", + "http://127.0.0.1:9000", + ] { + let _ = cors_layer(&[origin.into()])?; + } + Ok(()) + } + + #[tokio::test] + async fn binding_errors_are_propagated_without_fallback() + -> Result<(), Box> { + let occupied = TcpListener::bind("127.0.0.1:0").await?; + let config = HttpConfig::new(occupied.local_addr()?); + let error = configure_server(&config, &Adj::default(), None) + .await + .err() + .ok_or_else(|| io::Error::other("occupied address did not fail"))?; + assert_eq!(error.kind(), io::ErrorKind::AddrInUse); + Ok(()) + } + + #[tokio::test] + async fn cache_policy_is_applied_only_to_catalogs() -> Result<(), Box> { + for (policy, expected) in [ + (CachePolicy::NoStore, Some("no-store")), + (CachePolicy::NoCache, Some("no-cache")), + (CachePolicy::Unspecified, None), + ] { + let mut config = HttpConfig::new("127.0.0.1:0".parse()?); + config.cache_policy = policy; + let (_listener, app) = configure_server(&config, &Adj::default(), None).await?; + for path in PATHS { + let response = app + .clone() + .oneshot(Request::builder().uri(path).body(Body::empty())?) + .await?; + assert_eq!( + response + .headers() + .get(header::CACHE_CONTROL) + .map(|value| value.to_str()) + .transpose()?, + expected + ); + } + let response = app + .oneshot(Request::builder().uri("/backend").body(Body::empty())?) + .await?; + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert!(!response.headers().contains_key(header::CACHE_CONTROL)); + } + Ok(()) + } + + #[tokio::test] + async fn configured_server_preserves_websocket_handoff() + -> Result<(), Box> { + let config = HttpConfig::new("127.0.0.1:0".parse()?); + let (connections, mut receiver) = mpsc::channel(1); + let (listener, app) = configure_server(&config, &Adj::default(), Some(connections)).await?; + let (headers, _client) = handshake_on(listener, app).await?; + assert!(headers.starts_with("HTTP/1.1 101 Switching Protocols\r\n")); + assert!(!headers.to_ascii_lowercase().contains("cache-control:")); + let socket = timeout(Duration::from_secs(5), receiver.recv()) + .await? + .ok_or_else(|| io::Error::other("socket was not handed off"))?; + drop(socket); + Ok(()) + } +} diff --git a/backend/crates/station/src/http/server.rs b/backend/crates/station/src/http/server.rs index 6a8718051..073d8c86c 100644 --- a/backend/crates/station/src/http/server.rs +++ b/backend/crates/station/src/http/server.rs @@ -2,31 +2,14 @@ use std::{io, sync::Arc}; -use axum::{Router, extract::ws::WebSocket, routing::get}; +use axum::{Router, extract::ws::WebSocket, http::header, routing::get}; use software_core::adj::Adj; use tokio::{net::TcpListener, sync::mpsc}; +use tower_http::set_header::SetResponseHeaderLayer; +use super::configure::CachePolicy; use super::handlers::{HttpState, data_packet, order_packet, protection_packet, websocket}; -/// Configures the HTTP server using the future application configuration. -/// -/// Once `HttpConfig` is defined, this function should translate its settings -/// into the server setup: select the listening address and port, apply the -/// allowed CORS origins, and configure cache headers for the ADJ catalogs. -/// Invalid settings should be reported before the server starts accepting -/// requests, rather than silently falling back to other values. -/// -/// It should consume configuration already loaded by the application, not read -/// configuration files or environment variables itself. ADJ loading and -/// WebSocket message handling remain outside its responsibilities. -/// -/// The parameter and return type will be finalized when the configuration -/// module is available. This placeholder is not called by the current startup. -#[expect(dead_code, reason = "Waiting for the application configuration module")] -fn configure_server(/* config: &HttpConfig */) { - todo!("Configure the HTTP server once HttpConfig is available"); -} - /// Serves the catalogs and hands connections to the future WebSocket module. /// /// The caller chooses the address and port when binding the listener. To enable @@ -48,20 +31,37 @@ pub async fn serve_with_websocket( } fn router(adj: &Adj, websocket_connections: Option>) -> io::Result { + // Keep the existing listener-based entry points unchanged for test startup. + router_with_cache(adj, websocket_connections, CachePolicy::Unspecified) +} + +pub(super) fn router_with_cache( + adj: &Adj, + websocket_connections: Option>, + cache_policy: CachePolicy, +) -> io::Result { // Build and serialize the catalogs once, before accepting requests. The // state retains the bytes even after the Adj is dropped. let state = Arc::new(HttpState::new(adj, websocket_connections).map_err(io::Error::other)?); - Ok(Router::new() + let mut catalogs = Router::new() .route("/backend/adj/DataPackets", get(data_packet)) .route("/backend/adj/OrderPackets", get(order_packet)) - .route("/backend/adj/ProtectionPackets", get(protection_packet)) - .route("/backend", get(websocket)) - .with_state(state)) + .route("/backend/adj/ProtectionPackets", get(protection_packet)); + + if let Some(value) = cache_policy.header_value() { + catalogs = catalogs.layer(SetResponseHeaderLayer::overriding( + header::CACHE_CONTROL, + value, + )); + } + + // Register WebSocket after the catalog layer so upgrades are not cached. + Ok(catalogs.route("/backend", get(websocket)).with_state(state)) } #[cfg(test)] -mod tests { +pub(super) mod tests { use std::{io, path::Path, time::Duration}; use axum::{ @@ -79,7 +79,7 @@ mod tests { use super::router; - const PATHS: [&str; 3] = [ + pub(in crate::http) const PATHS: [&str; 3] = [ "/backend/adj/DataPackets", "/backend/adj/OrderPackets", "/backend/adj/ProtectionPackets", @@ -147,6 +147,13 @@ mod tests { app: axum::Router, ) -> Result<(String, TcpStream), Box> { let listener = TcpListener::bind("127.0.0.1:0").await?; + handshake_on(listener, app).await + } + + pub(in crate::http) async fn handshake_on( + listener: TcpListener, + app: axum::Router, + ) -> Result<(String, TcpStream), Box> { let address = listener.local_addr()?; let (shutdown, stopped) = oneshot::channel(); let server = tokio::spawn(async move { From 7f8a3805b9ee6f3785d609d2d6345d5119df84a8 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Fri, 13 Nov 2026 23:07:41 +0100 Subject: [PATCH 20/34] docs(backend, http): docs HTTP endpoints, configuration and ws handoff --- backend/crates/station/src/http/README.md | 166 ++++++++++++++++++++++ 1 file changed, 166 insertions(+) create mode 100644 backend/crates/station/src/http/README.md diff --git a/backend/crates/station/src/http/README.md b/backend/crates/station/src/http/README.md new file mode 100644 index 000000000..9c905dbd2 --- /dev/null +++ b/backend/crates/station/src/http/README.md @@ -0,0 +1,166 @@ +# HTTP + +Station's Axum server exposes the ADJ catalogs and accepts WebSocket upgrades +from the frontend. It does not load the ADJ or handle WebSocket messages. + +## Files + +| File | Responsibility | +| --- | --- | +| [`../http.rs`](../http.rs) | Module entry points, with or without a WebSocket consumer. | +| [`configure.rs`](configure.rs) | Provisional HTTP configuration, validation, server preparation, and configuration tests. | +| [`server.rs`](server.rs) | Router construction, server execution, and route/WebSocket tests. | +| [`handlers.rs`](handlers.rs) | Shared state, pre-serialized catalog responses, and WebSocket handoff. | + +The response models and transformations from `Adj` belong to +[`software_core::adj`](../../../core/src/adj.rs). Their JSON examples are in +[`core/src/adj/http/example`](../../../core/src/adj/http/example). + +## Routes + +| Method | Path | Response | +| --- | --- | --- | +| GET | `/backend/adj/DataPackets` | Boards and data packet definitions, without measurement protections. | +| GET | `/backend/adj/OrderPackets` | Boards and order definitions, including parameter protections. | +| GET | `/backend/adj/ProtectionPackets` | Flat protection catalog and protection-type display metadata. | +| GET with WebSocket upgrade headers | `/backend` | Upgrades the connection and hands the socket to the configured channel. | + +Catalog responses return `200 OK` with `Content-Type: application/json`. + +## Catalog lifecycle + +When the router is built, the server: + +1. Builds the three response structures from the already-loaded `Adj`. +2. Serializes each response once into `Bytes`. +3. Stores the bytes in shared `Arc` state. + +Each request clones the relevant `Bytes` handle and sends the existing JSON +buffer. It does not rebuild the catalog, copy the whole buffer, or serialize +the response again. No application-level mutex is needed for these reads. + +The catalogs are a snapshot of the ADJ at startup; they are not refreshed +automatically. Serialization errors are propagated before requests are served. +This in-memory reuse is separate from browser caching. `configure_server` +applies the configured `Cache-Control` policy to the catalog routes. The older +listener-based entry points do not set an explicit cache policy. + +## Starting the server + +The caller supplies a bound `tokio::net::TcpListener` and an already-loaded +`&Adj`. The listener determines the address and port. Both entry points are +async and run until the server stops. + +Without a WebSocket consumer: + +```rust +http::serve(listener, &adj).await?; +``` + +With a bounded `tokio::sync::mpsc::Sender` whose +receiver belongs to the future WebSocket module: + +```rust +http::serve_with_websocket(listener, &adj, Some(sender)).await?; +``` + +Passing `None` to `serve_with_websocket` has the same behavior as `serve`. + +## WebSocket handoff + +The HTTP handler only performs the handshake and transfers ownership of the +socket. It does not read messages, manage clients, implement subscriptions, +broadcast telemetry, or execute orders. + +Before approving an upgrade, it reserves a slot in the bounded channel: + +- With an available slot, it completes the handshake (`101 Switching Protocols` + for HTTP/1.1) and places the socket in the channel. +- Without a configured channel, with a closed receiver, or with no available + capacity, it returns `503 Service Unavailable` instead of upgrading. +- Invalid upgrade requests are rejected by Axum's `WebSocketUpgrade` extractor. + +The future WebSocket module must consume the receiver and manage each socket's +lifetime, messages, and closure. Keeping a receiver alive without reading it +does not provide a functioning WebSocket service; the queue will eventually +fill. If the receiver disappears during the handoff, the socket is dropped. + +## Configuration + +`HttpConfig` is defined provisionally in `configure.rs` and reexported by `http`. +It does not depend on the future application configuration module or read files +and environment variables. + +| Field | Purpose | +| --- | --- | +| `bind_addr` | Explicit IP address and port to bind; port zero requests an available port. | +| `allowed_origins` | Exact HTTP(S) origins allowed by CORS; an empty list allows none. | +| `cache_policy` | Catalog policy: `NoStore`, `NoCache`, or `Unspecified`. | + +`HttpConfig::new(bind_addr)` uses no allowed CORS origins and defaults to +`CachePolicy::NoStore` (`Cache-Control: no-store`). `NoCache` allows storage +but requires revalidation before reuse; `Unspecified` sets no Cache-Control +header. These policies do not affect the server's reusable JSON buffers and +are not applied to WebSocket upgrades. + +The configuration path prepares the server without starting it: + +```rust +let mut config = http::HttpConfig::new("127.0.0.1:8080".parse()?); +config.allowed_origins = vec!["http://localhost:9000".into()]; + +let (listener, router) = http::configure_server(&config, &adj, None).await?; +axum::serve(listener, router).await?; +``` + +`configure_server` validates origins and serializes the catalogs before binding +the listener. Invalid settings and binding errors are returned to the caller; +there is no fallback to another address or port. To enable socket handoff, +replace `None` with `Some(sender)` as described above. + +CORS permits GET and HEAD from explicitly listed origins, handles preflight +requests, and does not enable credentials. Wildcards and origin URLs with +embedded credentials, paths (including a trailing slash), queries, fragments, +or invalid ports are rejected. The opaque origin `null` can be explicitly +listed for local-file clients, but it is not exclusive to Electron: other +opaque origins share it too. + +CORS controls browser access to responses; it is not HTTP authentication. +WebSocket Origin validation is still not implemented and is independent of +CORS. The existing `serve` and `serve_with_websocket` entry points remain +available for the current test startup and do not apply `HttpConfig` policies. + +## Manual checks + +From the backend workspace root, the current `main.rs` test startup can be run +with: + +```sh +cargo run -p station --locked +``` + +It currently loads the ADJ fixture and listens on `127.0.0.1:8080`. These are +temporary test settings, not configuration defaults. It uses `http::serve`, so +valid WebSocket upgrade requests receive `503` until a consumer is integrated. + +In another terminal: + +```sh +curl -i http://127.0.0.1:8080/backend/adj/DataPackets +curl -i http://127.0.0.1:8080/backend/adj/OrderPackets +curl -i http://127.0.0.1:8080/backend/adj/ProtectionPackets +``` + +## Tests + +From the backend workspace root: + +```sh +cargo test -p station http:: --locked +``` + +The tests cover catalog contents and repeated responses, empty catalogs, +configuration validation, binding errors, cache headers, CORS and preflight +handling, WebSocket upgrade and socket delivery over a real TCP connection, +unavailable channels (missing, closed, or full), and requests without upgrade +headers. From 8896a8e9e08b7e875318ec3e56cca76a13d6aba3 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Mon, 16 Nov 2026 18:19:53 +0100 Subject: [PATCH 21/34] refactor(backend, http): move http to model and simplify adj.rs moving the implementation of Adj to http.rs --- backend/crates/core/src/adj.rs | 206 +---------------- backend/crates/core/src/adj/http.rs | 210 +++++++++++++++++- backend/crates/core/src/model.rs | 3 + backend/crates/core/src/model/http.rs | 9 + .../core/src/{adj => model}/http/README.md | 0 .../core/src/{adj => model}/http/data.rs | 0 .../src/{adj => model}/http/example/data.json | 0 .../{adj => model}/http/example/order.json | 0 .../http/example/protection.json | 0 .../core/src/{adj => model}/http/order.rs | 0 .../src/{adj => model}/http/protection.rs | 0 11 files changed, 216 insertions(+), 212 deletions(-) create mode 100644 backend/crates/core/src/model/http.rs rename backend/crates/core/src/{adj => model}/http/README.md (100%) rename backend/crates/core/src/{adj => model}/http/data.rs (100%) rename backend/crates/core/src/{adj => model}/http/example/data.json (100%) rename backend/crates/core/src/{adj => model}/http/example/order.json (100%) rename backend/crates/core/src/{adj => model}/http/example/protection.json (100%) rename backend/crates/core/src/{adj => model}/http/order.rs (100%) rename backend/crates/core/src/{adj => model}/http/protection.rs (100%) diff --git a/backend/crates/core/src/adj.rs b/backend/crates/core/src/adj.rs index 854800f4f..0110db68d 100644 --- a/backend/crates/core/src/adj.rs +++ b/backend/crates/core/src/adj.rs @@ -21,6 +21,7 @@ mod info; mod raw; #[cfg(feature = "http")] +/// asdfasd pub mod http; #[cfg(feature = "git")] @@ -47,211 +48,6 @@ pub struct Adj { pub info: AdjInfo, } -#[cfg(feature = "http")] -use self::http::{ - data::{ - DataBoardResponse, DataMeasurementKind, DataMeasurementResponse, DataPacketResponse, - DataResponse, - }, - order::{ - OrderBoardResponse, OrderMeasurementResponse, OrderPacketResponse, OrderProtectionResponse, - OrderResponse, - }, - protection::{ProtectionInfoResponse, ProtectionResponse, ProtectionTypeResponse}, -}; - -#[cfg(feature = "http")] -use crate::model::{MeasurementKind, PacketType}; - -#[cfg(feature = "http")] -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 = self - .pod_data - .boards - .values() - .map(|board| { - let mut packets: Vec = board - .packets - .values() - .filter_map(|packet| { - 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 { - MeasurementKind::Numeric { wire_type } => { - DataMeasurementKind::Numeric { - wire_type: *wire_type, - } - } - MeasurementKind::Boolean => DataMeasurementKind::Boolean, - MeasurementKind::Enum { options } => { - DataMeasurementKind::Enum { - options: options.clone(), - } - } - }, - }) - .collect(), - }) - }) - .collect(); - packets.sort_unstable_by_key(|packet| packet.id.0); - - DataBoardResponse { - id: board.id, - name: board.name.clone(), - packets, - } - }) - .collect(); - 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; - /// protection ids remain their one-based positions within each measurement. - pub fn order_response(&self) -> OrderResponse { - let mut boards: Vec = self - .pod_data - .boards - .values() - .map(|board| { - let mut orders: Vec = board - .packets - .values() - .filter_map(|packet| { - let PacketType::Order(measurements) = &packet.packet_type else { - return None; - }; - - Some(OrderPacketResponse { - id: packet.id, - name: packet.name.clone(), - packet_type: "order".to_string(), - measurements: measurements - .iter() - .map(|measurement| OrderMeasurementResponse { - id: measurement.id, - alias: measurement.alias.clone(), - name: measurement.name.clone(), - display_units: measurement.display_units.clone(), - kind: match &measurement.kind { - MeasurementKind::Numeric { wire_type } => { - DataMeasurementKind::Numeric { - wire_type: *wire_type, - } - } - MeasurementKind::Boolean => DataMeasurementKind::Boolean, - MeasurementKind::Enum { options } => { - DataMeasurementKind::Enum { - options: options.clone(), - } - } - }, - protections: measurement - .protections - .iter() - .map(|protection| OrderProtectionResponse { - id: protection.id, - kind: protection.kind, - severity: protection.severity, - time: protection.time, - }) - .collect(), - }) - .collect(), - }) - }) - .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 = self - .pod_data - .boards - .values() - .flat_map(|board| board.packets.values()) - .filter_map(|packet| { - 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: 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 } - } -} - /// The result of [`auto_adj`]: the loaded ADJ data and the checked-out commit hash. #[cfg(feature = "git")] #[derive(Debug, Clone)] diff --git a/backend/crates/core/src/adj/http.rs b/backend/crates/core/src/adj/http.rs index d577f026c..f96c7ef1a 100644 --- a/backend/crates/core/src/adj/http.rs +++ b/backend/crates/core/src/adj/http.rs @@ -1,9 +1,205 @@ -//! Models for HTTP response bodies. +use crate::{ + adj::Adj, + model::{ + MeasurementKind, PacketType, + http::{ + data::{ + DataBoardResponse, DataMeasurementKind, DataMeasurementResponse, + DataPacketResponse, DataResponse, + }, + order::{ + OrderBoardResponse, OrderMeasurementResponse, OrderPacketResponse, + OrderProtectionResponse, OrderResponse, + }, + protection::{ProtectionInfoResponse, ProtectionResponse, ProtectionTypeResponse}, + }, + }, +}; -pub(super) mod data; -pub(super) mod order; -pub(super) mod protection; +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 = self + .pod_data + .boards + .values() + .map(|board| { + let mut packets: Vec = board + .packets + .values() + .filter_map(|packet| { + let PacketType::Data(measurements) = &packet.packet_type else { + return None; + }; -pub use data::DataResponse; -pub use order::OrderResponse; -pub use protection::ProtectionResponse; + 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 { + MeasurementKind::Numeric { wire_type } => { + DataMeasurementKind::Numeric { + wire_type: *wire_type, + } + } + MeasurementKind::Boolean => DataMeasurementKind::Boolean, + MeasurementKind::Enum { options } => { + DataMeasurementKind::Enum { + options: options.clone(), + } + } + }, + }) + .collect(), + }) + }) + .collect(); + packets.sort_unstable_by_key(|packet| packet.id.0); + + DataBoardResponse { + id: board.id, + name: board.name.clone(), + packets, + } + }) + .collect(); + 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; + /// protection ids remain their one-based positions within each measurement. + pub fn order_response(&self) -> OrderResponse { + let mut boards: Vec = self + .pod_data + .boards + .values() + .map(|board| { + let mut orders: Vec = board + .packets + .values() + .filter_map(|packet| { + let PacketType::Order(measurements) = &packet.packet_type else { + return None; + }; + + Some(OrderPacketResponse { + id: packet.id, + name: packet.name.clone(), + packet_type: "order".to_string(), + measurements: measurements + .iter() + .map(|measurement| OrderMeasurementResponse { + id: measurement.id, + alias: measurement.alias.clone(), + name: measurement.name.clone(), + display_units: measurement.display_units.clone(), + kind: match &measurement.kind { + MeasurementKind::Numeric { wire_type } => { + DataMeasurementKind::Numeric { + wire_type: *wire_type, + } + } + MeasurementKind::Boolean => DataMeasurementKind::Boolean, + MeasurementKind::Enum { options } => { + DataMeasurementKind::Enum { + options: options.clone(), + } + } + }, + protections: measurement + .protections + .iter() + .map(|protection| OrderProtectionResponse { + id: protection.id, + kind: protection.kind, + severity: protection.severity, + time: protection.time, + }) + .collect(), + }) + .collect(), + }) + }) + .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 = self + .pod_data + .boards + .values() + .flat_map(|board| board.packets.values()) + .filter_map(|packet| { + 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: 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 } + } +} diff --git a/backend/crates/core/src/model.rs b/backend/crates/core/src/model.rs index 75cdb319e..74b79b99a 100644 --- a/backend/crates/core/src/model.rs +++ b/backend/crates/core/src/model.rs @@ -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}; diff --git a/backend/crates/core/src/model/http.rs b/backend/crates/core/src/model/http.rs new file mode 100644 index 000000000..837d95618 --- /dev/null +++ b/backend/crates/core/src/model/http.rs @@ -0,0 +1,9 @@ +//! Models for HTTP response bodies. + +pub(crate) mod data; +pub(crate) mod order; +pub(crate) mod protection; + +pub use data::DataResponse; +pub use order::OrderResponse; +pub use protection::ProtectionResponse; diff --git a/backend/crates/core/src/adj/http/README.md b/backend/crates/core/src/model/http/README.md similarity index 100% rename from backend/crates/core/src/adj/http/README.md rename to backend/crates/core/src/model/http/README.md diff --git a/backend/crates/core/src/adj/http/data.rs b/backend/crates/core/src/model/http/data.rs similarity index 100% rename from backend/crates/core/src/adj/http/data.rs rename to backend/crates/core/src/model/http/data.rs diff --git a/backend/crates/core/src/adj/http/example/data.json b/backend/crates/core/src/model/http/example/data.json similarity index 100% rename from backend/crates/core/src/adj/http/example/data.json rename to backend/crates/core/src/model/http/example/data.json diff --git a/backend/crates/core/src/adj/http/example/order.json b/backend/crates/core/src/model/http/example/order.json similarity index 100% rename from backend/crates/core/src/adj/http/example/order.json rename to backend/crates/core/src/model/http/example/order.json diff --git a/backend/crates/core/src/adj/http/example/protection.json b/backend/crates/core/src/model/http/example/protection.json similarity index 100% rename from backend/crates/core/src/adj/http/example/protection.json rename to backend/crates/core/src/model/http/example/protection.json diff --git a/backend/crates/core/src/adj/http/order.rs b/backend/crates/core/src/model/http/order.rs similarity index 100% rename from backend/crates/core/src/adj/http/order.rs rename to backend/crates/core/src/model/http/order.rs diff --git a/backend/crates/core/src/adj/http/protection.rs b/backend/crates/core/src/model/http/protection.rs similarity index 100% rename from backend/crates/core/src/adj/http/protection.rs rename to backend/crates/core/src/model/http/protection.rs From e30d059448a4ef783602b54647e47a4052a06397 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 17 Nov 2026 00:22:39 +0100 Subject: [PATCH 22/34] fix(backend, http): problems with time and other minor fixes --- backend/crates/core/src/adj.rs | 5 +- backend/crates/core/src/adj/http.rs | 69 +++++++++++-------- .../core/src/model/http/example/order.json | 11 +-- .../src/model/http/example/protection.json | 16 +---- backend/crates/core/src/model/http/order.rs | 9 ++- .../crates/core/src/model/http/protection.rs | 9 +-- 6 files changed, 57 insertions(+), 62 deletions(-) diff --git a/backend/crates/core/src/adj.rs b/backend/crates/core/src/adj.rs index 0110db68d..d47286223 100644 --- a/backend/crates/core/src/adj.rs +++ b/backend/crates/core/src/adj.rs @@ -20,10 +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")] -/// asdfasd +/// Strctures for the responses of the HTTP requests pub mod http; +// Imports for the "git" feature #[cfg(feature = "git")] use std::path::PathBuf; #[cfg(feature = "git")] diff --git a/backend/crates/core/src/adj/http.rs b/backend/crates/core/src/adj/http.rs index f96c7ef1a..1d57463f2 100644 --- a/backend/crates/core/src/adj/http.rs +++ b/backend/crates/core/src/adj/http.rs @@ -1,7 +1,7 @@ use crate::{ adj::Adj, model::{ - MeasurementKind, PacketType, + AdjId, MeasurementKind, PacketType, http::{ data::{ DataBoardResponse, DataMeasurementKind, DataMeasurementResponse, @@ -16,6 +16,8 @@ use crate::{ }, }; +use std::time::Duration; + impl Adj { /// Builds the data catalog without modifying or consuming the ADJ. /// @@ -47,19 +49,7 @@ impl Adj { alias: measurement.alias.clone(), name: measurement.name.clone(), display_units: measurement.display_units.clone(), - kind: match &measurement.kind { - MeasurementKind::Numeric { wire_type } => { - DataMeasurementKind::Numeric { - wire_type: *wire_type, - } - } - MeasurementKind::Boolean => DataMeasurementKind::Boolean, - MeasurementKind::Enum { options } => { - DataMeasurementKind::Enum { - options: options.clone(), - } - } - }, + kind: match_measurement_kind(&measurement.kind), }) .collect(), }) @@ -109,27 +99,15 @@ impl Adj { alias: measurement.alias.clone(), name: measurement.name.clone(), display_units: measurement.display_units.clone(), - kind: match &measurement.kind { - MeasurementKind::Numeric { wire_type } => { - DataMeasurementKind::Numeric { - wire_type: *wire_type, - } - } - MeasurementKind::Boolean => DataMeasurementKind::Boolean, - MeasurementKind::Enum { options } => { - DataMeasurementKind::Enum { - options: options.clone(), - } - } - }, + kind: match_measurement_kind(&measurement.kind), protections: measurement .protections .iter() .map(|protection| OrderProtectionResponse { - id: protection.id, + id: AdjId((protection.id.0 << 13) | measurement.id.0), kind: protection.kind, severity: protection.severity, - time: protection.time, + time: protection_time_to_nanos(protection.time), }) .collect(), }) @@ -178,7 +156,7 @@ impl Adj { measurement_id: measurement.id, kind: protection.kind, severity: protection.severity, - time: protection.time, + time: protection_time_to_nanos(protection.time), }) }) .collect(); @@ -203,3 +181,34 @@ impl Adj { ProtectionResponse { protections, info } } } + +// Returns Some("(time)xs") if the time is not 0 +fn protection_time_to_nanos(time: Duration) -> Option { + if time == Duration::new(0, 0) { + None + } else { + // If the duration is in nanoseconds (default) + let mut res = format!("{}ns", time.as_nanos().to_string()); + + if time.as_millis() > 0 { + res = format!("{}ms", time.as_millis().to_string()); + } else if time.as_micros() > 0 { + res = format!("{}us", time.as_micros().to_string()); + } + + Some(res) + } +} + +// 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(), + }, + } +} diff --git a/backend/crates/core/src/model/http/example/order.json b/backend/crates/core/src/model/http/example/order.json index f4951532b..06d460bbe 100644 --- a/backend/crates/core/src/model/http/example/order.json +++ b/backend/crates/core/src/model/http/example/order.json @@ -26,11 +26,7 @@ "min": 0.0, "max": 50.0 }, - "severity": "fault", - "time": { - "secs": 0, - "nanos": 0 - } + "severity": "fault" }, { "id": 2, @@ -39,10 +35,7 @@ "limit": 40.0 }, "severity": "warning", - "time": { - "secs": 0, - "nanos": 500000000 - } + "time": "200ms" } ] } diff --git a/backend/crates/core/src/model/http/example/protection.json b/backend/crates/core/src/model/http/example/protection.json index 3c4cf66d7..4cb3cd0ba 100644 --- a/backend/crates/core/src/model/http/example/protection.json +++ b/backend/crates/core/src/model/http/example/protection.json @@ -11,10 +11,7 @@ "max": 100.0 }, "severity": "fault", - "time": { - "secs": 0, - "nanos": 500000000 - } + "time": "500ms" }, { "id": 19384, @@ -26,10 +23,7 @@ "limit": 10.0 }, "severity": "warning", - "time": { - "secs": 1, - "nanos": 0 - } + "time": "1s" }, { "id": 11292, @@ -41,11 +35,7 @@ "min": 300.0, "max": 500.0 }, - "severity": "fault", - "time": { - "secs": 0, - "nanos": 0 - } + "severity": "fault" } ], "info": { diff --git a/backend/crates/core/src/model/http/order.rs b/backend/crates/core/src/model/http/order.rs index 330615022..feb7d8614 100644 --- a/backend/crates/core/src/model/http/order.rs +++ b/backend/crates/core/src/model/http/order.rs @@ -1,7 +1,5 @@ //! ADJ v3 order catalog returned by `/backend/adj/OrderPackets`. -use std::time::Duration; - use serde::Serialize; use crate::{ @@ -68,7 +66,7 @@ pub struct OrderMeasurementResponse { /// A parameter protection's definition, not a triggered protection event. #[derive(Debug, Clone, PartialEq, Serialize)] pub struct OrderProtectionResponse { - /// One-based protection position within its measurement, not a packet id. + /// id of the protection, composed as specified #[serde(serialize_with = "serialize_adj_id")] pub id: AdjId, /// Trigger condition, serialized with its type and named bounds. @@ -77,6 +75,7 @@ pub struct OrderProtectionResponse { /// Severity serialized as `fault` or `warning`. #[serde(serialize_with = "serialize_severity")] pub severity: Severity, - /// Required duration, serialized as `{"secs": ..., "nanos": ...}`. - pub time: Duration, + /// Optional duration. + #[serde(skip_serializing_if = "Option::is_none")] + pub time: Option, } diff --git a/backend/crates/core/src/model/http/protection.rs b/backend/crates/core/src/model/http/protection.rs index a19cabde6..f5965e0fd 100644 --- a/backend/crates/core/src/model/http/protection.rs +++ b/backend/crates/core/src/model/http/protection.rs @@ -1,6 +1,6 @@ //! Flat ADJ v3 protection catalog returned by `/backend/adj/ProtectionPackets`. -use std::{collections::HashMap, time::Duration}; +use std::collections::HashMap; use serde::Serialize; @@ -42,8 +42,9 @@ pub struct ProtectionInfoResponse { /// Severity serialized as `fault` or `warning`. #[serde(serialize_with = "serialize_severity")] pub severity: Severity, - /// Required duration, serialized as `{"secs": ..., "nanos": ...}`. - pub time: Duration, + /// Optional duration. + #[serde(skip_serializing_if = "Option::is_none")] + pub time: Option, } /// Display metadata for one entry of `general_info.json`'s `protectionTypes`. @@ -55,6 +56,6 @@ pub struct ProtectionTypeResponse { /// Display template; `{}` marks bounds and `%` the measured value. pub text: String, /// Optional time-related display template, omitted if absent from the ADJ. - #[serde(rename = "textTime", skip_serializing_if = "Option::is_none")] + #[serde(skip_serializing_if = "Option::is_none")] pub text_time: Option, } From 9b5045e5640c9e766c65d913efa1d6fe32aca0ec Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 17 Nov 2026 00:55:29 +0100 Subject: [PATCH 23/34] fix(backend, http): add comments --- backend/crates/core/src/adj/http.rs | 14 ++++++++ .../crates/core/src/model/http/protection.rs | 4 +-- backend/crates/core/src/utils/serialize.rs | 32 ++++++++----------- 3 files changed, 29 insertions(+), 21 deletions(-) diff --git a/backend/crates/core/src/adj/http.rs b/backend/crates/core/src/adj/http.rs index 1d57463f2..5feeca4a5 100644 --- a/backend/crates/core/src/adj/http.rs +++ b/backend/crates/core/src/adj/http.rs @@ -29,11 +29,14 @@ impl Adj { .pod_data .boards .values() + // For each board .map(|board| { let mut packets: Vec = board .packets .values() + // For each packet of this board .filter_map(|packet| { + // If the PacketType is Data, return Some(DataPacketResponse) -> Will be a Vec let PacketType::Data(measurements) = &packet.packet_type else { return None; }; @@ -57,13 +60,17 @@ impl Adj { .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 } @@ -79,15 +86,19 @@ impl Adj { .pod_data .boards .values() + // For each board .map(|board| { let mut orders: Vec = 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 { id: packet.id, name: packet.name.clone(), @@ -114,6 +125,7 @@ impl Adj { .collect(), }) }) + // Collect all the OrderPacketResponses .collect(); orders.sort_unstable_by_key(|order| order.id.0); @@ -140,8 +152,10 @@ impl Adj { .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; }; diff --git a/backend/crates/core/src/model/http/protection.rs b/backend/crates/core/src/model/http/protection.rs index f5965e0fd..132f4e66d 100644 --- a/backend/crates/core/src/model/http/protection.rs +++ b/backend/crates/core/src/model/http/protection.rs @@ -7,7 +7,7 @@ use serde::Serialize; use crate::{ model::{AdjId, BoardId, ProtectionKind, Severity}, utils::serialize::{ - serialize_adj_id, serialize_adj_protection_kind, serialize_board_id, serialize_severity, + serialize_adj_id, serialize_protection_kind, serialize_board_id, serialize_severity, }, }; @@ -37,7 +37,7 @@ pub struct ProtectionInfoResponse { #[serde(serialize_with = "serialize_adj_id")] pub measurement_id: AdjId, /// Trigger condition; `type` preserves the ADJ name to index `info` directly. - #[serde(serialize_with = "serialize_adj_protection_kind")] + #[serde(serialize_with = "serialize_protection_kind")] pub kind: ProtectionKind, /// Severity serialized as `fault` or `warning`. #[serde(serialize_with = "serialize_severity")] diff --git a/backend/crates/core/src/utils/serialize.rs b/backend/crates/core/src/utils/serialize.rs index 99e880cfe..1a8e3354d 100644 --- a/backend/crates/core/src/utils/serialize.rs +++ b/backend/crates/core/src/utils/serialize.rs @@ -1,6 +1,17 @@ use crate::model::{AdjId, BoardId, NumericKind, ProtectionKind, Severity}; use serde::{Serialize, Serializer}; +// EXPLANATION OF THE OBJECT SERIALIZER +// When using the macro #[serde(serialize_with = "")] you specify a function +// which takes to arguments: +// - 1st with the type of the atribute you apply the object +// - 2nd with the type `Serializer` +// The second one is just for setting the specified value obtained in the function +// when the serialization occurs. Very simple. +// +// If you want to serialize a structure you have to implement the trait Serialize, +// which + // Serialize domain types locally without changing the internal model. pub(crate) fn serialize_board_id( id: &BoardId, @@ -38,6 +49,7 @@ pub(crate) fn serialize_numeric_kind( // A remote derive keeps the JSON representation here, without changing model. #[derive(Serialize)] +// Mirroring the struct `ProtectionKind`, we our rules for serialization. #[serde(remote = "ProtectionKind", tag = "type", rename_all = "snake_case")] enum ProtectionKindDef { Above { limit: f64 }, @@ -51,28 +63,10 @@ pub(crate) fn serialize_protection_kind( kind: &ProtectionKind, serializer: S, ) -> Result { + // We apply the serialization to this specific enum, with rules setted in the definition ProtectionKindDef::serialize(kind, serializer) } -// This endpoint indexes general_info.json's protectionTypes by the original -// ADJ names. Keep the order response's existing snake_case format unchanged. -#[derive(Serialize)] -#[serde(remote = "ProtectionKind", tag = "type")] -enum AdjProtectionKindDef { - Above { limit: f64 }, - Below { limit: f64 }, - Equal { target: f64 }, - NotEqual { target: f64 }, - Range { min: f64, max: f64 }, -} - -pub(crate) fn serialize_adj_protection_kind( - kind: &ProtectionKind, - serializer: S, -) -> Result { - AdjProtectionKindDef::serialize(kind, serializer) -} - pub(crate) fn serialize_severity( severity: &Severity, serializer: S, From 2817ae7829536b6964f6c88455220ff3ad561983 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 17 Nov 2026 01:20:22 +0100 Subject: [PATCH 24/34] fix(backend, http): simplification of server configuration --- backend/crates/station/src/http.rs | 23 +- backend/crates/station/src/http/configure.rs | 381 ------------------- backend/crates/station/src/http/handlers.rs | 2 +- backend/crates/station/src/http/server.rs | 151 ++++++-- 4 files changed, 120 insertions(+), 437 deletions(-) delete mode 100644 backend/crates/station/src/http/configure.rs diff --git a/backend/crates/station/src/http.rs b/backend/crates/station/src/http.rs index f0d2d6484..50183c88e 100644 --- a/backend/crates/station/src/http.rs +++ b/backend/crates/station/src/http.rs @@ -6,27 +6,24 @@ use std::io; +use axum::extract::ws::WebSocket; use software_core::adj::Adj; -use tokio::net::TcpListener; +use tokio::{net::TcpListener, sync::mpsc}; + +use crate::http::server::setup_router; -mod configure; mod handlers; mod server; -pub use server::serve_with_websocket; -// The test main still uses the listener-based entry point. Configuration will -// be connected by the application startup when its config module is available. -#[allow( - unused_imports, - reason = "The test startup does not use configuration yet" -)] -pub use configure::{CachePolicy, HttpConfig, configure_server}; - /// Serves the catalogs without connecting a WebSocket consumer yet. /// /// Preserves the entry point used by the test startup code. Upgrade requests /// to `/backend` receive `503` until [`serve_with_websocket`] is used with a /// channel connected to the future WebSocket module. -pub async fn serve(listener: TcpListener, adj: &Adj) -> io::Result<()> { - serve_with_websocket(listener, adj, None).await +pub async fn serve( + listener: TcpListener, + adj: &Adj, + ws: Option>, +) -> io::Result<()> { + axum::serve(listener, setup_router(adj, ws)?).await } diff --git a/backend/crates/station/src/http/configure.rs b/backend/crates/station/src/http/configure.rs deleted file mode 100644 index bf6a4a38f..000000000 --- a/backend/crates/station/src/http/configure.rs +++ /dev/null @@ -1,381 +0,0 @@ -//! Provisional HTTP settings, validation, and server preparation. - -use std::{io, net::SocketAddr}; - -use axum::{ - Router, - extract::ws::WebSocket, - http::{HeaderValue, Method, Uri, header}, -}; -use software_core::adj::Adj; -use tokio::{net::TcpListener, sync::mpsc}; -use tower_http::cors::{AllowOrigin, CorsLayer}; - -use super::server::router_with_cache; - -/// Provisional HTTP settings, independent of configuration files and ADJ data. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct HttpConfig { - /// Address and port to bind. Port zero requests an available port from the OS. - pub bind_addr: SocketAddr, - /// Exact HTTP(S) origins permitted by CORS; an empty list grants none. - /// - /// Wildcards, credentials, paths, queries, and fragments are not accepted. - /// The opaque origin `null` can be explicitly allowed for local-file clients, - /// but it is shared by other opaque origins too, not exclusive to Electron. - /// This list does not perform WebSocket Origin validation. - pub allowed_origins: Vec, - /// Cache-Control policy for the three catalog routes, not WebSocket upgrades. - pub cache_policy: CachePolicy, -} - -impl HttpConfig { - /// Uses an explicit bind address, no allowed CORS origins, and `no-store`. - pub fn new(bind_addr: SocketAddr) -> Self { - Self { - bind_addr, - allowed_origins: Vec::new(), - cache_policy: CachePolicy::default(), - } - } -} - -/// HTTP caching is independent of the pre-serialized buffers held by the server. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub enum CachePolicy { - /// Do not emit an explicit Cache-Control header. - Unspecified, - /// Allow storage, but require revalidation before reuse (`no-cache`). - NoCache, - /// Prevent clients and intermediaries from storing responses (`no-store`). - #[default] - NoStore, -} - -impl CachePolicy { - pub(super) fn header_value(self) -> Option { - match self { - Self::Unspecified => None, - Self::NoCache => Some(HeaderValue::from_static("no-cache")), - Self::NoStore => Some(HeaderValue::from_static("no-store")), - } - } -} - -/// Validates settings and prepares a bound listener and router without serving. -/// -/// The returned router owns the precomputed catalogs, CORS middleware, optional -/// WebSocket sender, and catalog cache policy. The caller can then run -/// `axum::serve(listener, router)`. Configuration is validated and responses are -/// serialized before binding, so invalid input does not leave a bound listener. -/// -/// This function consumes already-loaded settings and ADJ data. It does not -/// read configuration files or implement WebSocket Origin checks or messages. -/// -/// # Errors -/// -/// Returns `InvalidInput` for invalid CORS origins, serialization errors wrapped -/// in `io::Error`, or the error from binding the configured address. -pub async fn configure_server( - config: &HttpConfig, - adj: &Adj, - websocket_connections: Option>, -) -> io::Result<(TcpListener, Router)> { - let cors = cors_layer(&config.allowed_origins)?; - let app = router_with_cache(adj, websocket_connections, config.cache_policy)?.layer(cors); - let listener = TcpListener::bind(config.bind_addr).await?; - Ok((listener, app)) -} - -/// Validates the explicit origin list and builds CORS rules for GET and HEAD. -/// Rejects malformed origins with `InvalidInput`; an empty list permits none. -/// Handles preflight requests without enabling credentials or wildcard origins. -fn cors_layer(allowed_origins: &[String]) -> io::Result { - let origins = allowed_origins - .iter() - .map(|origin| { - let invalid = || { - io::Error::new( - io::ErrorKind::InvalidInput, - format!("invalid CORS origin {origin:?}: expected an HTTP(S) origin or null"), - ) - }; - let value = origin.parse::().map_err(|_| invalid())?; - if origin == "null" { - return Ok(value); - } - - let uri = origin.parse::().map_err(|_| invalid())?; - let (Some(scheme), Some(authority)) = (uri.scheme_str(), uri.authority()) else { - return Err(invalid()); - }; - if !matches!(scheme, "http" | "https") - || origin != &format!("{scheme}://{authority}") - || authority.host().is_empty() - || authority.as_str().contains(['@', '*']) - || (authority.as_str() != authority.host() && authority.port_u16().is_none()) - { - return Err(invalid()); - } - Ok(value) - }) - .collect::>>()?; - - // CORS controls browser access, not authentication or WebSocket origins. - Ok(CorsLayer::new() - .allow_origin(AllowOrigin::list(origins)) - .allow_methods([Method::GET, Method::HEAD]) - .allow_headers([header::ACCEPT, header::CONTENT_TYPE])) -} - -#[cfg(test)] -mod tests { - use std::{io, time::Duration}; - - use axum::{ - body::Body, - http::{Request, StatusCode, header}, - }; - use software_core::adj::Adj; - use tokio::{net::TcpListener, sync::mpsc, time::timeout}; - use tower::ServiceExt; - - use super::{CachePolicy, HttpConfig, configure_server, cors_layer}; - use crate::http::server::tests::{PATHS, handshake_on}; - - #[tokio::test] - async fn configuration_binds_the_requested_address_and_defaults_to_no_store() - -> Result<(), Box> { - let config = HttpConfig::new("127.0.0.1:0".parse()?); - assert!(config.allowed_origins.is_empty()); - assert_eq!(config.cache_policy, CachePolicy::NoStore); - let (listener, app) = configure_server(&config, &Adj::default(), None).await?; - assert_eq!(listener.local_addr()?.ip(), config.bind_addr.ip()); - assert_ne!(listener.local_addr()?.port(), 0); - - for path in PATHS { - let response = app - .clone() - .oneshot(Request::builder().uri(path).body(Body::empty())?) - .await?; - assert_eq!(response.status(), StatusCode::OK); - assert_eq!(response.headers()[header::CACHE_CONTROL], "no-store"); - assert_eq!(response.headers()[header::CONTENT_TYPE], "application/json"); - assert!( - !response - .headers() - .contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN) - ); - } - Ok(()) - } - - #[tokio::test] - async fn configured_cors_allows_only_explicit_origins() -> Result<(), Box> - { - let mut config = HttpConfig::new("127.0.0.1:0".parse()?); - config.allowed_origins = vec![ - "http://localhost:9000".into(), - "https://station.example".into(), - ]; - let (_listener, app) = configure_server(&config, &Adj::default(), None).await?; - - for origin in [ - "http://localhost:9000", - "https://station.example", - "http://untrusted.example", - ] { - let response = app - .clone() - .oneshot( - Request::builder() - .uri(PATHS[0]) - .header(header::ORIGIN, origin) - .body(Body::empty())?, - ) - .await?; - // CORS restricts browser access; it is not authorization for HTTP clients. - assert_eq!(response.status(), StatusCode::OK); - if config - .allowed_origins - .iter() - .any(|allowed| allowed == origin) - { - assert_eq!( - response.headers()[header::ACCESS_CONTROL_ALLOW_ORIGIN], - origin - ); - } else { - assert!( - !response - .headers() - .contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN) - ); - } - assert!( - !response - .headers() - .contains_key(header::ACCESS_CONTROL_ALLOW_CREDENTIALS) - ); - } - Ok(()) - } - - #[tokio::test] - async fn configured_cors_handles_preflight() -> Result<(), Box> { - let mut config = HttpConfig::new("127.0.0.1:0".parse()?); - config.allowed_origins.push("http://localhost:9000".into()); - let (_listener, app) = configure_server(&config, &Adj::default(), None).await?; - - for (origin, method, expected_origin) in [ - ( - "http://localhost:9000", - "GET", - Some("http://localhost:9000"), - ), - ("http://untrusted.example", "GET", None), - ( - "http://localhost:9000", - "POST", - Some("http://localhost:9000"), - ), - ] { - let response = app - .clone() - .oneshot( - Request::builder() - .method("OPTIONS") - .uri(PATHS[0]) - .header(header::ORIGIN, origin) - .header(header::ACCESS_CONTROL_REQUEST_METHOD, method) - .header(header::ACCESS_CONTROL_REQUEST_HEADERS, "content-type") - .body(Body::empty())?, - ) - .await?; - assert!(response.status().is_success()); - assert_eq!( - response - .headers() - .get(header::ACCESS_CONTROL_ALLOW_ORIGIN) - .map(|value| value.to_str()) - .transpose()?, - expected_origin - ); - let methods = response.headers()[header::ACCESS_CONTROL_ALLOW_METHODS].to_str()?; - assert!(methods.split(',').any(|value| value.trim() == "GET")); - assert!(!methods.split(',').any(|value| value.trim() == "POST")); - assert!( - response.headers()[header::ACCESS_CONTROL_ALLOW_HEADERS] - .to_str()? - .contains("content-type") - ); - } - Ok(()) - } - - #[tokio::test] - async fn invalid_origins_are_rejected_before_binding() -> Result<(), Box> - { - let occupied = TcpListener::bind("127.0.0.1:0").await?; - for origin in [ - "*", - "", - "localhost:9000", - "ws://localhost:9000", - "http://*.example.com", - "http://localhost:9000/", - "http://localhost:9000/path", - "http://localhost?query=1", - "http://localhost#fragment", - "http://user:password@localhost", - "http://localhost:", - "http://localhost:abc", - "http://localhost:99999", - "http://localhost\r\nInjected: value", - ] { - let mut config = HttpConfig::new(occupied.local_addr()?); - config.allowed_origins = vec![origin.into()]; - let error = configure_server(&config, &Adj::default(), None) - .await - .err() - .ok_or_else(|| io::Error::other("invalid origin was accepted"))?; - assert_eq!(error.kind(), io::ErrorKind::InvalidInput, "{origin:?}"); - } - Ok(()) - } - - #[test] - fn explicit_opaque_and_ipv6_origins_are_valid() -> Result<(), Box> { - for origin in [ - "null", - "http://[::1]:9000", - "https://example.com", - "http://127.0.0.1:9000", - ] { - let _ = cors_layer(&[origin.into()])?; - } - Ok(()) - } - - #[tokio::test] - async fn binding_errors_are_propagated_without_fallback() - -> Result<(), Box> { - let occupied = TcpListener::bind("127.0.0.1:0").await?; - let config = HttpConfig::new(occupied.local_addr()?); - let error = configure_server(&config, &Adj::default(), None) - .await - .err() - .ok_or_else(|| io::Error::other("occupied address did not fail"))?; - assert_eq!(error.kind(), io::ErrorKind::AddrInUse); - Ok(()) - } - - #[tokio::test] - async fn cache_policy_is_applied_only_to_catalogs() -> Result<(), Box> { - for (policy, expected) in [ - (CachePolicy::NoStore, Some("no-store")), - (CachePolicy::NoCache, Some("no-cache")), - (CachePolicy::Unspecified, None), - ] { - let mut config = HttpConfig::new("127.0.0.1:0".parse()?); - config.cache_policy = policy; - let (_listener, app) = configure_server(&config, &Adj::default(), None).await?; - for path in PATHS { - let response = app - .clone() - .oneshot(Request::builder().uri(path).body(Body::empty())?) - .await?; - assert_eq!( - response - .headers() - .get(header::CACHE_CONTROL) - .map(|value| value.to_str()) - .transpose()?, - expected - ); - } - let response = app - .oneshot(Request::builder().uri("/backend").body(Body::empty())?) - .await?; - assert_eq!(response.status(), StatusCode::BAD_REQUEST); - assert!(!response.headers().contains_key(header::CACHE_CONTROL)); - } - Ok(()) - } - - #[tokio::test] - async fn configured_server_preserves_websocket_handoff() - -> Result<(), Box> { - let config = HttpConfig::new("127.0.0.1:0".parse()?); - let (connections, mut receiver) = mpsc::channel(1); - let (listener, app) = configure_server(&config, &Adj::default(), Some(connections)).await?; - let (headers, _client) = handshake_on(listener, app).await?; - assert!(headers.starts_with("HTTP/1.1 101 Switching Protocols\r\n")); - assert!(!headers.to_ascii_lowercase().contains("cache-control:")); - let socket = timeout(Duration::from_secs(5), receiver.recv()) - .await? - .ok_or_else(|| io::Error::other("socket was not handed off"))?; - drop(socket); - Ok(()) - } -} diff --git a/backend/crates/station/src/http/handlers.rs b/backend/crates/station/src/http/handlers.rs index 815e33385..52ca92c01 100644 --- a/backend/crates/station/src/http/handlers.rs +++ b/backend/crates/station/src/http/handlers.rs @@ -77,7 +77,7 @@ pub(super) async fn websocket( upgrade .on_failed_upgrade(|error| { - tracing::warn!(%error, "falló el upgrade WebSocket"); + tracing::warn!(%error, "WebSocket upgrade failed"); }) .on_upgrade(move |socket| async move { // The receiver now owns the socket and manages its lifetime and diff --git a/backend/crates/station/src/http/server.rs b/backend/crates/station/src/http/server.rs index 073d8c86c..0bb27dedf 100644 --- a/backend/crates/station/src/http/server.rs +++ b/backend/crates/station/src/http/server.rs @@ -2,12 +2,16 @@ use std::{io, sync::Arc}; -use axum::{Router, extract::ws::WebSocket, http::header, routing::get}; +use axum::{ + Router, + extract::ws::WebSocket, + http::{HeaderValue, header}, + routing::get, +}; use software_core::adj::Adj; -use tokio::{net::TcpListener, sync::mpsc}; -use tower_http::set_header::SetResponseHeaderLayer; +use tokio::sync::mpsc; +use tower_http::{cors::CorsLayer, set_header::SetResponseHeaderLayer}; -use super::configure::CachePolicy; use super::handlers::{HttpState, data_packet, order_packet, protection_packet, websocket}; /// Serves the catalogs and hands connections to the future WebSocket module. @@ -22,42 +26,25 @@ use super::handlers::{HttpState, data_packet, order_packet, protection_packet, w /// # Errors /// /// Propagates errors serializing the catalogs or running the Axum server. -pub async fn serve_with_websocket( - listener: TcpListener, +pub(super) fn setup_router( adj: &Adj, websocket_connections: Option>, -) -> io::Result<()> { - axum::serve(listener, router(adj, websocket_connections)?).await -} - -fn router(adj: &Adj, websocket_connections: Option>) -> io::Result { - // Keep the existing listener-based entry points unchanged for test startup. - router_with_cache(adj, websocket_connections, CachePolicy::Unspecified) -} - -pub(super) fn router_with_cache( - adj: &Adj, - websocket_connections: Option>, - cache_policy: CachePolicy, ) -> io::Result { // Build and serialize the catalogs once, before accepting requests. The // state retains the bytes even after the Adj is dropped. let state = Arc::new(HttpState::new(adj, websocket_connections).map_err(io::Error::other)?); - let mut catalogs = Router::new() + Ok(Router::new() .route("/backend/adj/DataPackets", get(data_packet)) .route("/backend/adj/OrderPackets", get(order_packet)) - .route("/backend/adj/ProtectionPackets", get(protection_packet)); - - if let Some(value) = cache_policy.header_value() { - catalogs = catalogs.layer(SetResponseHeaderLayer::overriding( + .route("/backend/adj/ProtectionPackets", get(protection_packet)) + .route("/backend/ws", get(websocket)) + .layer(CorsLayer::permissive()) + .layer(SetResponseHeaderLayer::overriding( header::CACHE_CONTROL, - value, - )); - } - - // Register WebSocket after the catalog layer so upgrades are not cached. - Ok(catalogs.route("/backend", get(websocket)).with_state(state)) + HeaderValue::from_static("no-cache"), + )) + .with_state(state)) } #[cfg(test)] @@ -66,7 +53,7 @@ pub(super) mod tests { use axum::{ body::{Body, to_bytes}, - http::{Request, StatusCode, header}, + http::{Method, Request, StatusCode, header}, }; use software_core::adj::{Adj, load_from_dir}; use tokio::{ @@ -77,7 +64,7 @@ pub(super) mod tests { }; use tower::ServiceExt; - use super::router; + use super::setup_router; pub(in crate::http) const PATHS: [&str; 3] = [ "/backend/adj/DataPackets", @@ -86,7 +73,7 @@ pub(super) mod tests { ]; #[tokio::test] - async fn catalogs_return_cached_json() -> Result<(), Box> { + async fn catalogs_return_precomputed_json() -> Result<(), Box> { let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../core/src/adj/test/adj"); let adj = load_from_dir(&path)?; let expected = [ @@ -94,7 +81,7 @@ pub(super) mod tests { serde_json::to_value(&adj.order_response())?, serde_json::to_value(&adj.protection_response())?, ]; - let app = router(&adj, None)?; + let app = setup_router(&adj, None)?; drop(adj); for (path, expected) in PATHS.into_iter().zip(expected) { @@ -121,7 +108,7 @@ pub(super) mod tests { #[tokio::test] async fn empty_catalogs_return_json_objects() -> Result<(), Box> { - let app = router(&Adj::default(), None)?; + let app = setup_router(&Adj::default(), None)?; let expected = [ serde_json::json!({"boards": []}), serde_json::json!({"boards": []}), @@ -141,6 +128,75 @@ pub(super) mod tests { Ok(()) } + #[tokio::test] + async fn all_routes_return_no_cache_and_allow_any_origin() + -> Result<(), Box> { + let app = setup_router(&Adj::default(), None)?; + + for path in PATHS.into_iter().chain(["/backend/ws"]) { + for origin in ["http://localhost:3000", "https://example.com"] { + let response = app + .clone() + .oneshot( + Request::builder() + .uri(path) + .header(header::ORIGIN, origin) + .body(Body::empty())?, + ) + .await?; + + let expected_status = if path == "/backend/ws" { + StatusCode::BAD_REQUEST + } else { + StatusCode::OK + }; + assert_eq!(response.status(), expected_status); + assert_eq!(response.headers()[header::CACHE_CONTROL], "no-cache"); + assert_eq!(response.headers()[header::ACCESS_CONTROL_ALLOW_ORIGIN], "*"); + assert!( + !response + .headers() + .contains_key(header::ACCESS_CONTROL_ALLOW_CREDENTIALS) + ); + } + } + Ok(()) + } + + #[tokio::test] + async fn all_routes_allow_cors_preflight_with_no_cache() + -> Result<(), Box> { + let app = setup_router(&Adj::default(), None)?; + + for path in PATHS.into_iter().chain(["/backend/ws"]) { + let response = app + .clone() + .oneshot( + Request::builder() + .method(Method::OPTIONS) + .uri(path) + .header(header::ORIGIN, "http://localhost:3000") + .header(header::ACCESS_CONTROL_REQUEST_METHOD, "GET") + .header(header::ACCESS_CONTROL_REQUEST_HEADERS, "x-client-id") + .body(Body::empty())?, + ) + .await?; + + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response.headers()[header::CACHE_CONTROL], "no-cache"); + assert_eq!(response.headers()[header::ACCESS_CONTROL_ALLOW_ORIGIN], "*"); + assert_eq!( + response.headers()[header::ACCESS_CONTROL_ALLOW_METHODS], + "*" + ); + assert_eq!( + response.headers()[header::ACCESS_CONTROL_ALLOW_HEADERS], + "*" + ); + } + Ok(()) + } + // Upgrades require a real HTTP connection: oneshot does not provide Hyper's // OnUpgrade extension. The server only runs for the duration of the test. async fn handshake( @@ -167,8 +223,9 @@ pub(super) mod tests { let response = timeout(Duration::from_secs(5), async { let mut stream = TcpStream::connect(address).await?; let request = format!( - "GET /backend HTTP/1.1\r\n\ + "GET /backend/ws HTTP/1.1\r\n\ Host: {address}\r\n\ + Origin: http://localhost:3000\r\n\ Connection: Upgrade\r\n\ Upgrade: websocket\r\n\ Sec-WebSocket-Version: 13\r\n\ @@ -195,7 +252,7 @@ pub(super) mod tests { #[tokio::test] async fn websocket_upgrade_delivers_the_socket() -> Result<(), Box> { let (connections, mut receiver) = mpsc::channel(1); - let app = router(&Adj::default(), Some(connections.clone()))?; + let app = setup_router(&Adj::default(), Some(connections.clone()))?; let (headers, _client) = handshake(app).await?; assert!(headers.starts_with("HTTP/1.1 101 Switching Protocols\r\n")); @@ -204,6 +261,16 @@ pub(super) mod tests { .to_ascii_lowercase() .contains("sec-websocket-accept: s3pplmbitxaq9kygzzhzrbk+xoo=\r\n") ); + assert!( + headers + .to_ascii_lowercase() + .contains("cache-control: no-cache\r\n") + ); + assert!( + headers + .to_ascii_lowercase() + .contains("access-control-allow-origin: *\r\n") + ); let socket = timeout(Duration::from_secs(5), receiver.recv()) .await? .ok_or_else(|| io::Error::other("no se entregó el socket"))?; @@ -215,7 +282,7 @@ pub(super) mod tests { #[tokio::test] async fn websocket_without_a_consumer_returns_unavailable() -> Result<(), Box> { - let app = router(&Adj::default(), None)?; + let app = setup_router(&Adj::default(), None)?; let (headers, _client) = handshake(app).await?; assert!(headers.starts_with("HTTP/1.1 503 Service Unavailable\r\n")); Ok(()) @@ -226,7 +293,7 @@ pub(super) mod tests { -> Result<(), Box> { let (connections, receiver) = mpsc::channel(1); drop(receiver); - let app = router(&Adj::default(), Some(connections))?; + let app = setup_router(&Adj::default(), Some(connections))?; let (headers, _client) = handshake(app).await?; assert!(headers.starts_with("HTTP/1.1 503 Service Unavailable\r\n")); Ok(()) @@ -238,7 +305,7 @@ pub(super) mod tests { let (connections, _receiver) = mpsc::channel(1); // Simulate an occupied slot without requiring another test socket. let reservation = connections.clone().try_reserve_owned()?; - let app = router(&Adj::default(), Some(connections))?; + let app = setup_router(&Adj::default(), Some(connections))?; let (headers, _client) = handshake(app).await?; assert!(headers.starts_with("HTTP/1.1 503 Service Unavailable\r\n")); drop(reservation); @@ -249,9 +316,9 @@ pub(super) mod tests { async fn websocket_rejects_requests_without_upgrade_headers() -> Result<(), Box> { let (connections, mut receiver) = mpsc::channel(1); - let app = router(&Adj::default(), Some(connections.clone()))?; + let app = setup_router(&Adj::default(), Some(connections.clone()))?; let response = app - .oneshot(Request::builder().uri("/backend").body(Body::empty())?) + .oneshot(Request::builder().uri("/backend/ws").body(Body::empty())?) .await?; assert_eq!(response.status(), StatusCode::BAD_REQUEST); From 69eaf1b88a85e018367ec29e95a4c77b9dcee134 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 17 Nov 2026 01:36:48 +0100 Subject: [PATCH 25/34] docs(backend, http): update readme and correct errors --- backend/crates/core/src/adj/README.md | 35 ++- backend/crates/core/src/model/README.md | 39 ++- backend/crates/core/src/model/http/README.md | 239 ++++++++++++++++-- .../core/src/model/http/example/order.json | 4 +- .../src/model/http/example/protection.json | 34 +-- 5 files changed, 306 insertions(+), 45 deletions(-) diff --git a/backend/crates/core/src/adj/README.md b/backend/crates/core/src/adj/README.md index a468ad4de..b60b6668a 100644 --- a/backend/crates/core/src/adj/README.md +++ b/backend/crates/core/src/adj/README.md @@ -2,7 +2,7 @@ This module deserializes, validates, and loads ADJ JSON fixtures into the backend domain model. -The `http` submodule converts a loaded `Adj` into serializable data, order, and protection catalogs for HTTP responses. It defines response bodies, not routes or a server. See the [HTTP submodule README](http/README.md) for usage and JSON examples. +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**. @@ -23,7 +23,6 @@ pub struct Adj { Adj ├── pod_data (PodData) │ └── boards: HashMap -│ ├── measurements: HashMap │ └── packets: HashMap │ ├── explicit (Data, Order, Message — declared in packets.json; │ │ a "message"-type packet's own `name` must be one of @@ -40,6 +39,11 @@ Adj └── protection_types: HashMap ``` +`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. @@ -49,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 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 = MessageLevel::ALL @@ -59,7 +63,7 @@ let message_levels: HashMap = 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. @@ -78,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**: @@ -88,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. diff --git a/backend/crates/core/src/model/README.md b/backend/crates/core/src/model/README.md index 20db8642d..40001c283 100644 --- a/backend/crates/core/src/model/README.md +++ b/backend/crates/core/src/model/README.md @@ -4,6 +4,10 @@ This module is meant to store and organize all the different structs, enums and other data structures necessary for the backend project. +The domain types describe vehicle definitions and decoded packets. With the +`http` feature enabled, `model::http` also exposes separate, serializable catalog +response models; see [section 7](#7-http-http-feature). + ## 1. `board.rs` All structs and enums needed for the Pod can be found defined in this file. ### 1.1 `PacketType` @@ -83,9 +87,13 @@ Enum used to classify every numerical value type a measurement can use. - 64-bit floating point number (`F64`) ### 3.2 `Range` -Struct used to define a maximum and minimum value of any measurement. +An inclusive range with independently optional lower and upper bounds. This +helper is not a field of the current `MeasurementKind::Numeric` variant; +protection bounds are represented by `ProtectionKind` instead. #### `min` +Optional lower bound (`Option`); `None` means no lower limit. #### `max` +Optional upper bound (`Option`); `None` means no upper limit. ### 3.3 `MeasurementKind` Enum used to classify the kind of measurement. @@ -219,7 +227,7 @@ Wraps a `ProtectionPacket` (triggered protection event). #### `Message` Wraps a `MessagePacket` (free-text log/diagnostic message). -## 5. `protection.rs` +## 5. `protections.rs` A `Protection` is a bound checked against a measurement's decoded value, as declared in the ADJ (`_measurements.json`). This defines the *declaration* (what to watch for, thresholds, and severity) rather than the runtime wire packet emitted when triggered (`ProtectionPacket` in `packet.rs`). In ADJv3, protections and messages are distinct formats with separate lifecycles. ### 5.1 `ProtectionKind` @@ -249,6 +257,10 @@ Struct defining a single protection rule attached to a measurement. #### `id` The protection's relative slot index within its parent measurement's protection list, stored as an `AdjId` in the `1–7` range. This is a local index rather than a global ID; it forms the upper 3 bits of the compound wire identifier alongside the 13-bit measurement ID. + +Do not confuse this internal position with an HTTP protection ID: both +`OrderResponse` and `ProtectionResponse` expose the compound ID +`(position << 13) | measurement_id`, as does `ProtectionPacket` on the wire. #### `kind` The evaluation rule and threshold bounds (`ProtectionKind`). #### `severity` @@ -267,4 +279,25 @@ A numeric measurement, regardless of its original wire type (`u8`, `i32`, `f32`, #### `Bool(bool)` A boolean measurement (`true` or `false`). #### `Enum(String)` -The selected variant name of an enumerated measurement (e.g. `"Operational"`). \ No newline at end of file +The selected variant name of an enumerated measurement (e.g. `"Operational"`). + +## 7. `http` (`http` feature) + +`model/http.rs` publicly re-exports three response types: + +- `DataResponse`: data packet definitions grouped by board, without protections. +- `OrderResponse`: order definitions grouped by board, including parameter protections. +- `ProtectionResponse`: flat protection definitions and display metadata. + +Their nested response structs live in `model/http/data.rs`, `order.rs`, and +`protection.rs`. Those submodules are crate-visible, not public import paths. +The response models derive `serde::Serialize`; the domain types do not need to +adopt the HTTP representation. Shared custom serializers live in +`utils/serialize.rs`. + +The builders are methods of `Adj`, implemented in `adj/http.rs`: +`adj.data_response()`, `adj.order_response()`, and `adj.protection_response()`. +This module defines no HTTP server, routes, CORS, or cache policy. + +See the [HTTP response models README](http/README.md) for usage, JSON type +notation, field omission rules, and concrete examples. diff --git a/backend/crates/core/src/model/http/README.md b/backend/crates/core/src/model/http/README.md index ce881f870..c099a5893 100644 --- a/backend/crates/core/src/model/http/README.md +++ b/backend/crates/core/src/model/http/README.md @@ -1,20 +1,29 @@ -# ADJ HTTP (`adj::http`) +# HTTP Response Models (`model::http`) -Builds serializable HTTP response bodies from a loaded `Adj`, without modifying -or consuming it. This submodule contains catalog models and builders only; -HTTP routes and server setup belong to the application. +Serializable models for the data, order, and protection catalogs of a loaded +ADJ. These are definitions, not live telemetry, order execution requests, or +triggered protection events. + +The `http` feature enables both sides of the conversion: + +- `model/http.rs` and `model/http/`: response types and their JSON representation. +- `adj/http.rs`: methods on `Adj` that build those response types without + consuming or modifying the ADJ. + +Routes, middleware, and server execution belong to the application (`station`), +not to either of these core modules. Shared custom serializers are implemented +in `utils/serialize.rs`, leaving the internal domain representation unchanged. ## Catalogs -| Builder | Response | Contents | JSON example | +| `Adj` method | Public response type | Station GET route | JSON example | | --- | --- | --- | --- | -| `data_response(&adj)` | `DataResponse` | Data packets grouped by board, with measurement definitions but no protections. | [data.json](example/data.json) | -| `order_response(&adj)` | `OrderResponse` | Orders grouped by board, including parameters and their protections. | [order.json](example/order.json) | -| `protection_response(&adj)` | `ProtectionResponse` | Flat protection list and display metadata from the ADJ's `protectionTypes`. | [protection.json](example/protection.json) | +| `adj.data_response()` | `model::http::DataResponse` | `/backend/adj/DataPackets` | [data.json](example/data.json) | +| `adj.order_response()` | `model::http::OrderResponse` | `/backend/adj/OrderPackets` | [order.json](example/order.json) | +| `adj.protection_response()` | `model::http::ProtectionResponse` | `/backend/adj/ProtectionPackets` | [protection.json](example/protection.json) | -These are definitions, not live telemetry, order execution requests, or triggered -protection events. Boards and their packets/orders are sorted by ID; measurement -order is preserved. The flat protection list is sorted by packet ID, then board ID. +Each example is a standalone illustrative catalog, not a snapshot of the +bundled test ADJ or part of a shared vehicle fixture. ## Usage @@ -24,16 +33,210 @@ Enable the `http` feature in the application's dependency: cargo add software-core -F http ``` -With an already loaded `adj`: +With an already loaded `adj: Adj`: ```rust -use software_core::adj::http::{data_response, order_response, protection_response}; +use software_core::model::http::{DataResponse, OrderResponse, ProtectionResponse}; -let data = data_response(&adj); -let orders = order_response(&adj); -let protections = protection_response(&adj); +let data: DataResponse = adj.data_response(); +let orders: OrderResponse = adj.order_response(); +let protections: ProtectionResponse = adj.protection_response(); ``` All three responses implement `serde::Serialize`, so the application can return -them as JSON using its HTTP framework. Serialization details are kept here, -without changing the internal domain model. +them as JSON using its HTTP framework. Only these three root types are publicly +re-exported; the nested Rust response types are in crate-visible submodules. + +## JSON Structure Templates + +These templates keep the JSON object and array structure, replacing values +with their types: `number`, `string`, or `boolean`. Quoted values such as +`"data"` are literals. Comments explain constraints and optional properties. +These are documentation templates, not valid JSON payloads; see the linked +`.json` files for concrete values. + +Each array shows one representative item but can contain zero or more items. +IDs are unsigned 16-bit integers, not strings or wrapper objects. +The catalog templates show numeric measurements and range protections; +the other possible `kind` shapes are listed below. + +### Data Catalog (`DataResponse`) + +```jsonc +{ + "boards": [ + { + "id": number, + "name": string, + "packets": [ + { + "id": number, + "name": string, + "type": "data", + "measurements": [ + { + "id": number, + "alias": string, + "name": string, + "display_units": string, + "kind": { + "type": "numeric", + "wire_type": string + } + } + ] + } + ] + } + ] +} +``` + +Data measurements deliberately have no `protections` property, even if their +internal ADJ definitions declare protections. + +### Order Catalog (`OrderResponse`) + +```jsonc +{ + "boards": [ + { + "id": number, + "name": string, + "orders": [ + { + "id": number, + "name": string, + "type": "order", + "measurements": [ + { + "id": number, + "alias": string, + "name": string, + "display_units": string, + "kind": { + "type": "numeric", + "wire_type": string + }, + "protections": [ + { + "id": number, // Compound ID, not the local position (1–7). + "kind": { + "type": "range", + "min": number, + "max": number + }, + "severity": string, // "fault" or "warning". + "time": string // Optional: omitted for a zero duration. + } + ] + } + ] + } + ] + } + ] +} +``` + +Only protections attached to an order's parameter measurements are included, +not every protection on its board. A parameterless order has `measurements: []`; +a parameter with no declared protections has `protections: []`. + +### Protection Catalog (`ProtectionResponse`) + +```jsonc +{ + "protections": [ + { + "id": number, // Compound ID. + "name": string, + "board_id": number, + "measurement_id": number, + "kind": { + "type": "range", + "min": number, + "max": number + }, + "severity": string, // "fault" or "warning". + "time": string // Optional: omitted for a zero duration. + } + ], + "info": { + "": { + "range": boolean, + "text": string, + "text_time": string // Optional: only included when declared in the ADJ. + } + } +} +``` + +`info` comes from `general_info.json`'s `protectionTypes`. Its keys preserve the +ADJ names, such as `"Range"` and `"NotEqual"`, whereas `kind.type` uses +`"range"` and `"not_equal"`. **Do not index `info` directly with `kind.type`** +when the ADJ uses those names: the current response does not normalize the keys. +For these conventional ADJ names, the correspondence is: + +| `kind.type` | ADJ metadata key | +| --- | --- | +| `above` | `Above` | +| `below` | `Below` | +| `equal` | `Equal` | +| `not_equal` | `NotEqual` | +| `range` | `Range` | + +Metadata is not synthesized for missing ADJ entries. In its text templates, +`{}` represents protection bounds and `%` the measured value. `text_time` is +omitted when the ADJ does not declare an alternative time-based template. + +### Measurement `kind` Variants + +Each measurement has exactly one of these objects as its `kind` value: + +Numeric: + +```jsonc +{ + "type": "numeric", + "wire_type": string +} +``` + +`wire_type` is one of `"uint8"`, `"uint16"`, `"uint32"`, `"uint64"`, +`"int8"`, `"int16"`, `"int32"`, `"int64"`, `"float32"`, or `"float64"`. + +Boolean: + +```jsonc +{ + "type": "boolean" +} +``` + +Enum: + +```jsonc +{ + "type": "enum", + "options": [string] +} +``` + +Numeric measurements do not carry separate safe/warning ranges; protection +definitions carry conditions and severity instead. `display_units` remains +present even when it is `""`. + +### Protection `kind` Variants + +Each protection has exactly one of these objects as its `kind` value: + +| Condition | JSON-shaped type template | +| --- | --- | +| Above a limit | `{"type": "above", "limit": number}` | +| Below a limit | `{"type": "below", "limit": number}` | +| Equal to a target | `{"type": "equal", "target": number}` | +| Not equal to a target | `{"type": "not_equal", "target": number}` | +| Outside a range | `{"type": "range", "min": number, "max": number}` | + +The protection `range` variant always has both bounds. \ No newline at end of file diff --git a/backend/crates/core/src/model/http/example/order.json b/backend/crates/core/src/model/http/example/order.json index 06d460bbe..2a7d30548 100644 --- a/backend/crates/core/src/model/http/example/order.json +++ b/backend/crates/core/src/model/http/example/order.json @@ -20,7 +20,7 @@ }, "protections": [ { - "id": 1, + "id": 11193, "kind": { "type": "range", "min": 0.0, @@ -29,7 +29,7 @@ "severity": "fault" }, { - "id": 2, + "id": 19385, "kind": { "type": "above", "limit": 40.0 diff --git a/backend/crates/core/src/model/http/example/protection.json b/backend/crates/core/src/model/http/example/protection.json index 4cb3cd0ba..1ea79e46b 100644 --- a/backend/crates/core/src/model/http/example/protection.json +++ b/backend/crates/core/src/model/http/example/protection.json @@ -6,48 +6,48 @@ "board_id": 1, "measurement_id": 3000, "kind": { - "type": "Range", + "type": "range", "min": 0.0, "max": 100.0 }, "severity": "fault", "time": "500ms" }, - { - "id": 19384, - "name": "LCU_temperature_1_protection_2", - "board_id": 1, - "measurement_id": 3000, - "kind": { - "type": "Below", - "limit": 10.0 - }, - "severity": "warning", - "time": "1s" - }, { "id": 11292, "name": "HVBMS_pack_voltage_protection_1", "board_id": 2, "measurement_id": 3100, "kind": { - "type": "Range", + "type": "range", "min": 300.0, "max": 500.0 }, "severity": "fault" + }, + { + "id": 19384, + "name": "LCU_temperature_1_protection_2", + "board_id": 1, + "measurement_id": 3000, + "kind": { + "type": "below", + "limit": 10.0 + }, + "severity": "warning", + "time": "1000ms" } ], "info": { - "Equal": { + "equal": { "range": false, "text": "Value is equal to {} (measured: %)" }, - "Range": { + "range": { "range": true, "text": "Value out of range {} (measured: %)" }, - "Below": { + "below": { "range": false, "text": "Value below {} (measured: %)" } From dbef8963482930c975e8b075f664379a712435ec Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 17 Nov 2026 01:38:52 +0100 Subject: [PATCH 26/34] fix(backend, http): update main --- backend/crates/station/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index c3288c29d..fa81b031b 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -26,7 +26,7 @@ async fn main() -> std::io::Result<()> { // Just testing, not the actual address let listener = TcpListener::bind("127.0.0.1:8080").await?; - http::serve(listener, &adj).await?; + http::serve(listener, &adj, None).await?; tracing::info!("demo finalizada"); From ee2e3546302a46c0d0b0989b1c26e44253a2df90 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 17 Nov 2026 18:43:21 +0100 Subject: [PATCH 27/34] fix(backend, git): clippy check --- backend/crates/core/src/git/update.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backend/crates/core/src/git/update.rs b/backend/crates/core/src/git/update.rs index 65fe5655c..25e081d41 100644 --- a/backend/crates/core/src/git/update.rs +++ b/backend/crates/core/src/git/update.rs @@ -39,14 +39,14 @@ const ADJ_URL: &str = "https://github.com/Hyperloop-UPV/adj.git"; pub fn update_adj(path: Option, branch: &str) -> Result { 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"); From 62c9ea5160e201a3961d0e65a5d3cef6129acd80 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 17 Nov 2026 18:49:11 +0100 Subject: [PATCH 28/34] fix(backend, http): clippy warings solved --- backend/crates/core/src/adj/http.rs | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/backend/crates/core/src/adj/http.rs b/backend/crates/core/src/adj/http.rs index 5feeca4a5..88ab5455c 100644 --- a/backend/crates/core/src/adj/http.rs +++ b/backend/crates/core/src/adj/http.rs @@ -118,7 +118,7 @@ impl Adj { id: AdjId((protection.id.0 << 13) | measurement.id.0), kind: protection.kind, severity: protection.severity, - time: protection_time_to_nanos(protection.time), + time: format_protection_time(protection.time), }) .collect(), }) @@ -170,7 +170,7 @@ impl Adj { measurement_id: measurement.id, kind: protection.kind, severity: protection.severity, - time: protection_time_to_nanos(protection.time), + time: format_protection_time(protection.time), }) }) .collect(); @@ -197,20 +197,21 @@ impl Adj { } // Returns Some("(time)xs") if the time is not 0 -fn protection_time_to_nanos(time: Duration) -> Option { +fn format_protection_time(time: Duration) -> Option { if time == Duration::new(0, 0) { None } else { // If the duration is in nanoseconds (default) - let mut res = format!("{}ns", time.as_nanos().to_string()); - - if time.as_millis() > 0 { - res = format!("{}ms", time.as_millis().to_string()); - } else if time.as_micros() > 0 { - res = format!("{}us", time.as_micros().to_string()); + 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)) } - - Some(res) } } From 2fdd73d6c3f2eaf38701ffc171a13d1f43f59275 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 17 Nov 2026 20:00:22 +0100 Subject: [PATCH 29/34] fix(backend, http): types in all the structures --- backend/crates/core/src/model/http/README.md | 112 ++++++++++++------ backend/crates/core/src/model/http/data.rs | 26 ++-- .../core/src/model/http/example/data.json | 19 +-- .../core/src/model/http/example/order.json | 9 +- .../src/model/http/example/protection.json | 6 +- backend/crates/core/src/model/http/order.rs | 6 +- .../crates/core/src/model/http/protection.rs | 2 +- backend/crates/core/src/utils/serialize.rs | 52 ++++++-- 8 files changed, 148 insertions(+), 84 deletions(-) diff --git a/backend/crates/core/src/model/http/README.md b/backend/crates/core/src/model/http/README.md index c099a5893..1f500cb49 100644 --- a/backend/crates/core/src/model/http/README.md +++ b/backend/crates/core/src/model/http/README.md @@ -58,7 +58,7 @@ These are documentation templates, not valid JSON payloads; see the linked Each array shows one representative item but can contain zero or more items. IDs are unsigned 16-bit integers, not strings or wrapper objects. The catalog templates show numeric measurements and range protections; -the other possible `kind` shapes are listed below. +the other possible `type` values are listed below. ### Data Catalog (`DataResponse`) @@ -79,10 +79,7 @@ the other possible `kind` shapes are listed below. "alias": string, "name": string, "display_units": string, - "kind": { - "type": "numeric", - "wire_type": string - } + "type": string // A numeric wire type, such as "float32", or "boolean"; see enum form below. } ] } @@ -114,14 +111,11 @@ internal ADJ definitions declare protections. "alias": string, "name": string, "display_units": string, - "kind": { - "type": "numeric", - "wire_type": string - }, + "type": string, // A numeric wire type, such as "float32", or "boolean"; see enum form below. "protections": [ { "id": number, // Compound ID, not the local position (1–7). - "kind": { + "type": { "type": "range", "min": number, "max": number @@ -153,7 +147,7 @@ a parameter with no declared protections has `protections: []`. "name": string, "board_id": number, "measurement_id": number, - "kind": { + "type": { "type": "range", "min": number, "max": number @@ -173,12 +167,14 @@ a parameter with no declared protections has `protections: []`. ``` `info` comes from `general_info.json`'s `protectionTypes`. Its keys preserve the -ADJ names, such as `"Range"` and `"NotEqual"`, whereas `kind.type` uses -`"range"` and `"not_equal"`. **Do not index `info` directly with `kind.type`** -when the ADJ uses those names: the current response does not normalize the keys. -For these conventional ADJ names, the correspondence is: - -| `kind.type` | ADJ metadata key | +ADJ names exactly, whereas the inner protection discriminator uses snake_case. +For example, a protection has `protection.type.type === "range"`, but the +metadata key may be `"Range"` or `"range"`, depending on the ADJ. +Direct access such as `response.info[protection.type.type]` only works when +those keys match: the builder does not normalize them. For the conventional +capitalized ADJ names, the correspondence is: + +| `protection.type.type` | Capitalized ADJ metadata key | | --- | --- | | `above` | `Above` | | `below` | `Below` | @@ -190,23 +186,25 @@ Metadata is not synthesized for missing ADJ entries. In its text templates, `{}` represents protection bounds and `%` the measured value. `text_time` is omitted when the ADJ does not declare an alternative time-based template. -### Measurement `kind` Variants +### Measurement `type` Values -Each measurement has exactly one of these objects as its `kind` value: +The Rust field is called `kind`, but is serialized as the JSON property `type` +in both data and order measurements. Its value is a string for numeric and +boolean measurements, or an object for enums. There is no separate `wire_type` +property in the JSON. -Numeric: +Numeric measurement (field excerpt): ```jsonc { - "type": "numeric", - "wire_type": string + "type": string // One of the numeric wire types listed below, e.g. "float32". } ``` -`wire_type` is one of `"uint8"`, `"uint16"`, `"uint32"`, `"uint64"`, +Numeric `type` is one of `"uint8"`, `"uint16"`, `"uint32"`, `"uint64"`, `"int8"`, `"int16"`, `"int32"`, `"int64"`, `"float32"`, or `"float64"`. -Boolean: +Boolean measurement (field excerpt): ```jsonc { @@ -214,12 +212,14 @@ Boolean: } ``` -Enum: +Enum measurement (field excerpt): ```jsonc { - "type": "enum", - "options": [string] + "type": { + "type": "enum", + "options": [string] + } } ``` @@ -227,16 +227,58 @@ Numeric measurements do not carry separate safe/warning ranges; protection definitions carry conditions and severity instead. `display_units` remains present even when it is `""`. -### Protection `kind` Variants +### Protection `type` Values -Each protection has exactly one of these objects as its `kind` value: +The Rust protection field is also called `kind`, but is serialized as `type`. +Unlike numeric and boolean measurement types, its JSON value is always an +object, with its own `type` discriminator and the condition's bound(s). +The following are field excerpts from a protection object: | Condition | JSON-shaped type template | | --- | --- | -| Above a limit | `{"type": "above", "limit": number}` | -| Below a limit | `{"type": "below", "limit": number}` | -| Equal to a target | `{"type": "equal", "target": number}` | -| Not equal to a target | `{"type": "not_equal", "target": number}` | -| Outside a range | `{"type": "range", "min": number, "max": number}` | +| Above a limit | `{"type": {"type": "above", "limit": number}}` | +| Below a limit | `{"type": {"type": "below", "limit": number}}` | +| Equal to a target | `{"type": {"type": "equal", "target": number}}` | +| Not equal to a target | `{"type": {"type": "not_equal", "target": number}}` | +| Outside a range | `{"type": {"type": "range", "min": number, "max": number}}` | + +The protection `range` variant always has both bounds. + +## IDs, Ordering, and Optional Fields + +- Protection IDs in both order and protection responses are composed as + `(position << 13) | measurement_id`: the high 3 bits hold the one-based + position (`1–7`), and the low 13 bits hold the measurement ID. For measurement + `3001`, the first two protections are `11193` and `19385`. The internal + `Protection::id` still stores only the local position. +- Boards are sorted by ID; their data packets or orders are sorted by ID. + Boards without matching packets/orders are retained with an empty array. +- Measurement order, enum option order, and order-parameter protection order + follow the ADJ. The flat protection catalog is sorted by compound packet ID, + then board ID; the keys of `info` have no guaranteed order. +- Catalog arrays remain present even when empty. An empty ADJ yields + `{"boards": []}` for data and orders, and + `{"protections": [], "info": {}}` for protections. + +### Protection Duration (`time`) + +`time` is a duration string, not a timestamp. It is omitted for +`Duration::ZERO`, not serialized as `null` or `"0ns"`. + +For positive durations, the formatter chooses an exact integer representation: + +1. Milliseconds (`ms`) when the nanosecond count is divisible by `1_000_000`. +2. Otherwise microseconds (`us`) when it is divisible by `1_000`. +3. Otherwise nanoseconds (`ns`). + +No precision is discarded during this formatting step. For example: + +| Duration | Serialized `time` | +| --- | --- | +| Zero | Property omitted | +| 1 second | `"1000ms"` | +| 1500 microseconds | `"1500us"` | +| 1500 nanoseconds | `"1500ns"` | -The protection `range` variant always has both bounds. \ No newline at end of file +This rule applies to protection `time`, not to the metadata template string +`text_time`, which is copied from the ADJ and omitted when absent. diff --git a/backend/crates/core/src/model/http/data.rs b/backend/crates/core/src/model/http/data.rs index dbb1778dc..d739e82a2 100644 --- a/backend/crates/core/src/model/http/data.rs +++ b/backend/crates/core/src/model/http/data.rs @@ -4,7 +4,7 @@ use serde::Serialize; use crate::{ model::{AdjId, BoardId, NumericKind}, - utils::serialize::{serialize_adj_id, serialize_board_id, serialize_numeric_kind}, + utils::serialize::{serialize_adj_id, serialize_board_id, serialize_data_measurement_type}, }; /// Data packet definitions grouped by board. @@ -56,25 +56,29 @@ pub struct DataMeasurementResponse { pub name: String, /// Unit label displayed to the user. pub display_units: String, - /// Numeric, boolean or enum metadata. + /// Measurement type metadata, serialized under the JSON key `type`. + /// Numeric and boolean types are strings; enums are objects with options. + #[serde(rename = "type", serialize_with = "serialize_data_measurement_type")] pub kind: DataMeasurementKind, } -/// Measurement metadata tagged with an explicit `type` field in JSON. -#[derive(Debug, Clone, PartialEq, Serialize)] -#[serde(tag = "type", rename_all = "snake_case")] +/// Measurement type metadata used by the custom response serializer. +/// +/// As a measurement's JSON `type` value, numeric types become their ADJ wire +/// type name, booleans become `"boolean"`, and enums become an object with +/// `"type": "enum"` and an `options` array. +#[derive(Debug, Clone, PartialEq)] pub enum DataMeasurementKind { - /// Numeric measurement, including its binary representation. + /// Numeric measurement, serialized as a wire type string such as `"float32"`. Numeric { - /// Wire type, serialized with its ADJ name, e.g. `float32`. - #[serde(serialize_with = "serialize_numeric_kind")] + /// Selects the ADJ type name; no separate `wire_type` JSON field is emitted. wire_type: NumericKind, }, - /// Boolean measurement, serialized as `{"type":"boolean"}`. + /// Boolean measurement, serialized as the string `"boolean"`. Boolean, - /// Enumeration with variants in ADJ order. + /// Enumeration, serialized as `{"type":"enum","options":[...]}`. Enum { - /// Allowed variant names. + /// Allowed variant names, preserved in ADJ order. options: Vec, }, } diff --git a/backend/crates/core/src/model/http/example/data.json b/backend/crates/core/src/model/http/example/data.json index e383f07eb..08d2f8461 100644 --- a/backend/crates/core/src/model/http/example/data.json +++ b/backend/crates/core/src/model/http/example/data.json @@ -14,10 +14,7 @@ "alias": "temperature_1", "name": "Motor temperature", "display_units": "ºC", - "kind": { - "type": "numeric", - "wire_type": "float32" - } + "type": "float32" } ] }, @@ -31,10 +28,7 @@ "alias": "levitation_distance", "name": "Levitation distance", "display_units": "mm", - "kind": { - "type": "numeric", - "wire_type": "float32" - } + "type": "float32" } ] } @@ -54,10 +48,7 @@ "alias": "pack_voltage", "name": "Pack voltage", "display_units": "V", - "kind": { - "type": "numeric", - "wire_type": "float32" - } + "type": "float32" } ] }, @@ -71,9 +62,7 @@ "alias": "contactor_closed", "name": "Contactor closed", "display_units": "", - "kind": { - "type": "boolean" - } + "type": "boolean" } ] } diff --git a/backend/crates/core/src/model/http/example/order.json b/backend/crates/core/src/model/http/example/order.json index 2a7d30548..63f9bedfb 100644 --- a/backend/crates/core/src/model/http/example/order.json +++ b/backend/crates/core/src/model/http/example/order.json @@ -14,14 +14,11 @@ "alias": "target_speed", "name": "Target speed", "display_units": "m/s", - "kind": { - "type": "numeric", - "wire_type": "float32" - }, + "type": "float32", "protections": [ { "id": 11193, - "kind": { + "type": { "type": "range", "min": 0.0, "max": 50.0 @@ -30,7 +27,7 @@ }, { "id": 19385, - "kind": { + "type": { "type": "above", "limit": 40.0 }, diff --git a/backend/crates/core/src/model/http/example/protection.json b/backend/crates/core/src/model/http/example/protection.json index 1ea79e46b..778e1a6d0 100644 --- a/backend/crates/core/src/model/http/example/protection.json +++ b/backend/crates/core/src/model/http/example/protection.json @@ -5,7 +5,7 @@ "name": "LCU_temperature_1_protection_1", "board_id": 1, "measurement_id": 3000, - "kind": { + "type": { "type": "range", "min": 0.0, "max": 100.0 @@ -18,7 +18,7 @@ "name": "HVBMS_pack_voltage_protection_1", "board_id": 2, "measurement_id": 3100, - "kind": { + "type": { "type": "range", "min": 300.0, "max": 500.0 @@ -30,7 +30,7 @@ "name": "LCU_temperature_1_protection_2", "board_id": 1, "measurement_id": 3000, - "kind": { + "type": { "type": "below", "limit": 10.0 }, diff --git a/backend/crates/core/src/model/http/order.rs b/backend/crates/core/src/model/http/order.rs index feb7d8614..964d442e6 100644 --- a/backend/crates/core/src/model/http/order.rs +++ b/backend/crates/core/src/model/http/order.rs @@ -5,7 +5,8 @@ use serde::Serialize; use crate::{ model::{AdjId, BoardId, ProtectionKind, Severity}, utils::serialize::{ - serialize_adj_id, serialize_board_id, serialize_protection_kind, serialize_severity, + serialize_adj_id, serialize_board_id, serialize_data_measurement_type, + serialize_protection_kind, serialize_severity, }, }; @@ -58,6 +59,7 @@ pub struct OrderMeasurementResponse { /// Unit label displayed to the user. pub display_units: String, /// Same numeric, boolean or enum metadata used by data measurements. + #[serde(rename = "type", serialize_with = "serialize_data_measurement_type")] pub kind: DataMeasurementKind, /// Protection definitions in ADJ order; empty when none are declared. pub protections: Vec, @@ -70,7 +72,7 @@ pub struct OrderProtectionResponse { #[serde(serialize_with = "serialize_adj_id")] pub id: AdjId, /// Trigger condition, serialized with its type and named bounds. - #[serde(serialize_with = "serialize_protection_kind")] + #[serde(rename = "type", serialize_with = "serialize_protection_kind")] pub kind: ProtectionKind, /// Severity serialized as `fault` or `warning`. #[serde(serialize_with = "serialize_severity")] diff --git a/backend/crates/core/src/model/http/protection.rs b/backend/crates/core/src/model/http/protection.rs index 132f4e66d..8e55e9477 100644 --- a/backend/crates/core/src/model/http/protection.rs +++ b/backend/crates/core/src/model/http/protection.rs @@ -37,7 +37,7 @@ pub struct ProtectionInfoResponse { #[serde(serialize_with = "serialize_adj_id")] pub measurement_id: AdjId, /// Trigger condition; `type` preserves the ADJ name to index `info` directly. - #[serde(serialize_with = "serialize_protection_kind")] + #[serde(rename = "type", serialize_with = "serialize_protection_kind")] pub kind: ProtectionKind, /// Severity serialized as `fault` or `warning`. #[serde(serialize_with = "serialize_severity")] diff --git a/backend/crates/core/src/utils/serialize.rs b/backend/crates/core/src/utils/serialize.rs index 1a8e3354d..58e2ad00b 100644 --- a/backend/crates/core/src/utils/serialize.rs +++ b/backend/crates/core/src/utils/serialize.rs @@ -1,16 +1,20 @@ -use crate::model::{AdjId, BoardId, NumericKind, ProtectionKind, Severity}; +use crate::{ + model::{ + AdjId, BoardId, NumericKind, ProtectionKind, Severity, http::data::DataMeasurementKind, + } +}; use serde::{Serialize, Serializer}; -// EXPLANATION OF THE OBJECT SERIALIZER +// EXPLANATION OF THE OBJECT SERIALIZER // When using the macro #[serde(serialize_with = "")] you specify a function // which takes to arguments: // - 1st with the type of the atribute you apply the object // - 2nd with the type `Serializer` // The second one is just for setting the specified value obtained in the function // when the serialization occurs. Very simple. -// +// // If you want to serialize a structure you have to implement the trait Serialize, -// which +// which // Serialize domain types locally without changing the internal model. pub(crate) fn serialize_board_id( @@ -28,11 +32,8 @@ pub(crate) fn serialize_adj_id( } // Serialize numeric kind to match ADJv3 types. -pub(crate) fn serialize_numeric_kind( - kind: &NumericKind, - serializer: S, -) -> Result { - let name = match kind { +pub(crate) fn get_numeric_kind(kind: &NumericKind) -> &str { + match kind { NumericKind::U8 => "uint8", NumericKind::U16 => "uint16", NumericKind::U32 => "uint32", @@ -43,8 +44,7 @@ pub(crate) fn serialize_numeric_kind( NumericKind::I64 => "int64", NumericKind::F32 => "float32", NumericKind::F64 => "float64", - }; - serializer.serialize_str(name) + } } // A remote derive keeps the JSON representation here, without changing model. @@ -76,3 +76,33 @@ pub(crate) fn serialize_severity( Severity::Warning => "warning", }) } + +// Little helper for serialize the data measurement type +#[derive(Serialize)] +struct EnumKind { + #[serde(rename = "type")] + type_kind: String, + options: Vec, +} + +pub(crate) fn serialize_data_measurement_type( + kind: &DataMeasurementKind, + serializer: S, +) -> Result { + match kind { + DataMeasurementKind::Numeric { wire_type } => { + serializer.serialize_str(get_numeric_kind(wire_type)) + } + DataMeasurementKind::Boolean => serializer.serialize_str("boolean"), + DataMeasurementKind::Enum { options } => { + let options = options.clone(); + + let enum_kind = EnumKind { + type_kind: "enum".to_string(), + options, + }; + + EnumKind::serialize(&enum_kind, serializer) + } + } +} \ No newline at end of file From ad236e056f159c72342b6ac9a82ba6e7938c8cd3 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 17 Nov 2026 20:16:19 +0100 Subject: [PATCH 30/34] docs(backend, http): comment some more --- backend/crates/core/src/adj/http.rs | 5 +++-- backend/crates/core/src/utils/serialize.rs | 14 +++++++------- backend/crates/station/src/http.rs | 6 +----- backend/crates/station/src/http/handlers.rs | 1 + 4 files changed, 12 insertions(+), 14 deletions(-) diff --git a/backend/crates/core/src/adj/http.rs b/backend/crates/core/src/adj/http.rs index 88ab5455c..8fcc13af5 100644 --- a/backend/crates/core/src/adj/http.rs +++ b/backend/crates/core/src/adj/http.rs @@ -79,8 +79,7 @@ impl Adj { /// 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; - /// protection ids remain their one-based positions within each measurement. + /// an empty list. Parameters and their protections keep their ADJ order. pub fn order_response(&self) -> OrderResponse { let mut boards: Vec = self .pod_data @@ -105,6 +104,7 @@ impl Adj { 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(), @@ -114,6 +114,7 @@ impl Adj { protections: measurement .protections .iter() + // Convert each protection .map(|protection| OrderProtectionResponse { id: AdjId((protection.id.0 << 13) | measurement.id.0), kind: protection.kind, diff --git a/backend/crates/core/src/utils/serialize.rs b/backend/crates/core/src/utils/serialize.rs index 58e2ad00b..02418e970 100644 --- a/backend/crates/core/src/utils/serialize.rs +++ b/backend/crates/core/src/utils/serialize.rs @@ -1,7 +1,5 @@ -use crate::{ - model::{ - AdjId, BoardId, NumericKind, ProtectionKind, Severity, http::data::DataMeasurementKind, - } +use crate::model::{ + AdjId, BoardId, NumericKind, ProtectionKind, Severity, http::data::DataMeasurementKind, }; use serde::{Serialize, Serializer}; @@ -13,8 +11,7 @@ use serde::{Serialize, Serializer}; // The second one is just for setting the specified value obtained in the function // when the serialization occurs. Very simple. // -// If you want to serialize a structure you have to implement the trait Serialize, -// which +// Serialize delegates the value's representation to a generic Serializer. // Serialize domain types locally without changing the internal model. pub(crate) fn serialize_board_id( @@ -90,10 +87,13 @@ pub(crate) fn serialize_data_measurement_type( serializer: S, ) -> Result { match kind { + // for example: NumericKind::F32 -> "type": "float32" DataMeasurementKind::Numeric { wire_type } => { serializer.serialize_str(get_numeric_kind(wire_type)) } + // "type": "boolean" DataMeasurementKind::Boolean => serializer.serialize_str("boolean"), + // Enum types become an object containing "type": "enum" and the declared options. DataMeasurementKind::Enum { options } => { let options = options.clone(); @@ -105,4 +105,4 @@ pub(crate) fn serialize_data_measurement_type( EnumKind::serialize(&enum_kind, serializer) } } -} \ No newline at end of file +} diff --git a/backend/crates/station/src/http.rs b/backend/crates/station/src/http.rs index 50183c88e..30c91003a 100644 --- a/backend/crates/station/src/http.rs +++ b/backend/crates/station/src/http.rs @@ -15,11 +15,7 @@ use crate::http::server::setup_router; mod handlers; mod server; -/// Serves the catalogs without connecting a WebSocket consumer yet. -/// -/// Preserves the entry point used by the test startup code. Upgrade requests -/// to `/backend` receive `503` until [`serve_with_websocket`] is used with a -/// channel connected to the future WebSocket module. +/// Serves the ADJ catalogs and the WebSocket upgrade endpoint. pub async fn serve( listener: TcpListener, adj: &Adj, diff --git a/backend/crates/station/src/http/handlers.rs b/backend/crates/station/src/http/handlers.rs index 52ca92c01..05ce0efa5 100644 --- a/backend/crates/station/src/http/handlers.rs +++ b/backend/crates/station/src/http/handlers.rs @@ -86,6 +86,7 @@ pub(super) async fn websocket( }) } +// Builds an HTTP JSON response from already serialized bytes. fn json_response(body: Bytes) -> Response { // Do not wrap these bytes in Json: that would serialize the content again. ([(header::CONTENT_TYPE, "application/json")], body).into_response() From f6d632df492700683c705775775875d726d689e0 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 17 Nov 2026 20:36:41 +0100 Subject: [PATCH 31/34] fix(backend, http): comment little things --- backend/crates/core/src/utils.rs | 1 - backend/crates/core/src/utils/serialize.rs | 1 + backend/crates/station/src/http/handlers.rs | 2 ++ 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/backend/crates/core/src/utils.rs b/backend/crates/core/src/utils.rs index 8e32a77ad..0063520a7 100644 --- a/backend/crates/core/src/utils.rs +++ b/backend/crates/core/src/utils.rs @@ -1,2 +1 @@ -#[cfg(feature = "http")] pub(crate) mod serialize; \ No newline at end of file diff --git a/backend/crates/core/src/utils/serialize.rs b/backend/crates/core/src/utils/serialize.rs index 02418e970..1abf05513 100644 --- a/backend/crates/core/src/utils/serialize.rs +++ b/backend/crates/core/src/utils/serialize.rs @@ -82,6 +82,7 @@ struct EnumKind { options: Vec, } +// Serializes the type of the data of the measurement, depends on each kind of measurement pub(crate) fn serialize_data_measurement_type( kind: &DataMeasurementKind, serializer: S, diff --git a/backend/crates/station/src/http/handlers.rs b/backend/crates/station/src/http/handlers.rs index 05ce0efa5..aabd23741 100644 --- a/backend/crates/station/src/http/handlers.rs +++ b/backend/crates/station/src/http/handlers.rs @@ -13,7 +13,9 @@ use tokio::sync::mpsc; /// Immutable state shared by all requests without a mutex. pub(super) struct HttpState { + // the three response JSON pre-serialized responses: Responses, + // the websocket channel websocket_connections: Option>, } From f5e9ee6682bc0a1141f8f95ee13c0310fe73d40d Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 17 Nov 2026 20:40:19 +0100 Subject: [PATCH 32/34] fix(backend, http): revert changes to main.rs --- backend/crates/station/src/main.rs | 26 +------------------------- 1 file changed, 1 insertion(+), 25 deletions(-) diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index fa81b031b..d872008d1 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -1,37 +1,13 @@ //! Ejecutable mínimo para demostrar la integración con `software-core`. -use tokio::net::TcpListener; use tracing_subscriber::EnvFilter; -#[tokio::main] -async fn main() -> std::io::Result<()> { +fn main() { let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); tracing_subscriber::fmt().with_env_filter(filter).init(); tracing::info!("iniciando demo de station"); let name = std::env::args().nth(1).unwrap_or_else(|| "World".into()); let _greeting = software_core::hello_world::greet(&name); - - let adj_path = - std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../core/src/adj/test/adj"); - let adj = match software_core::adj::load_from_dir(&adj_path) { - Ok(adj) => adj, - Err(err) => { - tracing::error!(%err, "no se pudo cargar el ADJ de prueba"); - std::process::exit(1); - } - }; - tracing::info!(boards = adj.pod_data.boards.len(), "adj de prueba cargado"); - - // Just testing, not the actual address - let listener = TcpListener::bind("127.0.0.1:8080").await?; - - http::serve(listener, &adj, None).await?; - tracing::info!("demo finalizada"); - - Ok(()) } - -mod http; -mod vehicle; \ No newline at end of file From 8f2b89c10077fa79dd0702b86a41b0d46913f275 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 17 Nov 2026 23:17:31 +0100 Subject: [PATCH 33/34] fix(backend, http): fix feature imports and usage --- backend/crates/core/src/utils/serialize.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/backend/crates/core/src/utils/serialize.rs b/backend/crates/core/src/utils/serialize.rs index 1abf05513..cb61543b9 100644 --- a/backend/crates/core/src/utils/serialize.rs +++ b/backend/crates/core/src/utils/serialize.rs @@ -1,8 +1,9 @@ -use crate::model::{ - AdjId, BoardId, NumericKind, ProtectionKind, Severity, http::data::DataMeasurementKind, -}; +use crate::model::{AdjId, BoardId, NumericKind, ProtectionKind, Severity}; use serde::{Serialize, Serializer}; +#[cfg(feature = "http")] +use crate::model::http::data::DataMeasurementKind; + // EXPLANATION OF THE OBJECT SERIALIZER // When using the macro #[serde(serialize_with = "")] you specify a function // which takes to arguments: @@ -82,6 +83,7 @@ struct EnumKind { options: Vec, } +#[cfg(feature = "http")] // Serializes the type of the data of the measurement, depends on each kind of measurement pub(crate) fn serialize_data_measurement_type( kind: &DataMeasurementKind, From ada7456ab716564716c96caaacfc4cb6cfd23b46 Mon Sep 17 00:00:00 2001 From: Pau Minguet Date: Tue, 17 Nov 2026 23:32:20 +0100 Subject: [PATCH 34/34] fix(backend, Cargo.lock): fix duplicated dependencies --- backend/Cargo.lock | 6 ------ 1 file changed, 6 deletions(-) diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 554d047d5..5ed9308bd 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -3737,12 +3737,6 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" -[[package]] -name = "wit-bindgen" -version = "0.57.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" - [[package]] name = "writeable" version = "0.6.4"