diff --git a/Cargo.lock b/Cargo.lock index f977092..3f40289 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11,6 +11,12 @@ dependencies = [ "memchr", ] +[[package]] +name = "allocator-api2" +version = "0.2.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57b212daf2e827b1ccdd778b7eb48ba433e58cb0e4f27b43cd6b7a608425a014" + [[package]] name = "anstream" version = "1.0.0" @@ -61,12 +67,27 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "approx" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6" +dependencies = [ + "num-traits", +] + [[package]] name = "atomic-waker" version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + [[package]] name = "aws-lc-rs" version = "1.19.0" @@ -117,12 +138,27 @@ version = "3.20.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" +[[package]] +name = "by_address" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06" + [[package]] name = "bytes" version = "1.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" +[[package]] +name = "castaway" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" +dependencies = [ + "rustversion", +] + [[package]] name = "cc" version = "1.11.3" @@ -154,6 +190,7 @@ dependencies = [ "clap", "clap_complete", "console", + "crossterm", "csv", "ctrlc", "env_logger", @@ -163,6 +200,7 @@ dependencies = [ "jiff", "log", "nix", + "ratatui", "regex", "reqwest", "serde", @@ -254,6 +292,20 @@ dependencies = [ "memchr", ] +[[package]] +name = "compact_str" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dfdd1c2274d9aa354115b09dc9a901d6c5576818cdf70d14cae2bdb47df00ab" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "rustversion", + "ryu", + "static_assertions", +] + [[package]] name = "console" version = "0.16.6" @@ -266,6 +318,15 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "convert_case" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" +dependencies = [ + "unicode-segmentation", +] + [[package]] name = "cookie" version = "0.18.3" @@ -320,6 +381,33 @@ dependencies = [ "libc", ] +[[package]] +name = "crossterm" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b" +dependencies = [ + "bitflags", + "crossterm_winapi", + "derive_more", + "document-features", + "mio", + "parking_lot", + "rustix", + "signal-hook", + "signal-hook-mio", + "winapi", +] + +[[package]] +name = "crossterm_winapi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" +dependencies = [ + "winapi", +] + [[package]] name = "csv" version = "1.4.0" @@ -352,12 +440,68 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.10", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.10", +] + [[package]] name = "deranged" version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", +] + [[package]] name = "dispatch2" version = "0.3.1" @@ -396,6 +540,12 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + [[package]] name = "encode_unicode" version = "1.0.0" @@ -431,6 +581,16 @@ 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 = "find-msvc-tools" version = "0.1.15" @@ -539,6 +699,11 @@ name = "hashbrown" version = "0.17.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] [[package]] name = "heck" @@ -732,6 +897,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + [[package]] name = "idna" version = "1.1.0" @@ -775,6 +946,28 @@ dependencies = [ "unit-prefix", ] +[[package]] +name = "indoc" +version = "2.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a37b2691796cffeb8a8cd305ac66e65841559f147f4e63231d0eafa4db5384d1" +dependencies = [ + "rustversion", +] + +[[package]] +name = "instability" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c3b5acc1e2fd9375041a388da33d1eb8aed5f7a8c0dd3543e3ea2805adfbe20" +dependencies = [ + "darling", + "indoc", + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "ipnet" version = "2.12.2" @@ -787,6 +980,15 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.19" @@ -915,12 +1117,44 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "kasuari" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f14c90e40a6133f4805b83542a7ed7364f56070b447f56e7f4e90297122209" +dependencies = [ + "hashbrown", + "portable-atomic", + "thiserror", +] + [[package]] name = "libc" version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "line-clipping" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e752191d037c44ad111a8caa762921926658402f01cc1253f7bef2020ece4f5e" +dependencies = [ + "bitflags", +] + +[[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" @@ -933,12 +1167,30 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" +[[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" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef9ac18847474e638e3702b76c65d4eb93428471a74778ef0f1be711717f89b5" +dependencies = [ + "hashbrown", +] + [[package]] name = "lru-slab" version = "0.1.3" @@ -958,6 +1210,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" dependencies = [ "libc", + "log", "wasi", "windows-sys 0.61.2", ] @@ -980,6 +1233,24 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_threads" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cabcc654086861f9e1bc5115258de62ef92c79b20f4615a1b0cc57c4e82027d4" +dependencies = [ + "libc", +] + [[package]] name = "objc2" version = "0.6.5" @@ -1013,6 +1284,62 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" +[[package]] +name = "palette" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddeed8580d347d2abf3dcf06a5f0b3dc020258338526b277847cd4248a70fc64" +dependencies = [ + "approx", + "libm", + "palette_derive", + "palette_math", +] + +[[package]] +name = "palette_derive" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88537020289b719d81be994ccf1bbf4990f477e2f69ee52fe3e45f43a02e56be" +dependencies = [ + "by_address", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "palette_math" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e6eb142958d64335fb0e345c5b9ead2ecd6fc438c307e9d7d3c4fd428dbaf12" +dependencies = [ + "libm", +] + +[[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" @@ -1184,6 +1511,81 @@ dependencies = [ "rand_core", ] +[[package]] +name = "ratatui" +version = "0.30.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3274ba0a2c5e1bcad2a2005d20f4dc59dad26b2eb0940fb094500dba4099d57d" +dependencies = [ + "instability", + "ratatui-core", + "ratatui-crossterm", + "ratatui-widgets", + "serde", +] + +[[package]] +name = "ratatui-core" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbb175c433c8e28a809d1f5773a2ae96e68c0ce40db865cbab1020bf33ae479c" +dependencies = [ + "bitflags", + "compact_str", + "hashbrown", + "itertools", + "kasuari", + "lru", + "palette", + "serde", + "strum", + "thiserror", + "unicode-segmentation", + "unicode-truncate", + "unicode-width", +] + +[[package]] +name = "ratatui-crossterm" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "567584a3b0e6a8203c23de40b4861497266725eb5363dbfd18a1edd603cca9f0" +dependencies = [ + "cfg-if", + "crossterm", + "instability", + "ratatui-core", +] + +[[package]] +name = "ratatui-widgets" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66e3d19bcc9130ca376277d93b60767ff121ace3be06f5f95f81dd68956407d1" +dependencies = [ + "bitflags", + "hashbrown", + "indoc", + "instability", + "itertools", + "line-clipping", + "ratatui-core", + "serde", + "strum", + "time", + "unicode-segmentation", + "unicode-width", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + [[package]] name = "regex" version = "1.13.2" @@ -1281,6 +1683,19 @@ dependencies = [ "semver", ] +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + [[package]] name = "rustls" version = "0.23.46" @@ -1386,6 +1801,12 @@ 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" @@ -1466,6 +1887,37 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "signal-hook" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[package]] +name = "signal-hook-mio" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc" +dependencies = [ + "libc", + "mio", + "signal-hook", +] + +[[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" @@ -1510,12 +1962,39 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + [[package]] name = "strsim" version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "strum" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "subtle" version = "2.6.1" @@ -1591,7 +2070,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" dependencies = [ "deranged", + "libc", "num-conv", + "num_threads", "powerfmt", "serde_core", "time-core", @@ -1730,6 +2211,23 @@ version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-truncate" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16b380a1238663e5f8a691f9039c73e1cdae598a30e9855f541d29b08b53e9a5" +dependencies = [ + "itertools", + "unicode-segmentation", + "unicode-width", +] + [[package]] name = "unicode-width" version = "0.2.3" @@ -1896,6 +2394,22 @@ dependencies = [ "rustls-pki-types", ] +[[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" @@ -1905,6 +2419,12 @@ 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" diff --git a/Cargo.toml b/Cargo.toml index 1710e00..e449759 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,6 +26,8 @@ httpdate = "1.0" ctrlc = { version = "3.5", features = ["termination"] } console = { version = "0.16", default-features = false, features = ["std"] } indicatif = { version = "0.18", default-features = false, features = ["unicode-width"] } +ratatui = { version = "0.30.0", default-features = false, features = ["crossterm"] } +crossterm = { version = "0.29.0", default-features = false, features = ["events"] } [target.'cfg(any(target_os = "linux", target_os = "macos"))'.dev-dependencies] nix = { version = "0.32", features = ["term"] } diff --git a/README.md b/README.md index aba3a1d..06b5ccd 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,8 @@ Options: Maximum total run duration in seconds [default: 120] --max-retry-wait Maximum cumulative retry wait in seconds [default: 30] + --tui + Open the experimental full-screen speed test dashboard -h, --help Print help -V, --version @@ -68,6 +70,18 @@ Example with json-pretty output: In human-readable mode, live progress is shown on stderr only when it is a terminal. When both stdout and stderr are terminals, each completed transfer size adds a row to the results table. Redirecting stdout keeps the end-of-run summary instead, without progress redraws. CSV and JSON modes never draw a progress bar. +### Experimental dashboard + +```sh +cfspeedtest --tui +``` + +The dashboard charts valid samples as they arrive and shows the current payload, retry countdown, and sample distributions. Dots on the timeline mark payload batches that were skipped or left unrun when the test stopped. The large Mbps figures are the 90th percentiles of the valid samples for each direction. Latency is the average of the unloaded probes. Jitter is the mean absolute change between consecutive valid probes. The dashboard does not measure loaded latency or packet loss. + +Press **Tab** to switch between Overview, Samples, and Events. Use **↑/↓** to scroll through samples and errors, **R** to rerun after the test ends, or **Q** to quit. Pressing **Q** or **Ctrl-C** during a run requests cancellation. The dashboard waits for any in-flight request to finish before restoring the terminal. + +`--tui` requires an interactive terminal and cannot be combined with `--output-format` or `--verbose`. Use the Events view for measurement diagnostics. Leave `RUST_LOG` unset so diagnostic logs do not interrupt the display. Without `--tui`, the existing CLI runs as before. + ### Run limits and failures Runs have a shared 120-second measurement deadline and a 30-second cumulative retry-wait budget by default. Both limits cover the entire run, including metadata, latency, and both transfer directions. Each request is limited to the smaller of 30 seconds and the remaining run time. @@ -88,7 +102,7 @@ Ctrl-C stops new measurements and interrupts retry waits. An in-flight blocking | 3 | Partial: some valid throughput samples exist, but a sample target was missed or a run limit stopped testing. | | 130 | Cancelled; any completed measurements are retained. | -Metadata is optional: an unavailable or invalid trace response is reported as an error, but does not by itself make a successful measurement run fail. Failed samples that are replaced by successful retries remain in the error history without making a completed run partial. Operational diagnostics go to stderr in every CLI output mode. In human-readable mode, recorded errors are grouped by stage and payload under the run outcome. A run without recorded errors does not print that heading. A closed stdout, as in `cfspeedtest | head`, is not treated as an error; any other stdout write failure is reported once on stderr. +Metadata is optional: an unavailable or invalid trace response is reported as an error, but does not by itself make a successful measurement run fail. Failed samples that are replaced by successful retries remain in the error history without making a completed run partial. Outside the dashboard, operational diagnostics go to stderr. In human-readable mode, recorded errors are grouped by stage and payload under the run outcome. A run without recorded errors does not print that heading. A closed stdout, as in `cfspeedtest | head`, is not treated as an error; any other stdout write failure is reported once on stderr. JSON includes `status`, `stop_reason` (`deadline`, `retry_budget`, `cancelled`, or null), and structured `errors` with stage, payload size, HTTP status when available, and reason. Missing metadata is null. `latency_measurement` is always present and includes `status`, `attempts`, `successes`, `target_samples`, and `errors`. Its summary values are null when no valid samples exist; human output uses N/A. `--nr-latency-tests 0` explicitly disables latency testing. CSV retains its throughput-only columns; use the exit code and stderr to detect failures, or JSON for the full outcome. diff --git a/_typos.toml b/_typos.toml new file mode 100644 index 0000000..ac8fa28 --- /dev/null +++ b/_typos.toml @@ -0,0 +1,2 @@ +[default.extend-identifiers] +ratatui = "ratatui" diff --git a/src/dashboard/mod.rs b/src/dashboard/mod.rs new file mode 100644 index 0000000..15085e6 --- /dev/null +++ b/src/dashboard/mod.rs @@ -0,0 +1,139 @@ +mod state; +mod view; + +use cfspeedtest::{run::RunConfig, speedtest::observe_speed_test, SpeedTestCLIOptions}; +use crossterm::{ + cursor::Show, + event::{self, Event, KeyCode, KeyEventKind, KeyModifiers}, + execute, + terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen}, +}; +use ratatui::{backend::CrosstermBackend, Terminal}; +use reqwest::blocking::Client; +use state::{Dashboard, Outcome, Update}; +use std::{ + io, + sync::{atomic::Ordering, mpsc}, + thread, + time::Duration, +}; + +struct Screen; + +impl Screen { + fn enter() -> io::Result { + enable_raw_mode()?; + let screen = Self; + execute!(io::stdout(), EnterAlternateScreen)?; + Ok(screen) + } +} + +impl Drop for Screen { + fn drop(&mut self) { + let _ = disable_raw_mode(); + let _ = execute!(io::stdout(), LeaveAlternateScreen, Show); + } +} + +fn start_run( + client: Client, + options: SpeedTestCLIOptions, + config: RunConfig, +) -> io::Result> { + let (send, receive) = mpsc::channel(); + thread::Builder::new() + .name("speedtest".into()) + .spawn(move || { + let report = observe_speed_test(client, options, config, |event| { + let _ = send.send(Update::Run(event)); + }); + let _ = send.send(Update::Finished(Outcome { + status: report.status, + stop: report.stop_reason, + exit: report.exit_code(), + })); + })?; + Ok(receive) +} + +pub(super) fn run( + client: Client, + options: SpeedTestCLIOptions, + config: RunConfig, + host: &str, +) -> io::Result { + let _screen = Screen::enter()?; + let mut terminal = Terminal::new(CrosstermBackend::new(io::stdout()))?; + let result = run_loop(&mut terminal, client, options, &config, host); + if result.is_err() { + config.cancelled.store(true, Ordering::SeqCst); + } + result +} + +fn run_loop( + terminal: &mut Terminal>, + client: Client, + options: SpeedTestCLIOptions, + config: &RunConfig, + host: &str, +) -> io::Result { + let mut app = Dashboard::new(&options, host); + let mut receive = start_run(client.clone(), options.clone(), config.clone())?; + loop { + loop { + match receive.try_recv() { + Ok(update) => app.apply(update), + Err(mpsc::TryRecvError::Empty) => break, + Err(mpsc::TryRecvError::Disconnected) if app.outcome.is_some() => break, + Err(mpsc::TryRecvError::Disconnected) => { + return Err(io::Error::other( + "measurement worker ended without a report", + )); + } + } + } + app.stopping = config.cancelled.load(Ordering::SeqCst); + if let Some(outcome) = &app.outcome { + if app.stopping { + return Ok(outcome.exit); + } + } + terminal.draw(|frame| view::render(frame, &app))?; + if !event::poll(Duration::from_millis(80))? { + continue; + } + let Event::Key(key) = event::read()? else { + continue; + }; + if key.kind == KeyEventKind::Release { + continue; + } + match key.code { + KeyCode::Esc | KeyCode::Char('q') => { + if let Some(outcome) = &app.outcome { + return Ok(outcome.exit); + } + config.cancelled.store(true, Ordering::SeqCst); + } + KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => { + if app.outcome.is_some() { + return Ok(130); + } + config.cancelled.store(true, Ordering::SeqCst); + } + KeyCode::Tab | KeyCode::Right => app.switch_view(1), + KeyCode::BackTab | KeyCode::Left => app.switch_view(-1), + KeyCode::Down | KeyCode::Char('j') => app.scroll(1), + KeyCode::Up | KeyCode::Char('k') => app.scroll(-1), + KeyCode::PageDown => app.scroll(8), + KeyCode::PageUp => app.scroll(-8), + KeyCode::Char('r') if app.outcome.is_some() => { + app = Dashboard::new(&options, host); + receive = start_run(client.clone(), options.clone(), config.clone())?; + } + _ => {} + } + } +} diff --git a/src/dashboard/state.rs b/src/dashboard/state.rs new file mode 100644 index 0000000..145e85f --- /dev/null +++ b/src/dashboard/state.rs @@ -0,0 +1,277 @@ +use cfspeedtest::{ + run::{RunError, RunEvent, RunStatus, StopReason}, + speedtest::{Metadata, PayloadSize, TestType}, + SpeedTestCLIOptions, +}; +use std::time::{Duration, Instant}; + +pub(super) enum Update { + Run(RunEvent), + Finished(Outcome), +} + +pub(super) struct Outcome { + pub status: RunStatus, + pub stop: Option, + pub exit: u8, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Stage { + Connecting, + Latency, + Transfer(usize), + Done, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum View { + Overview, + Samples, + Events, +} + +impl View { + pub const ALL: [Self; 3] = [Self::Overview, Self::Samples, Self::Events]; + + pub fn label(self) -> &'static str { + match self { + Self::Overview => "Overview", + Self::Samples => "Samples", + Self::Events => "Events", + } + } +} + +#[derive(Default)] +pub(super) struct Series { + pub values: Vec, + sorted: Vec, +} + +impl Series { + pub fn push(&mut self, value: f64) { + if value.is_finite() && value >= 0.0 { + self.values.push(value); + let idx = self.sorted.partition_point(|v| *v <= value); + self.sorted.insert(idx, value); + } + } + + pub fn max(&self) -> Option { + self.sorted.last().copied() + } + + pub fn mean(&self) -> Option { + (!self.values.is_empty()) + .then(|| self.values.iter().sum::() / self.values.len() as f64) + } + + // Nearest-rank p90, reported over all valid samples in the direction. + pub fn p90(&self) -> Option { + let rank = (9 * self.sorted.len()).div_ceil(10); + rank.checked_sub(1).map(|index| self.sorted[index]) + } + + pub fn jitter(&self) -> Option { + (self.values.len() > 1).then(|| { + let sum = self + .values + .windows(2) + .map(|v| (v[0] - v[1]).abs()) + .sum::(); + sum / (self.values.len() - 1) as f64 + }) + } + + // Interpolated quartiles for the distribution display. + pub fn distribution(&self) -> Option<[f64; 5]> { + let last = self.sorted.len().checked_sub(1)?; + Some([0.0, 0.25, 0.5, 0.75, 1.0].map(|p| { + let rank = p * last as f64; + let low = rank.floor() as usize; + let high = rank.ceil() as usize; + self.sorted[low] + (self.sorted[high] - self.sorted[low]) * rank.fract() + })) + } +} + +pub(super) struct Batch { + pub direction: TestType, + pub bytes: usize, + pub target: u32, + pub samples: Series, + pub failures: u32, + pub finished: bool, +} + +pub(super) struct Dashboard { + pub host: String, + pub metadata: Option, + pub latency: Series, + pub latency_target: u32, + pub latency_attempts: u32, + pub download: Series, + pub upload: Series, + pub batches: Vec, + pub stage: Stage, + pub errors: Vec, + pub retry_until: Option, + pub outcome: Option, + pub started: Instant, + pub finished: Option, + pub stopping: bool, + pub view: View, + pub offset: usize, +} + +impl Dashboard { + pub fn new(options: &SpeedTestCLIOptions, host: &str) -> Self { + let sizes = PayloadSize::sizes_from_max(options.max_payload_size.clone()); + let batches = [ + (options.should_download(), TestType::Download), + (options.should_upload(), TestType::Upload), + ] + .into_iter() + .filter(|(enabled, _)| *enabled) + .flat_map(|(_, direction)| { + sizes.iter().map(move |&bytes| Batch { + direction, + bytes, + target: options.nr_tests, + samples: Series::default(), + failures: 0, + finished: false, + }) + }) + .collect(); + Self { + host: host.into(), + metadata: None, + latency: Series::default(), + latency_target: options.nr_latency_tests, + latency_attempts: 0, + download: Series::default(), + upload: Series::default(), + batches, + stage: Stage::Connecting, + errors: vec![], + retry_until: None, + outcome: None, + started: Instant::now(), + finished: None, + stopping: false, + view: View::Overview, + offset: 0, + } + } + + pub fn apply(&mut self, update: Update) { + let event = match update { + Update::Run(event) => event, + Update::Finished(outcome) => { + self.outcome = Some(outcome); + self.finished = Some(Instant::now()); + self.stage = Stage::Done; + self.retry_until = None; + return; + } + }; + match event { + RunEvent::Metadata(metadata) => self.metadata = Some(metadata), + RunEvent::LatencyStarted { target } => { + self.stage = Stage::Latency; + self.latency_target = target; + } + RunEvent::LatencyAttempt { ms } => { + self.latency_attempts += 1; + if let Some(ms) = ms { + self.latency.push(ms); + } + } + RunEvent::PayloadStarted { + direction, bytes, .. + } => { + if let Some(index) = self + .batches + .iter() + .position(|batch| batch.direction == direction && batch.bytes == bytes) + { + self.stage = Stage::Transfer(index); + self.retry_until = None; + } + } + RunEvent::ThroughputSample { mbps } => { + if let Stage::Transfer(index) = self.stage { + let batch = &mut self.batches[index]; + batch.samples.push(mbps); + match batch.direction { + TestType::Download => self.download.push(mbps), + TestType::Upload => self.upload.push(mbps), + } + self.retry_until = None; + } + } + RunEvent::Error(error) => { + if error.payload_size.is_some() { + if let Stage::Transfer(index) = self.stage { + self.batches[index].failures += 1; + } + } + self.errors.push(error); + } + RunEvent::RetryWait(delay) => self.retry_until = Instant::now().checked_add(delay), + RunEvent::PayloadFinished(stats) => { + if let Stage::Transfer(index) = self.stage { + self.batches[index].failures = stats.skipped; + self.batches[index].finished = true; + } + self.retry_until = None; + } + _ => {} + } + } + + pub fn elapsed(&self) -> Duration { + self.finished + .unwrap_or_else(Instant::now) + .duration_since(self.started) + } + + pub fn switch_view(&mut self, step: isize) { + let current = self.view as isize; + self.view = View::ALL[(current + step).rem_euclid(View::ALL.len() as isize) as usize]; + self.offset = 0; + } + + pub fn scroll(&mut self, step: isize) { + let max = match self.view { + View::Overview => return, + View::Samples => self.batches.len(), + View::Events => self.errors.len().saturating_sub(1), + }; + self.offset = self.offset.saturating_add_signed(step).min(max); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn uses_measurement_order_for_jitter_and_sorted_values_for_percentiles() { + let mut series = Series::default(); + assert_eq!(series.p90(), None); + assert_eq!(series.jitter(), None); + for value in [7.0, 1.0, 9.0, 3.0, 5.0, f64::NAN] { + series.push(value); + } + assert_eq!(series.jitter(), Some(5.5)); + assert_eq!(series.distribution(), Some([1.0, 3.0, 5.0, 7.0, 9.0])); + assert_eq!(series.p90(), Some(9.0)); + for value in [4.0, 6.0, 10.0, 11.0, 12.0] { + series.push(value); + } + assert_eq!(series.p90(), Some(11.0)); + } +} diff --git a/src/dashboard/view.rs b/src/dashboard/view.rs new file mode 100644 index 0000000..00b6433 --- /dev/null +++ b/src/dashboard/view.rs @@ -0,0 +1,940 @@ +use super::state::{Dashboard, Series, Stage, View}; +use cfspeedtest::{ + run::{RunStatus, StopReason}, + speedtest::TestType, +}; +use ratatui::{ + layout::{Constraint, Layout, Margin, Rect}, + style::{Color, Modifier, Style}, + symbols::Marker, + text::{Line, Span}, + widgets::{Axis, Block, Chart, Dataset, GraphType, Padding, Paragraph, Wrap}, + Frame, +}; +use std::{net::IpAddr, time::Instant}; + +const BG: Color = Color::Rgb(16, 18, 24); +const PANEL: Color = Color::Rgb(24, 27, 36); +const BORDER: Color = Color::Rgb(63, 71, 90); +const DIM: Color = Color::Rgb(151, 161, 181); +const TEXT: Color = Color::Rgb(236, 240, 249); +const DOWN: Color = Color::Rgb(255, 167, 81); +const UP: Color = Color::Rgb(195, 167, 255); +const RTT: Color = Color::Rgb(122, 199, 255); +const GOOD: Color = Color::Rgb(104, 224, 172); +const WARN: Color = Color::Rgb(255, 206, 114); + +fn bold(color: Color) -> Style { + Style::new().fg(color).add_modifier(Modifier::BOLD) +} + +fn panel(title: impl Into>) -> Block<'static> { + Block::bordered() + .border_type(ratatui::widgets::BorderType::Rounded) + .border_style(Style::new().fg(BORDER)) + .style(Style::new().bg(PANEL).fg(TEXT)) + .padding(Padding::horizontal(1)) + .title(title) +} + +fn title(label: &str, color: Color) -> Line<'static> { + Line::styled(format!(" {label} "), bold(color)) +} + +pub(super) fn render(frame: &mut Frame, app: &Dashboard) { + frame.render_widget( + Block::new().style(Style::new().bg(BG).fg(TEXT)), + frame.area(), + ); + let area = frame.area().inner(Margin { + horizontal: 1, + vertical: 0, + }); + if area.width < 48 || area.height < 18 { + render_compact(frame, area, app); + return; + } + + let [header, body, footer] = Layout::vertical([ + Constraint::Length(3), + Constraint::Fill(1), + Constraint::Length(1), + ]) + .areas(area); + render_header(frame, header, app); + match app.view { + View::Overview => render_overview(frame, body, app), + View::Samples => render_samples(frame, body, app), + View::Events => render_events(frame, body, app), + } + let controls = if app.outcome.is_some() { + "Tab Views ↑↓ Scroll R Rerun Q Quit" + } else { + "Tab Views ↑↓ Scroll Q Stop" + }; + frame.render_widget(Line::styled(controls, Style::new().fg(DIM)), footer); +} + +fn render_header(frame: &mut Frame, area: Rect, app: &Dashboard) { + let tabs = View::ALL.into_iter().flat_map(|view| { + let style = if app.view == view { + bold(BG).bg(RTT) + } else { + Style::new().fg(DIM) + }; + [ + Span::raw(" "), + Span::styled(format!(" {} ", view.label()), style), + ] + }); + let (status, color) = status(app); + let header = Line::from(vec![ + Span::styled("◈ SPEED TEST", bold(TEXT)), + Span::styled(" / ", Style::new().fg(BORDER)), + Span::styled(status, bold(color)), + ]); + frame.render_widget(Paragraph::new(vec![header, Line::from_iter(tabs)]), area); +} + +fn status(app: &Dashboard) -> (&'static str, Color) { + match app.outcome.as_ref().map(|o| (o.status, o.stop)) { + Some((_, Some(StopReason::Cancelled))) => ("CANCELLED", WARN), + Some((RunStatus::Complete, _)) => ("COMPLETE", GOOD), + Some((RunStatus::Partial, _)) => ("PARTIAL", WARN), + Some((RunStatus::Failed, _)) => ("FAILED", WARN), + None if app.stopping => ("STOPPING", WARN), + None => ("LIVE", GOOD), + } +} + +fn render_overview(frame: &mut Frame, area: Rect, app: &Dashboard) { + let wide = area.width >= 98; + let hero_height = if area.height >= 26 { + 15 + } else if area.height >= 21 { + 12 + } else { + 8 + }; + let [hero, progress, info, measurements] = Layout::vertical([ + Constraint::Length(hero_height), + Constraint::Length(3), + Constraint::Length(if wide { 0 } else { 1 }), + Constraint::Fill(1), + ]) + .areas(area); + let [down, up, side] = Layout::horizontal([ + Constraint::Fill(1), + Constraint::Fill(1), + Constraint::Length(if wide { 29 } else { 0 }), + ]) + .spacing(1) + .areas(hero); + render_chart( + frame, + down, + TestType::Download, + &app.download, + app.batches + .iter() + .any(|b| b.direction == TestType::Download), + ); + render_chart( + frame, + up, + TestType::Upload, + &app.upload, + app.batches.iter().any(|b| b.direction == TestType::Upload), + ); + if wide { + render_connection(frame, side, app); + } else { + let (edge, _) = connection(app); + let baseline = format!( + "RTT {} ms · Jitter {} ms · {edge}", + metric(app.latency.mean()), + metric(app.latency.jitter()) + ); + frame.render_widget(Line::styled(baseline, Style::new().fg(DIM)), info); + } + render_timeline(frame, progress, app); + let [download, upload, latency] = Layout::horizontal([ + Constraint::Fill(1), + Constraint::Fill(1), + Constraint::Length(if wide { 29 } else { 0 }), + ]) + .spacing(1) + .areas(measurements); + render_groups(frame, download, TestType::Download, app); + render_groups(frame, upload, TestType::Upload, app); + if wide { + let block = panel(title("Latency samples", RTT)); + let inner = block.inner(latency); + frame.render_widget(block, latency); + let count = format!( + "Unloaded {}/{}", + app.latency.values.len(), + app.latency_target + ); + let mut rows = vec![Line::styled(count, bold(TEXT))]; + rows.extend(distribution( + &app.latency, + app.latency.max(), + inner.width, + RTT, + true, + )); + rows.push(Line::styled( + format!("0 – {} ms", metric(app.latency.max())), + Style::new().fg(DIM), + )); + if inner.height >= 7 { + rows.push(Line::raw("")); + rows.push(Line::styled( + "Loaded latency and packet", + Style::new().fg(DIM), + )); + rows.push(Line::styled("loss are not measured.", Style::new().fg(DIM))); + } + frame.render_widget(Paragraph::new(rows), inner); + } +} + +fn direction_name(direction: TestType) -> &'static str { + match direction { + TestType::Download => "Download", + TestType::Upload => "Upload", + } +} + +fn direction_color(direction: TestType) -> Color { + match direction { + TestType::Download => DOWN, + TestType::Upload => UP, + } +} + +fn render_chart( + frame: &mut Frame, + area: Rect, + direction: TestType, + series: &Series, + enabled: bool, +) { + let color = direction_color(direction); + let arrow = if direction == TestType::Download { + "↓" + } else { + "↑" + }; + let block = panel(title( + &format!("{arrow} {}", direction_name(direction)), + color, + )); + let inner = block.inner(area); + frame.render_widget(block, area); + let p90 = series.p90(); + let label = metric(p90); + let large = + p90.is_some() && inner.height >= 10 && label.len() * 4 + 5 <= usize::from(inner.width); + let [headline, plot, note] = Layout::vertical([ + Constraint::Length(if large { 3 } else { 1 }), + Constraint::Fill(1), + Constraint::Length(1), + ]) + .areas(inner); + if large { + frame.render_widget(Paragraph::new(big_number(&label, color)), headline); + } else { + frame.render_widget( + Line::from(vec![Span::styled(label, bold(color)), Span::raw(" Mbps")]), + headline, + ); + } + frame.render_widget( + Line::styled( + format!("p90 · {} samples", series.values.len()), + Style::new().fg(DIM), + ), + note, + ); + let Some(max) = series.max() else { + let hint = if enabled { + "Waiting for samples" + } else { + "Direction disabled" + }; + let [_, msg, _] = Layout::vertical([ + Constraint::Fill(1), + Constraint::Length(1), + Constraint::Fill(1), + ]) + .areas(plot); + frame.render_widget(Line::styled(hint, Style::new().fg(DIM)).centered(), msg); + return; + }; + let ceiling = (max * 1.12).max(1.0); + let x_max = series.values.len().saturating_sub(1).max(1) as f64; + let samples: Vec<_> = series + .values + .iter() + .enumerate() + .map(|(index, &v)| (index as f64, v)) + .collect(); + let reference = [ + (0.0, p90.unwrap_or_default()), + (x_max, p90.unwrap_or_default()), + ]; + let fill = match direction { + TestType::Download => Color::Rgb(100, 63, 34), + TestType::Upload => Color::Rgb(70, 54, 109), + }; + let datasets = vec![ + Dataset::default() + .graph_type(GraphType::Area) + .marker(Marker::HalfBlock) + .style(Style::new().fg(fill)) + .data(&samples), + Dataset::default() + .graph_type(GraphType::Line) + .marker(Marker::HalfBlock) + .style(Style::new().fg(BORDER)) + .data(&reference), + Dataset::default() + .graph_type(GraphType::Line) + .marker(Marker::HalfBlock) + .style(Style::new().fg(color)) + .data(&samples), + ]; + let labels = if plot.height >= 7 { + vec![ + "0".into(), + metric(Some(ceiling / 2.0)), + metric(Some(ceiling)), + ] + } else { + vec!["0".into(), metric(Some(ceiling))] + }; + let chart = Chart::new(datasets) + .style(Style::new().bg(PANEL)) + .x_axis(Axis::default().bounds([0.0, x_max])) + .y_axis( + Axis::default() + .style(Style::new().fg(BORDER)) + .bounds([0.0, ceiling]) + .labels(labels), + ); + frame.render_widget(chart, plot); +} + +fn big_number(value: &str, color: Color) -> Vec> { + const DIGITS: [[&str; 3]; 10] = [ + ["┏━┓", "┃ ┃", "┗━┛"], + [" ╻ ", " ┃ ", " ╹ "], + ["╺━┓", "┏━┛", "┗━╸"], + ["╺━┓", "╺━┫", "╺━┛"], + ["╻ ╻", "┗━┫", " ╹"], + ["┏━╸", "┗━┓", "╺━┛"], + ["┏━╸", "┣━┓", "┗━┛"], + ["╺━┓", " ┃", " ╹"], + ["┏━┓", "┣━┫", "┗━┛"], + ["┏━┓", "┗━┫", "╺━┛"], + ]; + (0..3) + .map(|row| { + let mut line = String::new(); + for c in value.chars() { + if let Some(digit) = c.to_digit(10) { + line.push_str(DIGITS[digit as usize][row]); + } else { + line.push_str(match (c, row) { + ('.', 2) => "▪", + ('k', 0) => "╻ ╱", + ('k', 1) => "┣╸ ", + ('k', 2) => "╹ ╲", + _ => " ", + }); + } + line.push(' '); + } + let mut spans = vec![Span::styled(line, bold(color))]; + if row == 2 { + spans.push(Span::styled("Mbps", Style::new().fg(DIM))); + } + Line::from(spans) + }) + .collect() +} + +fn connection(app: &Dashboard) -> (String, &'static str) { + let Some(metadata) = &app.metadata else { + return ("Edge unavailable".into(), ""); + }; + let family = match metadata.ip.parse::() { + Ok(IpAddr::V4(_)) => "IPv4", + Ok(IpAddr::V6(_)) => "IPv6", + Err(_) => "", + }; + ( + format!("{} · {}", metadata.colo, metadata.country), + family, + ) +} + +fn render_connection(frame: &mut Frame, area: Rect, app: &Dashboard) { + let block = panel(title("Connection", RTT)); + let inner = block.inner(area); + frame.render_widget(block, area); + let (edge, family) = connection(app); + let tail = if family.is_empty() { + edge + } else { + format!("{edge} · {family}") + }; + let attempts = format!( + "{}/{} valid probes", + app.latency.values.len(), + app.latency_target + ); + let metrics = vec![ + Line::from(vec![ + Span::styled("Latency ", Style::new().fg(DIM)), + Span::styled(format!("{} ms", metric(app.latency.mean())), bold(RTT)), + ]), + Line::from(vec![ + Span::styled("Jitter ", Style::new().fg(DIM)), + Span::styled(format!("{} ms", metric(app.latency.jitter())), bold(RTT)), + ]), + ]; + let mut rows = vec![ + Line::styled(app.host.clone(), bold(TEXT)), + Line::styled(tail, Style::new().fg(DIM)), + ]; + if inner.height >= 7 { + rows.push(Line::raw("")); + } + rows.extend(metrics); + rows.push(Line::styled(attempts, Style::new().fg(DIM))); + if inner.height >= 7 { + let plot = sparkline(&app.latency, inner.width); + rows.push(Line::styled(plot, Style::new().fg(RTT))); + } + if inner.height >= 10 { + rows.push(Line::raw("")); + rows.push(Line::styled( + format!("Elapsed {:.1}s", app.elapsed().as_secs_f64()), + Style::new().fg(DIM), + )); + rows.push(Line::styled( + format!("Events {}", error_count(app.errors.len())), + Style::new().fg(DIM), + )); + } + frame.render_widget(Paragraph::new(rows), inner); +} + +fn sparkline(series: &Series, width: u16) -> String { + const LEVELS: [char; 8] = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█']; + let width = usize::from(width); + let max = series.max().unwrap_or_default().max(1.0); + series + .values + .iter() + .skip(series.values.len().saturating_sub(width)) + .map(|v| LEVELS[(7.0 * *v / max).round() as usize]) + .collect() +} + +fn error_count(count: usize) -> String { + let noun = if count == 1 { "error" } else { "errors" }; + format!("{count} {noun}") +} + +fn stage_line(app: &Dashboard) -> String { + if app.stopping && app.outcome.is_none() { + return "Stopping after the current request…".into(); + } + let text = match app.stage { + Stage::Connecting => "Connecting to the test server…".into(), + Stage::Latency => format!( + "Measuring unloaded latency · {}/{} probes", + app.latency_attempts, app.latency_target + ), + Stage::Transfer(i) => { + let batch = &app.batches[i]; + format!( + "{} · {} · {}/{} samples", + direction_name(batch.direction), + payload(batch.bytes), + batch.samples.values.len(), + batch.target + ) + } + Stage::Done => { + let reason = match app.outcome.as_ref().and_then(|o| o.stop) { + Some(StopReason::Deadline) => "Deadline reached", + Some(StopReason::RetryBudget) => "Retry budget exhausted", + Some(StopReason::Cancelled) => "Run cancelled", + None => "Run finished", + }; + return format!( + "{reason} · {:.1}s · {}", + app.elapsed().as_secs_f64(), + error_count(app.errors.len()) + ); + } + }; + if let Some(remaining) = app + .retry_until + .and_then(|until| until.checked_duration_since(Instant::now())) + { + let cause = match app.errors.last().and_then(|e| e.error.status_code) { + Some(code) if !(200..300).contains(&code) => format!("HTTP {code} · "), + _ => String::new(), + }; + let seconds = (remaining.as_secs_f64() * 10.0).ceil() / 10.0; + return format!("{cause}Retrying in {seconds:.1}s · {text}"); + } + text +} + +const OMITTED_MARK: &str = "·"; + +fn timeline_bar(app: &Dashboard, width: usize) -> Line<'static> { + struct Segment { + target: usize, + complete: usize, + color: Color, + omitted: bool, + } + + let latency = Segment { + target: app.latency_target as usize, + complete: app.latency_attempts as usize, + color: RTT, + omitted: false, + }; + let plan: Vec<_> = std::iter::once(latency) + .chain( + app.batches + .iter() + .enumerate() + .map(|(index, batch)| Segment { + target: batch.target as usize, + complete: batch.samples.values.len(), + color: direction_color(batch.direction), + omitted: omitted(app, index), + }), + ) + .collect(); + let total: usize = plan.iter().map(|segment| segment.target).sum(); + Line::from_iter((0..width).map(|cell| { + let mut index = cell * total / width; + for segment in &plan { + if index < segment.target { + return if segment.omitted { + Span::styled(OMITTED_MARK, Style::new().fg(DIM)) + } else if index < segment.complete { + Span::styled("›", bold(segment.color)) + } else { + Span::styled("›", Style::new().fg(BORDER)) + }; + } + index -= segment.target; + } + Span::raw(" ") + })) +} + +fn omitted_legend(app: &Dashboard) -> Option> { + let count = (0..app.batches.len()).filter(|&i| omitted(app, i)).count(); + if count == 0 { + return None; + } + let noun = if count == 1 { "batch" } else { "batches" }; + let label = if app + .outcome + .as_ref() + .is_some_and(|outcome| outcome.stop.is_some()) + { + "not run" + } else { + "skipped" + }; + Some(Line::styled( + format!("{OMITTED_MARK} {count} payload {noun} {label}"), + Style::new().fg(DIM), + )) +} + +fn render_timeline(frame: &mut Frame, area: Rect, app: &Dashboard) { + let color = if app.retry_until.is_some_and(|until| until > Instant::now()) { + WARN + } else { + status(app).1 + }; + let mut rows = vec![ + Line::styled(stage_line(app), bold(color)), + timeline_bar(app, usize::from(area.width)), + ]; + rows.extend(omitted_legend(app)); + frame.render_widget(Paragraph::new(rows), area); +} + +fn payload(bytes: usize) -> String { + if bytes >= 1_000_000 { + format!("{} MB", bytes / 1_000_000) + } else { + format!("{} KB", bytes / 1_000) + } +} + +fn metric(value: Option) -> String { + match value { + None => "—".into(), + Some(value) if value >= 10_000.0 => format!("{:.1}k", value / 1000.0), + Some(value) => format!("{value:.1}"), + } +} + +fn render_groups(frame: &mut Frame, area: Rect, direction: TestType, app: &Dashboard) { + let (color, series) = match direction { + TestType::Download => (DOWN, &app.download), + TestType::Upload => (UP, &app.upload), + }; + let block = panel(title( + &format!("{} samples", direction_name(direction)), + color, + )); + let inner = block.inner(area); + frame.render_widget(block, area); + let mut rows = Vec::new(); + for (index, batch) in app + .batches + .iter() + .enumerate() + .filter(|(_, b)| b.direction == direction) + { + let active = app.stage == Stage::Transfer(index) && !batch.finished; + let skipped = omitted(app, index); + let count = format!("{}/{}", batch.samples.values.len(), batch.target); + let (mark, accent) = if active { + ("●", color) + } else if skipped { + ("–", DIM) + } else { + ("·", DIM) + }; + rows.push(Line::from(vec![ + Span::styled(format!("{mark} {:<7}", payload(batch.bytes)), bold(accent)), + Span::styled( + if skipped { "not run".into() } else { count }, + Style::new().fg(DIM), + ), + ])); + rows.extend(distribution( + &batch.samples, + series.max(), + inner.width, + color, + false, + )); + } + if rows.is_empty() { + rows.push(Line::styled("Direction disabled", Style::new().fg(DIM))); + } + frame.render_widget(Paragraph::new(rows), inner); +} + +fn omitted(app: &Dashboard, index: usize) -> bool { + !app.batches[index].finished + && match app.stage { + Stage::Transfer(active) => index < active, + Stage::Done => true, + _ => false, + } +} + +fn distribution( + series: &Series, + ceiling: Option, + width: u16, + color: Color, + dots: bool, +) -> Vec> { + let Some(stats) = series.distribution() else { + return vec![Line::styled(" · · ·", Style::new().fg(BORDER))]; + }; + let width = usize::from(width).min(100); + let ceiling = ceiling.unwrap_or(stats[4]).max(f64::EPSILON); + let position = + |v: f64| ((v / ceiling).clamp(0.0, 1.0) * width.saturating_sub(1) as f64).round() as usize; + let [min, q1, median, q3, max] = stats.map(position); + let graph = (0..width) + .map(|cell| match cell { + i if i == median => '╋', + i if i == min || i == max => '┼', + i if (q1..=q3).contains(&i) => '━', + i if (min..=max).contains(&i) => '─', + _ => '·', + }) + .collect::(); + let mut result = vec![Line::styled(graph, Style::new().fg(color))]; + if dots { + let mut points = vec![' '; width]; + for value in &series.values { + if let Some(point) = points.get_mut(position(*value)) { + *point = if *point == ' ' { '·' } else { '●' }; + } + } + result.push(Line::styled( + points.into_iter().collect::(), + Style::new().fg(color), + )); + } + result +} + +fn render_samples(frame: &mut Frame, area: Rect, app: &Dashboard) { + let block = panel(title("Sample distributions", TEXT)); + let inner = block.inner(area); + frame.render_widget(block, area); + let latency = format!( + "Unloaded latency · {}/{} valid · avg {} ms", + app.latency.values.len(), + app.latency_target, + metric(app.latency.mean()) + ); + let mut rows = Vec::new(); + if app.offset == 0 { + rows.push(Line::styled(latency, bold(RTT))); + rows.extend(distribution( + &app.latency, + app.latency.max(), + inner.width, + RTT, + true, + )); + rows.push(Line::raw("")); + } + for (index, batch) in app + .batches + .iter() + .enumerate() + .skip(app.offset.saturating_sub(1)) + { + let color = direction_color(batch.direction); + let name = direction_name(batch.direction); + let payload = payload(batch.bytes); + let status = if omitted(app, index) { + "not run".into() + } else if batch.samples.values.is_empty() + && !batch.finished + && app.stage != Stage::Transfer(index) + { + "pending".into() + } else { + format!( + "{}/{} samples · {} failed attempts", + batch.samples.values.len(), + batch.target, + batch.failures + ) + }; + let axis = match batch.direction { + TestType::Download => app.download.max(), + TestType::Upload => app.upload.max(), + }; + rows.push(Line::styled( + format!("{name} {payload} · {status}"), + bold(color), + )); + rows.extend(distribution(&batch.samples, axis, inner.width, color, true)); + if let Some([min, _, median, _, max]) = batch.samples.distribution() { + rows.push(Line::styled( + format!( + "min {} · median {} · max {} Mbps", + metric(Some(min)), + metric(Some(median)), + metric(Some(max)) + ), + Style::new().fg(DIM), + )); + } + rows.push(Line::raw("")); + } + frame.render_widget(Paragraph::new(rows), inner); +} + +fn render_events(frame: &mut Frame, area: Rect, app: &Dashboard) { + let block = panel(title("Run events", WARN)); + let inner = block.inner(area); + frame.render_widget(block, area); + let mut rows = vec![ + Line::styled(stage_line(app), bold(status(app).1)), + Line::raw(""), + ]; + if app.errors.is_empty() { + rows.push(Line::styled("No measurement errors.", Style::new().fg(DIM))); + } + for error in app + .errors + .iter() + .skip(app.offset) + .take(usize::from(inner.height)) + { + let context = error + .payload_size + .map(|size| format!("{} {}", error.stage, payload(size))) + .unwrap_or_else(|| error.stage.clone()); + let reason: String = error + .error + .reason + .chars() + .map(|c| if c.is_control() { ' ' } else { c }) + .collect(); + let status = error + .error + .status_code + .map(|code| format!("HTTP {code} · ")) + .unwrap_or_default(); + rows.push(Line::from(vec![ + Span::styled(format!("{context} · "), bold(WARN)), + Span::raw(format!("{status}{reason}")), + ])); + } + frame.render_widget(Paragraph::new(rows).wrap(Wrap { trim: true }), inner); +} + +fn render_compact(frame: &mut Frame, area: Rect, app: &Dashboard) { + let (label, color) = status(app); + let down = metric(app.download.p90()); + let up = metric(app.upload.p90()); + let latency = metric(app.latency.mean()); + let mut lines = vec![ + Line::styled(format!("SPEED TEST / {label}"), bold(color)), + Line::styled(format!("↓ {down} Mbps ↑ {up} Mbps"), bold(TEXT)), + Line::styled(format!("Latency {latency} ms"), bold(RTT)), + Line::raw(stage_line(app)), + ]; + lines.extend(omitted_legend(app)); + lines.push(Line::styled( + "Resize for charts · Q Quit", + Style::new().fg(DIM), + )); + frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: true }), area); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::dashboard::state::{Outcome, Update}; + use cfspeedtest::{measurements::PayloadAttemptStats, run::RunEvent, SpeedTestCLIOptions}; + use clap::Parser; + use ratatui::{backend::TestBackend, Terminal}; + + #[test] + fn renders_all_views_for_wide_narrow_and_tiny_terminals() { + let options = SpeedTestCLIOptions::parse_from(["cfspeedtest", "-m", "100m"]); + let mut app = Dashboard::new(&options, "localhost"); + app.apply(Update::Run(RunEvent::LatencyAttempt { ms: Some(0.0) })); + app.apply(Update::Run(RunEvent::PayloadStarted { + direction: TestType::Download, + bytes: 100_000, + target: 10, + })); + app.apply(Update::Run(RunEvent::ThroughputSample { mbps: 17.0 })); + for (width, height) in [(1, 1), (42, 14), (50, 18), (80, 24), (124, 34)] { + let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); + for view in View::ALL { + app.view = view; + terminal.draw(|frame| render(frame, &app)).unwrap(); + } + } + } + + #[test] + fn timeline_marks_adaptive_skips_without_marking_pending_batches() { + let mut app = sample_timeline(); + assert_eq!(timeline_bar(&app, 6).to_string(), "››››››"); + assert!(omitted_legend(&app).is_none()); + + start_batch(&mut app, TestType::Download); + finish_batch(&mut app, TestType::Download); + start_batch(&mut app, TestType::Upload); + let bar = timeline_bar(&app, 6); + assert_eq!(bar.to_string(), "›··›››"); + assert_eq!(bar.spans[0].style.fg, Some(DOWN)); + assert_eq!(bar.spans[3].style.fg, Some(BORDER)); + assert_eq!( + omitted_legend(&app).unwrap().to_string(), + "· 2 payload batches skipped" + ); + + finish_batch(&mut app, TestType::Upload); + app.apply(Update::Finished(Outcome { + status: RunStatus::Complete, + stop: None, + exit: 0, + })); + let bar = timeline_bar(&app, 6); + assert_eq!(bar.to_string(), "›··›··"); + assert_eq!(bar.spans[3].style.fg, Some(UP)); + assert_eq!( + omitted_legend(&app).unwrap().to_string(), + "· 4 payload batches skipped" + ); + } + + #[test] + fn timeline_does_not_describe_batches_left_after_a_deadline_as_adaptive_skips() { + let mut app = sample_timeline(); + start_batch(&mut app, TestType::Download); + finish_batch(&mut app, TestType::Download); + app.apply(Update::Finished(Outcome { + status: RunStatus::Partial, + stop: Some(StopReason::Deadline), + exit: 3, + })); + assert_eq!(timeline_bar(&app, 6).to_string(), "›·····"); + assert_eq!( + omitted_legend(&app).unwrap().to_string(), + "· 5 payload batches not run" + ); + } + + fn sample_timeline() -> Dashboard { + let options = SpeedTestCLIOptions::parse_from([ + "cfspeedtest", + "-m", + "10m", + "-n", + "1", + "--nr-latency-tests", + "0", + ]); + Dashboard::new(&options, "localhost") + } + + fn start_batch(app: &mut Dashboard, direction: TestType) { + app.apply(Update::Run(RunEvent::PayloadStarted { + direction, + bytes: 100_000, + target: 1, + })); + } + + fn finish_batch(app: &mut Dashboard, direction: TestType) { + app.apply(Update::Run(RunEvent::ThroughputSample { mbps: 10.0 })); + app.apply(Update::Run(RunEvent::PayloadFinished( + PayloadAttemptStats { + test_type: direction, + payload_size: 100_000, + attempts: 1, + successes: 1, + skipped: 0, + target_successes: 1, + }, + ))); + } +} diff --git a/src/lib.rs b/src/lib.rs index 35f7b75..76035b6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -40,7 +40,7 @@ impl OutputFormat { } /// Unofficial CLI for speed.cloudflare.com -#[derive(Parser, Debug)] +#[derive(Clone, Parser, Debug)] #[command(author, version, about, long_about = None)] pub struct SpeedTestCLIOptions { /// Number of test runs per payload size. diff --git a/src/main.rs b/src/main.rs index a69edda..b9e3458 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,4 @@ +mod dashboard; mod diagnostics; use cfspeedtest::run::RunConfig; @@ -8,7 +9,7 @@ use clap::error::ErrorKind; use clap::{CommandFactory, Parser}; use clap_complete::generate; use std::error::Error; -use std::io::{self, Write}; +use std::io::{self, IsTerminal, Write}; use std::net::IpAddr; use std::process::ExitCode; use std::sync::atomic::Ordering; @@ -28,6 +29,9 @@ struct CliOptions { /// Maximum cumulative retry wait in seconds #[arg(long, default_value_t = 30, value_parser = clap::value_parser!(u64).range(0..=86400))] max_retry_wait: u64, + /// Open the experimental full-screen speed test dashboard + #[arg(long, conflicts_with_all = ["output_format", "verbose", "completion"])] + tui: bool, } // clap_complete's generators assume writes succeed, so render into a buffer @@ -83,6 +87,23 @@ fn main() -> ExitCode { return command_exit_code(0); } + if cli.tui { + let unsupported = if !io::stdin().is_terminal() || !io::stdout().is_terminal() { + Some("--tui requires terminal input and output") + } else if std::env::var("TERM").as_deref() == Ok("dumb") { + Some("--tui requires a terminal that supports full-screen output") + } else if log::max_level() != log::LevelFilter::Off { + Some("unset RUST_LOG to use --tui without diagnostic output") + } else { + None + }; + if let Some(message) = unsupported { + CliOptions::command() + .error(ErrorKind::ValueValidation, message) + .exit(); + } + } + let client = match reqwest::blocking::Client::builder() .timeout(Duration::from_secs(30)) .cookie_store(true) @@ -111,6 +132,20 @@ fn main() -> ExitCode { eprintln!("Failed to install cancellation handler: {error}"); return ExitCode::FAILURE; } + if cli.tui { + return match dashboard::run( + client, + options, + config, + cli.server.host_str().unwrap_or("Unknown host"), + ) { + Ok(exit) => ExitCode::from(exit), + Err(error) => { + eprintln!("Dashboard error: {error}"); + ExitCode::FAILURE + } + }; + } let human_output = options.output_format == OutputFormat::StdOut; if human_output { stdout::write(|stdout| writeln!(stdout, "Starting Cloudflare speed test")); diff --git a/src/run.rs b/src/run.rs index c9f975c..3e8671e 100644 --- a/src/run.rs +++ b/src/run.rs @@ -1,6 +1,6 @@ //! Run outcomes and shared limits for metadata, latency, transfers, and retries. use crate::measurements::{Measurement, PayloadAttemptStats}; -use crate::speedtest::Metadata; +use crate::speedtest::{Metadata, TestType}; use serde::Serialize; use std::sync::{ atomic::{AtomicBool, Ordering}, @@ -154,7 +154,35 @@ impl SpeedTestReport { } } -pub(crate) struct RunControl { +/// Live updates from [`crate::speedtest::observe_speed_test`], in measurement order. +#[derive(Debug)] +#[non_exhaustive] +pub enum RunEvent { + Metadata(Metadata), + LatencyStarted { + target: u32, + }, + /// A completed probe. A failed probe advances progress but has no sample. + LatencyAttempt { + ms: Option, + }, + PayloadStarted { + direction: TestType, + bytes: usize, + target: u32, + }, + /// A validated transfer sample for the current payload. + ThroughputSample { + mbps: f64, + }, + Error(RunError), + /// A retry was reserved and the worker is about to sleep. + RetryWait(Duration), + PayloadFinished(PayloadAttemptStats), +} + +pub(crate) struct RunControl<'a> { + observer: Option<&'a mut dyn FnMut(RunEvent)>, pub config: RunConfig, deadline: Instant, retry_wait: Duration, @@ -162,13 +190,14 @@ pub(crate) struct RunControl { pub errors: Vec, } -impl RunControl { +impl<'a> RunControl<'a> { pub fn new(config: RunConfig) -> Self { Self::new_at(config, Instant::now()) } fn new_at(config: RunConfig, now: Instant) -> Self { Self { + observer: None, deadline: now.checked_add(config.max_duration).unwrap_or(now), config, retry_wait: Duration::ZERO, @@ -221,12 +250,25 @@ impl RunControl { self.reserve_retry_at(delay, Instant::now()) } + pub fn observing(mut self, observer: &'a mut dyn FnMut(RunEvent)) -> Self { + self.observer = Some(observer); + self + } + + pub fn emit(&mut self, event: impl FnOnce() -> RunEvent) { + if let Some(observer) = &mut self.observer { + observer(event()); + } + } + pub fn record(&mut self, stage: &str, payload_size: Option, error: MeasurementError) { - self.errors.push(RunError { + let error = RunError { stage: stage.into(), payload_size, error, - }); + }; + self.emit(|| RunEvent::Error(error.clone())); + self.errors.push(error); } } diff --git a/src/speedtest.rs b/src/speedtest.rs index 225d107..b5f976d 100644 --- a/src/speedtest.rs +++ b/src/speedtest.rs @@ -6,7 +6,7 @@ use crate::measurements::{transfer_columns, TransferTable}; use crate::progress::{print_progress, Progress}; use crate::run::{ interruptible_sleep, LatencyReport, LatencyStatus, MeasurementError, RunConfig, RunControl, - RunStatus, SpeedTestReport, + RunEvent, RunStatus, SpeedTestReport, }; use crate::stdout; use crate::OutputFormat; @@ -123,7 +123,31 @@ pub fn speed_test_with_config( options: SpeedTestCLIOptions, config: RunConfig, ) -> SpeedTestReport { - let mut control = RunControl::new(config); + run_speed_test(client, options, RunControl::new(config)) +} + +/// Run the same measurements and return the same report as [`speed_test_with_config`], +/// but emit updates on the calling thread instead of printing to the terminal. +/// The observer should return promptly so it does not consume the run's time budget. +pub fn observe_speed_test( + client: Client, + mut options: SpeedTestCLIOptions, + config: RunConfig, + mut observer: impl FnMut(RunEvent), +) -> SpeedTestReport { + options.output_format = OutputFormat::None; + run_speed_test( + client, + options, + RunControl::new(config).observing(&mut observer), + ) +} + +fn run_speed_test( + client: Client, + options: SpeedTestCLIOptions, + mut control: RunControl<'_>, +) -> SpeedTestReport { let base_url = control.config.base_url.trim_end_matches('/').to_string(); let metadata = if let Some(timeout) = control.request_timeout() { match fetch_metadata_request(&client, &base_url, Some(timeout)) { @@ -136,8 +160,9 @@ pub fn speed_test_with_config( } else { None }; - if options.output_format == OutputFormat::StdOut { - if let Some(metadata) = &metadata { + if let Some(metadata) = &metadata { + control.emit(|| RunEvent::Metadata(metadata.clone())); + if options.output_format == OutputFormat::StdOut { stdout::print_line(format_args!("{metadata}")); } } @@ -204,7 +229,7 @@ pub fn speed_test_with_config( payload_attempt_stats, errors: control.errors, }; - if table.is_none() { + if table.is_none() && options.output_format != OutputFormat::None { log_measurements( &report, payload_sizes, @@ -257,18 +282,28 @@ fn run_latency_with_control( let mut report = LatencyReport::new(nr_latency_tests); let base_url = control.config.base_url.trim_end_matches('/').to_string(); let progress = Progress::new(output_format, nr_latency_tests, "Latency", false, None); + if nr_latency_tests > 0 { + control.emit(|| RunEvent::LatencyStarted { + target: nr_latency_tests, + }); + } for _ in 0..nr_latency_tests { let Some(timeout) = control.request_timeout() else { break; }; report.attempts += 1; - match test_latency_request(client, &base_url, Some(timeout)) { - Ok(latency) => report.latency_measurements.push(latency), + let ms = match test_latency_request(client, &base_url, Some(timeout)) { + Ok(latency) => { + report.latency_measurements.push(latency); + Some(latency) + } Err(error) => { control.record("latency", None, error.clone()); report.errors.push(error); + None } - } + }; + control.emit(|| RunEvent::LatencyAttempt { ms }); progress.set_position(report.attempts); } progress.clear(); @@ -515,6 +550,11 @@ fn run_tests_with_control( break; } log::debug!("running tests for payload_size {payload_size}"); + control.emit(|| RunEvent::PayloadStarted { + direction: test_type, + bytes: payload_size, + target: options.nr_tests, + }); let first_sample = measurements.len(); let table_label = table.as_deref_mut().map(|table| { table.start(); @@ -577,6 +617,7 @@ fn run_tests_with_control( duration.as_millis(), ); successes += 1; + control.emit(|| RunEvent::ThroughputSample { mbps: mbits }); progress.set_position(successes); progress.set_status(|| { format!( @@ -632,6 +673,7 @@ fn run_tests_with_control( format_retry_eta(delay), ) }); + control.emit(|| RunEvent::RetryWait(delay)); sleep_fn(delay); } } @@ -685,6 +727,7 @@ fn run_tests_with_control( if let Some(table) = table.as_deref() { table.print_row(&stats, &measurements[first_sample..]); } + control.emit(|| RunEvent::PayloadFinished(stats.clone())); payload_attempt_stats.push(stats); if !options.disable_dynamic_max_payload_size && duration > TIME_THRESHOLD { log::info!("Exceeded threshold"); diff --git a/tests/cli.rs b/tests/cli.rs index c2c85fb..1d4e5ef 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -563,3 +563,20 @@ fn run_with_closed_stdout(command: &mut Command) -> Output { .unwrap(); support::finish(child, Duration::from_secs(4)) } + +#[test] +fn dashboard_rejects_redirected_output_and_explicit_formats() { + for (args, expected) in [ + (&["--tui"][..], "requires terminal input and output"), + (&["--tui", "-o", "json"][..], "cannot be used with"), + ] { + let output = Command::new(env!("CARGO_BIN_EXE_cfspeedtest")) + .args(args) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(2)); + assert!(output.stdout.is_empty()); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains(expected), "{stderr:?}"); + } +} diff --git a/tests/cli_terminal.rs b/tests/cli_terminal.rs index ae0feb7..df1a509 100644 --- a/tests/cli_terminal.rs +++ b/tests/cli_terminal.rs @@ -3,16 +3,26 @@ mod support; use nix::pty::{openpty, Winsize}; +use nix::sys::termios::tcgetattr; use std::cell::Cell; use std::fs::File; -use std::io::{self, Read}; -use std::process::Command; -use std::sync::mpsc; +use std::io::{self, Read, Write}; +use std::process::{Command, ExitStatus}; +use std::sync::{ + atomic::{AtomicUsize, Ordering}, + mpsc, Arc, +}; use std::thread; use std::time::{Duration, Instant}; use support::{finish, Response, Server}; -fn terminal_output(mut command: Command, log_filter: Option<&str>) -> Vec<(Instant, Vec)> { +type Transcript = Vec<(Instant, Vec)>; + +fn capture_terminal( + mut command: Command, + log_filter: Option<&str>, + mut on_output: impl FnMut(&mut File, &[u8]) + Send + 'static, +) -> (ExitStatus, Transcript) { let pty = openpty( &Winsize { ws_row: 30, @@ -24,9 +34,11 @@ fn terminal_output(mut command: Command, log_filter: Option<&str>) -> Vec<(Insta ) .unwrap(); let slave = File::from(pty.slave); + let initial_mode = tcgetattr(&slave).unwrap(); command + .stdin(slave.try_clone().unwrap()) .stdout(slave.try_clone().unwrap()) - .stderr(slave) + .stderr(slave.try_clone().unwrap()) .env("TERM", "xterm") .env("RUST_LOG_STYLE", "never"); if let Some(filter) = log_filter { @@ -43,7 +55,11 @@ fn terminal_output(mut command: Command, log_filter: Option<&str>) -> Vec<(Insta loop { match master.read(&mut buf) { Ok(0) => break, // macOS PTY EOF - Ok(size) => chunks.push((Instant::now(), buf[..size].to_vec())), + Ok(size) => { + let bytes = &buf[..size]; + chunks.push((Instant::now(), bytes.to_vec())); + on_output(&mut master, bytes); + } Err(err) if err.raw_os_error() == Some(nix::libc::EIO) => break, // Linux PTY EOF Err(err) if err.kind() == io::ErrorKind::Interrupted => continue, Err(err) => panic!("PTY read failed: {err}"), @@ -52,13 +68,19 @@ fn terminal_output(mut command: Command, log_filter: Option<&str>) -> Vec<(Insta chunks }); let output = finish(child, Duration::from_secs(8)); - let chunks = reader.join().unwrap(); - assert!( - output.status.success(), - "{}: {:?}", - output.status, - text(&chunks) - ); + let final_mode = tcgetattr(&slave).unwrap(); + // Compare the mode flags rather than unused/padded termios fields. + assert_eq!(final_mode.input_flags, initial_mode.input_flags); + assert_eq!(final_mode.output_flags, initial_mode.output_flags); + assert_eq!(final_mode.control_flags, initial_mode.control_flags); + assert_eq!(final_mode.local_flags, initial_mode.local_flags); + drop(slave); + (output.status, reader.join().unwrap()) +} + +fn terminal_output(command: Command, log_filter: Option<&str>) -> Transcript { + let (status, chunks) = capture_terminal(command, log_filter, |_, _| {}); + assert!(status.success(), "{}: {:?}", status, text(&chunks)); chunks } @@ -145,3 +167,104 @@ fn keeps_dependency_logs_and_disables_terminal_redraws() { assert!(transcript.contains("Summary Statistics"), "{transcript:?}"); assert!(!transcript.contains("Last sample:"), "{transcript:?}"); } + +fn send_keys_on_output(script: &'static [(&str, &[u8])]) -> impl FnMut(&mut File, &[u8]) { + let mut script = script.iter(); + let mut next = script.next(); + let mut received = Vec::new(); + move |terminal, bytes| { + let Some((marker, keys)) = next else { + return; + }; + received.extend_from_slice(bytes); + if received + .windows(marker.len()) + .any(|slice| slice == marker.as_bytes()) + { + terminal.write_all(keys).unwrap(); + received.clear(); + next = script.next(); + } + } +} + +#[test] +fn dashboard_can_change_views_rerun_and_restore_the_terminal() { + let requests = Arc::new(AtomicUsize::new(0)); + let observed = requests.clone(); + let server = Server::new(move |path| { + let mut response = Response::normal(path); + if path == "/__down?bytes=100000" { + observed.fetch_add(1, Ordering::Relaxed); + response.delay = Duration::from_millis(120); + } + response + }); + let (status, chunks) = capture_terminal( + // The shared fixture normally supplies an explicit output format, which + // conflicts with --tui. Build this command without that default. + dashboard_command(&server), + None, + send_keys_on_output(&[ + ("COMPLETE", b"\t"), + ("Sample distributions", b"r"), + ("COMPLETE", b"q"), + ]), + ); + assert_eq!(status.code(), Some(0)); + assert_eq!(requests.load(Ordering::Relaxed), 2); + let transcript = text(&chunks); + assert!(transcript.starts_with("\x1b[?1049h"), "{transcript:?}"); + assert!( + transcript.ends_with("\x1b[?1049l\x1b[?25h"), + "{transcript:?}" + ); + assert!(!transcript.contains("Summary Statistics")); +} + +#[test] +fn dashboard_cancels_during_backoff_and_restores_the_terminal() { + let requests = Arc::new(AtomicUsize::new(0)); + let observed = requests.clone(); + let server = Server::new(move |path| { + if path == "/__down?bytes=100000" { + observed.fetch_add(1, Ordering::Relaxed); + let mut response = Response::new(429, ""); + response.headers.push(("Retry-After".into(), "5".into())); + response + } else { + Response::normal(path) + } + }); + let (status, chunks) = capture_terminal( + dashboard_command(&server), + None, + send_keys_on_output(&[("Retrying in", b"\x03")]), + ); + assert_eq!(status.code(), Some(130)); + assert_eq!(requests.load(Ordering::Relaxed), 1); + let transcript = text(&chunks); + assert!(transcript.contains("HTTP 429"), "{transcript:?}"); + assert!( + transcript.ends_with("\x1b[?1049l\x1b[?25h"), + "{transcript:?}" + ); +} + +fn dashboard_command(server: &Server) -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_cfspeedtest")); + command.args([ + "--server", + &server.url, + "--tui", + "--download-only", + "-m", + "100k", + "-n", + "1", + "--nr-latency-tests", + "0", + ]); + command.env("NO_PROXY", "*").env("no_proxy", "*"); + command +}