diff --git a/.github/workflows/rust-tests.yaml b/.github/workflows/rust-tests.yaml index 6ab44a9ce..b3ebd6fc6 100644 --- a/.github/workflows/rust-tests.yaml +++ b/.github/workflows/rust-tests.yaml @@ -13,7 +13,14 @@ jobs: strategy: fail-fast: false matrix: - crate: [software-core, station] + include: + # software-core's modules sit behind features (net, git, logger, + # ntp, http...) that are all off by default: without + # --all-features none of their tests would run, UDP's included. + - crate: software-core + flags: --all-features + - crate: station + flags: "" steps: - uses: actions/checkout@v4 @@ -27,4 +34,4 @@ jobs: - name: Run tests working-directory: backend - run: cargo test --package ${{ matrix.crate }} + run: cargo test --package ${{ matrix.crate }} ${{ matrix.flags }} diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 5f25ff681..e09a599b4 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -12,383 +12,3057 @@ dependencies = [ ] [[package]] -name = "byteorder" -version = "1.5.0" +name = "allocator-api2" +version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" [[package]] -name = "bytes" -version = "1.12.1" +name = "arc-swap" +version = "1.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +checksum = "84a22b5d51209f6de83d37a0b33d320acb8da88823e42a94c075140708f032a5" +dependencies = [ + "rustversion", +] [[package]] -name = "cfg-if" -version = "1.0.5" +name = "arrayvec" +version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" [[package]] -name = "crossbeam-channel" -version = "0.5.17" +name = "atomic-waker" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" -dependencies = [ - "crossbeam-utils", -] +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" [[package]] -name = "crossbeam-utils" -version = "0.8.23" +name = "autocfg" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] -name = "deranged" -version = "0.5.8" +name = "aws-lc-rs" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53" +dependencies = [ + "aws-lc-sys", + "zeroize", +] [[package]] -name = "equivalent" -version = "1.0.2" +name = "aws-lc-sys" +version = "0.47.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] [[package]] -name = "errno" -version = "0.3.14" +name = "axum" +version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" dependencies = [ - "libc", - "windows-sys", + "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 = "hashbrown" -version = "0.17.1" +name = "axum-core" +version = "0.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +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 = "indexmap" -version = "2.14.2" +name = "base64" +version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" -dependencies = [ - "equivalent", - "hashbrown", -] +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" [[package]] -name = "itoa" -version = "1.0.18" +name = "base64" +version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" [[package]] -name = "lazy_static" -version = "1.5.1" +name = "bitflags" +version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] -name = "libc" -version = "0.2.189" +name = "bitflags" +version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" [[package]] -name = "log" -version = "0.4.34" +name = "block-buffer" +version = "0.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] [[package]] -name = "matchers" -version = "0.2.0" +name = "bstr" +version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" dependencies = [ + "memchr", "regex-automata", + "serde_core", ] [[package]] -name = "memchr" -version = "2.8.3" +name = "bumpalo" +version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" [[package]] -name = "mio" -version = "1.2.3" +name = "byteorder" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" -dependencies = [ - "libc", - "wasi", - "windows-sys", -] +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] -name = "ntp_usg-proto" -version = "5.0.0" +name = "bytes" +version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31316ff46fc87e03a95e55b93525a27feecfd86fab094ca887a773395f13f50a" -dependencies = [ - "byteorder", - "log", -] +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" [[package]] -name = "ntp_usg-server" -version = "5.0.0" +name = "bytesize" +version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0002bd55912864af88a46077abd71db2c4cda88887b46b19c31e1e9a1f289e4e" -dependencies = [ - "ntp_usg-proto", - "tokio", - "tracing", -] +checksum = "7354288c522e7e980fafd2075d63d1285794c3a6a16cdd492f189ea406e5f18b" [[package]] -name = "nu-ansi-term" -version = "0.50.3" +name = "cc" +version = "1.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" dependencies = [ - "windows-sys", + "find-msvc-tools", + "jobserver", + "libc", + "shlex", ] [[package]] -name = "num-conv" -version = "0.2.2" +name = "cfg-if" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" [[package]] -name = "once_cell" -version = "1.21.4" +name = "cfg_aliases" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" [[package]] -name = "pin-project-lite" -version = "0.2.17" +name = "chacha20" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] [[package]] -name = "powerfmt" -version = "0.2.0" +name = "clru" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" +checksum = "197fd99cb113a8d5d9b6376f3aa817f32c1078f2343b714fff7d2ca44fdf67d5" +dependencies = [ + "hashbrown 0.16.1", +] [[package]] -name = "proc-macro2" -version = "1.0.107" +name = "cmake" +version = "0.1.58" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" dependencies = [ - "unicode-ident", + "cc", ] [[package]] -name = "quote" -version = "1.0.47" +name = "combine" +version = "4.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" dependencies = [ - "proc-macro2", + "bytes", + "memchr", ] [[package]] -name = "regex-automata" -version = "0.4.18" +name = "core-foundation" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", + "core-foundation-sys", + "libc", ] [[package]] -name = "regex-syntax" -version = "0.8.11" +name = "core-foundation-sys" +version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" [[package]] -name = "serde" -version = "1.0.229" +name = "core_detect" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" dependencies = [ - "serde_core", - "serde_derive", + "libc", ] [[package]] -name = "serde_core" -version = "1.0.229" +name = "cpufeatures" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" dependencies = [ - "serde_derive", + "libc", ] [[package]] -name = "serde_derive" -version = "1.0.229" +name = "crc32fast" +version = "1.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", + "cfg-if", ] [[package]] -name = "serde_json" -version = "1.0.151" +name = "crossbeam-channel" +version = "0.5.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" dependencies = [ - "itoa", - "memchr", - "serde", - "serde_core", - "zmij", + "crossbeam-utils", ] [[package]] -name = "serde_spanned" -version = "1.1.1" +name = "crossbeam-deque" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" dependencies = [ - "serde_core", + "crossbeam-epoch", + "crossbeam-utils", ] [[package]] -name = "sharded-slab" +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ - "lazy_static", + "generic-array", + "typenum", ] [[package]] -name = "signal-hook-registry" -version = "1.4.8" +name = "dashmap" +version = "6.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c" dependencies = [ - "errno", - "libc", + "cfg-if", + "crossbeam-utils", + "hashbrown 0.14.5", + "lock_api", + "once_cell", + "parking_lot_core", ] [[package]] -name = "smallvec" -version = "1.16.2" +name = "data-encoding" +version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" [[package]] -name = "socket2" -version = "0.6.5" +name = "defmt" +version = "0.3.101" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +checksum = "4deef977660e373c458df605a913d4ab121db0ccd18d1ad6976dff7d37cddb53" dependencies = [ - "libc", - "windows-sys", + "defmt 1.2.0", ] [[package]] -name = "software-core" -version = "0.1.0" +name = "defmt" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" dependencies = [ - "bytes", - "ntp_usg-server", - "serde", - "serde_json", - "thiserror", - "tokio", - "tracing", - "tracing-appender", - "tracing-subscriber", + "bitflags 1.3.2", + "defmt-macros", ] [[package]] -name = "station" -version = "0.1.0" +name = "defmt-macros" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" +dependencies = [ + "defmt-parser", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "defmt-parser" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" dependencies = [ - "serde", - "software-core", "thiserror", - "tokio", - "toml", - "tracing", - "tracing-subscriber", ] [[package]] -name = "symlink" -version = "0.1.0" +name = "deranged" +version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" [[package]] -name = "syn" -version = "2.0.119" +name = "digest" +version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", + "block-buffer", + "crypto-common", ] [[package]] -name = "syn" -version = "3.0.6" +name = "dirs" +version = "7.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f" dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", + "dirs-sys", ] [[package]] -name = "thiserror" -version = "2.0.21" +name = "dirs-sys" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" dependencies = [ - "thiserror-impl", + "libc", + "option-ext", + "redox_users", + "windows-sys 0.61.2", ] [[package]] -name = "thiserror-impl" -version = "2.0.21" +name = "displaydoc" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] -name = "thread_local" -version = "1.1.10" +name = "dunce" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "faster-hex" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04839bdf9d8c10f66806fad16b852fc72aab80873aebc3cb69d85b4fa41543ed" +dependencies = [ + "autocfg", + "defmt 0.3.101", + "heapless", + "serde", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "filetime" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if", + "libc", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi 0.11.1+wasi-snapshot-preview1", + "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", + "wasm-bindgen", +] + +[[package]] +name = "gix" +version = "0.87.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdefc1465d8631807deaf504dacdeff628b978de515653b47976ca7c28ab2a7a" +dependencies = [ + "gix-actor", + "gix-archive", + "gix-attributes", + "gix-blame", + "gix-command", + "gix-commitgraph", + "gix-config", + "gix-credentials", + "gix-date", + "gix-diff", + "gix-dir", + "gix-discover", + "gix-error", + "gix-features", + "gix-filter", + "gix-fs", + "gix-glob", + "gix-hash", + "gix-hashtable", + "gix-ignore", + "gix-index", + "gix-lock", + "gix-mailmap", + "gix-merge", + "gix-negotiate", + "gix-note", + "gix-object", + "gix-odb", + "gix-pack", + "gix-path", + "gix-pathspec", + "gix-prompt", + "gix-protocol", + "gix-quote", + "gix-ref", + "gix-refspec", + "gix-revision", + "gix-revwalk", + "gix-sec", + "gix-shallow", + "gix-status", + "gix-submodule", + "gix-tempfile", + "gix-trace", + "gix-transport", + "gix-traverse", + "gix-url", + "gix-utils", + "gix-validate", + "gix-worktree", + "gix-worktree-state", + "gix-worktree-stream", + "gix-zlib", + "nonempty", + "parking_lot", + "regex", + "signal-hook", + "smallvec", + "thiserror", +] + +[[package]] +name = "gix-actor" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e37efa99929ac62f980fb1a7dcd09dea85b3aa6ead6ba0498362add3f4e698de" +dependencies = [ + "bstr", + "gix-date", + "gix-error", +] + +[[package]] +name = "gix-archive" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c4ef97efd3920d3525104c5f253dec94dc935f953a50055954939177aed2cdd" +dependencies = [ + "bstr", + "gix-date", + "gix-error", + "gix-object", + "gix-worktree-stream", +] + +[[package]] +name = "gix-attributes" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76b83782ac69ae28921a6e8fbcf2e24069613f1518030b97ae622b079abffa54" +dependencies = [ + "bstr", + "gix-features", + "gix-glob", + "gix-path", + "gix-quote", + "gix-trace", + "smallvec", + "thiserror", + "unicode-bom", +] + +[[package]] +name = "gix-bitmap" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f17013c7ef5cb95ebb4bf4978201e6a8a42ffea9d666fd5388f1b7e742307d80" +dependencies = [ + "gix-error", +] + +[[package]] +name = "gix-blame" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54fe27f8037c58cb4b6d60fe0aacf7ee2c998633cedf4e989351c07d9a3a575d" +dependencies = [ + "gix-commitgraph", + "gix-date", + "gix-diff", + "gix-error", + "gix-hash", + "gix-object", + "gix-revwalk", + "gix-trace", + "gix-traverse", + "gix-worktree", + "smallvec", + "thiserror", +] + +[[package]] +name = "gix-chunk" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00e32f938b3745ac93d73bc7490b6a15a661b2fc81973bfe90e275cc53c908e1" +dependencies = [ + "gix-error", +] + +[[package]] +name = "gix-command" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa00adbd2c77f584cfe41f348772d2f131af1fa519a7f6b98638f1144ead96a4" +dependencies = [ + "bstr", + "gix-path", + "gix-quote", + "gix-trace", +] + +[[package]] +name = "gix-commitgraph" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b93c9fb1f5be01bba54a7a3b7455d359efc68555539c75ef74b8021bb6db497" +dependencies = [ + "bstr", + "gix-chunk", + "gix-error", + "gix-hash", + "memmap2", + "nonempty", +] + +[[package]] +name = "gix-config" +version = "0.60.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f973c28c0a4871a7926fc90c8377d4458fd6cbb19692f56582b4d2022313ae90" +dependencies = [ + "bstr", + "gix-config-value", + "gix-features", + "gix-glob", + "gix-path", + "gix-ref", + "gix-sec", + "gix-utils", + "smallvec", + "thiserror", + "unicode-bom", +] + +[[package]] +name = "gix-config-value" +version = "0.19.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f6af5321bfd3711a279d6b244d58532ba1cfabf9eb6374791f19929d8970082" +dependencies = [ + "bitflags 2.13.2", + "bstr", + "gix-path", + "libc", + "thiserror", +] + +[[package]] +name = "gix-credentials" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16c11822054fd4b80a1ab722b703f2e7c691b20484d898374289b742c1f49e50" +dependencies = [ + "bstr", + "gix-command", + "gix-config-value", + "gix-date", + "gix-path", + "gix-prompt", + "gix-quote", + "gix-sec", + "gix-trace", + "gix-url", + "thiserror", +] + +[[package]] +name = "gix-date" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e63d9aa18f29facd571c8953e66224ee0075b9e16622024794555ed4acceea85" +dependencies = [ + "bstr", + "gix-error", + "itoa", + "jiff", +] + +[[package]] +name = "gix-diff" +version = "0.67.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b1689ff5ddeee4acfb2a43e875a1072a76d208624b15a9065c938b39cb0da2a" +dependencies = [ + "bstr", + "gix-attributes", + "gix-command", + "gix-filter", + "gix-fs", + "gix-hash", + "gix-imara-diff", + "gix-index", + "gix-object", + "gix-path", + "gix-pathspec", + "gix-tempfile", + "gix-trace", + "gix-traverse", + "gix-worktree", + "thiserror", +] + +[[package]] +name = "gix-dir" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8342d5eb0ea054ed6ef807e628e38f06dd51eceeec9529767d8b23e33eff9c09" +dependencies = [ + "bstr", + "gix-discover", + "gix-fs", + "gix-ignore", + "gix-index", + "gix-object", + "gix-path", + "gix-pathspec", + "gix-trace", + "gix-utils", + "gix-worktree", + "thiserror", +] + +[[package]] +name = "gix-discover" +version = "0.55.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec32a30ec2934735599c2545f30067e80bd255fd3454b52a5d59bc02b52874a3" +dependencies = [ + "bstr", + "dunce", + "gix-fs", + "gix-path", + "gix-ref", + "gix-sec", + "thiserror", +] + +[[package]] +name = "gix-error" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a1ba536602db507119eb5f3cdf80bef3ca5a5ec0dfc6e9c7f46dc70ade7c112" +dependencies = [ + "bstr", +] + +[[package]] +name = "gix-features" +version = "0.49.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39c0e59d9d253dcccc38c3a46b91bfb9b46bd63eed54fe1a719e12194884d52a" +dependencies = [ + "bytes", + "bytesize", + "crc32fast", + "crossbeam-channel", + "gix-path", + "gix-trace", + "gix-utils", + "libc", + "once_cell", + "parking_lot", + "prodash", + "walkdir", +] + +[[package]] +name = "gix-filter" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c30b28d957e2e6f1e1bbfbfd26b8e0bb0aab68d8a5e730fb4fd3049943575e3" +dependencies = [ + "bstr", + "encoding_rs", + "gix-attributes", + "gix-command", + "gix-hash", + "gix-object", + "gix-packetline", + "gix-path", + "gix-quote", + "gix-trace", + "gix-utils", + "smallvec", + "thiserror", +] + +[[package]] +name = "gix-fs" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebcfa9fd253f25350a3b21b3dd74034a446098e373c6123d4cee3519894f12ef" +dependencies = [ + "bstr", + "gix-features", + "gix-path", + "gix-utils", + "thiserror", +] + +[[package]] +name = "gix-glob" +version = "0.27.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b417cf515fd8c91468b578071f76d6cba716f8a1eccd853906bff4908b2c1413" +dependencies = [ + "bitflags 2.13.2", + "bstr", + "gix-features", + "gix-path", +] + +[[package]] +name = "gix-hash" +version = "0.26.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "380b9c423a54f0821064b954b5a5ab25c660812f6a91da03c3f1cb4b10762aa5" +dependencies = [ + "faster-hex", + "gix-features", + "sha1-checked", + "thiserror", +] + +[[package]] +name = "gix-hashtable" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78fccd6fea3bcf0b39c076bae60ae49b08daaf538b950202101a981f9d3c01d3" +dependencies = [ + "gix-hash", + "hashbrown 0.17.1", + "parking_lot", +] + +[[package]] +name = "gix-ignore" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65859a2f7de5e159d4344a5486ebf53b6bac22d5ec6afa836e47c10ae88a7f0f" +dependencies = [ + "bstr", + "gix-glob", + "gix-path", + "gix-trace", + "unicode-bom", +] + +[[package]] +name = "gix-imara-diff" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c91d8cffac8849493a82233811bd02b2b183b8cf39bf704de0fa0841b737595" +dependencies = [ + "bstr", + "hashbrown 0.17.1", +] + +[[package]] +name = "gix-index" +version = "0.55.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "632e16cb48b0e88a747e106924cb2765194105d8070a7a961b0d080ed806c632" +dependencies = [ + "bitflags 2.13.2", + "bstr", + "filetime", + "fnv", + "gix-bitmap", + "gix-features", + "gix-fs", + "gix-hash", + "gix-lock", + "gix-object", + "gix-traverse", + "gix-utils", + "gix-validate", + "hashbrown 0.17.1", + "itoa", + "libc", + "memmap2", + "rustix", + "smallvec", + "thiserror", +] + +[[package]] +name = "gix-lock" +version = "24.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4c69157820343bf1c6e4b88b9808e920900de02e18aaf5862b30ada43814848" +dependencies = [ + "gix-tempfile", + "gix-utils", + "thiserror", +] + +[[package]] +name = "gix-macros" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3836b4b051393464a753c5a08fe19c7ce0d8b77574a92bd558972941d4553cb" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "gix-mailmap" +version = "0.34.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a1c6ca2f9481e5e98b3600b859bc595d46cdf3b600709d5f91b8c118ae452a1" +dependencies = [ + "bstr", + "gix-actor", + "gix-date", + "gix-error", +] + +[[package]] +name = "gix-merge" +version = "0.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72fad4279c940a0fa460ffdf3a3c0e48b7ca5ccb2b08f51a02b22ffcd1efb900" +dependencies = [ + "bstr", + "gix-command", + "gix-diff", + "gix-filter", + "gix-fs", + "gix-hash", + "gix-imara-diff", + "gix-index", + "gix-object", + "gix-path", + "gix-quote", + "gix-revision", + "gix-revwalk", + "gix-tempfile", + "gix-trace", + "gix-worktree", + "nonempty", + "thiserror", +] + +[[package]] +name = "gix-negotiate" +version = "0.35.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91068ecee956121d663635b873ae87ad9c5d3f2d6788facfd12829140b39c897" +dependencies = [ + "bitflags 2.13.2", + "gix-commitgraph", + "gix-date", + "gix-hash", + "gix-object", + "gix-revwalk", +] + +[[package]] +name = "gix-note" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9af6bbdb3f3c62b4920407c479af1cc0beb27fd75a762782d48baed53d330958" +dependencies = [ + "gix-error", + "gix-hash", + "gix-hashtable", + "gix-object", +] + +[[package]] +name = "gix-object" +version = "0.64.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56fef799ca40cdeab4de5a3e74a696d8fa9b9c6264592646bf022e026f13ce2c" +dependencies = [ + "bstr", + "gix-actor", + "gix-command", + "gix-date", + "gix-features", + "gix-hash", + "gix-hashtable", + "gix-tempfile", + "gix-utils", + "gix-validate", + "itoa", + "smallvec", + "thiserror", +] + +[[package]] +name = "gix-odb" +version = "0.84.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf45d195b71cb6363886e7b466821bf4dffd7aba1b6b814ff75488e0061d72a7" +dependencies = [ + "arc-swap", + "gix-features", + "gix-fs", + "gix-hash", + "gix-hashtable", + "gix-object", + "gix-pack", + "gix-path", + "gix-quote", + "gix-zlib", + "memmap2", + "parking_lot", + "tempfile", + "thiserror", +] + +[[package]] +name = "gix-pack" +version = "0.74.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d199d515cbdcf05f531f3859be9771fc12acac7b7fe0f5b581b2c1ab1c3a61e" +dependencies = [ + "clru", + "crossbeam-deque", + "gix-chunk", + "gix-error", + "gix-features", + "gix-hash", + "gix-hashtable", + "gix-object", + "gix-path", + "gix-tempfile", + "gix-zlib", + "memmap2", + "parking_lot", + "smallvec", + "thiserror", + "uluru", +] + +[[package]] +name = "gix-packetline" +version = "0.22.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "792bd92bea390087e6223b18d4d023decc36467de31e6b066b69b94beea1b9e2" +dependencies = [ + "bstr", + "faster-hex", + "gix-trace", + "thiserror", +] + +[[package]] +name = "gix-path" +version = "0.12.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38fc6f029ea67de83cbcbd33fd98c05a48360d2932b39d9fdacbc6eae802d475" +dependencies = [ + "bstr", + "gix-trace", + "gix-validate", + "thiserror", +] + +[[package]] +name = "gix-pathspec" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92e44c63ba53bb55aa88ee48847664beae9446417621582fb14dfc69b2f8c72" +dependencies = [ + "bitflags 2.13.2", + "bstr", + "gix-attributes", + "gix-config-value", + "gix-glob", + "gix-path", + "thiserror", +] + +[[package]] +name = "gix-prompt" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "802256e13ecb2133ba5f9e6acbaa6b08bac027b1c5929f85f6adbb56ba3a4f28" +dependencies = [ + "gix-command", + "gix-config-value", + "parking_lot", + "rustix", + "thiserror", +] + +[[package]] +name = "gix-protocol" +version = "0.65.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68878c37ae168b474c762d70adc8a8e0f9323ed0d80444a672e2eb561fa16691" +dependencies = [ + "bstr", + "gix-credentials", + "gix-date", + "gix-features", + "gix-hash", + "gix-lock", + "gix-macros", + "gix-negotiate", + "gix-object", + "gix-ref", + "gix-refspec", + "gix-revwalk", + "gix-shallow", + "gix-trace", + "gix-transport", + "gix-utils", + "nonempty", + "thiserror", +] + +[[package]] +name = "gix-quote" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f74795eb76eab8313063849f9cbd2bbcdc6e4692f71c1d7d0244ab11cd777329" +dependencies = [ + "bstr", + "gix-error", + "gix-utils", +] + +[[package]] +name = "gix-ref" +version = "0.67.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8328387e7ab354e1dc3afb63e6b4d1866f82d7ce035222bc9d5baaf36bc88020" +dependencies = [ + "gix-actor", + "gix-features", + "gix-fs", + "gix-hash", + "gix-lock", + "gix-object", + "gix-path", + "gix-tempfile", + "gix-utils", + "gix-validate", + "memmap2", + "thiserror", +] + +[[package]] +name = "gix-refspec" +version = "0.45.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7de280d46e8fd9e4d3e7e2ab4276b965e377ba68b2b9a8fce56371015e8bb059" +dependencies = [ + "bstr", + "gix-hash", + "gix-validate", + "smallvec", + "thiserror", +] + +[[package]] +name = "gix-revision" +version = "0.49.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4577b864c3e134697e91564553e43230c2e401bb1bcc51cfa998edca21c95078" +dependencies = [ + "bitflags 2.13.2", + "bstr", + "gix-commitgraph", + "gix-date", + "gix-error", + "gix-hash", + "gix-hashtable", + "gix-object", + "gix-revwalk", + "gix-trace", + "nonempty", +] + +[[package]] +name = "gix-revwalk" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "248823eefe405e2c0754b74f6f43ab6faab68670cdbf2d6e114cb0471f766450" +dependencies = [ + "gix-commitgraph", + "gix-date", + "gix-error", + "gix-hash", + "gix-hashtable", + "gix-object", + "smallvec", + "thiserror", +] + +[[package]] +name = "gix-sec" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af4fe6c152c1d50aea36f299825702cd37e303307832fec1d0fdd5844e47ce2f" +dependencies = [ + "bitflags 2.13.2", + "gix-path", + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "gix-shallow" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ecc9f4b40537043e4bbd7d3d1760e74fb8e7b07a546166b558acaa73ad97f4a" +dependencies = [ + "bstr", + "gix-hash", + "gix-lock", + "nonempty", + "thiserror", +] + +[[package]] +name = "gix-status" +version = "0.34.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1401d871c01d82add5a9f654439b00722d0c632b332cd2cb63193f94327c8458" +dependencies = [ + "bstr", + "filetime", + "gix-diff", + "gix-dir", + "gix-features", + "gix-filter", + "gix-fs", + "gix-hash", + "gix-index", + "gix-object", + "gix-path", + "gix-pathspec", + "gix-worktree", + "hashbrown 0.16.1", + "portable-atomic", + "thiserror", + "windows-sys 0.61.2", +] + +[[package]] +name = "gix-submodule" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da85564d6725c483b8d95d7b31d1db0b78c29e462a2b481949e2f18e1ed55a6a" +dependencies = [ + "bstr", + "gix-config", + "gix-path", + "gix-pathspec", + "gix-refspec", + "gix-url", + "thiserror", +] + +[[package]] +name = "gix-tempfile" +version = "24.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b675b920bd5a61d17ad542772f03ec34c60feb8ff683e1560c03ae967363731e" +dependencies = [ + "dashmap", + "gix-fs", + "libc", + "parking_lot", + "signal-hook", + "signal-hook-registry", + "tempfile", +] + +[[package]] +name = "gix-trace" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be3eb81d9dc914335923e50d52829c551feefd6a72d176c4130c546b67a60814" + +[[package]] +name = "gix-transport" +version = "0.59.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3f41a64939953ff49117df4eb91334d299abc59ff57a90fb2193d8ffa5886f1" +dependencies = [ + "base64 0.22.1", + "bstr", + "gix-command", + "gix-credentials", + "gix-features", + "gix-packetline", + "gix-path", + "gix-quote", + "gix-sec", + "gix-url", + "parking_lot", + "reqwest", + "thiserror", +] + +[[package]] +name = "gix-traverse" +version = "0.61.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9af3503668739f4de5dba57fe15cfd9adc443b08bcbbf195e5de16b648872245" +dependencies = [ + "bitflags 2.13.2", + "gix-commitgraph", + "gix-date", + "gix-hash", + "gix-hashtable", + "gix-object", + "gix-revwalk", + "smallvec", + "thiserror", +] + +[[package]] +name = "gix-url" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5bda80ccb4bc81fb9fb07a975916eb0c7a889bcbcb0c8a239c3f82a9cc2abdda" +dependencies = [ + "bstr", + "gix-path", + "gix-utils", + "percent-encoding", + "thiserror", +] + +[[package]] +name = "gix-utils" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0da1c46491b49458a446cc76f0085860f8164c2290742e0aa8c653ce67240a97" +dependencies = [ + "bstr", + "fastrand", + "getrandom 0.4.3", + "unicode-normalization", +] + +[[package]] +name = "gix-validate" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dae8780f63ed8a803b8bdabbd7aa5f5c5d74592c8b50eed875c1bb4f6545a6a" +dependencies = [ + "bstr", +] + +[[package]] +name = "gix-worktree" +version = "0.56.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ed36b627476e2072c129900a17c977a38052b5497e27308159bc881fbf4eecf" +dependencies = [ + "bstr", + "gix-attributes", + "gix-features", + "gix-fs", + "gix-glob", + "gix-hash", + "gix-ignore", + "gix-index", + "gix-object", + "gix-path", + "gix-validate", +] + +[[package]] +name = "gix-worktree-state" +version = "0.34.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c14faa5b9527823c656a033e841dde11ca5b774f1bca7a9cdc23db677e55d56" +dependencies = [ + "bstr", + "gix-features", + "gix-filter", + "gix-fs", + "gix-index", + "gix-object", + "gix-path", + "gix-worktree", + "io-close", + "thiserror", +] + +[[package]] +name = "gix-worktree-stream" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de5ec0ccbab39c9994656ea031ded8ffd90b370a3cc8e360fbe3c4ebe7c64964" +dependencies = [ + "gix-attributes", + "gix-error", + "gix-features", + "gix-filter", + "gix-fs", + "gix-hash", + "gix-object", + "gix-path", + "gix-traverse", + "parking_lot", +] + +[[package]] +name = "gix-zlib" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e8813f5579b3075ff9c90f7c59cd2b62b4ebb639361f0911648b22d7446cc7c" +dependencies = [ + "thiserror", + "zlib-rs", +] + +[[package]] +name = "h2" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hash32" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606" +dependencies = [ + "byteorder", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "heapless" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad" +dependencies = [ + "hash32", + "stable_deref_trait", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaec953f16e5bcf6b8a3cb3aa959b17e5577dbd2693e94554c462c08be22624b" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "io-close" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cadcf447f06744f8ce713d2d6239bb5bde2c357a452397a9ed90c625da390bc" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "jiff" +version = "0.2.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26699905cc795a23e3949585cc7ba3ee8ade090872a27e4316304a777297894a" +dependencies = [ + "jiff-core", + "jiff-static", + "jiff-tzdb-platform", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "windows-link", +] + +[[package]] +name = "jiff-core" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffe6854081f5ac0a3046a9b223729ccd7a20b1e0e8277e44dc0660eedf67dfe2" +dependencies = [ + "log", +] + +[[package]] +name = "jiff-static" +version = "0.2.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b4ff49b2887190c760b86207b55cdcaabbdecaf7a0660d68aa2ed6f652abf0a" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jiff-tzdb" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" + +[[package]] +name = "jiff-tzdb-platform" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" +dependencies = [ + "jiff-tzdb", +] + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "libc", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +dependencies = [ + "libc", +] + +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi 0.11.1+wasi-snapshot-preview1", + "windows-sys 0.61.2", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "nonempty" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9737e026353e5cd0736f98eddae28665118eb6f6600902a7f50db585621fecb6" + +[[package]] +name = "ntp_usg-proto" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31316ff46fc87e03a95e55b93525a27feecfd86fab094ca887a773395f13f50a" +dependencies = [ + "byteorder", + "log", +] + +[[package]] +name = "ntp_usg-server" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0002bd55912864af88a46077abd71db2c4cda88887b46b19c31e1e9a1f289e4e" +dependencies = [ + "ntp_usg-proto", + "tokio", + "tracing", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "objc2-system-configuration" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7216bd11cbda54ccabcab84d523dc93b858ec75ecfb3a7d89513fa22464da396" +dependencies = [ + "objc2-core-foundation", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "prodash" +version = "31.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf52d87428247c5aa3760ac8e7d8b13ec7b3579b955a8c3f311668b6860acba5" +dependencies = [ + "bytesize", + "human_format", + "parking_lot", +] + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "aws-lc-rs", + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.3", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "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]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "redox_users" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" +dependencies = [ + "libredox", + "thiserror", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64 0.23.1", + "bytes", + "encoding_rs", + "futures-channel", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "mime", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rlimit" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f35ee2729c56bb610f6dba436bf78135f728b7373bdffae2ec815b2d3eb98cc3" +dependencies = [ + "libc", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "aws-lc-rs", + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "aws-lc-rs", + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.2", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "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.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + +[[package]] +name = "sha1-checked" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89f599ac0c323ebb1c6082821a54962b839832b03984598375bff3975b804423" +dependencies = [ + "digest", + "sha1", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49f7447afd772ca79ad17ae0a3972a6b0df0cb4b80990fd82707593e9e012a74" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "software-core" +version = "0.1.0" +dependencies = [ + "bytes", + "dirs", + "gix", + "ntp_usg-server", + "rlimit", + "serde", + "serde_json", + "socket2", + "tempfile", + "thiserror", + "tokio", + "tracing", + "tracing-appender", + "tracing-subscriber", + "whoami", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "station" +version = "0.1.0" +dependencies = [ + "axum", + "serde", + "serde_json", + "software-core", + "thiserror", + "tokio", + "toml", + "tower", + "tower-http", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "symlink" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" dependencies = [ "cfg-if", ] @@ -423,11 +3097,27 @@ dependencies = [ "time-core", ] +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + [[package]] name = "tokio" -version = "1.53.1" +version = "1.54.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" dependencies = [ "bytes", "libc", @@ -436,7 +3126,7 @@ dependencies = [ "signal-hook-registry", "socket2", "tokio-macros", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -447,7 +3137,43 @@ checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", ] [[package]] @@ -466,28 +3192,74 @@ dependencies = [ ] [[package]] -name = "toml_datetime" -version = "0.7.5+spec-1.1.0" +name = "toml_datetime" +version = "0.7.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow 1.0.5", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" dependencies = [ - "serde_core", + "bitflags 2.13.2", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", ] [[package]] -name = "toml_parser" -version = "1.1.3+spec-1.1.0" +name = "tower-layer" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" -dependencies = [ - "winnow 1.0.4", -] +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" [[package]] -name = "toml_writer" -version = "1.1.2+spec-1.1.0" +name = "tower-service" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" [[package]] name = "tracing" @@ -577,11 +3349,96 @@ dependencies = [ "tracing-serde", ] +[[package]] +name = "try-lock" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "uluru" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c8a2469e56e6e5095c82ccd3afb98dad95f7af7929aab6d8ba8d6e0f73657da" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "unicode-bom" +version = "2.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7eec5d1121208364f6793f7d2e222bf75a915c19557537745b195b253dd64217" + [[package]] name = "unicode-ident" -version = "1.0.26" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +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 = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" [[package]] name = "valuable" @@ -589,18 +3446,207 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasi" +version = "0.14.7+wasi-0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "883478de20367e224c0090af9cf5f9fa85bed63a95c1abf3afc5c083ebc06e8c" +dependencies = [ + "wasip2", +] + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasite" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66fe902b4a6b8028a753d5424909b764ccf79b7a209eac9bf97e59cda9f71a42" +dependencies = [ + "wasi 0.14.7+wasi-0.2.4", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "whoami" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626c4bac6755d76ffc12cb01b2eac751db1996b9e0041de9aa02c8c211ddc82c" +dependencies = [ + "libc", + "libredox", + "objc2-system-configuration", + "wasite", + "web-sys", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -610,6 +3656,70 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + [[package]] name = "winnow" version = "0.7.15" @@ -618,9 +3728,130 @@ checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" [[package]] name = "winnow" -version = "1.0.4" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" [[package]] name = "zmij" diff --git a/backend/crates/core/Cargo.toml b/backend/crates/core/Cargo.toml index 0a3e434e8..08324ed3f 100644 --- a/backend/crates/core/Cargo.toml +++ b/backend/crates/core/Cargo.toml @@ -12,16 +12,27 @@ repository.workspace = true default = [] # NTP server ntp = ["dep:tokio", "dep:ntp_usg-server", "dep:tracing-subscriber"] -# TCP/UDP transport (pulls in tokio) -net = ["dep:tokio"] -# ADJ download through git (dependency added when the module is written) -git = [] +# TCP/UDP transport (pulls in tokio and socket2 for SO_RCVBUF) +net = ["dep:tokio", "dep:socket2"] +# ADJ download through git +git = ["dep:tempfile", "dep:dirs", "dep:gix"] # Packet sniffing through pcap (dependency added when the module is written) pcap = ["net"] # CSV data logger (records, sessions, subloggers) logger = [] +# `logger::files`: copying, moving and removing files. No dependencies +# of its own: a tool that only wants to copy a file shouldn't have to +# take anything else with it, beyond the `logger` module it lives in. +files = ["logger"] +# `logger::host`: a snapshot of the machine, the user and the build, for +# the metadata of a recording. `rlimit` is only a dependency on unix, so +# on Windows this enables `whoami` alone and `logger::host::open_file_limit` +# reports nothing. +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 @@ -37,9 +48,27 @@ tokio = { workspace = true, optional = true, features = [ "rt-multi-thread", "io-util", ] } +socket2 = { version = "0.6", optional = true } tracing-subscriber = { workspace = true, optional = true , features = ["env-filter", "fmt"]} tracing-appender = { workspace = true, optional = true } +gix = { version = "0.87.1", optional = true, features = ["blocking-http-transport-reqwest-rust-tls", "blocking-network-client", "worktree-mutation"] } +dirs = { version = "7.0.0", optional = true } +tempfile = { version = "3.27", optional = true } ntp_usg-server = { version = "5.0.0", optional = true, features = ["ipv4", "tokio"] } +# User, machine and OS metadata. Every call returns a `Result`, which is +# what makes a best-effort snapshot cheap to build. +whoami = { version = "2.1.3", optional = true } + +# `getrlimit` has no meaning on Windows, so the dependency isn't there +# either; `logger::host::open_file_limit` is `None` on that target. +[target.'cfg(unix)'.dependencies] +rlimit = { version = "0.11.0", optional = true } + +# The `logger` and `files` tests need a real directory to write into; +# `tempfile` is also an optional dependency of the `git` feature, which is +# why it shows up twice. +[dev-dependencies] +tempfile = "3.27" # `workspace = true` can't be combined with extra lints in the same table, # so the workspace list is repeated here with `missing_docs` added: this is diff --git a/backend/crates/core/src/adj.rs b/backend/crates/core/src/adj.rs index 839f4fa4a..d47286223 100644 --- a/backend/crates/core/src/adj.rs +++ b/backend/crates/core/src/adj.rs @@ -2,23 +2,42 @@ //! [`crate::model::PodData`], plus backend-session metadata not modeled as //! vehicle data ([`crate::adj::AdjInfo`]). //! -//! Loading (and if `git` feature is enabled also downloading) is not specific to `station`: a sniffer, a -//! simulator, or any other tool that reads an ADJ needs exactly the same -//! parsing. Scope for this iteration: no `sockets.json`, no +//! [`load_from_dir`] loads an existing ADJ directory. With the `git` feature +//! enabled, `auto_adj` updates the ADJ repository before loading its data +//! and returns the checked-out commit hash. +//! +//! Loading is not specific to `station`: a sniffer, a simulator, or any +//! other tool that reads an ADJ needs exactly the same parsing. +//! +//! Scope for this iteration: no `sockets.json`, no //! `period`/`period_type`/`socket` packet fields (matches //! [`crate::model::PacketDef`]'s own omission), and no schema validation //! (`adj::validate` is a separate, deliberately out-of-scope concern for -//! now) — this module only surfaces structural errors it cannot avoid, +//! now). This module only surfaces structural errors it cannot avoid, //! e.g. a packet referencing a measurement alias that doesn't exist. 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")] +use tracing::{info, instrument}; + pub use error::{LoadError, MeasurementError, ProtectionError}; pub use info::{AdjInfo, ProtectionTypeInfo}; pub use raw::load_from_dir; +#[cfg(feature = "git")] +use crate::git::{unwrap_repo_path, update_adj}; use crate::model::PodData; /// The result of loading an ADJ: the vehicle's data (as [`crate::model`] @@ -31,3 +50,45 @@ pub struct Adj { /// Backend-session metadata from `general_info.json`. pub info: AdjInfo, } + +/// The result of [`auto_adj`]: the loaded ADJ data and the checked-out commit hash. +#[cfg(feature = "git")] +#[derive(Debug, Clone)] +pub struct AutoAdj { + /// Vehicle data + pub adj: Adj, + /// Full commit hash of the repository checkout used to load the ADJ. + pub hash: String, +} + +/// Updates the ADJ repository and returns an [`AutoAdj`] containing the loaded +/// data and the full commit hash of the checkout used to load it. +/// +/// `path` identifies the repository directory, not its parent. If omitted, +/// the platform's user cache directory is used. +/// +/// Online, the repository is replaced and local edits and commits are discarded. +/// Offline, the current cached checkout is loaded without switching branches, +/// so it may differ from `branch`; `hash` is the full commit hash of its HEAD. +/// If no cached repository is available offline, or a Git operation fails, +/// returns [`LoadError::Git`] instead of an [`AutoAdj`], so no hash is returned. +/// Clone failures do not fall back to the cache. +/// +/// This performs blocking network and filesystem operations. Call during startup, +/// before readers use ADJ, with only one updater at a time. +/// +/// # Errors +/// +/// Returns [`LoadError::Git`] if path resolution or the update fails. +/// Other variants report failures loading the checked-out ADJ data. +/// Loading failures do not restore the previous cache. +#[cfg(feature = "git")] +#[instrument(level = "debug")] +pub fn auto_adj(path: Option, branch: &str) -> Result { + let repo_path = unwrap_repo_path(path)?; + let hash = update_adj(Some(repo_path.clone()), branch)?; + let adj = load_from_dir(&repo_path)?; + + info!(path = ?repo_path, %hash, "ADJ loaded"); + Ok(AutoAdj { adj, hash }) +} 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/error.rs b/backend/crates/core/src/adj/error.rs index 53fcf1bed..04a1e0ba4 100644 --- a/backend/crates/core/src/adj/error.rs +++ b/backend/crates/core/src/adj/error.rs @@ -1,4 +1,4 @@ -//! Errors produced while loading an ADJ. +//! Errors produced while acquiring or loading an ADJ. //! //! Layered on purpose: [`LoadError`] is the only public error type here — //! the one a composition root's own aggregate error would `#[from]`-chain @@ -10,7 +10,10 @@ use std::net::AddrParseError; use std::path::PathBuf; -/// An error produced while loading an ADJ directory into an [`crate::adj::Adj`]. +#[cfg(feature = "git")] +use crate::git::GitError; + +/// An error produced while acquiring or loading an [`crate::adj::Adj`]. #[derive(Debug, thiserror::Error)] pub enum LoadError { /// Couldn't read a file. @@ -118,6 +121,11 @@ pub enum LoadError { #[source] source: MeasurementError, }, + + /// Couldn't resolve the ADJ repository path or update its checkout. + #[cfg(feature = "git")] + #[error("couldn't prepare ADJ repository: {0}")] + Git(#[from] GitError), } /// An error converting a raw measurement into [`crate::model::Measurement`]. 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.rs b/backend/crates/core/src/git.rs new file mode 100644 index 000000000..3418342c0 --- /dev/null +++ b/backend/crates/core/src/git.rs @@ -0,0 +1,11 @@ +//! Blocking Git helpers for ADJ, an application-owned, replaceable data cache. + +mod clone; +mod error; +mod repository; +mod update; + +pub use error::{CloneError, GitError, RepositoryError}; +pub use repository::{branch_exists, list_remote_branches, open_repo}; +pub(crate) use update::unwrap_repo_path; +pub use update::update_adj; diff --git a/backend/crates/core/src/git/README.md b/backend/crates/core/src/git/README.md new file mode 100644 index 000000000..ef4cb55c4 --- /dev/null +++ b/backend/crates/core/src/git/README.md @@ -0,0 +1,82 @@ +# ADJ Git helpers + +This module downloads and updates the local [ADJ repository](https://github.com/Hyperloop-UPV/adj) using [`gix`](https://crates.io/crates/gix), with [`tracing`](https://crates.io/crates/tracing) for logging. It supports branch selection and offline use of an existing local checkout. + +## Workflow + +`update_adj(path, branch)` returns the full hash of the checked-out commit. +A custom path identifies the ADJ repository itself. The default is +`/hyperloop-control-station/adj`, using `dirs::cache_dir()`. +An existing invalid repository or inaccessible path returns an error. + +The existing connectivity check attempts a TCP connection to `1.1.1.1:443` +with a three-second timeout. This checks external TCP connectivity, not GitHub +availability. + +### Online + +Online updates require a non-empty branch. They replace the local checkout and +do not preserve local edits or commits. + +- Shallow-clone the requested branch into a temporary directory beside ADJ. +- Complete checkout and read its commit hash before touching the cache. +- Move the old cache aside and install the new checkout. +- Restore the old cache if installation fails. If restoration also fails, + preserve the backup and include its location in the error. +- Remove the old cache after successful installation. + +A clone error leaves the old cache untouched and is returned directly; it does +not automatically fall back to offline operation. No separate fetch of the +existing cache, merge, or branch switch is needed because the checkout is replaced. + +### Offline + +- If ADJ exists, return its current commit hash without updating or switching branches. +- Otherwise, return `ADJ is not available locally and cannot be downloaded`. + +The cached branch may differ from the requested branch when offline. + +### Empty Branch + +Passing `branch = ""` skips downloading and replacing ADJ, even when online. + +- If a cached repository exists, return its current commit hash without updating + or switching branches, preserving local edits and commits. +- Otherwise, return `GitError::UnavailableOffline`, even if connectivity is available. + +The connectivity probe still runs when the branch is empty. + +## Other Helpers + +- `open_repo` opens the custom or default repository path. +- `list_remote_branches(repo)` queries the default fetch remote and returns sorted short + branch names, without downloading objects or updating local references. It + requires remote access and does not fall back to cached branches on failure. +- `branch_exists(repo, name)` uses that listing to check an exact short branch + name. Query errors are propagated; `false` means a successful query did not + find the branch, not that the remote was unreachable. + +## Limitations + +Replacement is intended for startup, before the backend reads ADJ, with one +updater at a time. The backup and installation renames are not jointly atomic +across a process crash. The connectivity probe can succeed when GitHub is +unreachable, or fail when GitHub is reachable. + +## Errors + +Public helpers return `GitError` with five categories: `Path`, `Repository`, +`Clone`, `Replacement`, and `UnavailableOffline`. `RepositoryError` and +`CloneError` group the concrete `gix` causes inside the corresponding categories. +If rollback fails, `Replacement` also retains the restoration error and backup +path for recovery. + +## Verification + +Tests use temporary local Git repositories and the Git CLI to create fixtures; +they do not require external network access. Production Git operations use `gix`. + +```bash +cargo test -p software-core -F git +cargo doc --open -p software-core -F git --no-deps +``` diff --git a/backend/crates/core/src/git/clone.rs b/backend/crates/core/src/git/clone.rs new file mode 100644 index 000000000..bccc73c9f --- /dev/null +++ b/backend/crates/core/src/git/clone.rs @@ -0,0 +1,222 @@ +use super::{ + error::{CloneError, GitError}, + update::get_commit_hash, +}; +use gix::Repository; +use std::{fs, path::Path, sync::atomic::AtomicBool}; +use tracing::{debug, info, instrument, warn}; + +const GIT_REMOTE: &str = "origin"; + +// Fetch and check out the requested branch instead of switching an existing repo. +#[instrument(level = "debug", skip(url))] +fn git_clone(path: &Path, branch: &str, url: &str) -> Result { + // These synchronous startup operations do not currently expose cancellation. + let interrupt = AtomicBool::new(false); + + debug!(?path, branch, "preparing shallow ADJ clone"); + // A depth of one keeps the current snapshot without downloading full history. + let mut prepare = gix::prepare_clone(url, path) + .map_err(CloneError::from)? + .with_remote_name(GIT_REMOTE) + .map_err(CloneError::from)? + .with_ref_name(Some(branch)) + .map_err(CloneError::from)? + .with_shallow(gix::remote::fetch::Shallow::DepthAtRemote( + std::num::NonZeroU32::MIN, + )); + + let (mut checkout, _) = prepare + .fetch_then_checkout(gix::progress::Discard, &interrupt) + .map_err(CloneError::from)?; + debug!( + ?path, + branch, "ADJ fetch completed; checking out working tree" + ); + let (repo, _) = checkout + .main_worktree(gix::progress::Discard, &interrupt) + .map_err(CloneError::from)?; + + debug!(?path, branch, "ADJ clone and checkout completed"); + Ok(repo) +} + +// Stage beside ADJ so both installation and rollback use same-filesystem renames. +#[instrument(level = "debug", skip(url))] +pub(crate) fn git_replace(path: &Path, branch: &str, url: &str) -> Result { + // A relative path like "adj" has an empty parent; stage in the current directory. + let parent = path + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + fs::create_dir_all(parent).map_err(GitError::Path)?; + let staging = tempfile::Builder::new() + .prefix(".adj-") + .tempdir_in(parent) + .map_err(GitError::Path)?; + let checkout = staging.path().join("new"); + let backup = staging.path().join("old"); + debug!(?checkout, ?backup, "created ADJ staging directory"); + + // Validate the new checkout and commit before touching the current cache. + // Early errors drop the staging directory, removing any incomplete clone. + let repo = git_clone(&checkout, branch, url)?; + let commit = get_commit_hash(&repo)?; + // The repository contains paths into staging and must not survive the move. + drop(repo); + + let had_cache = path.try_exists().map_err(GitError::Path)?; + if had_cache { + fs::rename(path, &backup).map_err(|source| GitError::Replacement { + source, + rollback: None, + })?; + debug!(?path, ?backup, "moved cached ADJ aside for replacement"); + } + if let Err(error) = fs::rename(&checkout, path) { + debug!(?path, %error, had_cache, "ADJ installation failed; restoring cache if present"); + if had_cache && let Err(rollback) = fs::rename(&backup, path) { + // Do not let temporary-directory cleanup delete the only remaining cache. + let saved = staging.keep(); + debug!(?backup, %rollback, "preserved ADJ backup after failed rollback"); + return Err(GitError::Replacement { + source: error, + rollback: Some((rollback, saved.join("old"))), + }); + } + if had_cache { + debug!(?path, "restored cached ADJ after installation failure"); + } + return Err(GitError::Replacement { + source: error, + rollback: None, + }); + } + + // Installation succeeded; cleanup now discards the old cache. A cleanup + // failure does not turn a successfully installed checkout into an error. + if let Err(error) = staging.close() { + warn!(?path, %error, "ADJ updated, but temporary directory cleanup failed"); + } + info!(?path, branch, commit = %commit, "ADJ updated"); + Ok(commit) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::{io, process::Command}; + + fn git(path: &Path, args: &[&str]) -> Result<(), Box> { + // Fixture commits need identity; disable signing, hooks, and templates + // so tests do not depend on the user's normal Git setup. + let output = Command::new("git") + .current_dir(path) + .args([ + "-c", + "user.name=ADJ tests", + "-c", + "user.email=adj@example.test", + "-c", + "commit.gpgSign=false", + "-c", + "core.hooksPath=", + "-c", + "init.templateDir=", + ]) + .args(args) + .output()?; + if !output.status.success() { + return Err(io::Error::other(String::from_utf8_lossy(&output.stderr)).into()); + } + Ok(()) + } + + fn source_repo(path: &Path) -> Result<(), Box> { + fs::create_dir(path)?; + git(path, &["init", "--initial-branch=main"])?; + fs::write(path.join("data.txt"), "main")?; + git(path, &["add", "."])?; + git(path, &["commit", "-m", "main data"])?; + // Leave HEAD on another branch to verify explicit clone branch selection. + git(path, &["checkout", "-b", "testing"])?; + fs::write(path.join("data.txt"), "testing")?; + git(path, &["commit", "-am", "testing data"]) + } + + // Verify branch selection, newer commits, and removal of stale cache files. + #[test] + fn clones_and_replaces_with_requested_branch() + -> Result<(), Box> { + let temp = tempfile::tempdir()?; + let source = temp.path().join("source"); + let cache = temp.path().join("cache").join("adj"); + source_repo(&source)?; + let url = source.to_str().ok_or("non-UTF-8 test path")?; + + let first = git_replace(&cache, "main", url)?; + let main_hash = gix::open(&source)? + .find_reference("refs/heads/main")? + .id() + .to_string(); + assert_eq!(first, main_hash); + assert_eq!(fs::read_to_string(cache.join("data.txt"))?, "main"); + // Replacement must discard old cache files, not just update tracked ones. + fs::write(cache.join("stale.txt"), "discard this cache file")?; + + // Add a newer remote commit and request a different branch on replacement. + fs::write(source.join("data.txt"), "latest testing")?; + git(&source, &["commit", "-am", "updated testing data"])?; + let expected = get_commit_hash(&gix::open(&source)?)?; + assert_eq!(git_replace(&cache, "testing", url)?, expected); + assert_ne!(first, expected); + assert_eq!(get_commit_hash(&gix::open(&cache)?)?, expected); + assert_eq!( + fs::read_to_string(cache.join("data.txt"))?, + "latest testing" + ); + assert!(!cache.join("stale.txt").exists()); + // Successful replacement must also remove staging and backup directories. + assert_eq!( + fs::read_dir(cache.parent().ok_or("missing parent")?)?.count(), + 1 + ); + Ok(()) + } + + // Verify clone failures preserve cached ADJ and leave no staging debris. + #[test] + fn failed_clone_preserves_existing_cache() + -> Result<(), Box> { + let temp = tempfile::tempdir()?; + let source = temp.path().join("source"); + let cache = temp.path().join("adj"); + source_repo(&source)?; + let url = source.to_str().ok_or("non-UTF-8 test path")?; + + // A failed first clone must not install a partial checkout. + assert!(git_replace(&cache, "missing-branch", url).is_err()); + assert!(!cache.exists()); + let expected = git_replace(&cache, "main", url)?; + fs::write(cache.join("stale.txt"), "keep on failure")?; + // Both an invalid branch and an unavailable source must leave ADJ intact. + assert!(git_replace(&cache, "missing-branch", url).is_err()); + let missing = temp.path().join("missing-source"); + assert!( + git_replace( + &cache, + "main", + missing.to_str().ok_or("non-UTF-8 test path")? + ) + .is_err() + ); + assert_eq!(get_commit_hash(&gix::open(&cache)?)?, expected); + assert_eq!(fs::read_to_string(cache.join("data.txt"))?, "main"); + assert_eq!( + fs::read_to_string(cache.join("stale.txt"))?, + "keep on failure" + ); + assert_eq!(fs::read_dir(temp.path())?.count(), 2); + Ok(()) + } +} diff --git a/backend/crates/core/src/git/error.rs b/backend/crates/core/src/git/error.rs new file mode 100644 index 000000000..ec3c3f69b --- /dev/null +++ b/backend/crates/core/src/git/error.rs @@ -0,0 +1,121 @@ +/// Errors produced while reading, downloading, or replacing the ADJ cache. +/// +/// Five categories identify the failed operation and preserve its underlying +/// error as [`std::error::Error::source`]. [`RepositoryError`] and [`CloneError`] +/// retain concrete `gix` causes and are boxed to keep this enum small. +/// +/// A failed connectivity probe is not itself an error when cached ADJ exists. +/// If no cache exists, the operation returns [`GitError::UnavailableOffline`]. +#[derive(Debug, thiserror::Error)] +pub enum GitError { + /// Resolving, inspecting, or preparing the cache directory failed. + #[error("ADJ path operation failed: {0}")] + Path(#[source] std::io::Error), + + /// Opening the repository, reading HEAD, or querying local or remote refs failed. + /// A branch missing from a successful remote listing is not an error. + #[error("ADJ repository operation failed: {0}")] + Repository(#[source] Box), + + /// Preparing, downloading, or checking out the requested branch failed. + /// + /// This can indicate a network, configuration, or remote-reference failure; + /// it does not necessarily mean that internet connectivity is unavailable. + #[error("ADJ clone failed: {0}")] + Clone(#[source] Box), + + /// Moving the old cache aside or installing the new checkout failed. + /// + /// When restoration also fails, `rollback` holds its error and the preserved + /// backup's location. Otherwise, the old cache was restored or never moved. + #[error( + "ADJ cache replacement failed: {source}{recovery}", + recovery = .rollback.as_ref().map(|(error, path)| { + format!("; rollback failed: {error}; backup kept at {}", path.display()) + }).unwrap_or_default() + )] + Replacement { + /// The original error moving the old cache or installing the new checkout. + #[source] + source: std::io::Error, + /// Restoration error and preserved backup path, if rollback failed. + rollback: Option<(std::io::Error, std::path::PathBuf)>, + }, + + /// The connectivity probe failed and no local ADJ cache was available. + #[error("ADJ is not available locally and cannot be downloaded")] + UnavailableOffline, +} + +// Convert repository errors for '?' propagation, boxing the concrete error to keep GitError small. +impl From for GitError { + fn from(error: RepositoryError) -> Self { + Self::Repository(Box::new(error)) + } +} + +// Convert clone errors for '?' propagation, boxing the concrete error to keep GitError small. +impl From for GitError { + fn from(error: CloneError) -> Self { + Self::Clone(Box::new(error)) + } +} + +/// Concrete clone failures wrapped by [`GitError::Clone`]. +/// +/// Preparation, name validation, fetching, and checkout expose different `gix` +/// error types. These variants retain each original error as their source. +#[derive(Debug, thiserror::Error)] +pub enum CloneError { + /// Clone preparation failed before downloading repository data. + #[error("clone preparation failed: {0}")] + Prepare(#[from] gix::clone::Error), + + /// The configured remote name was invalid. + #[error("remote name is invalid: {0}")] + RemoteName(#[from] gix::remote::name::Error), + + /// The requested branch name was not a valid Git reference name. + #[error("branch name is invalid: {0}")] + BranchName(#[from] gix::validate::reference::name::Error), + + /// Fetching failed, including a missing requested branch. + /// This can indicate network, configuration, or remote-reference failures. + #[error("fetch failed: {0}")] + Fetch(#[from] gix::clone::fetch::Error), + + /// Downloaded data could not be checked out into the working tree. + #[error("checkout failed: {0}")] + Checkout(#[from] gix::clone::checkout::main_worktree::Error), +} + +/// Concrete repository failures wrapped by [`GitError::Repository`]. +/// +/// Variants identify local reads or remote-reference queries and preserve the +/// original `gix` error as their source. +#[derive(Debug, thiserror::Error)] +pub enum RepositoryError { + /// An existing repository could not be opened or validated. + #[error("repository could not be opened: {0}")] + Open(#[from] gix::open::Error), + + /// HEAD could not be resolved to a commit ID, including an unborn HEAD. + #[error("HEAD could not be resolved: {0}")] + Head(#[from] gix::reference::head_id::Error), + + /// No default fetch remote could be determined, including ambiguous configurations. + #[error("no default fetch remote could be determined")] + NoDefaultRemote, + + /// The selected default remote could not be loaded from repository configuration. + #[error("default fetch remote could not be loaded: {0}")] + FindDefaultRemote(#[from] gix::remote::find::existing::Error), + + /// A transport connection to the selected remote could not be prepared. + #[error("remote connection failed: {0}")] + RemoteConnect(#[from] gix::remote::connect::Error), + + /// The remote handshake or query of advertised references failed. + #[error("remote reference query failed: {0}")] + RemoteRefMap(#[from] gix::remote::ref_map::Error), +} diff --git a/backend/crates/core/src/git/repository.rs b/backend/crates/core/src/git/repository.rs new file mode 100644 index 000000000..22e16b294 --- /dev/null +++ b/backend/crates/core/src/git/repository.rs @@ -0,0 +1,254 @@ +use super::{ + error::{GitError, RepositoryError}, + update::unwrap_repo_path, +}; +use gix::Repository; +use std::path::PathBuf; +use tracing::{debug, instrument}; + +/// Opens an existing repository without fetching or changing its checkout. +/// +/// `path` is the repository directory. If omitted, it defaults to +/// `/hyperloop-control-station/adj`. This does not create ADJ. +/// +/// # Errors +/// +/// Returns [`GitError::Path`] if the cache directory cannot be resolved, or +/// [`GitError::Repository`] if the repository is missing, invalid, or inaccessible. +#[instrument(level = "debug", err(level = "warn"))] +pub fn open_repo(path: Option) -> Result { + let path = unwrap_repo_path(path)?; + + let repo = gix::open(path).map_err(RepositoryError::from)?; + + debug!(git_dir = ?repo.path(), "opened repository"); + Ok(repo) +} + +/// Lists the branch names advertised by the repository's default fetch remote. +/// +/// `repo` supplies the configuration used to select the default fetch remote. +/// Returns sorted short names such as `main` or `feature/example`, excluding tags +/// and `HEAD`. Queries the remote without downloading objects or updating local +/// references. Configured fetch refspecs do not limit the advertised branches. +/// This is a blocking operation and requires access to the remote. +/// +/// # Errors +/// +/// Returns [`GitError::Repository`] if no default remote can be determined, or +/// remote configuration, connection, or reference discovery fails. Does not fall +/// back to cached branches on failure. +#[instrument(level = "debug", skip(repo), err(level = "warn"))] +pub fn list_remote_branches(repo: &Repository) -> Result, GitError> { + let remote = repo + .find_default_remote(gix::remote::Direction::Fetch) + .ok_or(RepositoryError::NoDefaultRemote)? + .map_err(RepositoryError::from)?; + + debug!( + git_dir = ?repo.path(), + "querying branches advertised by the default fetch remote" + ); + let conexion = remote + .connect(gix::remote::Direction::Fetch) + .map_err(RepositoryError::from)?; + let (mapa, _handshake) = conexion + .ref_map( + gix::progress::Discard, + gix::remote::ref_map::Options { + // Protocol v2 must not restrict ls-refs to a single-branch refspec. + prefix_from_spec_as_filter_on_remote: false, + ..Default::default() + }, + ) + .map_err(RepositoryError::from)?; + + let mut ramas: Vec = mapa + .remote_refs + .iter() + .filter_map(|r| { + let (nombre, _, _) = r.unpack(); + nombre + .to_string() + .strip_prefix("refs/heads/") + .map(str::to_string) + }) + .collect(); + + ramas.sort(); + debug!( + git_dir = ?repo.path(), + count = ramas.len(), + "listed advertised remote branches" + ); + Ok(ramas) +} + +/// Checks whether the default fetch remote advertises the requested branch. +/// +/// `repo` selects the remote and `name` is its exact short branch name, such as +/// `main` or `feature/example`, without an `origin/` prefix. Calls +/// [`list_remote_branches`] and returns `true` if the name is in the result. +/// `false` means the query succeeded but the remote did not advertise that name. +/// This is a blocking remote query, not a check of cached references. +/// +/// # Errors +/// +/// Propagates the original [`GitError`] from [`list_remote_branches`]. A missing +/// remote or failed connection is an error, never `Ok(false)`. +// The delegated listing logs failures; do not emit the same warning twice. +#[instrument(level = "debug", skip(repo))] +pub fn branch_exists(repo: &Repository, name: &str) -> Result { + let branches = list_remote_branches(repo)?; + let exists = branches.iter().any(|branch| branch == name); + debug!(name, exists, "checked advertised remote branch"); + Ok(exists) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::{fs, io, path::Path, process::Command}; + + type TestResult = Result>; + + fn git(path: &Path, args: &[&str]) -> TestResult { + // Provide fixture identity and disable user signing, hooks, and templates. + let output = Command::new("git") + .current_dir(path) + .args([ + "-c", + "user.name=ADJ tests", + "-c", + "user.email=adj@example.test", + "-c", + "commit.gpgSign=false", + "-c", + "tag.gpgSign=false", + "-c", + "core.hooksPath=", + "-c", + "init.templateDir=", + ]) + .args(args) + .output()?; + if !output.status.success() { + return Err(io::Error::other(String::from_utf8_lossy(&output.stderr)).into()); + } + Ok(()) + } + + fn local_remote() -> TestResult<(tempfile::TempDir, Repository)> { + let temp = tempfile::tempdir()?; + let remote = temp.path().join("remote"); + let client = temp.path().join("client"); + fs::create_dir(&remote)?; + fs::create_dir(&client)?; + git(&remote, &["init", "--initial-branch=main"])?; + fs::write(remote.join("data.txt"), "ADJ fixture")?; + git(&remote, &["add", "."])?; + git(&remote, &["commit", "-m", "fixture data"])?; + git(&remote, &["branch", "software"])?; + git(&remote, &["branch", "feature/example"])?; + git(&remote, &["tag", "v1"])?; + + // No clone or fetch: only main is tracked, and no remote refs are cached. + git(&client, &["init", "--initial-branch=main"])?; + git( + &client, + &[ + "remote", + "add", + "-t", + "main", + "origin", + remote.to_str().ok_or("non-UTF-8 test path")?, + ], + )?; + // Exercise ls-refs prefix filtering rather than protocol v1's full advertisement. + git(&client, &["config", "protocol.version", "2"])?; + let repo = gix::open(&client)?; + Ok((temp, repo)) + } + + // List all advertised branches despite a main-only refspec, without fetching. + #[test] + fn lists_all_remote_branches_without_fetching() -> TestResult { + let (temp, repo) = local_remote()?; + assert_eq!( + list_remote_branches(&repo)?, + ["feature/example", "main", "software"] + ); + for name in ["feature/example", "main", "software"] { + let reference = format!("refs/remotes/origin/{name}"); + assert!(repo.try_find_reference(reference.as_str())?.is_none()); + } + let remote_commit = gix::open(temp.path().join("remote"))?.head_id()?.detach(); + assert!(repo.find_object(remote_commit).is_err()); + Ok(()) + } + + // Remote existence must not depend on having the branch cached locally. + #[test] + fn finds_uncached_remote_branch() -> TestResult { + let (_temp, repo) = local_remote()?; + assert!( + repo.try_find_reference("refs/remotes/origin/feature/example")? + .is_none() + ); + assert!(branch_exists(&repo, "feature/example")?); + Ok(()) + } + + // Only exact short names match after a successful remote query. + #[test] + fn rejects_missing_and_remote_prefixed_branch_names() -> TestResult { + let (_temp, repo) = local_remote()?; + assert!(!branch_exists(&repo, "missing-branch")?); + assert!(!branch_exists(&repo, "origin/main")?); + Ok(()) + } + + // Missing remote configuration is an explicit error for both helpers. + #[test] + fn propagates_missing_default_remote() -> TestResult { + let temp = tempfile::tempdir()?; + let repo = gix::init(temp.path())?; + for result in [ + list_remote_branches(&repo).map(|_| ()), + branch_exists(&repo, "main").map(|_| ()), + ] { + assert!(matches!(result, Err(GitError::Repository(error)) + if matches!(*error, RepositoryError::NoDefaultRemote))); + } + Ok(()) + } + + // An unreachable source must remain an error, not false or an empty listing. + #[test] + fn propagates_inaccessible_remote() -> TestResult { + let (temp, _) = local_remote()?; + let client = temp.path().join("client"); + let missing = temp.path().join("missing-remote"); + git( + &client, + &[ + "remote", + "set-url", + "origin", + missing.to_str().ok_or("non-UTF-8 test path")?, + ], + )?; + // Reopen to pick up the changed remote URL instead of the old config snapshot. + let repo = gix::open(&client)?; + for result in [ + list_remote_branches(&repo).map(|_| ()), + branch_exists(&repo, "main").map(|_| ()), + ] { + assert!(matches!(result, Err(GitError::Repository(error)) + if matches!(*error, + RepositoryError::RemoteConnect(_) | RepositoryError::RemoteRefMap(_)))); + } + Ok(()) + } +} diff --git a/backend/crates/core/src/git/update.rs b/backend/crates/core/src/git/update.rs new file mode 100644 index 000000000..6e58684dc --- /dev/null +++ b/backend/crates/core/src/git/update.rs @@ -0,0 +1,146 @@ +use super::{GitError, RepositoryError, clone::git_replace}; +use gix::Repository; +use std::{ + io, + net::{Ipv4Addr, SocketAddr, TcpStream}, + path::PathBuf, + time::Duration, +}; +use tracing::{debug, info, instrument, warn}; + +const ADJ_URL: &str = "https://github.com/Hyperloop-UPV/adj.git"; + +/// Updates ADJ to the requested branch or uses the existing application-managed cache. +/// +/// `path` is the repository directory, not its parent. If omitted, it defaults to +/// `/hyperloop-control-station/adj`. `branch` selects the branch +/// to clone when non-empty and the connectivity probe succeeds. +/// +/// With a non-empty branch and connectivity, local edits and commits are discarded +/// only after a fresh checkout succeeds. Offline, the current cached checkout is +/// used without switching branches, so it may differ from `branch`. +/// +/// An empty `branch` ("") uses the cached checkout without updating or switching +/// branches, preserving local edits and commits regardless of connectivity. +/// The connectivity probe still runs. Returns the checked-out commit's full hash. +/// +/// This performs blocking network and filesystem operations. Call during startup, +/// before readers use ADJ, with only one updater at a time. Replacement uses two +/// renames and is not atomic across a process crash. +/// +/// # Errors +/// +/// Returns [`GitError::UnavailableOffline`] if ADJ is missing offline. Other +/// variants identify path, repository, cloning, checkout, or replacement failures. +/// Clone errors do not automatically fall back to the cache. If restoration fails, +/// [`GitError::Replacement`] preserves both errors and the backup's location. +// Log returned errors at the public boundary; helpers trace progress without duplicate warnings. +#[instrument(level = "debug", err(level = "warn"))] +pub fn update_adj(path: Option, branch: &str) -> Result { + let (repo, dir) = adj_exists_repo(path)?; + + 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.is_empty() { + warn!(path = ?dir, requested_branch = branch, + "branch not specified; using cached ADJ with current branch"); + } else { + warn!(path = ?dir, requested_branch = branch, + "connectivity probe failed; using cached ADJ without switching branches"); + } + get_commit_hash(&repo) + } else { + Err(GitError::UnavailableOffline) + } +} + +// Checks external TCP connectivity with a three-second timeout, not GitHub availability. +#[instrument(level = "info")] +fn check_internet_connection() -> bool { + // Use a fixed IPv4 address to avoid a separate DNS lookup and its timeout. + let address = SocketAddr::from((Ipv4Addr::new(1, 1, 1, 1), 443)); + let timeout = Duration::from_secs(3); + + // Attempt only the TCP handshake; no application data is sent. + match TcpStream::connect_timeout(&address, timeout) { + Ok(_stream) => { + info!(%address, "connectivity probe succeeded"); + true + } + Err(error) => { + // Record why the probe failed without treating it as an application error. + info!(%address, %error, "connectivity probe failed"); + false + } + } +} + +// Preserve explicit paths; otherwise use the platform's user cache directory. +pub(crate) fn unwrap_repo_path(path: Option) -> Result { + let dir = match path { + Some(path) => path, + None => { + let path = dirs::cache_dir().ok_or_else(|| { + GitError::Path(io::Error::new( + io::ErrorKind::NotFound, + "cache directory not found", + )) + })?; + + path.join("hyperloop-control-station").join("adj") + } + }; + + debug!(path = ?dir, "resolved ADJ repository path"); + Ok(dir) +} + +// Only an absent directory is a cache miss; invalid repositories remain errors. +pub(crate) fn adj_exists_repo( + path: Option, +) -> Result<(Option, PathBuf), GitError> { + let dir = unwrap_repo_path(path)?; + + let res = if dir.try_exists().map_err(GitError::Path)? { + Some(gix::open(&dir).map_err(RepositoryError::from)?) + } else { + None + }; + + debug!(path = ?dir, exists = res.is_some(), "checked local ADJ repository"); + Ok((res, dir)) +} + +// Report the checked-out HEAD, which can differ from the requested branch offline. +pub(crate) fn get_commit_hash(repo: &Repository) -> Result { + let hash = repo.head_id().map_err(RepositoryError::from)?.to_string(); + + // Log only the commit ID, not potentially large or sensitive message text. + debug!(commit = %hash, "read checked-out ADJ commit"); + Ok(hash) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + + // Distinguish missing, invalid, and valid local repositories. + #[test] + fn detects_missing_and_invalid_repositories() + -> Result<(), Box> { + let temp = tempfile::tempdir()?; + let path = temp.path().join("adj"); + assert!(adj_exists_repo(Some(path.clone()))?.0.is_none()); + fs::create_dir(&path)?; + assert!(adj_exists_repo(Some(path.clone())).is_err()); + gix::init(&path)?; + assert!(adj_exists_repo(Some(path))?.0.is_some()); + Ok(()) + } +} diff --git a/backend/crates/core/src/lib.rs b/backend/crates/core/src/lib.rs index 573dd787e..a0644a70c 100644 --- a/backend/crates/core/src/lib.rs +++ b/backend/crates/core/src/lib.rs @@ -2,13 +2,20 @@ pub mod hello_world; -/// Basic domain types: identifiers, values, measurements, protections, -/// packets and boards. -pub mod model; +/// # Git module +/// Handles updates and changes within the ADJ. +/// Checks the ADJ Github repository and +#[cfg(feature = "git")] +pub mod git; + /// NTP server #[cfg(feature = "ntp")] pub mod ntp; +/// Basic domain types: identifiers, values, measurements, protections, +/// packets and boards. +pub mod model; + /// Parses an ADJ (Architecture Description JSON) directory into /// [`model::PodData`], plus backend-session metadata not modeled as /// vehicle data. See [`adj::load_from_dir`]. @@ -23,3 +30,14 @@ pub mod protocol; /// into [`protocol`] to decode. See [`net::tcp`], [`net::udp`]. #[cfg(feature = "net")] pub mod net; + +// 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 +/// snapshot of the machine that produced them ([`logger::host`], +/// feature `host`). The policy — which files a recording has, what goes +/// in each row — belongs to whoever calls this. +#[cfg(feature = "logger")] +pub mod logger; diff --git a/backend/crates/core/src/logger.rs b/backend/crates/core/src/logger.rs new file mode 100644 index 000000000..6d2146c27 --- /dev/null +++ b/backend/crates/core/src/logger.rs @@ -0,0 +1,111 @@ +//! Plain, synchronous file writing: the one place that knows how to put +//! a CSV row, a line of text or a JSON document on disk without +//! corrupting it. +//! +//! Deliberately boring, and deliberately small. It knows nothing about +//! the vehicle — no [`crate::model`] types, no ADJ, no boards, no +//! recording session, no notion of a timestamp or of a log level. +//! Deciding *what* to write, *when*, and under which name is the job of +//! the backend's own `station::logging`, which will own the four +//! subloggers (data, protections, messages and orders), the session +//! directory and the hot enable/disable. This module only answers "how +//! do I write this file". +//! +//! What it buys over calling [`std::fs`] from each of those subloggers: +//! +//! - **Flushing is explicit.** [`crate::logger::CsvFile::close`] and [`crate::logger::CsvFile::flush`] +//! return a `Result`. A fatal error in the backend ends in +//! `std::process::exit`, which runs no destructor, so a file that only +//! flushes when it is dropped loses its tail exactly in the case the +//! log was there to explain. [`Drop`] is kept as a courtesy flush that +//! traces its own failure, never as the plan. *When* to flush stays +//! the caller's decision, but it doesn't have to keep its own tally to +//! make it: every file reports its `bytes_since_flush`, so "flush +//! every so many kilobytes, or every so often" is a couple of lines +//! over a map of open files. +//! - **Errors name the file.** A bare [`std::io::Error`] says what went +//! wrong but not where; every [`crate::logger::Error`] here carries the path or the +//! label of the file it happened on. +//! - **A row can't silently go out of step.** A [`crate::logger::CsvFile`] knows its +//! header, so a row with one field too few is an error, not a file +//! whose columns are shifted from that line on. +//! - **Quoting is done once, here.** A board's free-text message and the +//! path it came from can both contain commas, quotes and newlines. +//! [`crate::logger::Row::text`] quotes per RFC 4180; four subloggers formatting their +//! own lines would each get a chance to get that wrong. +//! - **A row allocates nothing.** Fields are formatted into a buffer the +//! file reuses, not into a `Vec` built and thrown away per +//! row — at telemetry rates that is tens of thousands of rows a +//! second. +//! +//! The three formats are *not* one abstraction, and that is deliberate. +//! What they share is how a file is **held** — the label it answers to +//! in its errors, the poisoning after a failed write, the explicit +//! flush, the courtesy flush on drop — and that lives in one private +//! place (`target`), so it is one behaviour instead of three copies of +//! it that drift apart. What they don't share is how a file is +//! **written**, because it genuinely isn't the same operation: a CSV row +//! is typed fields validated against a header, a text line is a string +//! taken verbatim, and a JSON document is a whole value serialized in +//! one go with no handle to keep. [`crate::logger::CsvFile`] and +//! [`crate::logger::TextFile`] therefore expose the same vocabulary — +//! `create`, `new`, `flush`, `close`, `get_ref`, `is_poisoned` — while +//! [`crate::logger::write_json`] stays a free function, since a file +//! written once and closed has no handle to give back. +//! +//! There is no public trait over the three. A trait would only pay for +//! itself once some caller needs to be generic over the format — the +//! same code path writing either CSV or JSON lines, say — and no caller +//! does today; reaching for one now would mean either flattening the +//! API down to "write these bytes", which throws away the field +//! validation and the quoting that are the point, or inventing an +//! open/write/close lifecycle for JSON that it doesn't have. Adding the +//! trait later is backwards compatible, so it can wait for the second +//! caller. +//! +//! Reading is in for JSON only ([`crate::logger::read_json`], +//! [`crate::logger::JsonDocument`]), and for one reason: a document that +//! gains properties over time can't be added to without being read +//! first. A CSV or a text log is appended to and never revisited, and +//! nothing here will read one back. +//! +//! Two neighbours live alongside the three formats, each behind its own +//! feature because neither is needed to write a file: +//! [`crate::logger::files`] (feature `files`) copies, moves and removes +//! them, which is what makes these types usable on a file that already +//! exists, and [`crate::logger::host`] (feature `host`) is the snapshot +//! of the machine that goes into a recording's metadata. Both are about +//! a recording's files rather than about a vehicle, which is why they +//! are here and not modules of their own; neither is used by `csv`, +//! `text` or `json`, which still know nothing about what they write. +//! +//! Not here, on purpose: reading a CSV or a text log back, sessions, timestamps, file +//! rotation, keeping a registry of many open files +//! (a `HashMap` with `entry().or_insert_with(...)` in the +//! caller is shorter and clearer than anything this module could wrap it +//! in), and anything asynchronous. These functions block; a caller +//! inside a `tokio` task is the one that decides whether to run them on +//! a thread of their own. + +mod csv; +mod error; +mod json; +mod target; +mod text; + +/// Copies, moves and removes files, creating the directories a +/// destination needs and naming the file in every error. See +/// [`files::copy_file`]. +#[cfg(feature = "files")] +pub mod files; + +/// A best-effort snapshot of the machine, the user and the build, for +/// the metadata of a recording. Nothing in it fails: what the system +/// won't say is left empty. See [`host::HostInfo`]. +#[cfg(feature = "host")] +pub mod host; + +pub use csv::{CsvFile, Row}; +pub use error::Error; +pub use json::{JsonDocument, read_json, write_json}; +pub use text::TextFile; diff --git a/backend/crates/core/src/logger/README.md b/backend/crates/core/src/logger/README.md new file mode 100644 index 000000000..c386b60a3 --- /dev/null +++ b/backend/crates/core/src/logger/README.md @@ -0,0 +1,408 @@ +# Logger Module (`logger`) + +Everything a recording needs on disk: writing CSV, text and JSON files +without knowing what is in them, moving those files around, and the +snapshot of the machine that produced them. + +Deliberately boring, and deliberately small. It knows nothing about the +vehicle — no `model` types, no ADJ, no boards, no session, no notion of a +timestamp or of a log level. Deciding **what** to write, **when**, and +under which name is the job of the backend's own `station::logging`, +which owns the subloggers (data, protections, messages and orders), the +session directory and the hot enable/disable. This module only answers +*"how do I write this file"*. + +Everything here blocks. A caller inside a `tokio` task is the one that +decides whether to run it on a thread of its own. + +--- + +## Directory Structure + +``` +logger/ +├── error.rs # `Error`: one variant per failure, every one naming its file +├── target.rs # private: the handle discipline the three formats share +├── csv.rs # `CsvFile`, `Row` — a CSV file that knows its header +├── text.rs # `TextFile` — one line at a time, verbatim +├── json.rs # `write_json`, `read_json`, `JsonDocument` +├── files.rs # `files` (feature `files`): copy, move, remove, size +│ └── error.rs # its own `Error`, naming both paths when there are two +└── host.rs # `host` (feature `host`): `HostInfo`, `open_file_limit` +``` + +Public API, re-exported at the module root: `CsvFile`, `Row`, `TextFile`, +`JsonDocument`, `read_json`, `write_json`, `Error`. The two submodules +stay namespaced (`logger::files`, `logger::host`) because they are used +far less often than the formats and read better qualified. + +--- + +## What It Buys Over Calling `std::fs` + +- **Flushing is explicit.** `close` and `flush` return a `Result`. A + fatal error in the backend ends in `std::process::exit`, which runs no + destructor, so a file that only flushes when it is dropped loses its + tail exactly in the case the log was there to explain. `Drop` is kept + as a courtesy flush that traces its own failure, never as the plan. + *When* to flush stays the caller's decision, but it doesn't have to + keep its own tally to make it: every file reports its + `bytes_since_flush`, so "flush every so many kilobytes, or every so + often" is a couple of lines over a map of open files. +- **Errors name the file.** A bare `std::io::Error` says what went wrong + but not where; every `Error` here carries the path or the label of the + file it happened on. +- **A row can't silently go out of step.** A `CsvFile` knows its header, + so a row with one field too few is an error, not a file whose columns + are shifted from that line on. +- **Quoting is done once, here.** A board's free-text message and the + path it came from can both contain commas, quotes and newlines; + `Row::text` quotes per RFC 4180. Four subloggers formatting their own + lines would each get a chance to get that wrong. +- **A row allocates nothing.** Fields are formatted into a buffer the + file reuses, not into a `Vec` built and thrown away per row — + at telemetry rates that is tens of thousands of rows a second. + +Nothing is traced per row, on purpose: that would be tens of thousands +of events per second. Only opening a file (`debug`), a copy or a move +(`debug`), and a failed flush on drop (`error`) are traced. + +--- + +## `target.rs` — The Shared Handle Discipline + +Private, and **not a trait**. `CsvFile` and `TextFile` differ in what +they put *in* a file (columns and quoting versus lines), not in how they +hold one, so the holding lives here once: + +| Behaviour | What it means | +| --- | --- | +| `label` | The name the file answers to in every `Error` — its path, or whatever a caller of `new` passed for an in-memory destination. | +| Poisoning | The first failed write or flush poisons the file: every later call returns `Error::Poisoned` instead of appending to something already inconsistent, or repeating the same I/O error once per row. | +| Explicit flush | `flush`/`close` report failure; `bytes_written` and `bytes_since_flush` are the counters a flush policy is built on. | +| Courtesy flush on drop | A file dropped without `close` is flushed best-effort, and a failure is traced (it cannot be returned, and the workspace lints rule out panicking). | + +It also owns the two ways a file is opened: + +- `create_file` — creates or truncates, creating parent directories, + behind a `BufWriter` of the default capacity (a bigger buffer is less + I/O but more lost if the process dies before the next flush, and that + trade is the caller's). +- `append_file` — opens for appending, creating the file and its parents + if needed, and reports how many bytes it already held. If that content + doesn't end in a newline, one is written first, so what gets appended + starts on its own line. That is the **only** thing looked at: what the + existing content *says* is never read or checked. + +--- + +## `csv.rs` — `CsvFile` and `Row` + +A CSV file written one row at a time, generic over its destination +(`CsvFile`, defaulting to `BufWriter`) so the format can +be exercised against an in-memory buffer. + +```rust +use software_core::logger::CsvFile; + +let mut csv = CsvFile::create("sessions/13/data/speed.csv", &["t_us", "origin", "value"])?; +csv.row().int(1_250).text("LCU, bay 2").num(53.2).end()?; +csv.flush()?; +csv.close()?; +``` + +**Constructors:** `create` (truncates, writes the header), `append` +(adds to the end; the header is written only if the file is new or +empty), `new` (wraps an already-open `W` with a label of its own). + +**A row:** `row()` starts one, then `int`, `num`, `bool` and `text` +append fields and `end()` validates and writes it. Every field method +keeps the first error it hits and returns `Self`, so a row reads as one +expression without a `?` per field; `end` is where that error — and the +field count — is reported. Nothing reaches the file until `end`, and a +row dropped without it writes nothing, so a row lands whole or not at +all, as a single `write_all`. + +**The header is the contract.** With a non-empty header, a row with a +different number of fields is an `Error::FieldCount` and is rejected +whole. An empty header writes no header line and leaves rows unchecked, +for a file whose columns aren't known up front. On `append`, the header +is *not* compared against what the file already holds — it is only taken +as a statement of how many fields a row has. The caller is the one who +knows that the file it opens is the file it thinks it is. + +**Formatting:** numbers and booleans are written with their `Display`, +i.e. the shortest form that round-trips (`1.0` is written `1`, and `NaN`, +`inf` and `-inf` are written as such rather than blanked — if a board +sent one, the log should say so). Only `text` can need quoting, and it is +the only one that does any: a field containing `,`, `"`, `\r` or `\n` is +wrapped in double quotes with inner quotes doubled, per RFC 4180. The +header goes through `Row` too, so a column name with a comma in it is +quoted the same way. + +**Also on the handle:** `flush`, `close`, `get_ref`, `is_poisoned`, +`label`, `bytes_written`, `bytes_since_flush` (see `target.rs` above). + +--- + +## `text.rs` — `TextFile` + +The same vocabulary as `CsvFile` — `create`, `append`, `new`, `flush`, +`close`, `get_ref`, `is_poisoned`, `label`, the byte counters, the same +`Error`, the same poisoning and the same courtesy flush — so there is +nothing to relearn moving between the two. `new` is the one that +differs: it can't fail, because there is no header to write. + +`write_line(line)` writes the line and its `\n` as a single write, so a +line lands whole or not at all. What `TextFile` does *not* have is +everything that only means something for columns: no header, no field +count, no quoting. A line is written exactly as given, and a line with a +comma or a quote in it is not special in any way — which also means a +text file can't tell you a line came out malformed. If the content has +fields in it, it wants `CsvFile` instead. + +--- + +## `json.rs` — Documents Written Whole + +Two ways in, for two different jobs: + +- **One-shot and typed.** `write_json(path, &value)` writes any + `Serialize` as pretty-printed JSON with a trailing newline, and + `read_json(path)` parses a whole document back as a `T`. Pretty, + because these are the files a person opens to find out what a + recording was. +- **A document that grows.** `JsonDocument` is for the file written when + a recording starts and added to when it stops: `new`/`open`/ + `open_or_new`, then `set`, `get`, `contains`, `remove`, `properties`, + `path` and `save`. It is held in memory as a `serde_json::Map`, so + properties this crate knows nothing about survive the round trip — the + document is edited, not rebuilt from a struct that would have dropped + them. `set` returns `&mut Self`, so several can be chained. + `open_or_new` forgives only a *missing* file; one that exists and is + broken still errors rather than quietly starting over and overwriting + it on the next save. + +```rust +use software_core::logger::JsonDocument; + +let mut session = JsonDocument::new("sessions/13/session.json"); +session.set("adj_commit", "4f1c3b0")?.set("time_unit", "us")?; +session.save()?; + +// Later, when the recording stops. +let mut session = JsonDocument::open("sessions/13/session.json")?; +session.set("rows", 128_000u64)?.set("stopped", true)?; +session.save()?; +``` + +**Every save is atomic.** The document is serialized into a `.tmp` +sibling, flushed, `sync_all`ed and then renamed over the destination, so +the file is never seen half-written: either the old contents or the new +ones. That matters more here than anywhere else in the module — a fatal +error in the backend ends in `std::process::exit`, and a session's +metadata truncated at that moment is what makes every CSV next to it +unreadable. The rename needs both files on one filesystem, which they +are by construction, being siblings. Not covered: the directory entry +isn't synced, so a power cut in the instant after the rename can still +lose it. + +**Properties come out in alphabetical order**, which is `serde_json`'s +own ordering for an object rather than something imposed here: the same +document always serializes the same way, which is what makes it readable +in a diff. + +Nothing is kept open between calls, which is why this file doesn't use +`Target` at all. Reading is in for JSON **only**, and for one reason: a +document that gains properties over time can't be added to without being +read first. A CSV or a text log is appended to and never revisited, and +nothing here will read one back. + +--- + +## `error.rs` — `logger::Error` + +One enum for the three formats. `Create`, `Read`, `Parse`, +`NotAnObject`, `Replace` and `Serialize` carry a `PathBuf`, since they +can only happen to a real file on disk; `Write`, `Flush`, `FieldCount` +and `Poisoned` carry a plain `label`, because a `CsvFile` can wrap any +`std::io::Write` and an in-memory buffer has no path. + +| Variant | When | +| --- | --- | +| `Create` | The file, or one of its parent directories, couldn't be created. | +| `Write` | A write to the file failed. The file is now poisoned. | +| `Flush` | The buffer couldn't be flushed, so what was written since the last flush may not have reached the disk. | +| `FieldCount` | A row didn't have as many fields as the header declares. Nothing was written. | +| `Poisoned` | An earlier write failed, so the file is no longer written to at all. | +| `Read` | The file couldn't be read (`read_json`, `JsonDocument::open`). | +| `Parse` | Not valid JSON, or a property isn't the type it was asked for. | +| `NotAnObject` | Valid JSON whose root isn't an object, so it has no properties. | +| `Replace` | The finished temporary file couldn't be renamed over its destination. | +| `Serialize` | A value couldn't be serialized as JSON, or its bytes couldn't be written. | + +`logger::files` has an `Error` of its own, listed below: a copy that +fails is not a failure of a file this module holds open, and its +variants name two paths rather than one. + +--- + +## `files.rs` — Moving Files Around *(feature `files`)* + +Plain `std::fs` with two things added, which is all it is for: the +destination's parent directories get created instead of the operation +failing, and every error names the file — both files, for the operations +that have two. + +| Function | Notes | +| --- | --- | +| `copy_file(from, to)` → `u64` | Replaces an existing `to` and returns the bytes copied. **Not atomic**: an interrupted copy leaves a partial file, so a reader that could see the destination mid-copy should be given a finished file under another name and then `move_file`d into place. | +| `copy_dir(from, to)` → `usize` | Recursive, returning how many files were copied. Directories are recreated as needed; a symbolic link is followed and its target copied as a plain file, so the result is real files rather than links pointing back at the original. | +| `move_file(from, to)` | A rename, atomic and free whatever the file's size. Across filesystems — a log directory on a USB stick — a rename is impossible, so it falls back to copy-then-remove, which is neither. | +| `remove_file(path)` | A file that isn't there is an error, as in `std::fs`: the caller is the one who knows whether that was expected. | +| `size(path)` → `u64` | How many bytes the file holds. | + +Its `Error` has `Copy`, `Move`, `CreateDir`, `Read` and `Remove`; +`Copy` and `Move` name both paths, since "couldn't copy" without saying +where to leaves the caller with nothing to act on. + +This is also what makes `CsvFile` and `JsonDocument` usable on a file +that already exists: copy it, then open the copy and carry on writing. + +```rust +use software_core::logger::{CsvFile, files}; + +files::copy_file("sessions/12/data/speed.csv", "sessions/13/data/speed.csv")?; +let mut speed = CsvFile::append("sessions/13/data/speed.csv", &["t_us", "value"])?; +speed.row().int(1_024).num(37.5).end()?; +speed.close()?; +``` + +Not wrapped: asking whether a file is there — that is `Path::exists`, +and a wrapper would only add a name to learn. Not here at all: anything +that walks a tree looking for something, rotation, quotas, watching for +changes, and anything asynchronous. + +--- + +## `host.rs` — Who Produced This *(feature `host`)* + +`HostInfo::collect()` takes one snapshot of the machine, the user and +the build, meant to be serialized straight into a recording's metadata +so that months later it is still possible to answer *which machine +produced this, running which build, and with whose clock and locale*. + +It is part of `logger` because it is part of a recording, but not of how +one is written: this is the **content** of a metadata file, not a way of +putting bytes on a disk. Nothing in `csv`, `text`, `json` or `files` +uses it; they still write files without knowing what is in them. + +**Nothing in it fails.** Every field is attempted on its own and left +empty if the system won't say, `collect` returns no `Result` and nothing +panics — a recording must never fail to start over a missing user name. +`Option` fields are skipped when serializing, so an unknown value is +absent from the JSON rather than `null`. + +What it reads: `user`, `real_name`, `git_name`, `email`, `host`, `os`, +`arch`, `distro`, `cpus`, `core_version`, `debug_build`, `pid`, `exe`, +`args`, `working_dir`, `timezone`, `locale`, `started_at_unix`, +`open_file_limit`. + +Three of those are worth their own note: + +- **`email`** is looked for in four places, in order: `user.email` in + the global git configuration, `$GIT_AUTHOR_EMAIL`, `$EMAIL`, then the + account name if it happens to look like an address. No operating + system exposes an email address portably, so git's own identity is + used instead — reliable on a developer's machine, and the identity the + person is already known by. The git configuration is only read with + the `git` feature on (global and system files only, never a + repository, so the result can't depend on which directory the backend + was started from); without it, the environment variables are all that + is left. +- **`timezone`** is a zone *name* (`Europe/Madrid`), not an offset, + because the offset depends on the date and a recording may straddle + the day summer time changes. It comes from `$TZ`, or from the target + of the `/etc/localtime` link. It is worth more than it looks: + protections and messages carry a time of day with no date or zone, so + without the recording machine's zone they can't be placed on a real + timeline or lined up against video. +- **`open_file_limit`** is also a free function, + `host::open_file_limit()`, worth calling before opening a file per + measurement: the soft limit is **256** by default on macOS and usually + 1024 on Linux, and past it opening a file starts failing in the middle + of a recording, which looks like a disk problem and isn't one. `None` + on Windows, honestly rather than as a failure — it has no equivalent + limit for the handles `std::fs::File` uses. + +`HostInfo::without_identity()` returns the same snapshot with the user +name, real name, git name, email and machine name removed, for a +recording that is going to be shared outside the team. + +`HostInfo` is `Serialize` only, on purpose: reading one back is reading +JSON, not rebuilding this struct, and a field like `os` is a +compile-time constant of the build that wrote it rather than something +to parse. Deliberately absent: free disk space and memory (another +dependency, and the disk is better checked by whoever is about to fill +it), the battery, and the network interfaces the backend bound to — +that last one belongs to whatever opened the sockets, the only thing +that actually knows. + +--- + +## Features + +| Feature | Enables | Dependencies | +| --- | --- | --- | +| `logger` | `CsvFile`, `TextFile`, the JSON API, `Error` | none beyond the crate's own `serde`/`serde_json`/`tracing` | +| `files` | `logger::files` (implies `logger`) | none of its own | +| `host` | `logger::host` (implies `logger`) | `whoami`, plus `rlimit` on unix | + +`files` and `host` are separate features because neither is needed to +write a file: a tool that only wants to put CSV rows on a disk shouldn't +have to take `whoami` with it. With the `git` feature also on, +`HostInfo` fills in the git identity as described above. + +--- + +## Why There Is No Trait Over The Three Formats + +What the formats share is how a file is **held**, and that is +`target.rs`. What they don't share is how a file is **written**, because +it genuinely isn't the same operation: a CSV row is typed fields +validated against a header, a text line is a string taken verbatim, and +a JSON document is a whole value serialized in one go with no handle to +keep. That is why `CsvFile` and `TextFile` expose the same vocabulary +while `write_json` stays a free function. + +A trait would only pay for itself once some caller needs to be generic +over the format — the same code path writing either CSV or JSON lines, +say — and no caller does today. Reaching for one now would mean either +flattening the API down to "write these bytes", which throws away the +field validation and the quoting that are the point, or inventing an +open/write/close lifecycle for JSON that it doesn't have. Adding the +trait later is backwards compatible, so it can wait for the second +caller. + +--- + +## Not Here, On Purpose + +Reading a CSV or a text log back, sessions, timestamps, file rotation, +quotas, keeping a registry of many open files (a `HashMap` +with `entry().or_insert_with(...)` in the caller is shorter and clearer +than anything this module could wrap it in), and anything asynchronous. + +--- + +## Verification + +```bash +cargo test -p software-core -F logger,files,host +cargo clippy -p software-core --features logger,files,host --all-targets -- -D warnings +cargo doc --open -p software-core -F logger,files,host --no-deps +``` + +The tests write into temporary directories (`tempfile`, a dev +dependency) and against in-memory buffers; none of them needs a network +or a real session directory. diff --git a/backend/crates/core/src/logger/csv.rs b/backend/crates/core/src/logger/csv.rs new file mode 100644 index 000000000..8c2fbd723 --- /dev/null +++ b/backend/crates/core/src/logger/csv.rs @@ -0,0 +1,707 @@ +//! A CSV file that knows its own header. + +use super::Error; +use super::target::{Target, append_file, create_file}; +use std::fmt; +use std::fs::File; +use std::io::{BufWriter, Write}; +use std::path::Path; +use tracing::debug; + +/// A CSV file being written to, one row at a time. +/// +/// Generic over its destination so the format can be exercised against +/// an in-memory buffer, but the common case is the default: a file on +/// disk behind a [`BufWriter`], built with [`CsvFile::create`]. +/// +/// Three things it guarantees, which are the reason this type exists +/// instead of a bare [`File`]: +/// +/// - **A row lands whole or not at all.** Fields are built up in a +/// buffer the file reuses, and only [`Row::end`] writes — so a row +/// rejected for having the wrong number of fields never reaches the +/// file, and a row that does reach it is a single +/// [`Write::write_all`] call. +/// - **A failed write stops the file.** The first failure that reaches +/// the file poisons it: every later call returns +/// [`Error::Poisoned`] instead of appending to something already +/// inconsistent, or repeating the same I/O error once per row. +/// - **Flushing is something you ask for.** [`CsvFile::flush`] and +/// [`CsvFile::close`] return a `Result`. [`Drop`] only does a +/// best-effort flush and traces the failure: a fatal error in the +/// backend ends in `std::process::exit`, which runs no destructor at +/// all, so a log that only flushes on drop loses its tail exactly +/// when it matters most. +/// +/// Nothing here is traced per row on purpose: at telemetry rates that +/// would be tens of thousands of events per second. Only opening a file +/// (`debug`) and a failed flush on drop (`error`) are traced. +/// +/// # Example +/// +/// ``` +/// use software_core::logger::CsvFile; +/// +/// let mut csv = CsvFile::new(Vec::new(), "in memory", &["t", "origin", "value"])?; +/// csv.row().int(1_250).text("LCU, bay 2").num(53.2).end()?; +/// +/// assert_eq!( +/// csv.get_ref().as_slice(), +/// b"t,origin,value\n1250,\"LCU, bay 2\",53.2\n", +/// ); +/// # Ok::<(), Box>(()) +/// ``` +#[derive(Debug)] +pub struct CsvFile> { + target: Target, + /// How many fields every row must have, or `None` when the file was + /// created with an empty header and there is nothing to check + /// against. + fields: Option, + /// The row currently being built, reused across rows so writing one + /// allocates nothing. + buf: Vec, +} + +impl CsvFile> { + /// Creates (or truncates) the file at `path`, creating its parent + /// directories, and writes `header` as its first line. + /// + /// An empty `header` writes no header line and leaves the row's + /// field count unchecked — see [`CsvFile::new`]. + pub fn create(path: impl AsRef, header: &[&str]) -> Result { + let path = path.as_ref(); + + // The file is created before the header is written so that a failure to write the header doesn't leave a partially written file. + let file = Self::new(create_file(path)?, path.display().to_string(), header)?; + debug!(path = %path.display(), fields = header.len(), "csv file created"); + Ok(file) + } + + /// Opens the file at `path` to add rows to the end of it, creating it + /// and its parent directories if they aren't there. + /// + /// `header` is written only when the file is empty or brand new. + /// Otherwise it is taken as a statement of how many fields a row has — + /// what [`Error::FieldCount`] is checked against — and **what the file + /// already contains is not looked at**: if its columns are not these + /// ones, both shapes end up in the same file and nothing says so. The + /// caller is the one who knows that the file it opens is the file it + /// thinks it is; copying one with [`CsvFile::create`]'s own header is + /// the way to be sure. + /// + /// The one thing that *is* checked is the line boundary: if the + /// existing content doesn't end in a newline, one is written first, so + /// the first new row can't be glued onto a half-finished line. + pub fn append(path: impl AsRef, header: &[&str]) -> Result { + let path = path.as_ref(); + let (writer, existing) = append_file(path)?; + + let file = if existing == 0 { + Self::new(writer, path.display().to_string(), header)? + } else { + Self { + target: Target::new(writer, path.display().to_string()), + // No header line to write, so the count is taken from the + // argument instead of from what was just written. An empty + // header leaves rows unchecked, as in `new`. + fields: (!header.is_empty()).then_some(header.len()), + buf: Vec::new(), + } + }; + + debug!( + path = %path.display(), + existing_bytes = existing, + fields = header.len(), + "csv file opened to append" + ); + Ok(file) + } +} + +impl CsvFile { + /// Wraps an already-open destination, writing `header` as its first + /// line. + /// + /// `label` is what this file is called in any [`Error`] it produces; + /// [`CsvFile::create`] uses the path for it. + /// + /// An empty `header` writes no header line, and leaves every row's + /// field count unchecked — for a file whose columns aren't known up + /// front. With a header, a row with a different number of fields is + /// an [`Error::FieldCount`]. + pub fn new(inner: W, label: impl Into, header: &[&str]) -> Result { + let mut file = Self { + target: Target::new(inner, label.into()), + fields: None, + buf: Vec::new(), + }; + + if !header.is_empty() { + // Written through `Row` like any other line, so a header + // with a comma or a quote in it is quoted the same way a + // field would be. The field count is still `None` here, so + // the header itself is what sets the count rather than being + // checked against it. + let mut row = file.row(); + for field in header { + row = row.text(field); + } + row.end()?; + file.fields = Some(header.len()); + } + + Ok(file) + } + + /// Starts a row. Add its fields, then call [`Row::end`]. + /// + /// Nothing is written to the file until `end`, and a row dropped + /// without it writes nothing at all. + pub fn row(&mut self) -> Row<'_, W> { + self.buf.clear(); + Row { + file: self, + count: 0, + error: None, + } + } + + /// Flushes everything written so far to the destination. + pub fn flush(&mut self) -> Result<(), Error> { + self.target.flush() + } + + /// Flushes and closes the file, reporting a failure instead of + /// swallowing it like [`Drop`] has to. + pub fn close(mut self) -> Result<(), Error> { + self.target.close() + } + + /// Borrows the destination, e.g. to read back what was written to an + /// in-memory buffer. + pub fn get_ref(&self) -> &W { + self.target.get_ref() + } + + /// Whether an earlier write or flush failed, leaving this file + /// closed to further writes. + pub fn is_poisoned(&self) -> bool { + self.target.is_poisoned() + } + + /// What this file is called in its errors: the path it was created + /// with, or the label it was given. + /// + /// Worth having beyond [`Error`]'s own text: a caller that notices a + /// file went [`CsvFile::is_poisoned`] has no error in hand any more, + /// and still needs to say which file stopped. + pub fn label(&self) -> &str { + self.target.label() + } + + /// Every byte handed to the destination so far, header included — + /// the file's size on disk, once flushed. + pub fn bytes_written(&self) -> u64 { + self.target.bytes_written() + } + + /// The bytes written since the last successful flush. + /// + /// This is what a flush policy is built on: "flush every so many + /// kilobytes, or every so often" is the caller's decision (see this + /// module's docs), and this saves it from keeping its own tally for + /// each of the hundreds of files it may have open. + pub fn bytes_since_flush(&self) -> u64 { + self.target.bytes_since_flush() + } + + /// Writes the row held in `buf`, terminator included, as one call. + fn write_row(&mut self) -> Result<(), Error> { + self.buf.push(b'\n'); + self.target.write_all(&self.buf) + } +} + +/// A single row being built, field by field. +/// +/// Every field method appends to the file's row buffer and keeps the +/// first error it hits, so a row reads as one expression without a `?` +/// per field; [`Row::end`] is where that error — and the field count — +/// is reported. +#[derive(Debug)] +pub struct Row<'a, W: Write> { + file: &'a mut CsvFile, + count: usize, + error: Option, +} + +impl Row<'_, W> { + /// Appends an integer field. + pub fn int(self, value: i64) -> Self { + self.number(format_args!("{value}")) + } + + /// Appends a floating point field. + /// + /// Written with its [`fmt::Display`], i.e. the shortest form that + /// round-trips back to the same `f64`: a value with no fractional + /// part has no decimal point (`1.0` is written `1`), and `NaN` and + /// the infinities are written as `NaN`, `inf` and `-inf` rather than + /// replaced by an empty field — if a board sent one, the log should + /// say so. + pub fn num(self, value: f64) -> Self { + self.number(format_args!("{value}")) + } + + /// Appends a boolean field, as `true` or `false`. + pub fn bool(self, value: bool) -> Self { + self.number(format_args!("{value}")) + } + + /// Appends a text field, quoted if it needs to be. + /// + /// A field containing a comma, a double quote, a carriage return or + /// a line feed is wrapped in double quotes, with every inner quote + /// doubled (RFC 4180). This is the only method that can need + /// quoting — a number or a boolean never contains any of those — and + /// the one that matters: a board's free-text message or the path it + /// came from can contain all four. + pub fn text(mut self, value: &str) -> Self { + if self.error.is_some() { + return self; + } + + let separated = self.count > 0; + match append_text(&mut self.file.buf, value, separated) { + Ok(()) => { + self.count += 1; + self + } + Err(source) => { + self.error = Some(Error::Write { + label: self.file.target.label().to_string(), + source, + }); + self + } + } + } + + /// Validates the row against the file's header and writes it. + /// + /// Errors with [`Error::FieldCount`] — writing nothing — if the row + /// doesn't have as many fields as the header declares. + pub fn end(mut self) -> Result<(), Error> { + if let Some(error) = self.error.take() { + return Err(error); + } + + if self.file.target.is_poisoned() { + return Err(self.file.target.poisoned_error()); + } + + if let Some(expected) = self.file.fields + && self.count != expected + { + return Err(Error::FieldCount { + label: self.file.target.label().to_string(), + expected, + got: self.count, + }); + } + + self.file.write_row() + } + + /// Appends a field that can't need quoting: every numeric and + /// boolean field goes through here, which is also what makes them + /// the cheap ones. + fn number(mut self, value: fmt::Arguments<'_>) -> Self { + if self.error.is_some() { + return self; + } + + let separator = if self.count > 0 { "," } else { "" }; + // Appending to a `Vec` can only fail by running out of + // memory, but `write!` is fallible all the same: keep the error + // rather than discard it, and let `end` be the one to report it. + match write!(self.file.buf, "{separator}{value}") { + Ok(()) => { + self.count += 1; + self + } + Err(source) => { + self.error = Some(Error::Write { + label: self.file.target.label().to_string(), + source, + }); + self + } + } + } +} + +/// Appends `value` to `buf`, preceded by a separator if `separated`, and +/// quoted per RFC 4180 if it contains anything that needs it. +fn append_text(buf: &mut Vec, value: &str, separated: bool) -> std::io::Result<()> { + if separated { + buf.write_all(b",")?; + } + + if !value.contains([',', '"', '\n', '\r']) { + return buf.write_all(value.as_bytes()); + } + + buf.write_all(b"\"")?; + let mut rest = value; + while let Some(quote) = rest.find('"') { + buf.write_all(&rest.as_bytes()[..quote])?; + buf.write_all(b"\"\"")?; + rest = &rest[quote + 1..]; + } + buf.write_all(rest.as_bytes())?; + buf.write_all(b"\"") +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + + type TestResult = Result>; + + fn in_memory(header: &[&str]) -> TestResult>> { + Ok(CsvFile::new(Vec::new(), "in memory", header)?) + } + + fn written(csv: &CsvFile>) -> String { + String::from_utf8_lossy(csv.get_ref()).into_owned() + } + + /// A destination that takes `ok_writes` writes and fails every one + /// after that — what a full disk looks like from in here. + #[derive(Debug)] + struct FailsAfter { + ok_writes: usize, + taken: Vec, + } + + impl Write for FailsAfter { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if self.ok_writes == 0 { + return Err(std::io::Error::other("disk full")); + } + self.ok_writes -= 1; + self.taken.extend_from_slice(buf); + Ok(buf.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + #[test] + fn appending_continues_a_file_without_writing_the_header_again() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("data/lcu.csv"); + + let mut csv = CsvFile::create(&path, &["t", "value"])?; + csv.row().int(1).num(1.5).end()?; + csv.close()?; + + let mut csv = CsvFile::append(&path, &["t", "value"])?; + csv.row().int(2).num(2.5).end()?; + csv.close()?; + + assert_eq!(fs::read_to_string(&path)?, "t,value\n1,1.5\n2,2.5\n"); + Ok(()) + } + + #[test] + fn appending_to_a_file_that_is_not_there_yet_writes_the_header() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("data/lcu.csv"); + + let mut csv = CsvFile::append(&path, &["t", "value"])?; + csv.row().int(1).num(1.5).end()?; + csv.close()?; + + assert_eq!(fs::read_to_string(&path)?, "t,value\n1,1.5\n"); + Ok(()) + } + + #[test] + fn appending_to_content_that_lacks_its_last_newline_starts_a_fresh_line() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("copied.csv"); + // What a file copied from elsewhere can easily look like. + fs::write(&path, "t,value\n1,1.5")?; + + let mut csv = CsvFile::append(&path, &["t", "value"])?; + csv.row().int(2).num(2.5).end()?; + csv.close()?; + + assert_eq!(fs::read_to_string(&path)?, "t,value\n1,1.5\n2,2.5\n"); + Ok(()) + } + + #[test] + fn an_appended_row_is_still_checked_against_the_header_it_was_given() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("data.csv"); + fs::write(&path, "t,value\n")?; + + let mut csv = CsvFile::append(&path, &["t", "value"])?; + let Err(error) = csv.row().int(1).num(1.5).text("extra").end() else { + unreachable!("three fields where the header says two"); + }; + + assert!(matches!( + error, + Error::FieldCount { + expected: 2, + got: 3, + .. + } + )); + Ok(()) + } + + #[test] + fn the_header_is_the_files_first_line() -> TestResult { + let csv = in_memory(&["t", "value"])?; + assert_eq!(written(&csv), "t,value\n"); + Ok(()) + } + + #[test] + fn an_empty_header_writes_nothing_and_leaves_the_field_count_unchecked() -> TestResult { + let mut csv = in_memory(&[])?; + assert_eq!(written(&csv), ""); + + csv.row().int(1).end()?; + csv.row().int(1).int(2).int(3).end()?; + + assert_eq!(written(&csv), "1\n1,2,3\n"); + Ok(()) + } + + #[test] + fn a_text_field_is_quoted_only_when_it_has_to_be() -> TestResult { + let mut csv = in_memory(&[])?; + + csv.row().text("LCU").end()?; + csv.row().text("LCU, bay 2").end()?; + csv.row().text("say \"hi\"").end()?; + csv.row().text("two\nlines").end()?; + csv.row().text("carriage\rreturn").end()?; + + assert_eq!( + written(&csv), + "LCU\n\"LCU, bay 2\"\n\"say \"\"hi\"\"\"\n\"two\nlines\"\n\"carriage\rreturn\"\n" + ); + Ok(()) + } + + #[test] + fn a_header_field_is_quoted_like_any_other_text() -> TestResult { + let csv = in_memory(&["t", "value, raw"])?; + assert_eq!(written(&csv), "t,\"value, raw\"\n"); + Ok(()) + } + + #[test] + fn numbers_and_booleans_are_never_quoted() -> TestResult { + let mut csv = in_memory(&[])?; + csv.row() + .int(-1_250) + .num(53.2) + .bool(true) + .bool(false) + .end()?; + assert_eq!(written(&csv), "-1250,53.2,true,false\n"); + Ok(()) + } + + #[test] + fn a_float_is_written_as_the_shortest_form_that_round_trips() -> TestResult { + let mut csv = in_memory(&[])?; + csv.row() + .num(1.0) + .num(53.2) + .num(-0.5) + .num(f64::NAN) + .num(f64::INFINITY) + .end()?; + assert_eq!(written(&csv), "1,53.2,-0.5,NaN,inf\n"); + Ok(()) + } + + #[test] + fn a_row_with_the_wrong_number_of_fields_is_rejected_whole() -> TestResult { + let mut csv = in_memory(&["t", "value"])?; + + let too_few = csv.row().int(1).end(); + assert!(matches!( + too_few, + Err(Error::FieldCount { + expected: 2, + got: 1, + .. + }) + )); + + let too_many = csv.row().int(1).int(2).int(3).end(); + assert!(matches!( + too_many, + Err(Error::FieldCount { + expected: 2, + got: 3, + .. + }) + )); + + // Neither rejected row reached the file, and the file still + // takes a correct row afterwards. + assert_eq!(written(&csv), "t,value\n"); + csv.row().int(1).num(2.5).end()?; + assert_eq!(written(&csv), "t,value\n1,2.5\n"); + Ok(()) + } + + #[test] + fn a_row_dropped_without_end_writes_nothing() -> TestResult { + let mut csv = in_memory(&["t"])?; + + let _ = csv.row().int(7); + assert_eq!(written(&csv), "t\n"); + + csv.row().int(8).end()?; + assert_eq!(written(&csv), "t\n8\n"); + Ok(()) + } + + #[test] + fn a_failed_write_poisons_the_file_instead_of_reporting_once_per_row() -> TestResult { + // One write for the header, so the first row is what fails. + let destination = FailsAfter { + ok_writes: 1, + taken: Vec::new(), + }; + let mut csv = CsvFile::new(destination, "failing", &["t"])?; + + assert!(matches!(csv.row().int(1).end(), Err(Error::Write { .. }))); + assert!(csv.is_poisoned()); + + assert!(matches!( + csv.row().int(2).end(), + Err(Error::Poisoned { .. }) + )); + assert!(matches!(csv.flush(), Err(Error::Poisoned { .. }))); + + // Nothing past the header ever reached the destination. + assert_eq!(String::from_utf8_lossy(&csv.get_ref().taken), "t\n"); + Ok(()) + } + + #[test] + fn writing_rows_reuses_one_buffer_instead_of_allocating_per_row() -> TestResult { + let mut csv = in_memory(&["t", "origin", "value"])?; + + // Two identical passes: the first lets the row buffer grow to + // whatever the widest of these rows needs, the second must not + // make it grow at all. Comparing passes rather than asserting + // some size keeps this about reuse and not about how wide a + // formatted `f64` happens to be. + let mut after_first_pass = None; + for _pass in 0..2 { + for i in 0..10_000usize { + let origin = &"src/boards/lcu/main.cpp"[..(i % 23) + 1]; + csv.row().int(i as i64).text(origin).num(i as f64).end()?; + } + + match after_first_pass { + None => after_first_pass = Some(csv.buf.capacity()), + Some(grown) => assert_eq!( + csv.buf.capacity(), + grown, + "the row buffer grew again on the second pass" + ), + } + } + // And it is one row's worth, not every row appended: if `row()` + // ever stopped clearing it, this would be in the megabytes. + assert!( + csv.buf.capacity() < 256, + "row buffer grew to {} bytes", + csv.buf.capacity() + ); + Ok(()) + } + + #[test] + fn a_file_reports_the_name_it_answers_to_in_its_errors() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("current.csv"); + + let on_disk = CsvFile::create(&path, &["t"])?; + assert_eq!(on_disk.label(), path.display().to_string()); + + let in_memory = in_memory(&["t"])?; + assert_eq!(in_memory.label(), "in memory"); + Ok(()) + } + + #[test] + fn bytes_written_counts_the_header_and_every_row() -> TestResult { + let mut csv = in_memory(&["t", "value"])?; + assert_eq!(csv.bytes_written(), "t,value\n".len() as u64); + + csv.row().int(1).num(2.5).end()?; + assert_eq!(csv.bytes_written(), "t,value\n1,2.5\n".len() as u64); + Ok(()) + } + + #[test] + fn bytes_since_flush_is_what_a_flush_policy_reads_and_resets() -> TestResult { + let mut csv = in_memory(&["t"])?; + csv.row().int(1).end()?; + assert_eq!(csv.bytes_since_flush(), "t\n1\n".len() as u64); + + csv.flush()?; + assert_eq!(csv.bytes_since_flush(), 0); + // Flushing doesn't reset the total, only what is pending. + assert_eq!(csv.bytes_written(), "t\n1\n".len() as u64); + + csv.row().int(2).end()?; + assert_eq!(csv.bytes_since_flush(), "2\n".len() as u64); + Ok(()) + } + + #[test] + fn a_rejected_row_counts_no_bytes() -> TestResult { + let mut csv = in_memory(&["t", "value"])?; + let header = csv.bytes_written(); + + assert!(csv.row().int(1).end().is_err()); + assert_eq!(csv.bytes_written(), header); + Ok(()) + } + + #[test] + fn create_makes_the_parent_directories_and_close_persists_every_row() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("session/data/LCU/current.csv"); + + let mut csv = CsvFile::create(&path, &["t", "value"])?; + csv.row().int(0).num(1.5).end()?; + csv.row().int(1_000).num(2.5).end()?; + csv.close()?; + + assert_eq!(fs::read_to_string(&path)?, "t,value\n0,1.5\n1000,2.5\n"); + Ok(()) + } +} diff --git a/backend/crates/core/src/logger/error.rs b/backend/crates/core/src/logger/error.rs new file mode 100644 index 000000000..691f43e08 --- /dev/null +++ b/backend/crates/core/src/logger/error.rs @@ -0,0 +1,135 @@ +//! Errors produced while writing a file. +//! +//! Every variant names the file it happened on. A bare +//! [`std::io::Error`] says what went wrong but never where, and by the +//! time it reaches whoever decides whether to keep logging, the file is +//! the only thing that makes it actionable. +//! +//! [`Error::Create`] and [`Error::Serialize`] carry a [`PathBuf`], since +//! they can only happen to a real file on disk. The rest carry a plain +//! `label`, because a [`super::CsvFile`] can wrap any +//! [`std::io::Write`] — an in-memory buffer in a test has no path, just +//! the name its caller gave it. + +use std::path::PathBuf; + +/// An error writing a file. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// Couldn't create the file, or one of its parent directories. + #[error("couldn't create {path:?}")] + Create { + /// The file that couldn't be created. + path: PathBuf, + /// The underlying I/O error. + #[source] + source: std::io::Error, + }, + + /// Couldn't write to the file. + #[error("couldn't write to {label}")] + Write { + /// The file that couldn't be written to. + label: String, + /// The underlying I/O error. + #[source] + source: std::io::Error, + }, + + /// Couldn't flush the file's buffer, so what was written since the + /// last flush may not have reached the disk. + #[error("couldn't flush {label}")] + Flush { + /// The file that couldn't be flushed. + label: String, + /// The underlying I/O error. + #[source] + source: std::io::Error, + }, + + /// A row didn't have as many fields as the file's header declares. + /// + /// Nothing was written: the row is rejected whole, instead of + /// shifting every column of the file from that point on. + #[error("{label}: row needs {expected} field(s), got {got}")] + FieldCount { + /// The file the row was meant for. + label: String, + /// How many fields the header declares. + expected: usize, + /// How many fields the row actually had. + got: usize, + }, + + /// An earlier write to this file failed, so it is no longer written + /// to at all. + /// + /// Returned instead of retrying, because a write that failed halfway + /// already left the file inconsistent — and because a failing file + /// written at telemetry rates would otherwise report the same error + /// thousands of times per second. + #[error("{label} was left in a failed state by an earlier write")] + Poisoned { + /// The file that failed earlier. + label: String, + }, + + /// Couldn't read the file. + #[error("couldn't read {path:?}")] + Read { + /// The file that couldn't be read. + path: PathBuf, + /// The underlying I/O error. + #[source] + source: std::io::Error, + }, + + /// Couldn't parse the file as JSON, or couldn't read one of its + /// properties as the type it was asked for. + #[error("couldn't parse {path:?} as JSON")] + Parse { + /// The file that failed to parse. + path: PathBuf, + /// The underlying `serde_json` error, which says where in the + /// document the problem is. + #[source] + source: serde_json::Error, + }, + + /// The file is valid JSON, but its root isn't an object, so it has + /// no properties to read or add to. + #[error("{path:?} is valid JSON but its root is not an object")] + NotAnObject { + /// The file whose root isn't an object. + path: PathBuf, + }, + + /// Couldn't put the finished file in place of the old one. + /// + /// A JSON document is built in a temporary file next to its + /// destination and renamed over it, so this is the last step of + /// [`super::write_json`] — and the only one that can fail with the + /// new content already complete on disk, under the temporary name + /// this error reports as its source path's sibling. + #[error("couldn't put the finished file in place of {path:?}")] + Replace { + /// The destination that couldn't be replaced. + path: PathBuf, + /// The underlying I/O error. + #[source] + source: std::io::Error, + }, + + /// Couldn't serialize the value as JSON, or couldn't write the + /// serialized bytes out. + #[error("couldn't write {path:?} as JSON")] + Serialize { + /// The file being written. + path: PathBuf, + /// The underlying `serde_json` error — which wraps the I/O error + /// too, when the failure was in writing rather than in + /// serializing. + #[source] + source: serde_json::Error, + }, +} diff --git a/backend/crates/core/src/logger/files.rs b/backend/crates/core/src/logger/files.rs new file mode 100644 index 000000000..af15e325e --- /dev/null +++ b/backend/crates/core/src/logger/files.rs @@ -0,0 +1,366 @@ +//! Copying, moving and removing files. +//! +//! Plain [`std::fs`] with two things added, which is all this is for: +//! the destination's parent directories get created instead of the +//! operation failing, and every error names the file — both files, for +//! the operations that have two — which is what makes it actionable by +//! the time it has travelled up to whoever decides what to do about it. +//! +//! No dependencies, on purpose: a tool that wants to copy a file +//! shouldn't have to take anything else with it. +//! +//! Copying is also what makes the types in [`crate::logger`] usable on a +//! file that already exists: copy it, then open the copy and carry on +//! writing to it. +//! +//! ```no_run +//! use software_core::logger::files; +//! use software_core::logger::{CsvFile, JsonDocument}; +//! +//! // A recording that starts from the previous session's layout. +//! files::copy_file("sessions/12/session.json", "sessions/13/session.json")?; +//! +//! let mut session = JsonDocument::open("sessions/13/session.json")?; +//! session.set("started", true)?; +//! session.save()?; +//! +//! // And a CSV that is continued rather than started over. +//! files::copy_file("sessions/12/data/speed.csv", "sessions/13/data/speed.csv")?; +//! let mut speed = CsvFile::append("sessions/13/data/speed.csv", &["t_us", "value"])?; +//! speed.row().int(1_024).num(37.5).end()?; +//! speed.close()?; +//! # Ok::<(), Box>(()) +//! ``` +//! +//! Not wrapped: asking whether a file is there. That is +//! [`std::path::Path::exists`], and a wrapper around it would only add a +//! name to learn. +//! +//! Not here at all: anything that walks a tree looking for something, +//! rotation, quotas, watching for changes, and anything asynchronous. A +//! recording copies a handful of files at the start and at the end; when +//! that stops being true, whatever needs more can say so then. + +mod error; + +pub use error::Error; + +use std::fs; +use std::path::Path; +use tracing::debug; + +/// Copies `from` over `to`, creating `to`'s parent directories, and +/// returns how many bytes were copied. +/// +/// An existing `to` is replaced. The copy is not atomic: an interrupted +/// copy leaves a partial file behind, so a reader that could see the +/// destination mid-copy should be given a finished file under a +/// different name and then [`move_file`]d into place. +/// +/// # Example +/// +/// ```no_run +/// use software_core::logger::files; +/// +/// let bytes = files::copy_file("settings.json", "backup/settings.json")?; +/// # Ok::<(), software_core::logger::files::Error>(()) +/// ``` +pub fn copy_file(from: impl AsRef, to: impl AsRef) -> Result { + let (from, to) = (from.as_ref(), to.as_ref()); + create_parents(to)?; + + let bytes = fs::copy(from, to).map_err(|source| Error::Copy { + from: from.to_path_buf(), + to: to.to_path_buf(), + source, + })?; + + debug!(from = %from.display(), to = %to.display(), bytes, "file copied"); + Ok(bytes) +} + +/// Copies everything under `from` into `to`, recursively, and returns +/// how many files were copied. +/// +/// Directories are recreated as needed; existing files in `to` are +/// replaced. A symbolic link is followed and its target copied as a +/// plain file, so the result is a directory of real files rather than a +/// tree of links pointing back at the original. +pub fn copy_dir(from: impl AsRef, to: impl AsRef) -> Result { + let (from, to) = (from.as_ref(), to.as_ref()); + let copied = copy_dir_inner(from, to)?; + + debug!(from = %from.display(), to = %to.display(), files = copied, "directory copied"); + Ok(copied) +} + +/// The recursive half of [`copy_dir`], without the event per level. +fn copy_dir_inner(from: &Path, to: &Path) -> Result { + fs::create_dir_all(to).map_err(|source| Error::CreateDir { + path: to.to_path_buf(), + source, + })?; + + let entries = fs::read_dir(from).map_err(|source| Error::Read { + path: from.to_path_buf(), + source, + })?; + + let mut copied = 0; + for entry in entries { + let entry = entry.map_err(|source| Error::Read { + path: from.to_path_buf(), + source, + })?; + + let source_path = entry.path(); + let destination = to.join(entry.file_name()); + + // `file_type` is the entry's own kind, so a link to a directory + // is not a directory here; `metadata` below follows it. + let kind = entry.file_type().map_err(|source| Error::Read { + path: source_path.clone(), + source, + })?; + + let is_dir = if kind.is_symlink() { + fs::metadata(&source_path) + .map_err(|source| Error::Read { + path: source_path.clone(), + source, + })? + .is_dir() + } else { + kind.is_dir() + }; + + if is_dir { + copied += copy_dir_inner(&source_path, &destination)?; + } else { + fs::copy(&source_path, &destination).map_err(|source| Error::Copy { + from: source_path.clone(), + to: destination.clone(), + source, + })?; + copied += 1; + } + } + + Ok(copied) +} + +/// Moves `from` to `to`, creating `to`'s parent directories. +/// +/// A rename when both paths are on the same filesystem, which is atomic +/// and costs nothing whatever the file's size. When they are not — a log +/// directory on a USB stick, say — a rename can't be done at all, so the +/// file is copied and the original removed, which is neither atomic nor +/// free. +pub fn move_file(from: impl AsRef, to: impl AsRef) -> Result<(), Error> { + let (from, to) = (from.as_ref(), to.as_ref()); + create_parents(to)?; + + match fs::rename(from, to) { + Ok(()) => { + debug!(from = %from.display(), to = %to.display(), "file moved"); + Ok(()) + } + Err(source) if source.kind() == std::io::ErrorKind::CrossesDevices => { + copy_file(from, to)?; + remove_file(from)?; + debug!( + from = %from.display(), + to = %to.display(), + "file moved across filesystems by copying" + ); + Ok(()) + } + Err(source) => Err(Error::Move { + from: from.to_path_buf(), + to: to.to_path_buf(), + source, + }), + } +} + +/// Removes the file at `path`. +/// +/// A file that isn't there is an error, like it is in [`std::fs`]: the +/// caller is the one who knows whether that was expected. +pub fn remove_file(path: impl AsRef) -> Result<(), Error> { + let path = path.as_ref(); + + fs::remove_file(path).map_err(|source| Error::Remove { + path: path.to_path_buf(), + source, + })?; + + debug!(path = %path.display(), "file removed"); + Ok(()) +} + +/// How many bytes the file at `path` holds. +pub fn size(path: impl AsRef) -> Result { + let path = path.as_ref(); + + let metadata = fs::metadata(path).map_err(|source| Error::Read { + path: path.to_path_buf(), + source, + })?; + + Ok(metadata.len()) +} + +/// Creates the directories a file is going to live in. +fn create_parents(path: &Path) -> Result<(), Error> { + let Some(parent) = path.parent() else { + return Ok(()); + }; + + // An empty parent is what `Path::parent` gives for a bare file name: + // the current directory, which already exists. + if parent.as_os_str().is_empty() { + return Ok(()); + } + + fs::create_dir_all(parent).map_err(|source| Error::CreateDir { + path: parent.to_path_buf(), + source, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + type TestResult = Result>; + + #[test] + fn copying_creates_the_directories_the_destination_needs() -> TestResult { + let temp = tempfile::tempdir()?; + let from = temp.path().join("settings.json"); + let to = temp.path().join("backup/2026/settings.json"); + fs::write(&from, "{}\n")?; + + let bytes = copy_file(&from, &to)?; + + assert_eq!(bytes, 3); + assert_eq!(fs::read_to_string(&to)?, "{}\n"); + Ok(()) + } + + #[test] + fn copying_over_an_existing_file_replaces_it() -> TestResult { + let temp = tempfile::tempdir()?; + let from = temp.path().join("new.csv"); + let to = temp.path().join("old.csv"); + fs::write(&from, "new\n")?; + fs::write(&to, "a much longer old file\n")?; + + copy_file(&from, &to)?; + + assert_eq!(fs::read_to_string(&to)?, "new\n"); + Ok(()) + } + + #[test] + fn a_failed_copy_names_both_paths() -> TestResult { + let temp = tempfile::tempdir()?; + let from = temp.path().join("missing.csv"); + let to = temp.path().join("copy.csv"); + + let Err(error) = copy_file(&from, &to) else { + unreachable!("the source was never written"); + }; + + let Error::Copy { + from: named_from, + to: named_to, + .. + } = &error + else { + unreachable!("a failed copy is an Error::Copy, got {error:?}"); + }; + assert_eq!(named_from, &from); + assert_eq!(named_to, &to); + Ok(()) + } + + #[test] + fn copying_a_directory_walks_into_its_subdirectories() -> TestResult { + let temp = tempfile::tempdir()?; + let from = temp.path().join("session"); + let to = temp.path().join("copy"); + fs::create_dir_all(from.join("data/lcu"))?; + fs::write(from.join("session.json"), "{}\n")?; + fs::write(from.join("data/lcu/speed.csv"), "t,value\n")?; + fs::write(from.join("data/lcu/current.csv"), "t,value\n")?; + + let copied = copy_dir(&from, &to)?; + + assert_eq!(copied, 3); + assert_eq!(fs::read_to_string(to.join("session.json"))?, "{}\n"); + assert_eq!( + fs::read_to_string(to.join("data/lcu/speed.csv"))?, + "t,value\n" + ); + Ok(()) + } + + #[test] + fn copying_a_directory_that_is_not_there_names_it() -> TestResult { + let temp = tempfile::tempdir()?; + let from = temp.path().join("not-a-session"); + + let Err(error) = copy_dir(&from, temp.path().join("copy")) else { + unreachable!("that directory was never created"); + }; + + assert!(matches!(&error, Error::Read { path, .. } if path == &from)); + Ok(()) + } + + #[test] + fn moving_leaves_nothing_behind() -> TestResult { + let temp = tempfile::tempdir()?; + let from = temp.path().join("session.json"); + let to = temp.path().join("done/session.json"); + fs::write(&from, "{}\n")?; + + move_file(&from, &to)?; + + assert!(!from.exists()); + assert_eq!(fs::read_to_string(&to)?, "{}\n"); + Ok(()) + } + + #[test] + fn size_and_remove_report_which_file_was_missing() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("data.csv"); + fs::write(&path, "t,value\n")?; + + assert_eq!(size(&path)?, 8); + remove_file(&path)?; + + let Err(error) = size(&path) else { + unreachable!("the file was just removed"); + }; + assert!(matches!(&error, Error::Read { path: named, .. } if named == &path)); + + let Err(error) = remove_file(&path) else { + unreachable!("the file was just removed"); + }; + assert!(matches!(&error, Error::Remove { path: named, .. } if named == &path)); + Ok(()) + } + + #[test] + fn a_bare_file_name_has_no_directory_to_create() -> TestResult { + // `Path::parent` of a bare name is an empty path, which must not + // reach `create_dir_all` — it would fail, and the directory the + // file is going into (the current one) is already there. + create_parents(Path::new("bare.txt"))?; + Ok(()) + } +} diff --git a/backend/crates/core/src/logger/files/error.rs b/backend/crates/core/src/logger/files/error.rs new file mode 100644 index 000000000..bf3bfeb41 --- /dev/null +++ b/backend/crates/core/src/logger/files/error.rs @@ -0,0 +1,66 @@ +//! Errors produced by the operations in [`crate::logger::files`]. +//! +//! Every variant names the file it happened on, and the two that work on +//! a pair of paths name **both**: "couldn't copy" without saying where to +//! leaves the caller with nothing to act on, and the destination is the +//! half that is usually wrong. + +use std::path::PathBuf; + +/// An error working with a file. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// Couldn't copy the file. + #[error("couldn't copy {from:?} to {to:?}")] + Copy { + /// The file being copied. + from: PathBuf, + /// Where it was being copied to. + to: PathBuf, + /// The underlying I/O error. + #[source] + source: std::io::Error, + }, + + /// Couldn't move the file. + #[error("couldn't move {from:?} to {to:?}")] + Move { + /// The file being moved. + from: PathBuf, + /// Where it was being moved to. + to: PathBuf, + /// The underlying I/O error. + #[source] + source: std::io::Error, + }, + + /// Couldn't create a directory. + #[error("couldn't create the directory {path:?}")] + CreateDir { + /// The directory that couldn't be created. + path: PathBuf, + /// The underlying I/O error. + #[source] + source: std::io::Error, + }, + + /// Couldn't read the file, the directory, or their metadata. + #[error("couldn't read {path:?}")] + Read { + /// The file or directory that couldn't be read. + path: PathBuf, + /// The underlying I/O error. + #[source] + source: std::io::Error, + }, + + /// Couldn't remove the file. + #[error("couldn't remove {path:?}")] + Remove { + /// The file that couldn't be removed. + path: PathBuf, + /// The underlying I/O error. + #[source] + source: std::io::Error, + }, +} diff --git a/backend/crates/core/src/logger/host.rs b/backend/crates/core/src/logger/host.rs new file mode 100644 index 000000000..68ffac93e --- /dev/null +++ b/backend/crates/core/src/logger/host.rs @@ -0,0 +1,480 @@ +//! What the operating system will say about who is running this and +//! where. +//! +//! Part of [`crate::logger`] because it is part of a recording, but +//! not of how one is written: this is the *content* of a recording's +//! metadata, not a way of putting bytes on a disk. Nothing in +//! `logger`'s three formats — nor in [`crate::logger::files`] — uses +//! this module; they still write files without knowing what is in them, +//! and that is worth keeping. +//! +//! One snapshot, [`crate::logger::host::HostInfo::collect`], meant to be written into a +//! recording's metadata so that months later it is still possible to +//! answer *which machine produced this, running which build, and with +//! whose clock and locale*. Every field is optional and nothing here +//! returns a [`Result`]: what the system won't say is simply absent, +//! because a recording must never fail to start over a missing user +//! name. +//! +//! What is deliberately not here: free disk space and memory (another +//! dependency, and the disk is better checked by whoever is about to +//! fill it), the battery, and the network interfaces the backend bound +//! to — that last one belongs to whatever opened the sockets, which is +//! the only thing that actually knows. + +use serde::Serialize; +use std::env; +use std::path::PathBuf; +use std::time::{SystemTime, UNIX_EPOCH}; +use tracing::debug; + +/// Who and what produced a recording. +/// +/// Built with [`HostInfo::collect`] and serialized straight into a +/// metadata file. It is a *snapshot*: the values are read once, when it +/// is built, and never refreshed. +/// +/// Serialize-only on purpose. Reading one back is reading JSON, not +/// rebuilding this struct, and a field like [`HostInfo::os`] is a +/// compile-time constant of the build that wrote it rather than +/// something to parse. +#[derive(Debug, Clone, Serialize)] +pub struct HostInfo { + /// The login name (`javier`), from the operating system. + #[serde(skip_serializing_if = "Option::is_none")] + pub user: Option, + + /// The user's full name as the operating system knows it + /// (`Javier Ribal del Río`), which is not the login name. + #[serde(skip_serializing_if = "Option::is_none")] + pub real_name: Option, + + /// `user.name` from the global git configuration. + #[serde(skip_serializing_if = "Option::is_none")] + pub git_name: Option, + + /// An email address for whoever is running this. See + /// [`HostInfo::collect`] for where it is looked for, and why no + /// operating system is one of the places. + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option, + + /// The machine's name: the one a person would recognize if the + /// system has one, and its network hostname otherwise. + #[serde(skip_serializing_if = "Option::is_none")] + pub host: Option, + + /// The operating system this was built for: `linux`, `macos`, + /// `windows`. + pub os: &'static str, + + /// The processor architecture this was built for: `x86_64`, + /// `aarch64`. + pub arch: &'static str, + + /// The operating system's own name for itself, with its version: + /// `Fedora Linux 44`, `macOS 15.1`, `Windows 11`. + #[serde(skip_serializing_if = "Option::is_none")] + pub distro: Option, + + /// How many threads the machine can actually run at once. + #[serde(skip_serializing_if = "Option::is_none")] + pub cpus: Option, + + /// The version of `software-core` that wrote this. The version of + /// the *binary* is the binary's own to add: this crate can only see + /// its own. + pub core_version: &'static str, + + /// Whether this was built without optimizations and with debug + /// assertions on, which is worth knowing before reading anything + /// into the timings of a recording. + pub debug_build: bool, + + /// The process id, for pairing a recording with whatever else was + /// logging at the time. + pub pid: u32, + + /// The binary that is running, which says which build this was far + /// more precisely than a version number does. + #[serde(skip_serializing_if = "Option::is_none")] + pub exe: Option, + + /// The arguments it was started with, without the program name + /// (which is [`HostInfo::exe`]). Usually this is where the + /// configuration file is named. + pub args: Vec, + + /// The directory it was started from, which is what any relative + /// path in those arguments was resolved against. + #[serde(skip_serializing_if = "Option::is_none")] + pub working_dir: Option, + + /// The time zone the machine is in, as a name like `Europe/Madrid`. + /// + /// Worth more here than it looks: protections and messages carry a + /// time of day and no date or zone, so without knowing the zone of + /// the machine that recorded them they can't be placed on a real + /// timeline, or lined up against video or another machine's log. + #[serde(skip_serializing_if = "Option::is_none")] + pub timezone: Option, + + /// The locale, which decides how dates and numbers get formatted by + /// anything that reads this with the system's settings. + #[serde(skip_serializing_if = "Option::is_none")] + pub locale: Option, + + /// When the snapshot was taken, in seconds since the Unix epoch. + #[serde(skip_serializing_if = "Option::is_none")] + pub started_at_unix: Option, + + /// How many files this process is allowed to have open at once. See + /// [`open_file_limit`], which is the reason this field exists. + #[serde(skip_serializing_if = "Option::is_none")] + pub open_file_limit: Option, +} + +impl HostInfo { + /// Reads everything the system will say, right now. + /// + /// Never fails and never panics: each field is attempted on its own + /// and left empty if it can't be read. + /// + /// The email is looked for in four places, in this order: `user.email` + /// in the global git configuration, then `$GIT_AUTHOR_EMAIL`, then + /// `$EMAIL`, then the account name if it happens to look like an + /// address. **No operating system exposes an email address + /// portably** — macOS keeps one in Contacts and Windows only knows + /// one on a domain-joined machine — so git's own identity is used + /// instead, which is both reliable on a developer's machine and the + /// identity the person is already known by. The git configuration is + /// only read with the `git` feature on; without it, the environment + /// variables are all that is left. + /// + /// # Example + /// + /// ``` + /// use software_core::logger::host::HostInfo; + /// + /// let host = HostInfo::collect(); + /// println!("{}", serde_json::to_string_pretty(&host)?); + /// # Ok::<(), serde_json::Error>(()) + /// ``` + pub fn collect() -> Self { + let git = git_identity(); + + let info = Self { + user: whoami::username().ok(), + real_name: whoami::realname().ok(), + git_name: git.name, + email: git + .email + .or_else(|| var("GIT_AUTHOR_EMAIL")) + .or_else(|| var("EMAIL")) + .or_else(account_email), + host: device_name(), + os: env::consts::OS, + arch: env::consts::ARCH, + distro: whoami::distro().ok(), + cpus: std::thread::available_parallelism().ok().map(Into::into), + core_version: env!("CARGO_PKG_VERSION"), + debug_build: cfg!(debug_assertions), + pid: std::process::id(), + exe: env::current_exe().ok(), + // `args_os`, not `args`: the latter panics on an argument + // that isn't valid Unicode, and nothing in here is allowed + // to bring the process down. + args: env::args_os() + .skip(1) + .map(|arg| arg.to_string_lossy().into_owned()) + .collect(), + working_dir: env::current_dir().ok(), + timezone: timezone(), + locale: locale(), + started_at_unix: unix_seconds(), + open_file_limit: open_file_limit(), + }; + + debug!( + user = ?info.user, + host = ?info.host, + os = info.os, + open_file_limit = ?info.open_file_limit, + "host snapshot taken" + ); + info + } + + /// The same snapshot with everything that identifies a person + /// removed: the user name, the real name, the git name, the email + /// and the machine's name. + /// + /// For when a recording is going to be shared outside the team and + /// only the machine and the build matter. + pub fn without_identity(mut self) -> Self { + self.user = None; + self.real_name = None; + self.git_name = None; + self.email = None; + self.host = None; + self + } +} + +/// The soft limit on how many files this process may have open at once. +/// +/// Worth checking before opening a file per measurement: the default on +/// macOS is **256**, and on Linux usually 1024. Past it, opening a file +/// starts failing in the middle of a recording, which looks like a disk +/// problem and isn't one. +/// +/// `None` on Windows, honestly rather than as a failure: it has no +/// equivalent limit for the handles Rust's [`std::fs::File`] uses. +#[cfg(unix)] +pub fn open_file_limit() -> Option { + rlimit::getrlimit(rlimit::Resource::NOFILE) + .ok() + .map(|(soft, _hard)| soft) +} + +/// The soft limit on how many files this process may have open at once, +/// which Windows does not define for the handles [`std::fs::File`] uses. +#[cfg(not(unix))] +pub fn open_file_limit() -> Option { + None +} + +/// The machine's name. +/// +/// The pretty name first — what a desktop shows, from +/// `/etc/machine-info` on Linux and the sharing name on macOS and +/// Windows — and the network hostname when there isn't one, which on a +/// plain Linux install is the usual case. +fn device_name() -> Option { + whoami::devicename().or_else(|_| whoami::hostname()).ok() +} + +/// The time zone the machine is in, as a zone name. +/// +/// `$TZ` when it is set, which on Linux it usually isn't: the system zone +/// lives in `/etc/localtime`, a link into the zone database whose target +/// ends in the name (`/usr/share/zoneinfo/Europe/Madrid`). Reading the +/// link is how every other tool finds it. Windows keeps its zones under +/// different names entirely and isn't read here, so there it comes down +/// to `$TZ`. +/// +/// A *name* and not an offset on purpose: the offset depends on the date, +/// and the recording this ends up next to may well straddle the day +/// summer time changes. +fn timezone() -> Option { + if let Some(from_environment) = var("TZ") { + return Some(from_environment); + } + + let target = std::fs::read_link("/etc/localtime").ok()?; + + zone_from_link(&target.to_string_lossy()) +} + +/// The zone name at the end of a link into the zone database, or `None` +/// if the target doesn't look like one. +fn zone_from_link(target: &str) -> Option { + let (_, zone) = target.rsplit_once("zoneinfo/")?; + + (!zone.is_empty()).then(|| zone.to_string()) +} + +/// An environment variable, if it is set to something that isn't empty. +fn var(name: &str) -> Option { + let value = env::var_os(name)?; + let value = value.to_string_lossy().trim().to_string(); + + (!value.is_empty()).then_some(value) +} + +/// Seconds since the Unix epoch, or `None` if the clock is set before +/// 1970. +fn unix_seconds() -> Option { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .ok() + .map(|since| since.as_secs()) +} + +/// The locale, from the environment first and from the operating +/// system's own language preferences otherwise — which is what a machine +/// with no `LANG` set, meaning most Windows and macOS desktops, needs. +fn locale() -> Option { + if let Some(from_environment) = var("LC_ALL").or_else(|| var("LANG")) { + return Some(from_environment); + } + + let preferences = whoami::lang_prefs().ok()?; + preferences.time_langs().next().map(|lang| lang.to_string()) +} + +/// Some accounts are named after an email address — a domain-joined +/// Windows account, a managed macOS one — and that is the one place an +/// operating system does hand one over. When the account name looks like +/// an address, take it as one. +fn account_email() -> Option { + whoami::account() + .ok() + .filter(|account| account.contains('@')) +} + +/// The name and email git would sign a commit with on this machine. +#[derive(Debug, Default)] +struct GitIdentity { + /// `user.name`, if it is set. + name: Option, + /// `user.email`, if it is set. + email: Option, +} + +/// Reads `user.name` and `user.email` from the git configuration. +/// +/// Global and system files only. No repository is opened: the identity +/// wanted here is the person's, and it must not depend on which +/// directory the backend happens to have been started from. A global +/// `includeIf` makes this fail, since resolving one needs a repository — +/// hence an empty identity rather than an error. +#[cfg(feature = "git")] +fn git_identity() -> GitIdentity { + let Ok(config) = gix::config::File::from_globals() else { + return GitIdentity::default(); + }; + + let value = |key| { + let raw = config.string(key)?; + let text = String::from_utf8_lossy(&raw).trim().to_string(); + (!text.is_empty()).then_some(text) + }; + + GitIdentity { + name: value("user.name"), + email: value("user.email"), + } +} + +/// Without the `git` feature there is no git configuration to read, so +/// the identity is left to the environment variables. +#[cfg(not(feature = "git"))] +fn git_identity() -> GitIdentity { + GitIdentity::default() +} + +#[cfg(test)] +mod tests { + use super::*; + + type TestResult = Result>; + + #[test] + fn a_snapshot_fills_in_what_the_build_already_knows() -> TestResult { + let host = HostInfo::collect(); + + // The fields that can't be missing, because they are decided at + // compile time or by the process itself. Everything else depends + // on the machine the tests run on and is not asserted here. + assert!(!host.os.is_empty()); + assert!(!host.arch.is_empty()); + assert!(!host.core_version.is_empty()); + assert!(host.pid > 0); + assert_eq!(host.debug_build, cfg!(debug_assertions)); + Ok(()) + } + + #[test] + fn a_snapshot_serializes_without_the_fields_it_could_not_read() -> TestResult { + let host = HostInfo { + user: None, + real_name: None, + git_name: None, + email: None, + host: None, + distro: None, + cpus: None, + exe: None, + working_dir: None, + timezone: None, + locale: None, + started_at_unix: None, + open_file_limit: None, + ..HostInfo::collect() + }; + + let json = serde_json::to_string(&host)?; + + assert!(!json.contains("null"), "{json}"); + assert!(json.contains("\"os\""), "{json}"); + Ok(()) + } + + #[test] + fn without_identity_leaves_the_machine_and_takes_the_person() -> TestResult { + let host = HostInfo { + user: Some("javier".into()), + real_name: Some("Javier".into()), + git_name: Some("Javier".into()), + email: Some("someone@example.test".into()), + host: Some("a-laptop".into()), + ..HostInfo::collect() + } + .without_identity(); + + assert_eq!(host.user, None); + assert_eq!(host.real_name, None); + assert_eq!(host.git_name, None); + assert_eq!(host.email, None); + assert_eq!(host.host, None); + + // The machine and the build survive, which is the point. + assert!(!host.os.is_empty()); + assert!(!host.core_version.is_empty()); + Ok(()) + } + + #[test] + fn unix_reports_a_file_limit_and_windows_says_nothing() -> TestResult { + let limit = open_file_limit(); + + if cfg!(unix) { + let Some(limit) = limit else { + unreachable!("every unix defines RLIMIT_NOFILE"); + }; + assert!(limit > 0); + } else { + assert_eq!(limit, None); + } + Ok(()) + } + + #[test] + fn a_zone_name_is_whatever_follows_the_zone_database() -> TestResult { + assert_eq!( + zone_from_link("/usr/share/zoneinfo/Europe/Madrid").as_deref(), + Some("Europe/Madrid") + ); + // Relative links are just as common as absolute ones. + assert_eq!( + zone_from_link("../usr/share/zoneinfo/UTC").as_deref(), + Some("UTC") + ); + + // Nothing that isn't a zone database link. + assert_eq!(zone_from_link("/etc/localtime"), None); + assert_eq!(zone_from_link("/usr/share/zoneinfo/"), None); + Ok(()) + } + + #[test] + fn a_variable_that_is_not_set_reads_as_none() -> TestResult { + // The other half of `var` — that a variable set to an empty or + // blank string also reads as `None` — can't be tested here: + // setting an environment variable is `unsafe` in this edition, + // and this crate forbids `unsafe`. + assert_eq!(var("SOFTWARE_CORE_UTILS_HOST_UNSET"), None); + Ok(()) + } +} diff --git a/backend/crates/core/src/logger/json.rs b/backend/crates/core/src/logger/json.rs new file mode 100644 index 000000000..b2b78510a --- /dev/null +++ b/backend/crates/core/src/logger/json.rs @@ -0,0 +1,619 @@ +//! JSON documents: written whole, read back whole, and updated by +//! being replaced. +//! +//! Two ways in, for two different jobs. [`write_json`] and [`read_json`] +//! are one-shot and typed: the caller has a type for the whole document +//! and hands it over, or gets it back. [`JsonDocument`] is for the file +//! that gains properties over time — a recording's metadata, written +//! when it starts and added to when it stops — which has to be read +//! before it can be added to, and whose properties this crate knows +//! nothing about have to survive the round trip all the same. +//! +//! Reading is deliberate here and nowhere else in the module: a JSON +//! document is small, whole and structured, so reading it back to change +//! it is the only way to change it. A CSV or a text log is appended to, +//! never revisited, and nothing here will read one back. +//! +//! None of this keeps a file open between calls, which is why nothing +//! here uses the `Target` that `csv` and `text` are built on: a document +//! lives in memory, and getting it onto the disk is one atomic +//! replacement, the same one [`write_json`] performs. + +use super::Error; +use super::target::create_file; +use serde::Serialize; +use serde::de::DeserializeOwned; +use serde_json::{Map, Value}; +use std::ffi::OsString; +use std::fs; +use std::io::Write; +use std::path::{Path, PathBuf}; +use tracing::debug; + +/// Writes `value` to `path` as pretty-printed JSON, creating its parent +/// directories and replacing whatever was there. +/// +/// Pretty-printed, with a trailing newline, because these are the files +/// a person opens to find out what a recording was: a session's +/// metadata, the ADJ commit it ran against, a dump of the configuration +/// in use. Anything appended to over time wants a CSV +/// ([`super::CsvFile`]) instead — this function writes the file once and +/// closes it. +/// +/// Written through a temporary file next to the destination, flushed to +/// the disk and then renamed over it, so `path` is never seen +/// half-written: either the old contents or the new ones, nothing in +/// between. That matters more here than anywhere else in this module — +/// a fatal error in the backend ends in `std::process::exit`, and a +/// session's metadata truncated at that moment is what makes every CSV +/// next to it unreadable. The rename needs both files on the same +/// filesystem, which they are by construction, being siblings. What +/// isn't covered: the directory entry itself isn't synced, so a power +/// cut in the instant after the rename can still lose it — surviving +/// that would mean syncing the directory too, which isn't worth it for +/// what this writes. +/// +/// # Example +/// +/// ``` +/// use software_core::logger::write_json; +/// use std::collections::BTreeMap; +/// +/// let path = std::env::temp_dir().join("software-core-logger-doc/write.json"); +/// let settings = BTreeMap::from([("adj_commit", "4f1c3b0"), ("time_unit", "us")]); +/// +/// write_json(&path, &settings)?; +/// +/// assert_eq!( +/// std::fs::read_to_string(&path)?, +/// "{\n \"adj_commit\": \"4f1c3b0\",\n \"time_unit\": \"us\"\n}\n", +/// ); +/// # std::fs::remove_file(&path)?; +/// # Ok::<(), Box>(()) +/// ``` +pub fn write_json(path: impl AsRef, value: &T) -> Result<(), Error> +where + T: Serialize + ?Sized, +{ + let path = path.as_ref(); + let temporary = temporary_path(path); + + // Anything that fails from here on leaves the destination untouched, + // so the temporary file is cleaned up and the error is about `path`, + // which is the file the caller asked for and the only one it knows. + match build(&temporary, path, value) { + Ok(()) => {} + Err(error) => { + // Best effort: the write already failed, and failing to + // remove the leftover is not what the caller needs to hear. + let _ = fs::remove_file(&temporary); + return Err(error); + } + } + + fs::rename(&temporary, path).map_err(|source| Error::Replace { + path: path.to_path_buf(), + source, + })?; + + debug!(path = %path.display(), "json file written"); + Ok(()) +} + +/// Serializes `value` into `temporary` and gets it onto the disk, with +/// every error reported against `path`, the destination it is about to +/// be renamed to. +fn build(temporary: &Path, path: &Path, value: &T) -> Result<(), Error> +where + T: Serialize + ?Sized, +{ + // `create_file` reports the file it actually tried to make: the + // temporary one, which the caller never named. Every error out of + // here is about the destination, so put its path back. + let mut writer = create_file(temporary).map_err(|error| match error { + Error::Create { source, .. } => Error::Create { + path: path.to_path_buf(), + source, + }, + other => other, + })?; + + serde_json::to_writer_pretty(&mut writer, value).map_err(|source| Error::Serialize { + path: path.to_path_buf(), + source, + })?; + + // `to_writer_pretty` leaves no terminator: add one so the file reads + // well with `cat` and behaves for anything line-oriented. + writer.write_all(b"\n").map_err(|source| Error::Write { + label: path.display().to_string(), + source, + })?; + + // The buffer is dropped with this function, and a drop swallows the + // flush error — so flush here, where it can still be reported. + writer.flush().map_err(|source| Error::Flush { + label: path.display().to_string(), + source, + })?; + + // Flushing only hands the bytes to the operating system. Syncing + // before the rename is what makes the swap meaningful: otherwise the + // rename can be on the disk while the contents it points at are + // still only in the page cache. Affordable here, where it happens + // once per file, in a way it wouldn't be per CSV row. + writer.get_ref().sync_all().map_err(|source| Error::Flush { + label: path.display().to_string(), + source, + }) +} + +/// The temporary name a document is built under: the destination's own +/// name plus `.tmp`, so it lands in the same directory — and therefore +/// the same filesystem, which [`fs::rename`] needs to be atomic. +fn temporary_path(path: &Path) -> PathBuf { + let mut name = OsString::from(path); + name.push(".tmp"); + PathBuf::from(name) +} + +/// Reads `path` and parses the whole document as `T`. +/// +/// The counterpart of [`write_json`], for a document whose shape the +/// caller has a type for. To read one property out of a document, or to +/// add properties to it, use [`JsonDocument`] instead. +/// +/// # Example +/// +/// ``` +/// use software_core::logger::{read_json, write_json}; +/// use std::collections::BTreeMap; +/// +/// let path = std::env::temp_dir().join("software-core-logger-doc/read.json"); +/// let written = BTreeMap::from([("time_unit".to_string(), "us".to_string())]); +/// write_json(&path, &written)?; +/// +/// let read: BTreeMap = read_json(&path)?; +/// assert_eq!(read, written); +/// # std::fs::remove_file(&path)?; +/// # Ok::<(), Box>(()) +/// ``` +pub fn read_json(path: impl AsRef) -> Result +where + T: DeserializeOwned, +{ + let path = path.as_ref(); + let text = read_text(path)?; + + serde_json::from_str(&text).map_err(|source| Error::Parse { + path: path.to_path_buf(), + source, + }) +} + +/// A JSON object held in memory, together with the file it came from. +/// +/// For the document that is added to over time instead of written once: +/// open it, set the properties that are known now, save, and later open +/// it again and set the ones that weren't. Properties nobody here knows +/// about are kept as they were — the document is edited, not rebuilt +/// from a struct that would have dropped them. +/// +/// Changes stay in memory until [`JsonDocument::save`], which replaces +/// the file atomically. Nothing is held open in between, so a document +/// can be opened, saved and forgotten without any flushing discipline. +/// +/// Properties come out in alphabetical order, which is `serde_json`'s +/// own ordering for an object and not something this type imposes: the +/// same document always serializes the same way, which is what makes it +/// readable in a diff. +/// +/// # Example +/// +/// ``` +/// use software_core::logger::JsonDocument; +/// +/// let path = std::env::temp_dir().join("software-core-logger-doc/document.json"); +/// +/// let mut session = JsonDocument::new(&path); +/// session +/// .set("adj_commit", "4f1c3b0")? +/// .set("time_unit", "us")?; +/// session.save()?; +/// +/// // Later, when the recording stops, by whoever has the path. +/// let mut session = JsonDocument::open(&path)?; +/// session.set("rows", 128_000u64)?.set("stopped", true)?; +/// session.save()?; +/// +/// let session = JsonDocument::open(&path)?; +/// assert_eq!(session.get::("adj_commit")?.as_deref(), Some("4f1c3b0")); +/// assert_eq!(session.get::("rows")?, Some(128_000)); +/// # std::fs::remove_file(&path)?; +/// # Ok::<(), Box>(()) +/// ``` +#[derive(Debug, Clone)] +pub struct JsonDocument { + path: PathBuf, + properties: Map, +} + +impl JsonDocument { + /// An empty document for `path`, which isn't touched until + /// [`JsonDocument::save`]. + pub fn new(path: impl Into) -> Self { + Self { + path: path.into(), + properties: Map::new(), + } + } + + /// Reads the document at `path`. + /// + /// Errors if the file isn't there ([`Error::Read`]), isn't valid + /// JSON ([`Error::Parse`]), or is valid JSON whose root isn't an + /// object and therefore has no properties + /// ([`Error::NotAnObject`]). Use [`JsonDocument::open_or_new`] when + /// a missing file just means there is nothing in it yet. + pub fn open(path: impl Into) -> Result { + let path = path.into(); + let text = read_text(&path)?; + + let value: Value = serde_json::from_str(&text).map_err(|source| Error::Parse { + path: path.clone(), + source, + })?; + + match value { + Value::Object(properties) => Ok(Self { path, properties }), + _ => Err(Error::NotAnObject { path }), + } + } + + /// Like [`JsonDocument::open`], but a file that isn't there yet + /// gives an empty document instead of an error. + /// + /// Only a missing file is forgiven: one that exists and is broken + /// still errors, rather than quietly starting over and overwriting + /// it on the next save. + pub fn open_or_new(path: impl Into) -> Result { + let path = path.into(); + + match Self::open(&path) { + Err(Error::Read { source, .. }) if source.kind() == std::io::ErrorKind::NotFound => { + Ok(Self::new(path)) + } + other => other, + } + } + + /// Sets `key`, replacing whatever was there. + /// + /// Takes anything serializable, so a property can be a number, a + /// string, a list or a whole struct. Returns `&mut Self` so several + /// can be chained: `doc.set("a", 1)?.set("b", 2)?;`. + pub fn set( + &mut self, + key: impl Into, + value: impl Serialize, + ) -> Result<&mut Self, Error> { + let value = serde_json::to_value(value).map_err(|source| Error::Serialize { + path: self.path.clone(), + source, + })?; + + self.properties.insert(key.into(), value); + Ok(self) + } + + /// Reads `key` as `T`, or `None` if the document has no such + /// property. + /// + /// Errors with [`Error::Parse`] if the property is there but isn't a + /// `T`. + pub fn get(&self, key: &str) -> Result, Error> + where + T: DeserializeOwned, + { + let Some(value) = self.properties.get(key) else { + return Ok(None); + }; + + serde_json::from_value(value.clone()) + .map(Some) + .map_err(|source| Error::Parse { + path: self.path.clone(), + source, + }) + } + + /// Whether the document has a `key` property. + pub fn contains(&self, key: &str) -> bool { + self.properties.contains_key(key) + } + + /// Removes `key`, reporting whether it was there. + pub fn remove(&mut self, key: &str) -> bool { + self.properties.remove(key).is_some() + } + + /// Every property, as they will be written. + pub fn properties(&self) -> &Map { + &self.properties + } + + /// The file this document is read from and saved to. + pub fn path(&self) -> &Path { + &self.path + } + + /// Writes the document back, replacing the file atomically. + pub fn save(&self) -> Result<(), Error> { + write_json(&self.path, &self.properties) + } +} + +/// Reads a whole file as text, naming it in the error. +fn read_text(path: &Path) -> Result { + fs::read_to_string(path).map_err(|source| Error::Read { + path: path.to_path_buf(), + source, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde::Serializer; + use std::collections::BTreeMap; + use std::fs; + + type TestResult = Result>; + + fn settings() -> BTreeMap { + BTreeMap::from([ + ("adj_commit".to_string(), "4f1c3b0".to_string()), + ("time_unit".to_string(), "us".to_string()), + ]) + } + + #[test] + fn writes_pretty_json_with_a_trailing_newline_creating_the_parents() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("session/others/settings.json"); + + write_json(&path, &settings())?; + + assert_eq!( + fs::read_to_string(&path)?, + "{\n \"adj_commit\": \"4f1c3b0\",\n \"time_unit\": \"us\"\n}\n" + ); + Ok(()) + } + + #[test] + fn what_was_written_parses_back_to_the_same_value() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("settings.json"); + + write_json(&path, &settings())?; + + let read: BTreeMap = serde_json::from_str(&fs::read_to_string(&path)?)?; + assert_eq!(read, settings()); + Ok(()) + } + + #[test] + fn writing_replaces_an_existing_file_rather_than_appending() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("settings.json"); + + write_json(&path, &settings())?; + write_json(&path, &BTreeMap::from([("time_unit", "ms")]))?; + + assert_eq!( + fs::read_to_string(&path)?, + "{\n \"time_unit\": \"ms\"\n}\n" + ); + Ok(()) + } + + /// A value that fails halfway through being serialized, to check + /// what the destination looks like when that happens. + #[derive(Debug)] + struct Unserializable; + + impl Serialize for Unserializable { + fn serialize(&self, _serializer: S) -> Result { + Err(serde::ser::Error::custom("not today")) + } + } + + #[test] + fn a_successful_write_leaves_no_temporary_file_behind() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("settings.json"); + + write_json(&path, &settings())?; + + assert!(path.exists()); + assert!(!temporary_path(&path).exists()); + Ok(()) + } + + #[test] + fn a_failed_write_leaves_the_previous_contents_untouched() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("settings.json"); + write_json(&path, &settings())?; + let before = fs::read_to_string(&path)?; + + let Err(error) = write_json(&path, &Unserializable) else { + unreachable!("this value can't be serialized"); + }; + assert!(matches!(error, Error::Serialize { .. })); + + // The destination still holds the old document, whole, and the + // half-written one is gone rather than left next to it. + assert_eq!(fs::read_to_string(&path)?, before); + assert!(!temporary_path(&path).exists()); + Ok(()) + } + + #[test] + fn the_temporary_file_is_a_sibling_so_the_rename_stays_atomic() { + let path = Path::new("/var/log/session/settings.json"); + let temporary = temporary_path(path); + + assert_eq!(temporary.parent(), path.parent()); + assert_eq!(temporary.file_name(), Some("settings.json.tmp".as_ref())); + } + + #[test] + fn read_json_gets_back_what_write_json_put_there() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("settings.json"); + write_json(&path, &settings())?; + + let read: BTreeMap = read_json(&path)?; + + assert_eq!(read, settings()); + Ok(()) + } + + #[test] + fn reading_names_the_file_when_it_is_missing_or_broken() -> TestResult { + let temp = tempfile::tempdir()?; + let missing = temp.path().join("not-there.json"); + let broken = temp.path().join("broken.json"); + fs::write(&broken, "{ not json")?; + + let Err(absent) = read_json::>(&missing) else { + unreachable!("that file was never written"); + }; + assert!(matches!(&absent, Error::Read { path, .. } if path == &missing)); + + let Err(malformed) = read_json::>(&broken) else { + unreachable!("that file is not valid JSON"); + }; + assert!(matches!(&malformed, Error::Parse { path, .. } if path == &broken)); + Ok(()) + } + + #[test] + fn a_document_takes_several_properties_and_reads_them_back() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("session.json"); + + let mut session = JsonDocument::new(&path); + session + .set("adj_commit", "4f1c3b0")? + .set("time_unit", "us")? + .set("rows", 128_000u64)?; + session.save()?; + + let session = JsonDocument::open(&path)?; + assert_eq!( + session.get::("adj_commit")?.as_deref(), + Some("4f1c3b0") + ); + assert_eq!(session.get::("rows")?, Some(128_000)); + assert_eq!(session.get::("never_set")?, None); + assert!(session.contains("time_unit")); + Ok(()) + } + + #[test] + fn adding_properties_keeps_the_ones_already_in_the_file() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("session.json"); + // A document with a property no type in this crate mentions. + fs::write(&path, "{\n \"written_by_someone_else\": [1, 2, 3]\n}\n")?; + + let mut session = JsonDocument::open(&path)?; + session.set("stopped", true)?; + session.save()?; + + let session = JsonDocument::open(&path)?; + assert_eq!( + session.get::>("written_by_someone_else")?, + Some(vec![1, 2, 3]) + ); + assert_eq!(session.get::("stopped")?, Some(true)); + Ok(()) + } + + #[test] + fn a_property_read_as_the_wrong_type_is_an_error_not_a_none() -> TestResult { + let path = Path::new("in-memory.json"); + let mut session = JsonDocument::new(path); + session.set("rows", "not a number")?; + + let Err(error) = session.get::("rows") else { + unreachable!("a string is not a u64"); + }; + + assert!(matches!(&error, Error::Parse { path: named, .. } if named == path)); + Ok(()) + } + + #[test] + fn removing_a_property_reports_whether_it_was_there() -> TestResult { + let mut session = JsonDocument::new("in-memory.json"); + session.set("time_unit", "us")?; + + assert!(session.remove("time_unit")); + assert!(!session.remove("time_unit")); + assert!(session.properties().is_empty()); + Ok(()) + } + + #[test] + fn open_or_new_forgives_a_missing_file_but_not_a_broken_one() -> TestResult { + let temp = tempfile::tempdir()?; + let missing = temp.path().join("session.json"); + let broken = temp.path().join("broken.json"); + fs::write(&broken, "{ not json")?; + + let mut session = JsonDocument::open_or_new(&missing)?; + assert!(session.properties().is_empty()); + session.set("time_unit", "us")?; + session.save()?; + assert!(missing.exists()); + + assert!(matches!( + JsonDocument::open_or_new(&broken), + Err(Error::Parse { .. }) + )); + Ok(()) + } + + #[test] + fn a_document_whose_root_is_not_an_object_has_no_properties_to_add_to() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("list.json"); + fs::write(&path, "[1, 2, 3]\n")?; + + let Err(error) = JsonDocument::open(&path) else { + unreachable!("the root of that document is an array"); + }; + + assert!(matches!(&error, Error::NotAnObject { path: named } if named == &path)); + Ok(()) + } + + #[test] + fn a_path_whose_parent_is_a_file_reports_which_file_it_was() -> TestResult { + let temp = tempfile::tempdir()?; + let blocking = temp.path().join("settings.json"); + write_json(&blocking, &settings())?; + + let path = blocking.join("nested.json"); + let Err(error) = write_json(&path, &settings()) else { + unreachable!("a file can't be used as a directory"); + }; + + assert!(matches!(&error, Error::Create { path: failed, .. } if failed == &path)); + Ok(()) + } +} diff --git a/backend/crates/core/src/logger/target.rs b/backend/crates/core/src/logger/target.rs new file mode 100644 index 000000000..f6bb33325 --- /dev/null +++ b/backend/crates/core/src/logger/target.rs @@ -0,0 +1,242 @@ +//! The handle discipline every file in this module shares: the label +//! that names it in its errors, the poisoning after a failed write, the +//! explicit flush, and the courtesy flush on drop. +//! +//! Private, and not a trait: [`super::CsvFile`] and [`super::TextFile`] +//! differ in what they put *in* a file (columns and quoting versus +//! lines), not in how they hold one. Keeping that part here is what +//! makes "flushing is explicit, and a failed write stops the file" one +//! behaviour rather than two copies of it that can drift. + +use super::Error; +use std::fs::{self, File, OpenOptions}; +use std::io::{BufWriter, Read, Seek, SeekFrom, Write}; +use std::path::Path; +use tracing::error; + +/// An open destination, plus the name it answers to in errors. +#[derive(Debug)] +pub(super) struct Target { + inner: W, // The actual file or buffer being written to. + label: String, // + poisoned: bool, // Whether a write or flush failed, so all future writes fail too. + closed: bool, // Whether the caller has called `close()`, so `Drop` doesn't flush again. + written: u64, // Total bytes written to the destination so far. + since_flush: u64, // Bytes written since the last successful flush, for the caller to decide when to flush. +} + +impl Target { + /// Takes over an already-open destination, to be called `label` in + /// any [`Error`] about it. + pub(super) fn new(inner: W, label: String) -> Self { + Self { + inner, + label, + poisoned: false, + closed: false, + written: 0, + since_flush: 0, + } + } + + /// What this destination is called in its errors. + pub(super) fn label(&self) -> &str { + &self.label + } + + /// Borrows the destination itself. + pub(super) fn get_ref(&self) -> &W { + &self.inner + } + + /// Whether an earlier write or flush failed. + pub(super) fn is_poisoned(&self) -> bool { + self.poisoned + } + + /// Every byte handed to the destination so far. + pub(super) fn bytes_written(&self) -> u64 { + self.written + } + + /// The bytes handed over since the last successful flush. + pub(super) fn bytes_since_flush(&self) -> u64 { + self.since_flush + } + + /// The error to return instead of touching a poisoned destination. + pub(super) fn poisoned_error(&self) -> Error { + Error::Poisoned { + label: self.label.clone(), + } + } + + /// Writes `bytes` in one call, poisoning the destination if it + /// fails: a write that failed halfway already left the file + /// inconsistent. + pub(super) fn write_all(&mut self, bytes: &[u8]) -> Result<(), Error> { + if self.poisoned { + return Err(self.poisoned_error()); + } + + match self.inner.write_all(bytes) { + Ok(()) => { + let bytes = bytes.len() as u64; + self.written += bytes; + self.since_flush += bytes; + Ok(()) + } + Err(source) => { + self.poisoned = true; + Err(Error::Write { + label: self.label.clone(), + source, + }) + } + } + } + + /// Flushes everything written so far. + pub(super) fn flush(&mut self) -> Result<(), Error> { + if self.poisoned { + return Err(self.poisoned_error()); + } + + match self.inner.flush() { + Ok(()) => { + self.since_flush = 0; + Ok(()) + } + Err(source) => { + self.poisoned = true; + Err(Error::Flush { + label: self.label.clone(), + source, + }) + } + } + } + + /// Flushes and marks the destination closed, so [`Drop`] neither + /// flushes again nor traces an error the caller is already getting. + pub(super) fn close(&mut self) -> Result<(), Error> { + let result = self.flush(); + self.closed = true; + result + } +} + +impl Drop for Target { + fn drop(&mut self) { + if self.closed || self.poisoned { + return; + } + + // A courtesy flush, nothing more: `Drop` can't return the error + // and the workspace lints rule out panicking, so all it can do + // is leave a trace saying this file's tail may be missing. + if let Err(source) = self.inner.flush() { + error!( + file = %self.label, + error = %source, + "file dropped without close() and its final flush failed" + ); + } + } +} + +/// Creates (or truncates) the file at `path`, creating its parent +/// directories, and wraps it in a buffer. +/// +/// The default [`BufWriter`] capacity is deliberate: a bigger buffer is +/// less I/O but more lost if the process dies before the next flush, and +/// how often to flush is a decision for whoever is writing. +pub(super) fn create_file(path: &Path) -> Result, Error> { + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).map_err(|source| Error::Create { + path: path.to_path_buf(), + source, + })?; + } + + let file = File::create(path).map_err(|source| Error::Create { + path: path.to_path_buf(), + source, + })?; + + Ok(BufWriter::new(file)) +} + +/// Opens `path` to add to the end of it, creating the file and its parent +/// directories if they aren't there. +/// +/// Returns the destination together with how many bytes the file already +/// held, which is what tells a brand new (or empty) file from one that +/// has content in it. +/// +/// If that content doesn't end in a newline, one is written before +/// anything else, so what gets appended starts on its own line instead of +/// being glued onto the last one. That is the only thing looked at: what +/// the existing content *says* is never read or checked. +pub(super) fn append_file(path: &Path) -> Result<(BufWriter, u64), Error> { + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).map_err(|source| Error::Create { + path: path.to_path_buf(), + source, + })?; + } + + let mut file = OpenOptions::new() + // Readable as well as appendable: the last byte has to be looked + // at to know whether a newline is owed. Appending still lands at + // the end of the file however the read leaves the cursor. + .read(true) + .append(true) + .create(true) + .open(path) + .map_err(|source| Error::Create { + path: path.to_path_buf(), + source, + })?; + + let existing = file + .metadata() + .map_err(|source| Error::Read { + path: path.to_path_buf(), + source, + })? + .len(); + + if !ends_with_newline(&mut file, existing, path)? { + // Opened in append mode, so this lands at the end of the file + // wherever the read above left the cursor. + file.write_all(b"\n").map_err(|source| Error::Write { + label: path.display().to_string(), + source, + })?; + } + + Ok((BufWriter::new(file), existing)) +} + +/// Whether the last byte of `file` is a newline. An empty file counts as +/// ending in one: there is no half-written line to finish. +fn ends_with_newline(file: &mut File, len: u64, path: &Path) -> Result { + let Some(last_byte) = len.checked_sub(1) else { + return Ok(true); + }; + + file.seek(SeekFrom::Start(last_byte)) + .map_err(|source| Error::Read { + path: path.to_path_buf(), + source, + })?; + + let mut last = [0u8; 1]; + file.read_exact(&mut last).map_err(|source| Error::Read { + path: path.to_path_buf(), + source, + })?; + + Ok(last[0] == b'\n') +} diff --git a/backend/crates/core/src/logger/text.rs b/backend/crates/core/src/logger/text.rs new file mode 100644 index 000000000..e27d4a8b2 --- /dev/null +++ b/backend/crates/core/src/logger/text.rs @@ -0,0 +1,300 @@ +//! A plain text file, written a line at a time. + +use super::Error; +use super::target::{Target, append_file, create_file}; +use std::fs::File; +use std::io::{BufWriter, Write}; +use std::path::Path; +use tracing::debug; + +/// A text file being written to, one line at a time. +/// +/// Deliberately the same vocabulary as [`crate::logger::CsvFile`] — +/// `create`, `new`, `flush`, `close`, `get_ref`, `is_poisoned`, the same +/// [`Error`], the same poisoning after a failed write and the same +/// courtesy flush on drop — so there is nothing to relearn moving +/// between the two. +/// +/// What it does *not* have is everything that only means something for +/// columns: no header, no field count, no quoting. A line is written +/// exactly as given, with a `\n` after it, and a line that contains a +/// comma or a quote is not special in any way. That also means a text +/// file can't tell you a line came out malformed — if the content has +/// fields in it, it wants [`crate::logger::CsvFile`] instead. +/// +/// # Example +/// +/// ``` +/// use software_core::logger::TextFile; +/// +/// let mut log = TextFile::new(Vec::new(), "in memory"); +/// log.write_line("session started")?; +/// log.write_line("board LCU connected")?; +/// +/// assert_eq!(log.get_ref().as_slice(), b"session started\nboard LCU connected\n"); +/// # Ok::<(), Box>(()) +/// ``` +#[derive(Debug)] +pub struct TextFile> { + target: Target, + /// The line currently being written, reused across lines so writing + /// one allocates nothing. + buf: Vec, +} + +impl TextFile> { + /// Creates (or truncates) the file at `path`, creating its parent + /// directories. + pub fn create(path: impl AsRef) -> Result { + let path = path.as_ref(); + let file = Self::new(create_file(path)?, path.display().to_string()); + debug!(path = %path.display(), "text file created"); + Ok(file) + } + + /// Opens the file at `path` to add lines to the end of it, creating it + /// and its parent directories if they aren't there. + /// + /// Nothing about what the file already contains is read, with one + /// exception: if it doesn't end in a newline, one is written first, so + /// the first new line can't continue a half-finished one. + pub fn append(path: impl AsRef) -> Result { + let path = path.as_ref(); + let (writer, existing) = append_file(path)?; + let file = Self::new(writer, path.display().to_string()); + debug!( + path = %path.display(), + existing_bytes = existing, + "text file opened to append" + ); + Ok(file) + } +} + +impl TextFile { + /// Wraps an already-open destination. + /// + /// `label` is what this file is called in any [`Error`] it produces; + /// [`TextFile::create`] uses the path for it. + /// + /// Unlike [`crate::logger::CsvFile::new`] this can't fail: there is + /// no header to write before the caller's first line. + pub fn new(inner: W, label: impl Into) -> Self { + Self { + target: Target::new(inner, label.into()), + buf: Vec::new(), + } + } + + /// Writes `line`, followed by a `\n`. + /// + /// The line and its terminator reach the destination as a single + /// write, so a line lands whole or not at all — the same guarantee + /// a CSV row gets. + pub fn write_line(&mut self, line: &str) -> Result<(), Error> { + self.buf.clear(); + self.buf.extend_from_slice(line.as_bytes()); + self.buf.push(b'\n'); + self.target.write_all(&self.buf) + } + + /// Flushes everything written so far to the destination. + pub fn flush(&mut self) -> Result<(), Error> { + self.target.flush() + } + + /// Flushes and closes the file, reporting a failure instead of + /// swallowing it like [`Drop`] has to. + pub fn close(mut self) -> Result<(), Error> { + self.target.close() + } + + /// Borrows the destination, e.g. to read back what was written to an + /// in-memory buffer. + pub fn get_ref(&self) -> &W { + self.target.get_ref() + } + + /// Whether an earlier write or flush failed, leaving this file + /// closed to further writes. + pub fn is_poisoned(&self) -> bool { + self.target.is_poisoned() + } + + /// What this file is called in its errors: the path it was created + /// with, or the label it was given. + /// + /// Worth having beyond [`Error`]'s own text: a caller that notices a + /// file went [`TextFile::is_poisoned`] has no error in hand any more, + /// and still needs to say which file stopped. + pub fn label(&self) -> &str { + self.target.label() + } + + /// Every byte handed to the destination so far, line terminators + /// included — the file's size on disk, once flushed. + pub fn bytes_written(&self) -> u64 { + self.target.bytes_written() + } + + /// The bytes written since the last successful flush. + /// + /// This is what a flush policy is built on: "flush every so many + /// kilobytes, or every so often" is the caller's decision (see this + /// module's docs), and this saves it from keeping its own tally for + /// each of the hundreds of files it may have open. + pub fn bytes_since_flush(&self) -> u64 { + self.target.bytes_since_flush() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + + type TestResult = Result>; + + fn written(text: &TextFile>) -> String { + String::from_utf8_lossy(text.get_ref()).into_owned() + } + + /// A destination that takes `ok_writes` writes and fails every one + /// after that — what a full disk looks like from in here. + #[derive(Debug)] + struct FailsAfter { + ok_writes: usize, + } + + impl Write for FailsAfter { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if self.ok_writes == 0 { + return Err(std::io::Error::other("disk full")); + } + self.ok_writes -= 1; + Ok(buf.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + #[test] + fn appending_keeps_the_lines_that_were_already_there() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("output/build.txt"); + + let mut log = TextFile::create(&path)?; + log.write_line("compiling")?; + log.close()?; + + let mut log = TextFile::append(&path)?; + log.write_line("done")?; + log.close()?; + + assert_eq!(fs::read_to_string(&path)?, "compiling\ndone\n"); + Ok(()) + } + + #[test] + fn appending_to_content_that_lacks_its_last_newline_starts_a_fresh_line() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("script.log"); + fs::write(&path, "the script stopped here")?; + + let mut log = TextFile::append(&path)?; + log.write_line("and this is ours")?; + log.close()?; + + assert_eq!( + fs::read_to_string(&path)?, + "the script stopped here\nand this is ours\n" + ); + Ok(()) + } + + #[test] + fn every_line_is_written_with_its_terminator() -> TestResult { + let mut text = TextFile::new(Vec::new(), "in memory"); + + text.write_line("session started")?; + text.write_line("board LCU connected")?; + + assert_eq!(written(&text), "session started\nboard LCU connected\n"); + Ok(()) + } + + #[test] + fn an_empty_line_is_just_a_terminator() -> TestResult { + let mut text = TextFile::new(Vec::new(), "in memory"); + + text.write_line("")?; + text.write_line("after the blank")?; + + assert_eq!(written(&text), "\nafter the blank\n"); + Ok(()) + } + + #[test] + fn a_line_is_written_verbatim_with_no_quoting() -> TestResult { + let mut text = TextFile::new(Vec::new(), "in memory"); + + text.write_line("LCU, bay 2: say \"hi\"")?; + + assert_eq!(written(&text), "LCU, bay 2: say \"hi\"\n"); + Ok(()) + } + + #[test] + fn a_failed_write_poisons_the_file() -> TestResult { + let mut text = TextFile::new(FailsAfter { ok_writes: 1 }, "failing"); + + text.write_line("this one gets through")?; + assert!(matches!( + text.write_line("this one doesn't"), + Err(Error::Write { .. }) + )); + assert!(text.is_poisoned()); + + assert!(matches!( + text.write_line("nor this one"), + Err(Error::Poisoned { .. }) + )); + assert!(matches!(text.flush(), Err(Error::Poisoned { .. }))); + Ok(()) + } + + #[test] + fn a_file_reports_the_name_it_answers_to_and_the_bytes_it_has_taken() -> TestResult { + let mut text = TextFile::new(Vec::new(), "in memory"); + assert_eq!(text.label(), "in memory"); + assert_eq!(text.bytes_written(), 0); + + text.write_line("session started")?; + assert_eq!(text.bytes_written(), "session started\n".len() as u64); + assert_eq!(text.bytes_since_flush(), "session started\n".len() as u64); + + text.flush()?; + assert_eq!(text.bytes_since_flush(), 0); + assert_eq!(text.bytes_written(), "session started\n".len() as u64); + Ok(()) + } + + #[test] + fn create_makes_the_parent_directories_and_close_persists_every_line() -> TestResult { + let temp = tempfile::tempdir()?; + let path = temp.path().join("session/others/session.log"); + + let mut text = TextFile::create(&path)?; + text.write_line("session started")?; + text.write_line("session stopped")?; + text.close()?; + + assert_eq!( + fs::read_to_string(&path)?, + "session started\nsession stopped\n" + ); + Ok(()) + } +} 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/net.rs b/backend/crates/core/src/net.rs index ff2824e13..3ba454472 100644 --- a/backend/crates/core/src/net.rs +++ b/backend/crates/core/src/net.rs @@ -33,7 +33,7 @@ //! //! Addresses are for the operator, not for the domain types: they show //! up interpolated in each submodule's error messages (`tcp::Error`, -//! `udp::Error`), which is where somebody actually reads them. +//! `udp::UdpError`), which is where somebody actually reads them. mod error; mod report; diff --git a/backend/crates/core/src/net/README.md b/backend/crates/core/src/net/README.md index f5f9cd5f3..dde1b5bd3 100644 --- a/backend/crates/core/src/net/README.md +++ b/backend/crates/core/src/net/README.md @@ -10,9 +10,10 @@ Two submodules do the I/O, and **this directory's shared part opens nothing**: net/ ├── net.rs # module root: docs and re-exports ├── report.rs # Event, Notification, ErrorReport, Reporter — what is reported -├── error.rs # Error — aggregates tcp::Error / udp::Error, nothing else +├── error.rs # Error — aggregates tcp::Error / udp::UdpError, nothing else ├── tcp.rs # the TCP client (not written yet: error type + contract) -└── udp.rs # the shared UDP socket (not written yet: error type + contract) +├── udp.rs # the shared UDP socket +└── udp/ # its tests: tests.rs, test_support.rs, manual_tests.rs (load probe) ``` ## The shared part @@ -35,7 +36,7 @@ And the board is all the identity there is: one connection per board, one shared socket for UDP, so nothing needs telling apart beyond it. Addresses are for the operator, not for the domain types: they show up -interpolated in `tcp::Error`/`udp::Error` messages, which is where somebody +interpolated in `tcp::Error`/`udp::UdpError` messages, which is where somebody actually reads them. ### `Event` and `Notification` — what happened, and when @@ -86,7 +87,7 @@ that it can afford to queue behind telemetry. failed lives inside the `Error` variant, which is the only place that always has it. A datagram that fails to decode resolves to no board at all — its id is not in the ADJ, so there is no `PacketDef` to ask — and all that can be said about it is -the address it came from, which is what `udp::Error::Decode` holds. +the address it came from, which is what `udp::UdpError::Decode` holds. ### `Error` — aggregation only @@ -102,14 +103,14 @@ submodule's own error: nobody outside knows which of its variants are fatal. | | `tcp` | `udp` | |---|---|---| -| Entry point | `spawn(Config, Arc, Reporter) -> Handles` | `spawn(Config, Arc, Reporter) -> Result, Error>` (binds first) | +| Entry point | `spawn(Config, Arc, Reporter) -> Handles` | `spawn_udp(UdpConfig, Arc, Reporter) -> Result, UdpError>` (binds first) | | Inputs | its `Config` (boards, timeouts, backoff, keep-alive) | its `Config` (bind address, `SO_RCVBUF`) | | Role | client only; one connection per board, one task each | one shared socket, receive-only, one task | | Framing | buffer + `&mut Cursor` + advance by `cursor.position()`; bail out past 374 bytes | none — `recv_from` delivers a whole datagram into a reused 64 KiB buffer | | Writing | yes (orders, keep-alive); a single writer task per connection | no | | On a decode error | report it; **fatal**, and close/reopen the connection (the stream cannot be resynchronised) | report it; **fatal**, and keep receiving | | `Connected`/`Disconnected` | per board | never | -| Fault | writes it: `Handles::propagate_fault()`, id 0 to every board | cannot write; only reports | +| Fault | writes it: `Handles::propagate_fault()`, id 0 to every board | cannot write; a received id 0 is reported as `UdpError::Fault`, before decoding | Both take the same two things besides their own `Config`: an `Arc` — the only part of the ADJ `net` needs, owned by `station` and read-only here — and a @@ -121,7 +122,9 @@ which is also what lets a test point it at a fake peer. reads `is_fatal()` and calls `Handles::propagate_fault()`, which puts the order with id 0 into every board's writer channel (the Go backend's `SendFault`). A *received* packet with id 0 is the same action requested by a board, and -`station` answers it the same way. +`station` answers it the same way. In `udp` it arrives on the error channel as +`UdpError::Fault { from }`: recognised by its id alone, before decoding, without +looking at the ADJ. Three rules both follow: @@ -131,18 +134,23 @@ Three rules both follow: ### What "fatal" means -`tcp::Error::is_fatal`/`udp::Error::is_fatal` are about the **pod**, not about -this process: it means the pod has to be sent to fault, and the backend -**stays up** — still reading, still serving the frontend, still recording — so the -operator can see why. Nothing in `net` ever calls `std::process::exit`. +`tcp::Error::is_fatal`/`udp::UdpError::is_fatal` are about the **pod**: they say +the pod has to be sent to fault. They are a hint, not a decision — what happens +next (the fault, closing the connections, shutting the backend down safely) is +decided by whoever consumes the error channel (`station`). Nothing in `net` ever +calls `std::process::exit`. -Only a decode failure is fatal, on either transport, and this is a deliberate +On either transport, a decode failure is fatal, and this is a deliberate departure from Go. Nothing corrupts a frame or a datagram in flight (both transports checksum, TCP retransmits, and the pod's network does not fragment), so something that will not decode means the loaded ADJ does not describe what the firmware is sending — which reconnecting cannot fix. A failed connect or write is *not* fatal: that is what the backoff is for. +Two more are fatal in `udp`: losing the socket (`UdpError::Recv`), which is every +board's telemetry gone at once, and a fault sent by a board (`UdpError::Fault`, +packet id 0), which is a board asking for exactly that. + `net` never raises the fault itself — neither transport does. It logs, it reports, and `is_fatal()` is the classification whoever consumes the error channel acts on. That is deliberate: a mismatched ADJ fails on every frame that follows, thousands diff --git a/backend/crates/core/src/net/error.rs b/backend/crates/core/src/net/error.rs index 64109a954..1588e2043 100644 --- a/backend/crates/core/src/net/error.rs +++ b/backend/crates/core/src/net/error.rs @@ -24,5 +24,5 @@ pub enum Error { Tcp(#[from] tcp::Error), /// On the shared UDP socket. #[error(transparent)] - Udp(#[from] udp::Error), + Udp(#[from] udp::UdpError), } diff --git a/backend/crates/core/src/net/report.rs b/backend/crates/core/src/net/report.rs index 35f7dc16c..7ff356f1f 100644 --- a/backend/crates/core/src/net/report.rs +++ b/backend/crates/core/src/net/report.rs @@ -57,7 +57,7 @@ pub struct Notification { /// board at all — its id is not in the ADJ, so there is no /// [`crate::model::PacketDef`] to ask — and all that can be said about /// it is the address it came from, which is exactly what -/// [`super::udp::Error::Decode`] holds. +/// [`super::udp::UdpError::Decode`] holds. #[derive(Debug)] pub struct ErrorReport { /// The instant the failure was reported, on the same clock as @@ -207,8 +207,8 @@ mod tests { Event::Received(Packet::Data(DataPacket::new(AdjId(1000), vec![]))) } - fn an_error() -> udp::Error { - udp::Error::Recv { + fn an_error() -> udp::UdpError { + udp::UdpError::Recv { source: std::io::Error::from(std::io::ErrorKind::ConnectionReset), } } @@ -333,7 +333,7 @@ mod tests { let Some(report) = sinks.errors.recv().await else { unreachable!("exactly one error was reported"); }; - let Error::Udp(udp::Error::Recv { .. }) = report.error else { + let Error::Udp(udp::UdpError::Recv { .. }) = report.error else { unreachable!("a udp error should arrive as Error::Udp"); }; // Nothing reached the notification channel. @@ -343,14 +343,14 @@ mod tests { #[test] fn a_udp_decode_error_keeps_the_address_it_cannot_resolve_to_a_board() { let addr = SocketAddr::new(IpAddr::from([192, 168, 1, 3]), 50400); - let error = udp::Error::Decode { + let error = udp::UdpError::Decode { from: addr, source: crate::protocol::DecodeError::UnknownId(AdjId(9999)), }; // The whole reason an error report carries no board: this one has // an address, and no board to attribute it to. - let Error::Udp(udp::Error::Decode { from, .. }) = Error::from(error) else { + let Error::Udp(udp::UdpError::Decode { from, .. }) = Error::from(error) else { unreachable!("a decode error should convert into Error::Udp"); }; assert_eq!(from, addr); diff --git a/backend/crates/core/src/net/udp.rs b/backend/crates/core/src/net/udp.rs index e8048507b..e1be8f6cb 100644 --- a/backend/crates/core/src/net/udp.rs +++ b/backend/crates/core/src/net/udp.rs @@ -1,20 +1,15 @@ //! The shared UDP socket: one socket, receive-only, every board's //! telemetry. //! -//! **Not written yet.** This file currently holds only the error type -//! [`super::Error`] aggregates, plus the contract below, so that the rest -//! of `net` compiles and whoever implements this module knows what the -//! shared part expects of it. See [`super`] and `net/README.md`. -//! //! # What this module is //! //! One socket bound to the backend's own address, carrying `Data` packets -//! from every board. Nothing is ever sent from it. One task is enough: -//! there is no per-board state to keep. +//! from every board, and the fault (packet id 0) any of them may send. +//! Nothing is ever sent from it. //! //! # Entry point //! -//! [`spawn`], taking [`Config`], an `Arc` and a +//! [`spawn_udp`], taking [`UdpConfig`], an `Arc` and a //! [`super::Reporter`] — written out with its reasoning on the items //! themselves. No handle comes back beyond the `JoinHandle`: there is no //! writing side. @@ -26,59 +21,118 @@ //! none of [`super::tcp`]'s buffer applies here. Read into one reused //! 64 KiB buffer and a datagram can never be silently truncated, //! whatever the ADJ grows to. -//! - The loop does three things and nothing else: receive, decode with -//! [`crate::protocol::udp::decode_datagram`], report. No disk, no -//! WebSocket, no aggregation — the socket's receive buffer is where -//! packets get dropped if this task falls behind, and the kernel drops -//! them silently, so this loop stays as short as it can be. Raising -//! `SO_RCVBUF` is part of setting the socket up. +//! - The loop does three things and nothing else: decode with +//! [`crate::protocol::udp::decode_datagram`], resolve the board, report +//! (a fault skips the first two, see below). No disk, no WebSocket, no +//! aggregation. +//! - **Packet id 0 is a fault** ([`UdpError::Fault`]): what a board sends +//! when it has detected an error. It is recognised by its id alone, +//! **before** decoding: it is not in the ADJ, the [`crate::protocol::Index`] +//! is not consulted and nothing after the id is read. It goes down the +//! error channel with the address it came from, the only thing that +//! says which board sent it. //! - [`super::Notification::board`] comes from the decoded packet's id, //! through [`crate::protocol::Index`] — every //! [`crate::model::PacketDef`] carries its `board` — so that a //! notification looks the same whichever transport brought it. That is //! one `HashMap` lookup per datagram, done here once rather than //! repeated by every consumer downstream. -//! - **A decode failure is fatal**: see [`Error::is_fatal`]. Nothing -//! corrupts a datagram in flight — UDP checksums it and the pod's -//! network does not fragment it — so a datagram that will not decode -//! means the ADJ this backend loaded does not describe what the boards -//! are actually sending, and every datagram after it is suspect for the -//! same reason. So: log it and report it on the error channel, exactly -//! as [`super::tcp`] does — and that is all. This socket writes -//! nothing, and sending the pod to fault is not `net`'s call anyway: -//! whoever consumes the error channel reads [`Error::is_fatal`] and -//! decides, which also keeps the "fault once" guard in one place -//! rather than one per transport. Keep receiving meanwhile: a -//! mismatched ADJ fails on every datagram that follows, several -//! thousand a second, and each one is reported, not acted on. +//! - **A decode failure is reported as fatal** (see [`UdpError::is_fatal`]), +//! but acting on it is not this module's call. Nothing corrupts a +//! datagram in flight — UDP checksums it and the pod's network does not +//! fragment it — so a datagram that will not decode most likely means +//! the ADJ this backend loaded does not describe what the boards are +//! actually sending. This module traces it and reports it on the error +//! channel, exactly as [`super::tcp`] does — and that is all. Whoever +//! consumes the error channel decides what happens next (sending the +//! pod to fault, shutting down), which also keeps the "fault once" guard +//! in one place rather than one per transport. +//! - **Every failure is reported, but the trace is rate-limited.** A +//! mismatched ADJ fails on every datagram that follows, several thousand +//! a second. Each one still goes down the error channel, so the consumer +//! sees them all; the trace gets the first one and then at most one line +//! a second, carrying how many were left out since the previous line. +//! Decode failures and faults are limited separately, so a burst of one +//! never hides the other. //! - [`super::Event::Connected`]/[`super::Event::Disconnected`] are never //! emitted: there is no connection to come up or go down. //! - Binding happens **before** the task is spawned, so a bad address is //! a startup failure returned to whoever is composing the backend -//! (`station::vehicle::bootstrap`), not something reported once +//! (`station`), not something reported once //! everything is already running. Hence the entry point returns -//! `Result, Error>`. +//! `Result, UdpError>`. +//! +//! # Stopping +//! +//! The loop stops on its own when a report fails because the consumer is +//! gone — but it only finds out the next time it has something to report, +//! that is, on the next datagram. With no telemetry arriving (boards off, +//! cable out), closing the [`super::Sinks`] alone leaves the task waiting +//! on the socket. +//! +//! To stop it at a moment of the caller's choosing (a shutdown), call +//! [`JoinHandle::abort`] on the handle [`spawn_udp`] returns. That is safe: +//! the task holds nothing that needs flushing, and all that is lost is +//! whatever was still sitting in the kernel's receive buffer. +//! +//! # Tests +//! +//! Kept out of this file, next to it in `udp/`: +//! +//! - `tests.rs` — unit tests, and tests through a real socket on loopback. +//! - `test_support.rs` — the fixtures both share: a minimal ADJ index, +//! loopback sockets, and waits on the reporter's channels that fail +//! instead of hanging. +//! - `manual_tests.rs` — `manual_udp_load`, an ignored load probe that +//! checks the loop keeps up with 25 Mbit/s of 76-byte datagrams: +//! +//! ```sh +//! cargo test -p software-core --features net --release manual_udp_load -- --ignored --nocapture +//! ``` use super::Reporter; +use crate::model::Packet; use crate::protocol::{DecodeError, Index}; use std::net::SocketAddr; use std::sync::Arc; +use std::time::{Duration, Instant}; use tokio::task::JoinHandle; +use tracing::{error, info, warn}; /// How to set the shared socket up. /// /// Everything here is resolved by `station` before `net` is reached: this /// module reads no config file and no ADJ of its own. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Config { - /// Where to bind: the backend's own address, `backend_ip` + - /// `ports["UDP"]` in the ADJ's general info. +pub struct UdpConfig { + /// Where to bind: the backend's own address, `addresses["backend"]` + /// and `ports["UDP"]` in the ADJ's `general_info.json`. pub addr: SocketAddr, - /// `SO_RCVBUF`, in bytes. + /// `SO_RCVBUF` to request, in bytes. /// /// The only thing absorbing a stall of the receive loop, since the - /// kernel drops the tail silently once it is full: 2 MiB is about - /// 0.8 s of margin at 20 Mbit/s. + /// kernel drops the tail silently once it is full. + /// + /// The margin it buys is counted in **datagrams**, not bytes: the + /// kernel charges each datagram its bookkeeping on top of its payload. + /// Measured on Linux over loopback, a 76-byte datagram (the average of + /// the H11 packets) takes about 960 bytes of buffer, so 2 MiB requested + /// (4 MiB granted, see below) holds about 4,400 datagrams — roughly + /// 0.1 s at 25 Mbit/s of 76-byte datagrams (~41,000 a second). A real + /// network card's driver may charge a different amount; measure on the + /// station's own machine. + /// + /// **This margin can be widened** by requesting more and raising the OS + /// limit so that the request is granted. On Linux, with + /// `sudo sysctl -w net.core.rmem_max=16777216` (16 MiB) and 16 MiB + /// requested here, 32 MiB are granted: by the figure above about 35,000 + /// datagrams, roughly 0.8 s at that rate. `sysctl -w` is lost on reboot; + /// to keep it, put `net.core.rmem_max = 16777216` in a file under + /// `/etc/sysctl.d/`. The limits on Windows and macOS have not been checked. + /// + /// The operating system may grant less than this — Linux silently caps + /// it at `net.core.rmem_max` — so [`spawn_udp`] reads the granted size back + /// and warns when it is smaller than requested. pub recv_buffer: usize, } @@ -94,23 +148,235 @@ pub struct Config { /// and hands out clones; it is read-only here, and a reload of the ADJ is /// a new [`Index`] with a new task, never a mutation of this one. /// +/// The returned handle is also how to stop the task: see the module's +/// "Stopping" section. +/// /// # Errors /// -/// [`Error::Bind`] only — every later failure goes out through +/// [`UdpError::Bind`] only — every later failure goes out through /// `reporter`, since by then there is nobody left to return it to. -pub fn spawn(config: Config, adj: Arc, reporter: Reporter) -> Result, Error> { - let _ = (config, adj, reporter); - todo!("the UDP socket is not written yet: see this module's contract") +pub fn spawn_udp( + config: UdpConfig, + adj: Arc, + reporter: Reporter, +) -> Result, UdpError> { + let socket = bind_telemetry_socket(config)?; + let handle = tokio::spawn(receive_telemetry(socket, adj, reporter)); + Ok(handle) +} + +/// Binds a UDP socket and configures its OS-level receive buffer size (`SO_RCVBUF`). +fn bind_telemetry_socket(config: UdpConfig) -> Result { + // Bind using the standard library socket first so we can configure non-blocking mode. + let std_socket = std::net::UdpSocket::bind(config.addr).map_err(|source| UdpError::Bind { + addr: config.addr, + source, + })?; + + // Tokio requires the underlying std socket to be in non-blocking mode. + std_socket + .set_nonblocking(true) + .map_err(|source| UdpError::Bind { + addr: config.addr, + source, + })?; + + // Convert the standard socket into an async Tokio UdpSocket. + let socket = tokio::net::UdpSocket::from_std(std_socket).map_err(|source| UdpError::Bind { + addr: config.addr, + source, + })?; + + // Asking is not getting: Linux caps the request at `net.core.rmem_max` + // without returning an error, so the size actually granted has to be + // read back. Linux also reports back twice what it granted (it reserves + // the other half for bookkeeping, see socket(7)): with `rmem_max` at + // 4 MiB, asking for 2 MiB reads back 4 MiB and asking for 16 MiB reads + // back 8 MiB. So on Linux a full grant reads back as twice the request, + // and anything less means the request was capped. Elsewhere the value + // read back is compared with the request as is. + let full_grant = if cfg!(target_os = "linux") { + config.recv_buffer.saturating_mul(2) + } else { + config.recv_buffer + }; + let sock_ref = socket2::SockRef::from(&socket); + let granted = sock_ref + .set_recv_buffer_size(config.recv_buffer) + .and_then(|()| sock_ref.recv_buffer_size()); + match granted { + Ok(granted) if granted >= full_grant => { + info!( + addr = %config.addr, + requested = config.recv_buffer, + granted, + "SO_RCVBUF set" + ); + } + Ok(granted) => { + warn!( + addr = %config.addr, + requested = config.recv_buffer, + granted, + "SO_RCVBUF is smaller than requested, so a stall loses datagrams sooner; \ + raise the OS limit (net.core.rmem_max on Linux) for more margin" + ); + } + Err(e) => { + warn!( + addr = %config.addr, + requested = config.recv_buffer, + %e, + "could not set SO_RCVBUF, using system default" + ); + } + } + + Ok(socket) } -/// Something that went wrong on the shared UDP socket. +/// Main UDP loop: reads datagrams into a reusable 64 KiB buffer, decodes in-place, and reports. +async fn receive_telemetry(socket: tokio::net::UdpSocket, adj: Arc, reporter: Reporter) { + // Reusable 64 KiB buffer — a datagram can never be silently truncated. + let mut buf = vec![0u8; 64 * 1024]; + let mut traces = ReceiveTraces::default(); + + loop { + match socket.recv_from(&mut buf).await { + Ok((len, from)) => { + if !decode_and_report(&buf[..len], from, &adj, &reporter, &mut traces).await { + // Downstream channels closed; exit cleanly. + break; + } + } + Err(source) => { + // Socket-level receive failure: log, report as fatal to the backend, and stop. + let err = UdpError::Recv { source }; + error!(%err, "UDP receive error"); + let _ = reporter.report(err).await; + break; + } + } + } +} + +/// The first two bytes of a fault datagram: packet id 0, little-endian +/// like every id on the wire. +/// +/// A board that has detected an error sends it. It is not declared in the +/// ADJ, and the Go backend broadcasts the same id to every board when it +/// raises a fault itself (`SendFault`). +const FAULT_ID: [u8; 2] = 0u16.to_le_bytes(); + +/// Decodes a single datagram slice against `adj` and forwards the result or error to `reporter`. +/// +/// A fault (packet id 0, see [`FAULT_ID`]) is reported before any of that, +/// without looking at `adj`. +/// +/// Returns `false` if the downstream `reporter` channels have closed and the loop should stop. +async fn decode_and_report( + bytes: &[u8], + from: SocketAddr, + adj: &Index, + reporter: &Reporter, + traces: &mut ReceiveTraces, +) -> bool { + if bytes.starts_with(&FAULT_ID) { + if let Some(suppressed) = traces.fault.should_trace(Instant::now()) { + error!(%from, suppressed, "a board signalled a fault (packet id 0)"); + } + return reporter.report(UdpError::Fault { from }).await.is_ok(); + } + + let packet = match crate::protocol::udp::decode_datagram(bytes, adj) { + Ok(p) => p, + Err(source) => { + if let Some(suppressed) = traces.decode.should_trace(Instant::now()) { + error!(%from, %source, suppressed, "UDP datagram could not be decoded"); + } + let error = UdpError::Decode { from, source }; + return reporter.report(error).await.is_ok(); + } + }; + + // A second lookup of the id `decode_datagram` has just resolved: it + // returns the packet, not its definition. Decoding already rejected + // any id the index does not know, so this branch is not expected to + // run; it is handled rather than unwrapped because the decode lives + // in another module. One extra `HashMap` lookup per datagram is not + // worth changing `protocol`'s API to avoid. + let Some(packet_def) = adj.packet(packet.id) else { + warn!(id = ?packet.id, "decoded packet id not in index"); + return true; + }; + + let board = packet_def.board; + + reporter + .notify(board, super::Event::Received(Packet::Data(packet))) + .await + .is_ok() +} + +/// How often, at most, each kind of failure reaches the trace. +const TRACE_INTERVAL: Duration = Duration::from_secs(1); + +/// The receive loop's trace rate limits, one per kind of failure, so that +/// a burst of decode failures never hides a fault from the trace, nor the +/// other way round. +#[derive(Debug, Default)] +struct ReceiveTraces { + /// Datagrams that would not decode. + decode: TraceRateLimit, + /// Faults (packet id 0). + fault: TraceRateLimit, +} + +/// Rate limit for tracing one kind of failure. +/// +/// Only the trace is limited: every failure is still reported down the +/// error channel. A burst that stops is summed up by the next failure +/// that gets traced, so if no further failure ever comes, its count is +/// only in the error channel — which already had every one of them. +#[derive(Debug, Default)] +struct TraceRateLimit { + /// Failures not traced since the last one that was. + suppressed: u64, + /// When a failure was last traced. + last: Option, +} + +impl TraceRateLimit { + /// Decides whether the failure seen at `now` is traced. + /// + /// `Some(n)` means trace it, `n` being how many were left out since the + /// previous traced one (`0` for the first). `None` means count it + /// only. `now` is a parameter rather than read here so that the + /// decision can be tested without waiting for real time to pass. + fn should_trace(&mut self, now: Instant) -> Option { + match self.last { + Some(last) if now.saturating_duration_since(last) < TRACE_INTERVAL => { + self.suppressed += 1; + None + } + _ => { + self.last = Some(now); + Some(std::mem::take(&mut self.suppressed)) + } + } + } +} + +/// Something that went wrong on the shared UDP socket, or that a board +/// says went wrong ([`UdpError::Fault`]). /// /// No [`crate::model::BoardId`] in any variant, on purpose: the socket /// belongs to no board, and a datagram that fails to decode may not -/// resolve to one at all — [`Error::Decode`] carries the address it came -/// from, which is the only identity that always exists. +/// resolve to one at all — [`UdpError::Decode`] and [`UdpError::Fault`] +/// carry the address the datagram came from, which is the only identity +/// that always exists. #[derive(Debug, thiserror::Error)] -pub enum Error { +pub enum UdpError { /// The socket could not be bound, so no telemetry will arrive at all. #[error("could not bind the shared UDP socket to {addr}")] Bind { @@ -129,9 +395,9 @@ pub enum Error { source: std::io::Error, }, - /// A datagram could not be decoded, which means the loaded ADJ does - /// not describe what the boards are sending. Fatal: see - /// [`Error::is_fatal`]. + /// A datagram could not be decoded, which most likely means the loaded + /// ADJ does not describe what the boards are sending. See + /// [`UdpError::is_fatal`]. #[error("could not decode a datagram from {from}")] Decode { /// Where the datagram came from — there may be no board to @@ -141,77 +407,57 @@ pub enum Error { #[source] source: DecodeError, }, + + /// A board has detected an error and said so with a fault: a datagram + /// whose packet id is 0. Not a failure of this socket — the datagram + /// arrived fine — but the pod telling the backend it is in trouble. + #[error("the board at {from} signalled a fault (packet id 0)")] + Fault { + /// Where the fault came from: the board's address, since a fault + /// carries nothing else that says which board sent it. + from: SocketAddr, + }, } -impl Error { - /// Whether this error means the pod has to be sent to fault. +impl UdpError { + /// Whether this module considers the error serious enough to send the + /// pod to fault. /// - /// "Fatal" is about the **pod**, not about this process: the backend - /// stays up — still reading, still serving the frontend, still - /// recording — so that whoever is operating the pod can see what - /// happened. Nothing here ever calls `std::process::exit`. + /// A **hint** for whoever consumes the error channel, not a decision: + /// `net` never raises the fault and never stops the process. What to + /// do about a fatal error — sending the pod to fault, shutting the + /// backend down, or something else — is decided by the application + /// (`station`), which may also look at the error's details (such as + /// the [`DecodeError`] variant) rather than at this answer alone. /// /// Both runtime failures of this socket qualify, and for the same /// reason: neither can be true of a single datagram. - /// [`Error::Decode`] means the loaded ADJ does not describe what the - /// boards are sending, and [`Error::Recv`] means the socket itself is - /// no longer usable, which is every board's telemetry gone at once. - /// Neither is something a retry fixes. + /// [`UdpError::Decode`] most likely means the loaded ADJ does not describe + /// what the boards are sending, and [`UdpError::Recv`] means the socket + /// itself is no longer usable, which is every board's telemetry gone + /// at once. Neither is something a retry fixes. + /// + /// [`UdpError::Fault`] is fatal by definition: it is a board asking for + /// the pod to go to fault. /// - /// [`Error::Bind`] never reaches this: binding happens before the - /// task is spawned, so it is a startup failure handed back to - /// whoever composes the backend. + /// [`UdpError::Bind`] never reaches the error channel: binding happens + /// before the task is spawned, so it is a startup failure handed back + /// to whoever composes the backend. pub fn is_fatal(&self) -> bool { - // Matched exhaustively rather than just returning `true`: a - // variant added later has to say which it is instead of - // inheriting this answer in silence. match self { - Error::Bind { .. } | Error::Recv { .. } | Error::Decode { .. } => true, + UdpError::Bind { .. } + | UdpError::Recv { .. } + | UdpError::Decode { .. } + | UdpError::Fault { .. } => true, } } } #[cfg(test)] -mod tests { - use super::*; - use crate::model::AdjId; - use std::net::IpAddr; - - fn peer() -> SocketAddr { - SocketAddr::new(IpAddr::from([192, 168, 1, 3]), 50400) - } - - #[test] - fn a_datagram_that_will_not_decode_faults_the_pod() { - let error = Error::Decode { - from: peer(), - source: DecodeError::UnknownId(AdjId(9999)), - }; - - // Nothing corrupts a datagram in flight, so this is a mismatched - // ADJ, not noise to skip over. - assert!(error.is_fatal()); - } - - #[test] - fn losing_the_socket_faults_the_pod_too() { - let error = Error::Recv { - source: std::io::Error::from(std::io::ErrorKind::ConnectionReset), - }; - - // Every board's telemetry at once. - assert!(error.is_fatal()); - } +mod manual_tests; - #[test] - fn a_decode_failure_says_where_it_came_from() { - let error = Error::Decode { - from: peer(), - source: DecodeError::UnknownId(AdjId(9999)), - }; +#[cfg(test)] +mod test_support; - // The only identity it has: there is no board to attribute an - // undeclared id to. - assert!(error.to_string().contains("192.168.1.3:50400")); - } -} +#[cfg(test)] +mod tests; diff --git a/backend/crates/core/src/net/udp/manual_tests.rs b/backend/crates/core/src/net/udp/manual_tests.rs new file mode 100644 index 000000000..eb890291d --- /dev/null +++ b/backend/crates/core/src/net/udp/manual_tests.rs @@ -0,0 +1,225 @@ +//! Manual load probe: can the receive loop keep up with the pod's +//! telemetry? +//! +//! Ignored by a normal `cargo test`. It sends 76-byte datagrams over +//! loopback at `UDP_LOAD_MBIT` Mbit/s (default 25, about 41,000 datagrams +//! a second) for `UDP_LOAD_SECS` seconds (default 10), through the real +//! socket, decode and reporter, into a consumer that only counts. It fails +//! if any datagram is lost or fails to decode. `UDP_LOAD_RCVBUF` sets the +//! `SO_RCVBUF` requested (default 2 MiB). Run it in release, which is how +//! the station runs: +//! +//! ```sh +//! cargo test -p software-core --features net --release manual_udp_load -- --ignored --nocapture +//! UDP_LOAD_MBIT=40 cargo test -p software-core --features net --release manual_udp_load -- --ignored --nocapture +//! ``` +//! +//! What it does **not** tell: the cost of the real consumer (`station`'s +//! event loop), which comes on top — a consumer that only adds a timer per +//! message was already enough to lose 0.7 % at 25 Mbit/s. And loopback is +//! not the pod's network: sender and receiver share this machine's CPUs, +//! and there is no network card. + +use super::test_support::{any_loopback_port, bind_on_loopback}; +use super::*; +use crate::model::{ + AdjId, Board, BoardId, DataPacket, MacAddress, Measurement, MeasurementKind, NumericKind, + PacketDef, PacketType, PodData, Value, +}; +use std::collections::HashMap; +use std::net::IpAddr; + +/// Bytes of one datagram in the probe: 2 of id and 74 of values. +const PROBE_DATAGRAM_LEN: usize = 76; + +fn measurement_with_id(id: u16, kind: MeasurementKind) -> Measurement { + Measurement { + id: AdjId(id), + alias: format!("m{id}"), + name: format!("measurement {id}"), + display_units: String::new(), + kind, + protections: vec![], + } +} + +/// An index with one `Data` packet (id 1000, board 1) whose datagram is +/// [`PROBE_DATAGRAM_LEN`] bytes, mixing value types the way board telemetry +/// does — floats, integers, enums (which decode into a `String`) and +/// booleans — together with the bytes of one such datagram. +fn telemetry_index_and_datagram() -> (Index, Vec) { + let mut measurements = Vec::new(); + let mut values = Vec::new(); + let mut add = |kind: MeasurementKind, value: Value, count: usize| { + for _ in 0..count { + let id = u16::try_from(measurements.len() + 1).unwrap_or(u16::MAX); + measurements.push(measurement_with_id(id, kind.clone())); + values.push(value.clone()); + } + }; + let numeric = |wire_type| MeasurementKind::Numeric { wire_type }; + let options = vec!["Idle".to_string(), "Running".into(), "Fault".into()]; + + add(numeric(NumericKind::F32), Value::Number(21.5), 14); // 56 bytes + add(numeric(NumericKind::U16), Value::Number(1234.0), 4); // 8 bytes + add(numeric(NumericKind::U8), Value::Number(7.0), 6); // 6 bytes + add(MeasurementKind::Enum { options }, Value::Number(1.0), 2); // 2 bytes + add(MeasurementKind::Boolean, Value::Bool(true), 2); // 2 bytes + + let packet = PacketDef { + id: AdjId(1000), + board: BoardId(1), + name: "telemetry".to_string(), + packet_type: PacketType::Data(measurements), + }; + let board = Board { + id: BoardId(1), + name: "TEST".to_string(), + ip: IpAddr::from([127, 0, 0, 1]), + mac: MacAddress([0; 6]), + packets: HashMap::from([(packet.id, packet)]), + }; + let index = Index::new( + &PodData { + boards: HashMap::from([(board.id, board)]), + }, + None, + ); + + let datagram = + crate::protocol::packet::data_order::encode(&DataPacket::new(AdjId(1000), values), &index); + let Ok(datagram) = datagram else { + unreachable!("the probe's telemetry packet should encode"); + }; + assert_eq!(datagram.len(), PROBE_DATAGRAM_LEN); + (index, datagram) +} + +/// Sends `datagram` to `to` at `per_second` for `duration`, paced in short +/// bursts as a board's network would deliver it. Returns how many were +/// sent and how many sends failed. +fn send_at_rate( + to: SocketAddr, + datagram: &[u8], + per_second: f64, + duration: Duration, +) -> (u64, u64) { + let Ok(socket) = std::net::UdpSocket::bind(any_loopback_port()) else { + unreachable!("binding the probe's sending socket should succeed"); + }; + let start = Instant::now(); + let (mut sent, mut failed) = (0u64, 0u64); + while start.elapsed() < duration { + let due = (start.elapsed().as_secs_f64() * per_second) as u64; + while sent + failed < due { + match socket.send_to(datagram, to) { + Ok(_) => sent += 1, + Err(_) => failed += 1, + } + } + std::thread::sleep(Duration::from_micros(200)); + } + (sent, failed) +} + +/// The kernel's count of UDP datagrams dropped for lack of receive buffer, +/// system-wide (`RcvbufErrors` in `/proc/net/snmp`). Linux only. +fn kernel_rcvbuf_errors() -> Option { + let snmp = std::fs::read_to_string("/proc/net/snmp").ok()?; + let mut udp = snmp.lines().filter(|line| line.starts_with("Udp:")); + let header = udp.next()?; + let values = udp.next()?; + let column = header + .split_whitespace() + .position(|c| c == "RcvbufErrors")?; + values.split_whitespace().nth(column)?.parse().ok() +} + +/// The environment variable `name` parsed as `T`, or `default`. +fn env_var_or(name: &str, default: T) -> T { + std::env::var(name) + .ok() + .and_then(|value| value.parse().ok()) + .unwrap_or(default) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "load probe: run in release with --ignored --nocapture"] +async fn manual_udp_load() { + let mbit: f64 = env_var_or("UDP_LOAD_MBIT", 25.0); + let secs: u64 = env_var_or("UDP_LOAD_SECS", 10); + let recv_buffer: usize = env_var_or("UDP_LOAD_RCVBUF", 2 * 1024 * 1024); + let per_second = mbit * 1_000_000.0 / 8.0 / PROBE_DATAGRAM_LEN as f64; + let (index, datagram) = telemetry_index_and_datagram(); + + let (socket, addr) = bind_on_loopback(recv_buffer); + let granted = socket2::SockRef::from(&socket).recv_buffer_size().ok(); + let (reporter, mut sinks) = Reporter::channels(8192, 16); + let receiver = tokio::spawn(receive_telemetry(socket, Arc::new(index), reporter)); + + // Counts until told the sender is done, then drains what is left. No + // timer per message, so that the consumer costs as little as possible + // and what is measured is this module. + let (done_tx, mut done_rx) = tokio::sync::oneshot::channel::<()>(); + let consumer = tokio::spawn(async move { + let (mut received, mut errors) = (0u64, 0u64); + loop { + tokio::select! { + biased; + Some(_) = sinks.notifications.recv() => received += 1, + Some(_) = sinks.errors.recv() => errors += 1, + _ = &mut done_rx => break, + } + } + while let Ok(Some(_)) = + tokio::time::timeout(Duration::from_millis(200), sinks.notifications.recv()).await + { + received += 1; + } + while sinks.errors.try_recv().is_ok() { + errors += 1; + } + (received, errors) + }); + + let drops_before = kernel_rcvbuf_errors(); + let started = Instant::now(); + let sender = tokio::task::spawn_blocking(move || { + send_at_rate(addr, &datagram, per_second, Duration::from_secs(secs)) + }); + let Ok((sent, failed)) = sender.await else { + unreachable!("the sender thread should not panic"); + }; + let send_time = started.elapsed(); + let _ = done_tx.send(()); + let Ok((received, errors)) = consumer.await else { + unreachable!("the consumer task should not panic"); + }; + let drops = match (drops_before, kernel_rcvbuf_errors()) { + (Some(before), Some(after)) => format!("+{}", after.saturating_sub(before)), + _ => "unavailable".to_string(), + }; + receiver.abort(); + + let lost = sent.saturating_sub(received); + println!( + "UDP load probe: {mbit} Mbit/s in {PROBE_DATAGRAM_LEN}-byte datagrams \ + = {per_second:.0} datagrams/s, for {secs} s" + ); + println!( + " sent {sent} in {:.2} s ({:.0}/s), {failed} sends failed", + send_time.as_secs_f64(), + sent as f64 / send_time.as_secs_f64() + ); + println!( + " received {received}, lost {lost} ({:.4} %), decode errors {errors}", + 100.0 * lost as f64 / sent.max(1) as f64 + ); + println!( + " SO_RCVBUF requested {recv_buffer} bytes, read back {granted:?}; \ + kernel RcvbufErrors (system-wide): {drops}" + ); + + assert_eq!(errors, 0, "every datagram should decode"); + assert_eq!(lost, 0, "every datagram sent should be received"); +} diff --git a/backend/crates/core/src/net/udp/test_support.rs b/backend/crates/core/src/net/udp/test_support.rs new file mode 100644 index 000000000..aa8425133 --- /dev/null +++ b/backend/crates/core/src/net/udp/test_support.rs @@ -0,0 +1,129 @@ +//! Fixtures shared by `tests.rs` and `manual_tests.rs`: a minimal ADJ +//! index, loopback sockets, and waits on the reporter's channels that fail +//! instead of hanging. + +use super::*; +use crate::model::{AdjId, Board, BoardId, MacAddress, PacketDef, PacketType, PodData}; +use crate::net::{ErrorReport, Event, Notification, Sinks}; +use std::collections::HashMap; +use std::net::IpAddr; + +/// How long a test waits for something to arrive before failing, so that +/// a broken expectation fails instead of hanging forever. +pub(super) const RECEIVE_TIMEOUT: Duration = Duration::from_secs(1); + +/// Id 1000, little-endian, with no measurements after it: the one packet +/// [`index_with_empty_data_packet`] declares. +pub(super) const EMPTY_DATA_DATAGRAM: [u8; 2] = [0xE8, 0x03]; + +/// Id 0xFFFF, which [`index_with_empty_data_packet`] does not declare. +pub(super) const UNKNOWN_ID_DATAGRAM: [u8; 2] = [0xFF, 0xFF]; + +/// A fault: packet id 0, which [`index_with_empty_data_packet`] does not +/// declare either — a fault is recognised without the ADJ. +pub(super) const FAULT_DATAGRAM: [u8; 2] = [0x00, 0x00]; + +/// A board's address on the pod's network, for errors that carry one. +pub(super) fn example_board_addr() -> SocketAddr { + SocketAddr::new(IpAddr::from([192, 168, 1, 3]), 50400) +} + +/// `127.0.0.1` with port 0, so that the OS picks a free one. +pub(super) fn any_loopback_port() -> SocketAddr { + SocketAddr::new(IpAddr::from([127, 0, 0, 1]), 0) +} + +/// An index with a single `Data` packet, id 1000 on board 1, that carries +/// no measurements. +/// +/// It has to be `Data`: that is the only type a UDP datagram can carry, +/// and decoding rejects any other with `WrongPacketType`. +pub(super) fn index_with_empty_data_packet() -> Index { + let packet = PacketDef { + id: AdjId(1000), + board: BoardId(1), + name: "test_data".to_string(), + packet_type: PacketType::Data(vec![]), + }; + let board = Board { + id: BoardId(1), + name: "TEST".to_string(), + ip: IpAddr::from([192, 168, 0, 10]), + mac: MacAddress([0; 6]), + packets: HashMap::from([(packet.id, packet)]), + }; + let pod_data = PodData { + boards: HashMap::from([(board.id, board)]), + }; + Index::new(&pod_data, None) +} + +/// The next notification, or a test failure after [`RECEIVE_TIMEOUT`]. +pub(super) async fn receive_notification(sinks: &mut Sinks) -> Notification { + let Ok(Some(notification)) = + tokio::time::timeout(RECEIVE_TIMEOUT, sinks.notifications.recv()).await + else { + unreachable!("a notification should have arrived within {RECEIVE_TIMEOUT:?}"); + }; + notification +} + +/// The next error report, or a test failure after [`RECEIVE_TIMEOUT`]. +pub(super) async fn receive_error_report(sinks: &mut Sinks) -> ErrorReport { + let Ok(Some(report)) = tokio::time::timeout(RECEIVE_TIMEOUT, sinks.errors.recv()).await else { + unreachable!("an error report should have arrived within {RECEIVE_TIMEOUT:?}"); + }; + report +} + +/// Asserts that `notification` is what [`EMPTY_DATA_DATAGRAM`] decodes to. +pub(super) fn assert_is_empty_data_packet(notification: Notification) { + assert_eq!(notification.board, BoardId(1)); + let Event::Received(Packet::Data(packet)) = notification.event else { + unreachable!("a datagram should arrive as Event::Received(Packet::Data)"); + }; + assert_eq!(packet.id, AdjId(1000)); + assert!(packet.values.is_empty()); +} + +/// Binds the telemetry socket on a free loopback port, as [`spawn_udp`] does on +/// the backend's own address, and returns it with the port the OS picked. +pub(super) fn bind_on_loopback(recv_buffer: usize) -> (tokio::net::UdpSocket, SocketAddr) { + let config = UdpConfig { + addr: any_loopback_port(), + recv_buffer, + }; + let Ok(socket) = bind_telemetry_socket(config) else { + unreachable!("binding to a free loopback port should succeed"); + }; + let Ok(addr) = socket.local_addr() else { + unreachable!("a bound socket has a local address"); + }; + (socket, addr) +} + +/// Starts receiving on a free loopback port with +/// [`index_with_empty_data_packet`], as [`spawn_udp`] does, and returns the +/// address to send to along with the task's handle. +pub(super) fn start_receiving_on_loopback(reporter: Reporter) -> (SocketAddr, JoinHandle<()>) { + let (socket, addr) = bind_on_loopback(256 * 1024); + let index = Arc::new(index_with_empty_data_packet()); + let handle = tokio::spawn(receive_telemetry(socket, index, reporter)); + (addr, handle) +} + +/// A socket standing in for a board that sends telemetry. +pub(super) async fn bind_fake_board() -> tokio::net::UdpSocket { + let Ok(socket) = tokio::net::UdpSocket::bind(any_loopback_port()).await else { + unreachable!("binding the fake board's socket should succeed"); + }; + socket +} + +/// Sends `bytes` as one datagram from `from` to `to`. +pub(super) async fn send_datagram(from: &tokio::net::UdpSocket, bytes: &[u8], to: SocketAddr) { + let Ok(sent) = from.send_to(bytes, to).await else { + unreachable!("sending on loopback should succeed"); + }; + assert_eq!(sent, bytes.len()); +} diff --git a/backend/crates/core/src/net/udp/tests.rs b/backend/crates/core/src/net/udp/tests.rs new file mode 100644 index 000000000..b71efb004 --- /dev/null +++ b/backend/crates/core/src/net/udp/tests.rs @@ -0,0 +1,327 @@ +//! Unit tests of the receive path, and tests through a real socket on +//! loopback. Fixtures live in `test_support.rs`. + +use super::test_support::*; +use super::*; +use crate::model::AdjId; + +// --------------------------------------------------------------------------- +// Error classification +// --------------------------------------------------------------------------- + +#[test] +fn a_datagram_that_will_not_decode_faults_the_pod() { + let error = UdpError::Decode { + from: example_board_addr(), + source: DecodeError::UnknownId(AdjId(9999)), + }; + + assert!(error.is_fatal()); +} + +#[test] +fn losing_the_socket_faults_the_pod_too() { + let error = UdpError::Recv { + source: std::io::Error::from(std::io::ErrorKind::ConnectionReset), + }; + + assert!(error.is_fatal()); +} + +#[test] +fn a_decode_failure_says_where_it_came_from() { + let error = UdpError::Decode { + from: example_board_addr(), + source: DecodeError::UnknownId(AdjId(9999)), + }; + + assert!(error.to_string().contains("192.168.1.3:50400")); +} + +#[test] +fn a_board_signalling_a_fault_faults_the_pod() { + let error = UdpError::Fault { + from: example_board_addr(), + }; + + assert!(error.is_fatal()); +} + +#[test] +fn a_fault_says_where_it_came_from() { + let error = UdpError::Fault { + from: example_board_addr(), + }; + + assert!(error.to_string().contains("192.168.1.3:50400")); +} + +// --------------------------------------------------------------------------- +// decode_and_report, without a socket +// --------------------------------------------------------------------------- + +#[tokio::test] +async fn decode_and_report_notifies_a_valid_datagram() { + let (reporter, mut sinks) = Reporter::channels(16, 16); + let index = index_with_empty_data_packet(); + let mut traces = ReceiveTraces::default(); + + let keep_going = decode_and_report( + &EMPTY_DATA_DATAGRAM, + example_board_addr(), + &index, + &reporter, + &mut traces, + ) + .await; + assert!(keep_going); + + assert_is_empty_data_packet(receive_notification(&mut sinks).await); + assert!( + sinks.errors.try_recv().is_err(), + "should not have reported an error" + ); +} + +#[tokio::test] +async fn decode_and_report_reports_an_unknown_id() { + let (reporter, mut sinks) = Reporter::channels(16, 16); + let index = index_with_empty_data_packet(); + let mut traces = ReceiveTraces::default(); + + let keep_going = decode_and_report( + &UNKNOWN_ID_DATAGRAM, + example_board_addr(), + &index, + &reporter, + &mut traces, + ) + .await; + assert!(keep_going); + + let report = receive_error_report(&mut sinks).await; + let crate::net::Error::Udp(UdpError::Decode { from, source }) = report.error else { + unreachable!("an undecodable datagram should be reported as udp::UdpError::Decode"); + }; + assert_eq!(from, example_board_addr()); + assert!(matches!(source, DecodeError::UnknownId(AdjId(0xFFFF)))); + assert!( + sinks.notifications.try_recv().is_err(), + "should not have notified a packet" + ); +} + +#[tokio::test] +async fn decode_and_report_reports_a_fault_without_looking_at_the_adj() { + let (reporter, mut sinks) = Reporter::channels(16, 16); + // Declares id 1000 only: id 0 is unknown to it, and yet it is a fault. + let index = index_with_empty_data_packet(); + let mut traces = ReceiveTraces::default(); + + let keep_going = decode_and_report( + &FAULT_DATAGRAM, + example_board_addr(), + &index, + &reporter, + &mut traces, + ) + .await; + assert!(keep_going); + + let report = receive_error_report(&mut sinks).await; + let crate::net::Error::Udp(UdpError::Fault { from }) = report.error else { + unreachable!("a datagram with packet id 0 should be reported as udp::UdpError::Fault"); + }; + assert_eq!(from, example_board_addr()); + assert!( + sinks.notifications.try_recv().is_err(), + "should not have notified a packet" + ); +} + +#[tokio::test] +async fn whatever_follows_the_fault_id_is_not_read() { + let (reporter, mut sinks) = Reporter::channels(16, 16); + let index = index_with_empty_data_packet(); + let mut traces = ReceiveTraces::default(); + + decode_and_report( + &[0x00, 0x00, 0xAB, 0xCD], + example_board_addr(), + &index, + &reporter, + &mut traces, + ) + .await; + + let report = receive_error_report(&mut sinks).await; + assert!(matches!( + report.error, + crate::net::Error::Udp(UdpError::Fault { .. }) + )); +} + +#[tokio::test] +async fn a_single_zero_byte_is_not_a_fault() { + let (reporter, mut sinks) = Reporter::channels(16, 16); + let index = index_with_empty_data_packet(); + let mut traces = ReceiveTraces::default(); + + // An id takes two bytes: one zero byte is a truncated datagram. + decode_and_report( + &[0x00], + example_board_addr(), + &index, + &reporter, + &mut traces, + ) + .await; + + let report = receive_error_report(&mut sinks).await; + let crate::net::Error::Udp(UdpError::Decode { source, .. }) = report.error else { + unreachable!("a one-byte datagram should be a decode failure, not a fault"); + }; + assert!(matches!(source, DecodeError::UnexpectedEof)); +} + +#[tokio::test] +async fn decode_and_report_stops_once_nobody_listens() { + let (reporter, sinks) = Reporter::channels(16, 16); + let index = index_with_empty_data_packet(); + let mut traces = ReceiveTraces::default(); + drop(sinks); + + // With the receivers gone, reporting tells the loop to stop (false). + let keep_going = decode_and_report( + &UNKNOWN_ID_DATAGRAM, + example_board_addr(), + &index, + &reporter, + &mut traces, + ) + .await; + assert!(!keep_going); +} + +// --------------------------------------------------------------------------- +// Rate limit of the decode-failure trace +// --------------------------------------------------------------------------- + +#[test] +fn decode_failures_are_traced_at_most_once_a_second() { + let mut trace = TraceRateLimit::default(); + let t0 = Instant::now(); + let at = |ms: u64| t0 + Duration::from_millis(ms); + + assert_eq!( + trace.should_trace(at(0)), + Some(0), + "the first one is traced" + ); + assert_eq!( + trace.should_trace(at(300)), + None, + "within the second: counted" + ); + assert_eq!( + trace.should_trace(at(900)), + None, + "within the second: counted" + ); + assert_eq!( + trace.should_trace(at(1100)), + Some(2), + "after a second: traced, with the two left out" + ); + assert_eq!(trace.should_trace(at(1500)), None); + assert_eq!( + trace.should_trace(at(2200)), + Some(1), + "the window restarts at the last traced one" + ); +} + +// --------------------------------------------------------------------------- +// Through a real socket on loopback +// --------------------------------------------------------------------------- + +#[tokio::test] +async fn a_datagram_sent_to_the_socket_arrives_as_a_notification() { + let (reporter, mut sinks) = Reporter::channels(16, 16); + let (addr, handle) = start_receiving_on_loopback(reporter); + let board = bind_fake_board().await; + + send_datagram(&board, &EMPTY_DATA_DATAGRAM, addr).await; + + assert_is_empty_data_packet(receive_notification(&mut sinks).await); + handle.abort(); +} + +#[tokio::test] +async fn an_undecodable_datagram_is_reported_with_its_sender() { + let (reporter, mut sinks) = Reporter::channels(16, 16); + let (addr, handle) = start_receiving_on_loopback(reporter); + let board = bind_fake_board().await; + let Ok(board_addr) = board.local_addr() else { + unreachable!("a bound socket has a local address"); + }; + + send_datagram(&board, &UNKNOWN_ID_DATAGRAM, addr).await; + + let report = receive_error_report(&mut sinks).await; + let crate::net::Error::Udp(UdpError::Decode { from, .. }) = report.error else { + unreachable!("an undecodable datagram should be reported as udp::UdpError::Decode"); + }; + assert_eq!(from, board_addr); + handle.abort(); +} + +#[tokio::test] +async fn a_fault_sent_to_the_socket_is_reported_with_its_sender() { + let (reporter, mut sinks) = Reporter::channels(16, 16); + let (addr, handle) = start_receiving_on_loopback(reporter); + let board = bind_fake_board().await; + let Ok(board_addr) = board.local_addr() else { + unreachable!("a bound socket has a local address"); + }; + + send_datagram(&board, &FAULT_DATAGRAM, addr).await; + + let report = receive_error_report(&mut sinks).await; + let crate::net::Error::Udp(UdpError::Fault { from }) = report.error else { + unreachable!("a datagram with packet id 0 should be reported as udp::UdpError::Fault"); + }; + assert_eq!(from, board_addr); + handle.abort(); +} + +#[tokio::test] +async fn the_loop_stops_on_the_next_datagram_once_nobody_listens() { + let (reporter, sinks) = Reporter::channels(16, 16); + let (addr, handle) = start_receiving_on_loopback(reporter); + drop(sinks); + let board = bind_fake_board().await; + + // Without a datagram the loop would keep waiting on the socket: it only + // notices the consumer is gone when it tries to report. + send_datagram(&board, &EMPTY_DATA_DATAGRAM, addr).await; + + let Ok(Ok(())) = tokio::time::timeout(RECEIVE_TIMEOUT, handle).await else { + unreachable!("the loop should end once a report finds nobody listening"); + }; +} + +#[tokio::test] +async fn binding_an_address_already_in_use_is_a_bind_error() { + let (_first, taken) = bind_on_loopback(256 * 1024); + + let second = bind_telemetry_socket(UdpConfig { + addr: taken, + recv_buffer: 256 * 1024, + }); + + let Err(UdpError::Bind { addr, .. }) = second else { + unreachable!("binding an address already in use should fail with UdpError::Bind"); + }; + assert_eq!(addr, taken); +} 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