diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 3a3943da1..5ed9308bd 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.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" 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" @@ -2152,9 +2236,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" @@ -2233,6 +2317,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" @@ -2283,7 +2376,7 @@ dependencies = [ "bytes", "getrandom 0.4.3", "lru-slab", - "rand", + "rand 0.10.3", "rand_pcg", "ring", "rustc-hash", @@ -2319,12 +2412,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" @@ -2333,7 +2442,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]] @@ -2348,7 +2476,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]] @@ -2479,9 +2607,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", @@ -2492,9 +2620,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", @@ -2506,9 +2634,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", @@ -2518,9 +2646,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", @@ -2555,9 +2683,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", @@ -2571,6 +2699,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" @@ -2582,9 +2716,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", ] @@ -2651,7 +2785,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -2667,15 +2801,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" @@ -2714,9 +2871,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", @@ -2756,9 +2913,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" @@ -2800,11 +2957,15 @@ checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" name = "station" version = "0.1.0" dependencies = [ + "axum", "serde", + "serde_json", "software-core", "thiserror", "tokio", "toml", + "tower", + "tower-http", "tracing", "tracing-subscriber", ] @@ -2834,9 +2995,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", @@ -2860,7 +3021,7 @@ checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -2893,7 +3054,7 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -2937,9 +3098,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", @@ -2953,9 +3114,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", @@ -2975,7 +3136,7 @@ checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -2988,6 +3149,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" @@ -3032,14 +3205,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" @@ -3054,6 +3227,7 @@ dependencies = [ "tokio", "tower-layer", "tower-service", + "tracing", ] [[package]] @@ -3180,6 +3354,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" @@ -3209,9 +3399,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", ] @@ -3236,9 +3426,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 = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" [[package]] name = "valuable" @@ -3306,12 +3505,11 @@ dependencies = [ [[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", @@ -3319,9 +3517,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", @@ -3330,9 +3528,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", @@ -3340,31 +3538,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", @@ -3382,9 +3580,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", ] @@ -3529,9 +3727,9 @@ 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" @@ -3547,9 +3745,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", @@ -3564,10 +3762,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" @@ -3585,7 +3803,7 @@ checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", "synstructure", ] @@ -3608,9 +3826,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", @@ -3619,13 +3837,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 4d78f7050..ac855d65f 100644 --- a/backend/crates/core/Cargo.toml +++ b/backend/crates/core/Cargo.toml @@ -31,6 +31,8 @@ files = ["logger"] host = ["logger", "dep:whoami", "dep:rlimit"] # Reusable tracing/diagnostics setup (console + non-blocking file + stderr layers) trace = ["dep:tracing-subscriber", "dep:tracing-appender"] +# Structure responses for HTTP petitions +http = [] [dependencies] bytes.workspace = true diff --git a/backend/crates/core/src/adj.rs b/backend/crates/core/src/adj.rs index ccd420add..d47286223 100644 --- a/backend/crates/core/src/adj.rs +++ b/backend/crates/core/src/adj.rs @@ -20,6 +20,13 @@ mod error; mod info; mod raw; +// To activate this module the feature "http" is required +// The structures used in this module aren't used for any other reason +#[cfg(feature = "http")] +/// 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/README.md b/backend/crates/core/src/adj/README.md index c167bdfbc..b60b6668a 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. +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**. --- @@ -21,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 @@ -38,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. @@ -47,7 +53,7 @@ other reserved names (e.g. `add_state_order`) share this same map. between. It's the reverse of `message_ids`, restricted to whichever of `MessageLevel::ALL`'s four names `message_ids` declares — built once in `adj::raw::types`'s `TryFrom 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 @@ -57,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. @@ -76,6 +82,27 @@ free-text log frame can reuse the same `"fault"` id. See --- +## HTTP Catalog Builders (`http` feature) + +The methods implemented in `adj/http.rs` borrow `&self`; they do not consume or +modify the loaded ADJ: + +| Method | Return type (in `model::http`) | Contents | +| --- | --- | --- | +| `adj.data_response()` | `DataResponse` | Data definitions grouped by board, without protection metadata. | +| `adj.order_response()` | `OrderResponse` | Order definitions grouped by board, including parameters and their protections. | +| `adj.protection_response()` | `ProtectionResponse` | Flat catalog of synthetic protection packets, plus display metadata. | + +These methods return owned response models, not JSON bytes or HTTP responses. +The application chooses when to call them and serialize the results. They do +not configure routes, CORS, or caching. + +In the order and protection catalogs, protection IDs are compound IDs: +`(position << 13) | measurement_id`. The internal `Protection::id` remains the +one-based position (`1–7`) within its measurement. Empty lists are retained; +zero protection durations are omitted from JSON. See the +[HTTP contract](../model/http/README.md) for the complete serialized shapes. + ## Why It Is Structured This Way The `Adj` object enforces a clear architectural boundary between **vehicle topology** and **session configuration**: @@ -86,7 +113,7 @@ The `Adj` object enforces a clear architectural boundary between **vehicle topol * **Design rationale**: The vehicle itself does not know or care about backend socket configurations or display strings. Separating them prevents UI and orchestration details from polluting the core telemetry model. ### 2. Standalone Loader Submodule (`raw`) -The raw deserialization types and the loader logic live isolated inside `raw`[cite: 2]. This enables non-station tools (such as bus sniffers, test runners, or simulators) to parse and ingest ADJ directories without dragging along application-level UI or station state logic. +The raw deserialization types and the loader logic live isolated inside `raw`. This enables non-station tools (such as bus sniffers, test runners, or simulators) to parse and ingest ADJ directories without dragging along application-level UI or station state logic. ### 3. Unified Packet Map (`packets`) -Protections defined under measurements are materialized during loading as first-class `PacketType::Protection(Measurement)` packets alongside the explicit data, order and message packets declared in `packets.json`. Downstream networking layers can route and handle every wire event uniformly via `Board::packets` without needing specialized traversal logic for nested measurement alarms. `packets.json` itself never declares a `"type": "protection"` entry directly — that shape only exists synthesized, one per protection a measurement declares, never as a free-standing declaration with its own arbitrary variable list. \ 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.rs b/backend/crates/core/src/adj/http.rs new file mode 100644 index 000000000..8fcc13af5 --- /dev/null +++ b/backend/crates/core/src/adj/http.rs @@ -0,0 +1,230 @@ +use crate::{ + adj::Adj, + model::{ + AdjId, MeasurementKind, PacketType, + http::{ + data::{ + DataBoardResponse, DataMeasurementKind, DataMeasurementResponse, + DataPacketResponse, DataResponse, + }, + order::{ + OrderBoardResponse, OrderMeasurementResponse, OrderPacketResponse, + OrderProtectionResponse, OrderResponse, + }, + protection::{ProtectionInfoResponse, ProtectionResponse, ProtectionTypeResponse}, + }, + }, +}; + +use std::time::Duration; + +impl Adj { + /// Builds the data catalog without modifying or consuming the ADJ. + /// + /// Boards and data packets are sorted by id. Boards without data packets are + /// retained with an empty list. Measurements keep their wire order and omit + /// protection metadata. + pub fn data_response(&self) -> DataResponse { + let mut boards: Vec = self + .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; + }; + + Some(DataPacketResponse { + id: packet.id, + name: packet.name.clone(), + packet_type: "data".to_string(), + measurements: measurements + .iter() + .map(|measurement| DataMeasurementResponse { + id: measurement.id, + alias: measurement.alias.clone(), + name: measurement.name.clone(), + display_units: measurement.display_units.clone(), + kind: match_measurement_kind(&measurement.kind), + }) + .collect(), + }) + }) + .collect(); + packets.sort_unstable_by_key(|packet| packet.id.0); + + // Set up each packet + DataBoardResponse { + id: board.id, + name: board.name.clone(), + packets, + } + }) + // Obtain a Vec<> of all the packets + .collect(); + + // Sort the responses by board.id + boards.sort_unstable_by_key(|board| board.id.0); + + DataResponse { boards } + } + + /// Builds the order catalog without modifying or consuming the ADJ. + /// + /// Boards and orders are sorted by id. Boards without orders are retained with + /// an empty list. Parameters and their protections keep their ADJ order. + pub fn order_response(&self) -> OrderResponse { + let mut boards: Vec = self + .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(), + packet_type: "order".to_string(), + measurements: measurements + .iter() + // Convert each parameter into its HTTP response representation + .map(|measurement| OrderMeasurementResponse { + id: measurement.id, + alias: measurement.alias.clone(), + name: measurement.name.clone(), + display_units: measurement.display_units.clone(), + kind: match_measurement_kind(&measurement.kind), + protections: measurement + .protections + .iter() + // Convert each protection + .map(|protection| OrderProtectionResponse { + id: AdjId((protection.id.0 << 13) | measurement.id.0), + kind: protection.kind, + severity: protection.severity, + time: format_protection_time(protection.time), + }) + .collect(), + }) + .collect(), + }) + }) + // Collect all the OrderPacketResponses + .collect(); + orders.sort_unstable_by_key(|order| order.id.0); + + OrderBoardResponse { + id: board.id, + name: board.name.clone(), + orders, + } + }) + .collect(); + boards.sort_unstable_by_key(|board| board.id.0); + + OrderResponse { boards } + } + + /// Builds the flat protection catalog without modifying or consuming the ADJ. + /// + /// Protection packet ids and names are reused from the loader. The position in + /// each compound id selects its definition within the watched measurement. + /// Packets with no definition at that position are omitted. The resulting list + /// is sorted by packet id, then board id to break ties. + pub fn protection_response(&self) -> ProtectionResponse { + let mut protections: Vec = self + .pod_data + .boards + .values() + // For each board + .flat_map(|board| board.packets.values()) + .filter_map(|packet| { + // If the packet is of type Protection... + let PacketType::Protection(measurement) = &packet.packet_type else { + return None; + }; + + let index = usize::from(packet.id.protection_position()).checked_sub(1)?; + let protection = measurement.protections.get(index)?; + + Some(ProtectionInfoResponse { + id: packet.id, + name: packet.name.clone(), + board_id: packet.board, + measurement_id: measurement.id, + kind: protection.kind, + severity: protection.severity, + time: format_protection_time(protection.time), + }) + }) + .collect(); + protections.sort_unstable_by_key(|protection| (protection.id.0, protection.board_id.0)); + + let info = self + .info + .protection_types + .iter() + .map(|(name, metadata)| { + ( + name.clone(), + ProtectionTypeResponse { + is_range: metadata.is_range, + text: metadata.text.clone(), + text_time: metadata.text_time.clone(), + }, + ) + }) + .collect(); + + ProtectionResponse { protections, info } + } +} + +// Returns Some("(time)xs") if the time is not 0 +fn format_protection_time(time: Duration) -> Option { + if time == Duration::new(0, 0) { + None + } else { + // If the duration is in nanoseconds (default) + let ns = time.as_nanos(); + + // Adjust the result + if ns.is_multiple_of(1_000_000) { + Some(format!("{}ms", ns / 1_000_000)) + } else if ns.is_multiple_of(1_000) { + Some(format!("{}us", ns / 1_000)) + } else { + Some(format!("{}ns", ns)) + } + } +} + +// Matches the kind of measurement and returns the specific type/structure +fn match_measurement_kind(measurement: &MeasurementKind) -> DataMeasurementKind { + match measurement { + MeasurementKind::Numeric { wire_type } => DataMeasurementKind::Numeric { + wire_type: *wire_type, + }, + MeasurementKind::Boolean => DataMeasurementKind::Boolean, + MeasurementKind::Enum { options } => DataMeasurementKind::Enum { + options: options.clone(), + }, + } +} diff --git a/backend/crates/core/src/git/update.rs b/backend/crates/core/src/git/update.rs index 603788b47..6e58684dc 100644 --- a/backend/crates/core/src/git/update.rs +++ b/backend/crates/core/src/git/update.rs @@ -39,13 +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"); } else { diff --git a/backend/crates/core/src/lib.rs b/backend/crates/core/src/lib.rs index 697257960..d7d151506 100644 --- a/backend/crates/core/src/lib.rs +++ b/backend/crates/core/src/lib.rs @@ -26,6 +26,8 @@ pub mod adj; /// [`protocol::tcp`], [`protocol::udp`]. pub mod protocol; +// Utils module +pub(crate) mod utils; /// Everything a recording needs on disk: writing CSV, text and JSON /// files without knowing what is in them ([`logger::CsvFile`]), moving /// those files around ([`logger::files`], feature `files`) and the 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/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.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/model/http/README.md b/backend/crates/core/src/model/http/README.md new file mode 100644 index 000000000..1f500cb49 --- /dev/null +++ b/backend/crates/core/src/model/http/README.md @@ -0,0 +1,284 @@ +# HTTP Response Models (`model::http`) + +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 + +| `Adj` method | Public response type | Station GET route | JSON example | +| --- | --- | --- | --- | +| `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) | + +Each example is a standalone illustrative catalog, not a snapshot of the +bundled test ADJ or part of a shared vehicle fixture. + +## Usage + +Enable the `http` feature in the application's dependency: + +```bash +cargo add software-core -F http +``` + +With an already loaded `adj: Adj`: + +```rust +use software_core::model::http::{DataResponse, OrderResponse, ProtectionResponse}; + +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. 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 `type` values 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, + "type": string // A numeric wire type, such as "float32", or "boolean"; see enum form below. + } + ] + } + ] + } + ] +} +``` + +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, + "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). + "type": { + "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, + "type": { + "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 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` | +| `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 `type` Values + +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 measurement (field excerpt): + +```jsonc +{ + "type": string // One of the numeric wire types listed below, e.g. "float32". +} +``` + +Numeric `type` is one of `"uint8"`, `"uint16"`, `"uint32"`, `"uint64"`, +`"int8"`, `"int16"`, `"int32"`, `"int64"`, `"float32"`, or `"float64"`. + +Boolean measurement (field excerpt): + +```jsonc +{ + "type": "boolean" +} +``` + +Enum measurement (field excerpt): + +```jsonc +{ + "type": { + "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 `type` Values + +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": {"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"` | + +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 new file mode 100644 index 000000000..d739e82a2 --- /dev/null +++ b/backend/crates/core/src/model/http/data.rs @@ -0,0 +1,84 @@ +//! ADJ v3 data packet catalog returned by `/backend/adj/DataPackets`. + +use serde::Serialize; + +use crate::{ + model::{AdjId, BoardId, NumericKind}, + utils::serialize::{serialize_adj_id, serialize_board_id, serialize_data_measurement_type}, +}; + +/// 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, + /// 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, + /// 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 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, serialized as a wire type string such as `"float32"`. + Numeric { + /// Selects the ADJ type name; no separate `wire_type` JSON field is emitted. + wire_type: NumericKind, + }, + /// Boolean measurement, serialized as the string `"boolean"`. + Boolean, + /// Enumeration, serialized as `{"type":"enum","options":[...]}`. + Enum { + /// 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 new file mode 100644 index 000000000..08d2f8461 --- /dev/null +++ b/backend/crates/core/src/model/http/example/data.json @@ -0,0 +1,72 @@ +{ + "boards": [ + { + "id": 1, + "name": "LCU", + "packets": [ + { + "id": 936, + "name": "Temperatures", + "type": "data", + "measurements": [ + { + "id": 3000, + "alias": "temperature_1", + "name": "Motor temperature", + "display_units": "ºC", + "type": "float32" + } + ] + }, + { + "id": 967, + "name": "Levitation distance", + "type": "data", + "measurements": [ + { + "id": 3001, + "alias": "levitation_distance", + "name": "Levitation distance", + "display_units": "mm", + "type": "float32" + } + ] + } + ] + }, + { + "id": 2, + "name": "HVBMS", + "packets": [ + { + "id": 1200, + "name": "Battery voltage", + "type": "data", + "measurements": [ + { + "id": 3100, + "alias": "pack_voltage", + "name": "Pack voltage", + "display_units": "V", + "type": "float32" + } + ] + }, + { + "id": 1201, + "name": "Contactors status", + "type": "data", + "measurements": [ + { + "id": 3101, + "alias": "contactor_closed", + "name": "Contactor closed", + "display_units": "", + "type": "boolean" + } + ] + } + ] + } + ] +} diff --git a/backend/crates/core/src/model/http/example/order.json b/backend/crates/core/src/model/http/example/order.json new file mode 100644 index 000000000..63f9bedfb --- /dev/null +++ b/backend/crates/core/src/model/http/example/order.json @@ -0,0 +1,68 @@ +{ + "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", + "type": "float32", + "protections": [ + { + "id": 11193, + "type": { + "type": "range", + "min": 0.0, + "max": 50.0 + }, + "severity": "fault" + }, + { + "id": 19385, + "type": { + "type": "above", + "limit": 40.0 + }, + "severity": "warning", + "time": "200ms" + } + ] + } + ] + }, + { + "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/model/http/example/protection.json b/backend/crates/core/src/model/http/example/protection.json new file mode 100644 index 000000000..778e1a6d0 --- /dev/null +++ b/backend/crates/core/src/model/http/example/protection.json @@ -0,0 +1,55 @@ +{ + "protections": [ + { + "id": 11192, + "name": "LCU_temperature_1_protection_1", + "board_id": 1, + "measurement_id": 3000, + "type": { + "type": "range", + "min": 0.0, + "max": 100.0 + }, + "severity": "fault", + "time": "500ms" + }, + { + "id": 11292, + "name": "HVBMS_pack_voltage_protection_1", + "board_id": 2, + "measurement_id": 3100, + "type": { + "type": "range", + "min": 300.0, + "max": 500.0 + }, + "severity": "fault" + }, + { + "id": 19384, + "name": "LCU_temperature_1_protection_2", + "board_id": 1, + "measurement_id": 3000, + "type": { + "type": "below", + "limit": 10.0 + }, + "severity": "warning", + "time": "1000ms" + } + ], + "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: %)" + } + } +} diff --git a/backend/crates/core/src/model/http/order.rs b/backend/crates/core/src/model/http/order.rs new file mode 100644 index 000000000..964d442e6 --- /dev/null +++ b/backend/crates/core/src/model/http/order.rs @@ -0,0 +1,83 @@ +//! ADJ v3 order catalog returned by `/backend/adj/OrderPackets`. + +use serde::Serialize; + +use crate::{ + model::{AdjId, BoardId, ProtectionKind, Severity}, + utils::serialize::{ + serialize_adj_id, serialize_board_id, serialize_data_measurement_type, + 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 { + /// 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. + #[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, +} + +/// A parameter protection's definition, not a triggered protection event. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct OrderProtectionResponse { + /// 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. + #[serde(rename = "type", serialize_with = "serialize_protection_kind")] + pub kind: ProtectionKind, + /// Severity serialized as `fault` or `warning`. + #[serde(serialize_with = "serialize_severity")] + pub severity: Severity, + /// 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 new file mode 100644 index 000000000..8e55e9477 --- /dev/null +++ b/backend/crates/core/src/model/http/protection.rs @@ -0,0 +1,61 @@ +//! Flat ADJ v3 protection catalog returned by `/backend/adj/ProtectionPackets`. + +use std::collections::HashMap; + +use serde::Serialize; + +use crate::{ + model::{AdjId, BoardId, ProtectionKind, Severity}, + utils::serialize::{ + serialize_adj_id, serialize_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(rename = "type", serialize_with = "serialize_protection_kind")] + pub kind: ProtectionKind, + /// Severity serialized as `fault` or `warning`. + #[serde(serialize_with = "serialize_severity")] + pub severity: Severity, + /// Optional duration. + #[serde(skip_serializing_if = "Option::is_none")] + pub time: Option, +} + +/// 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(skip_serializing_if = "Option::is_none")] + pub text_time: Option, +} diff --git a/backend/crates/core/src/utils.rs b/backend/crates/core/src/utils.rs new file mode 100644 index 000000000..0063520a7 --- /dev/null +++ b/backend/crates/core/src/utils.rs @@ -0,0 +1 @@ +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 new file mode 100644 index 000000000..cb61543b9 --- /dev/null +++ b/backend/crates/core/src/utils/serialize.rs @@ -0,0 +1,111 @@ +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: +// - 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. +// +// 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( + 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 get_numeric_kind(kind: &NumericKind) -> &str { + match kind { + NumericKind::U8 => "uint8", + NumericKind::U16 => "uint16", + NumericKind::U32 => "uint32", + NumericKind::U64 => "uint64", + NumericKind::I8 => "int8", + NumericKind::I16 => "int16", + NumericKind::I32 => "int32", + NumericKind::I64 => "int64", + NumericKind::F32 => "float32", + NumericKind::F64 => "float64", + } +} + +// 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 }, + 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 { + // We apply the serialization to this specific enum, with rules setted in the definition + 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", + }) +} + +// Little helper for serialize the data measurement type +#[derive(Serialize)] +struct EnumKind { + #[serde(rename = "type")] + type_kind: String, + 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, + 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(); + + let enum_kind = EnumKind { + type_kind: "enum".to_string(), + options, + }; + + EnumKind::serialize(&enum_kind, serializer) + } + } +} diff --git a/backend/crates/station/Cargo.toml b/backend/crates/station/Cargo.toml index 20c403657..9eed62cbe 100644 --- a/backend/crates/station/Cargo.toml +++ b/backend/crates/station/Cargo.toml @@ -9,14 +9,17 @@ 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"] } +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 new file mode 100644 index 000000000..30c91003a --- /dev/null +++ b/backend/crates/station/src/http.rs @@ -0,0 +1,25 @@ +//! 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 axum::extract::ws::WebSocket; +use software_core::adj::Adj; +use tokio::{net::TcpListener, sync::mpsc}; + +use crate::http::server::setup_router; + +mod handlers; +mod server; + +/// Serves the ADJ catalogs and the WebSocket upgrade endpoint. +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/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. diff --git a/backend/crates/station/src/http/handlers.rs b/backend/crates/station/src/http/handlers.rs new file mode 100644 index 000000000..aabd23741 --- /dev/null +++ b/backend/crates/station/src/http/handlers.rs @@ -0,0 +1,95 @@ +//! Handlers for precomputed catalogs and WebSocket upgrades. + +use std::sync::Arc; + +use axum::{ + body::Bytes, + extract::{State, WebSocketUpgrade, ws::WebSocket}, + http::{StatusCode, header}, + response::{IntoResponse, Response}, +}; +use software_core::adj::Adj; +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>, +} + +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 { + // ADJ transformation and serialization happen only at startup. + fn new(adj: &Adj) -> Result { + Ok(Self { + 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(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 protection_packet(State(state): State>) -> Response { + json_response(state.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, "WebSocket upgrade failed"); + }) + .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); + }) +} + +// 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() +} diff --git a/backend/crates/station/src/http/server.rs b/backend/crates/station/src/http/server.rs new file mode 100644 index 000000000..0bb27dedf --- /dev/null +++ b/backend/crates/station/src/http/server.rs @@ -0,0 +1,332 @@ +//! Router construction and server execution using an existing listener. + +use std::{io, sync::Arc}; + +use axum::{ + Router, + extract::ws::WebSocket, + http::{HeaderValue, header}, + routing::get, +}; +use software_core::adj::Adj; +use tokio::sync::mpsc; +use tower_http::{cors::CorsLayer, set_header::SetResponseHeaderLayer}; + +use super::handlers::{HttpState, data_packet, order_packet, protection_packet, websocket}; + +/// 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`. +/// +/// This future runs until the server stops; await it or spawn it on Tokio. +/// +/// # Errors +/// +/// Propagates errors serializing the catalogs or running the Axum server. +pub(super) fn setup_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)) + .route("/backend/ws", get(websocket)) + .layer(CorsLayer::permissive()) + .layer(SetResponseHeaderLayer::overriding( + header::CACHE_CONTROL, + HeaderValue::from_static("no-cache"), + )) + .with_state(state)) +} + +#[cfg(test)] +pub(super) mod tests { + use std::{io, path::Path, time::Duration}; + + use axum::{ + body::{Body, to_bytes}, + http::{Method, Request, StatusCode, header}, + }; + 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; + + use super::setup_router; + + pub(in crate::http) const PATHS: [&str; 3] = [ + "/backend/adj/DataPackets", + "/backend/adj/OrderPackets", + "/backend/adj/ProtectionPackets", + ]; + + #[tokio::test] + 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 = [ + serde_json::to_value(&adj.data_response())?, + serde_json::to_value(&adj.order_response())?, + serde_json::to_value(&adj.protection_response())?, + ]; + let app = setup_router(&adj, None)?; + 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 = setup_router(&Adj::default(), None)?; + 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(()) + } + + #[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( + 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 { + 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/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\ + 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 = 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")); + assert!( + headers + .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"))?; + assert_eq!(connections.capacity(), 1); + drop(socket); + Ok(()) + } + + #[tokio::test] + async fn websocket_without_a_consumer_returns_unavailable() + -> Result<(), Box> { + let app = setup_router(&Adj::default(), None)?; + let (headers, _client) = handshake(app).await?; + assert!(headers.starts_with("HTTP/1.1 503 Service Unavailable\r\n")); + Ok(()) + } + + #[tokio::test] + async fn websocket_with_a_closed_channel_returns_unavailable() + -> Result<(), Box> { + let (connections, receiver) = mpsc::channel(1); + drop(receiver); + let app = setup_router(&Adj::default(), Some(connections))?; + let (headers, _client) = handshake(app).await?; + assert!(headers.starts_with("HTTP/1.1 503 Service Unavailable\r\n")); + 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 = 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); + Ok(()) + } + + #[tokio::test] + async fn websocket_rejects_requests_without_upgrade_headers() + -> Result<(), Box> { + let (connections, mut receiver) = mpsc::channel(1); + let app = setup_router(&Adj::default(), Some(connections.clone()))?; + let response = app + .oneshot(Request::builder().uri("/backend/ws").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(()) + } +} diff --git a/backend/crates/station/src/main.rs b/backend/crates/station/src/main.rs index 27767e13f..d872008d1 100644 --- a/backend/crates/station/src/main.rs +++ b/backend/crates/station/src/main.rs @@ -9,17 +9,5 @@ fn main() { 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"); - tracing::info!("demo finalizada"); } diff --git a/backend/crates/station/src/vehicle.rs b/backend/crates/station/src/vehicle.rs new file mode 100644 index 000000000..e69de29bb