From 31c3d7d5ddb1feb5857852f48454cf45aa43e2da Mon Sep 17 00:00:00 2001 From: ByteBaker <42913098+ByteBaker@users.noreply.github.com> Date: Sat, 9 May 2026 16:06:54 +0530 Subject: [PATCH] feat: create a multi-user broadcast chat server & client - a server hosts channels where users can join using the client shipped with this project - the client is a CLI, supporting messages `send `, `leave` - any new user joining/leaving or message is broadcast to all - client uses websocket, server uses tokio broadcast and axum - add unit & integration tests - clippy and fmt check - add tests at CI time - update README with specification --- .github/workflows/ci.yml | 53 ++ .gitignore | 4 - Cargo.lock | 1697 +++++++++++++++++++++++++++++++++++ Cargo.toml | 19 + README.md | 96 +- client/Cargo.toml | 20 + client/src/connection.rs | 164 ++++ client/src/main.rs | 35 + client/src/repl.rs | 217 +++++ proto/Cargo.toml | 8 + proto/src/lib.rs | 125 +++ server/Cargo.toml | 27 + server/src/error.rs | 46 + server/src/lib.rs | 3 + server/src/main.rs | 34 + server/src/state.rs | 96 ++ server/src/ws.rs | 122 +++ server/tests/integration.rs | 223 +++++ 18 files changed, 2931 insertions(+), 58 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 client/Cargo.toml create mode 100644 client/src/connection.rs create mode 100644 client/src/main.rs create mode 100644 client/src/repl.rs create mode 100644 proto/Cargo.toml create mode 100644 proto/src/lib.rs create mode 100644 server/Cargo.toml create mode 100644 server/src/error.rs create mode 100644 server/src/lib.rs create mode 100644 server/src/main.rs create mode 100644 server/src/state.rs create mode 100644 server/src/ws.rs create mode 100644 server/tests/integration.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..2e661bd --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,53 @@ +name: CI + +on: + push: + branches: ["**"] + pull_request: + branches: ["**"] + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + - uses: actions/cache@v4 + with: + path: | + ~/.cargo/registry + ~/.cargo/git + target/ + key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} + restore-keys: ${{ runner.os }}-cargo- + - run: cargo fmt --check + - run: cargo clippy -- -D warnings + - run: cargo test + + e2e: + runs-on: ubuntu-latest + needs: check + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - uses: actions/cache@v4 + with: + path: | + ~/.cargo/registry + ~/.cargo/git + target/ + key: ${{ runner.os }}-cargo-e2e-${{ hashFiles('**/Cargo.lock') }} + restore-keys: ${{ runner.os }}-cargo-e2e- + - run: cargo build --release + - name: smoke test + run: | + CHAT_PORT=3001 ./target/release/server & + SERVER_PID=$! + sleep 1 + echo -e "send hello from CI\nleave" \ + | CHAT_HOST=127.0.0.1 CHAT_PORT=3001 CHAT_USERNAME=ci-bot \ + ./target/release/client + kill $SERVER_PID + wait $SERVER_PID 2>/dev/null || true diff --git a/.gitignore b/.gitignore index 6985cf1..73fab07 100644 --- a/.gitignore +++ b/.gitignore @@ -3,10 +3,6 @@ debug/ target/ -# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries -# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html -Cargo.lock - # These are backup files generated by rustfmt **/*.rs.bk diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..8cd8d8d --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1697 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.102" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "base64", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sha1", + "sync_wrapper", + "tokio", + "tokio-tungstenite", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bitflags" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bytes" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" + +[[package]] +name = "cc" +version = "1.2.62" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1dce859f0832a7d088c4f1119888ab94ef4b5d6795d1ce05afb7fe159d79f98" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "clap" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" + +[[package]] +name = "client" +version = "0.1.0" +dependencies = [ + "anyhow", + "clap", + "crossterm", + "futures-util", + "proto", + "serde_json", + "tokio", + "tokio-tungstenite", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crossterm" +version = "0.28.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6" +dependencies = [ + "bitflags", + "crossterm_winapi", + "futures-core", + "mio", + "parking_lot", + "rustix 0.38.44", + "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 = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "data-encoding" +version = "2.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4ae5f15dda3c708c0ade84bfee31ccab44a3da4f88015ed22f63732abe300c8" + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[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 = "futures-channel" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + +[[package]] +name = "futures-macro" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "futures-sink" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" + +[[package]] +name = "futures-task" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" + +[[package]] +name = "futures-util" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +dependencies = [ + "futures-core", + "futures-macro", + "futures-sink", + "futures-task", + "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.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.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", + "wasip2", + "wasip3", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f467dd6dccf739c208452f8014c75c18bb8301b050ad1cfb27153803edb0f51" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "http" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" +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 = "hyper" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6299f016b246a94207e63da54dbe807655bf9e00044f73ded42c3ac5305fbcca" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "bytes", + "http", + "http-body", + "hyper", + "pin-project-lite", + "tokio", + "tower-service", +] + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown 0.17.0", + "serde", + "serde_core", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "libc" +version = "0.2.186" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[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.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" + +[[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.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mio" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "native-tls" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2" +dependencies = [ + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + +[[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 = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "openssl" +version = "0.10.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf0b434746ee2832f4f0baf10137e1cabb18cbe6912c69e2e33263c45250f542" +dependencies = [ + "bitflags", + "cfg-if", + "foreign-types", + "libc", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + +[[package]] +name = "openssl-sys" +version = "0.9.115" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "158fe5b292746440aa6e7a7e690e55aeb72d41505e2804c23c6973ad0e9c9781" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[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.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "proto" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "quote" +version = "1.0.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +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.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" +dependencies = [ + "rand_chacha", + "rand_core", +] + +[[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", +] + +[[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 = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex-automata" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "schannel" +version = "0.1.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +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", + "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.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.149" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" +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_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 = "server" +version = "0.1.0" +dependencies = [ + "anyhow", + "axum", + "clap", + "futures-util", + "proto", + "serde", + "serde_json", + "tokio", + "tokio-tungstenite", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "sha1" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[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 = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[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 = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + +[[package]] +name = "socket2" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "syn" +version = "2.0.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +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" + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.2", + "once_cell", + "rustix 1.1.4", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "thread_local" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tokio" +version = "1.52.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "110a78583f19d5cdb2c5ccf321d1290344e71313c6c37d43520d386027d18386" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio-native-tls" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" +dependencies = [ + "native-tls", + "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", + "native-tls", + "tokio", + "tokio-native-tls", + "tungstenite", +] + +[[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-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[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", + "native-tls", + "rand", + "sha1", + "thiserror", +] + +[[package]] +name = "typenum" +version = "1.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.3+wasi-0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6" +dependencies = [ + "wit-bindgen 0.57.1", +] + +[[package]] +name = "wasip3" +version = "0.4.0+wasi-0.3.0-rc-2026-01-06" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" +dependencies = [ + "wit-bindgen 0.51.0", +] + +[[package]] +name = "wasm-encoder" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" +dependencies = [ + "bitflags", + "hashbrown 0.15.5", + "indexmap", + "semver", +] + +[[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-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.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +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 = "wit-bindgen" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" +dependencies = [ + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "wit-bindgen-core" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "zerocopy" +version = "0.8.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zmij" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..be3da46 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,19 @@ +[workspace] +resolver = "2" +members = ["proto", "server", "client"] + +[workspace.package] +edition = "2024" +version = "0.1.0" + +[workspace.dependencies] +serde = { version = "1", features = ["derive"] } +serde_json = "1" +tokio = { version = "1", features = ["full"] } +axum = { version = "0.8", features = ["ws"] } +futures-util = "0.3" +tokio-tungstenite = { version = "0.29", features = ["native-tls"] } +clap = { version = "4", features = ["derive", "env"] } +anyhow = "1" +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } diff --git a/README.md b/README.md index 8c4d4e1..acd599d 100644 --- a/README.md +++ b/README.md @@ -1,71 +1,59 @@ -# Simple Chat +# simple-chat -## Summary +A single-room chat server and CLI client. The server broadcasts each message to everyone except the sender. Usernames must be unique. -You have been tasked with writing a simple asynchronous chat server and CLI -client. +## Build -Since this is a simple chat server there is only a single room. Users may -freely join or leave this room. They may also send messages to the room, which -will be sent to all connected users minus the sender. +```bash +cargo build +``` -Even though the server is simple, it has high throughput. Because of this, all -code should be non-blocking for maximum concurrency. +## Run -The following is a rough specification of the server and client. +Start the server: -## Server +```bash +cargo run -p server +``` -* The servers job is to manage users. -* It should be able to receive a message from a user and process it. -* The user may wish to join, leave or send a message through the chat server. -* Any other user who is currently connected should get the message sent to -them. -* The user who sent the message should not get the message. -* When a user sends a leave message, or disconnects their client, the server -should no longer send messages to them, and do any internal bookkeeping to -clean up. -* Username's should be unique. -* The server should be able to support many users without a large delay -* The server should be able to support many users with a small memory footprint +By default it listens on `0.0.0.0:3000`. Override with flags or env vars: +```bash +cargo run -p server -- --host 127.0.0.1 --port 4000 +# or +CHAT_HOST=127.0.0.1 CHAT_PORT=4000 cargo run -p server +``` -## Client +Connect a client (username is required): -* The client is an async CLI program. -* It is responsible for sending messages to the server and displaying any -messages from the server. -* The client should accept environment variables or command line arguments -indicating the host and port where the server is listening. It should also -accept a username that will be used as an identifier on the server. -* The client should automatically connect to the chat server upon -initialization using the specified host and port. -* The client should display an interactive command prompt. The prompt should -be able to handle the following inputs: - * `send ` where `` is the message that should be sent to the - server - * `leave` this will disconnect the client from the server and exit the CLI. +```bash +cargo run -p client -- --username alice +# or +CHAT_USERNAME=alice cargo run -p client +``` +The client defaults to `127.0.0.1:3000`. To point it elsewhere: -## Additional Requirements +```bash +cargo run -p client -- --username alice --host 192.168.1.5 --port 4000 +``` -* Your source should contain both unit and integration tests where necessary. -* All code must be formatted using the standard formatting tool. -* Code must compile without clippy errors. +## Chat -## Submission +Once connected, you'll see a `>` prompt. -Please fork this repository to your own GitHub account and submit a pull -request to your own repository. Your pull request should include a -video of a working demo at the top along with any other key information -that should be highlighted. A link to the pull request can be submitted when -it is ready for review. +| Input | What it does | +|---|---| +| `send hello everyone` | Sends a message to the room | +| `leave` | Disconnects and exits | +| `Ctrl+C` | Same as leave | -## Bonus +Join/leave notifications for other users are printed automatically as they happen. You won't see your own messages echoed back. -* Include a pre-commit hook that will ensure that all code is formatted, compiles -without error, and is free of clippy errors. -* Create a GitHub Action that will launch your chat server and attempt to -send a message to the server from the client. Make sure that niether the server -or client exit with a failure. This action should be run anytime new code -is pushed to a branch or landed on the main branch. +If the username you picked is already taken, the server will reject the connection immediately. + +## Tests + +```bash +cargo test +``` diff --git a/client/Cargo.toml b/client/Cargo.toml new file mode 100644 index 0000000..de910bc --- /dev/null +++ b/client/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "client" +edition.workspace = true +version.workspace = true + +[[bin]] +name = "client" +path = "src/main.rs" + +[dependencies] +proto = { path = "../proto" } +tokio = { workspace = true } +tokio-tungstenite = { workspace = true } +futures-util = { workspace = true } +serde_json = { workspace = true } +anyhow = { workspace = true } +clap = { workspace = true } +tracing = { workspace = true } +tracing-subscriber = { workspace = true } +crossterm = { version = "0.28", features = ["event-stream"] } diff --git a/client/src/connection.rs b/client/src/connection.rs new file mode 100644 index 0000000..33507e0 --- /dev/null +++ b/client/src/connection.rs @@ -0,0 +1,164 @@ +use std::{ + io::{IsTerminal, Write}, + sync::{Arc, Mutex}, +}; + +use anyhow::Result; +use futures_util::StreamExt; +use proto::{ServerMsg, decode_server}; +use tokio_tungstenite::{ + connect_async, + tungstenite::{Error as WsError, Message, error::ProtocolError}, +}; + +use crate::repl; + +pub async fn run(url: &str) -> Result<()> { + let ws_stream = match connect_async(url).await { + Ok((stream, _)) => stream, + Err(e) => { + eprintln!("{}", format_connect_error(&e)); + return Ok(()); + } + }; + let (mut write, mut read) = ws_stream.split(); + + let input_buf: Arc> = Arc::new(Mutex::new(String::new())); + let recv_buf = Arc::clone(&input_buf); + + let is_tty = std::io::stdin().is_terminal(); + let stdin_task: std::pin::Pin>>> = if is_tty { + Box::pin(repl::run_repl(&mut write, input_buf)) + } else { + Box::pin(repl::run_pipe(&mut write)) + }; + + let recv_task = async move { + while let Some(frame) = read.next().await { + match frame { + Ok(Message::Text(text)) => print_server_msg(text.as_str(), &recv_buf), + Ok(Message::Close(_)) | Err(WsError::ConnectionClosed) => break, + Err(WsError::Protocol(ProtocolError::ResetWithoutClosingHandshake)) => break, + Ok(_) => {} + Err(e) => return Err(anyhow::anyhow!(e)), + } + } + Ok::<(), anyhow::Error>(()) + }; + + tokio::select! { + res = stdin_task => res?, + res = recv_task => res?, + } + Ok(()) +} + +fn format_connect_error(e: &WsError) -> String { + match e { + WsError::Io(io_err) if io_err.kind() == std::io::ErrorKind::ConnectionRefused => { + "error: connection refused — is the server running?".to_owned() + } + WsError::Http(response) => { + format!( + "error: server rejected connection (HTTP {})", + response.status() + ) + } + _ => format!("error: {e}"), + } +} + +fn format_server_msg(msg: &ServerMsg) -> String { + match msg { + ServerMsg::Message { from, text } => format!("{from}: {text}\r\n"), + ServerMsg::Welcome { username } => { + format!("connected as {username}. commands: send , leave\r\n") + } + ServerMsg::UsernameTaken { username } => { + format!("error: username '{username}' is taken\r\n") + } + ServerMsg::UserJoined { username } => format!("*** {username} joined\r\n"), + ServerMsg::UserLeft { username } => format!("*** {username} left\r\n"), + ServerMsg::Error { reason } => format!("server error: {reason}\r\n"), + } +} + +fn print_server_msg(text: &str, input_buf: &Arc>) { + let current = input_buf.lock().unwrap(); + + // Clear current input line, print message, then reprint the buffer. + print!("\r\x1b[2K"); + match decode_server(text) { + Ok(msg) => print!("{}", format_server_msg(&msg)), + Err(e) => tracing::warn!("parse error: {e}"), + } + // Reprint whatever the user had typed so far. + print!("{}", *current); + std::io::stdout().flush().ok(); +} + +#[cfg(test)] +mod tests { + use proto::ServerMsg; + + use super::format_server_msg; + + #[test] + fn formats_message() { + let msg = ServerMsg::Message { + from: "alice".into(), + text: "hi there".into(), + }; + let out = format_server_msg(&msg); + assert!(out.contains("alice")); + assert!(out.contains("hi there")); + } + + #[test] + fn formats_welcome() { + let msg = ServerMsg::Welcome { + username: "bob".into(), + }; + let out = format_server_msg(&msg); + assert!(out.contains("bob")); + } + + #[test] + fn formats_username_taken() { + let msg = ServerMsg::UsernameTaken { + username: "bob".into(), + }; + let out = format_server_msg(&msg); + assert!(out.contains("bob")); + assert!(out.contains("taken")); + } + + #[test] + fn formats_user_joined() { + let msg = ServerMsg::UserJoined { + username: "carol".into(), + }; + let out = format_server_msg(&msg); + assert!(out.contains("carol")); + assert!(out.contains("joined")); + } + + #[test] + fn formats_user_left() { + let msg = ServerMsg::UserLeft { + username: "carol".into(), + }; + let out = format_server_msg(&msg); + assert!(out.contains("carol")); + assert!(out.contains("left")); + } + + #[test] + fn formats_error() { + let msg = ServerMsg::Error { + reason: "internal failure".into(), + }; + let out = format_server_msg(&msg); + assert!(out.contains("internal failure")); + } +} diff --git a/client/src/main.rs b/client/src/main.rs new file mode 100644 index 0000000..b8270a4 --- /dev/null +++ b/client/src/main.rs @@ -0,0 +1,35 @@ +use anyhow::Result; +use clap::Parser; + +mod connection; +mod repl; + +#[derive(Parser)] +#[command(about = "simple chat client")] +struct Args { + #[arg(long, env = "CHAT_HOST", default_value = "127.0.0.1")] + host: String, + + #[arg(long, short, env = "CHAT_PORT", default_value_t = 3000u16)] + port: u16, + + #[arg(long, short = 'u', env = "CHAT_USERNAME")] + username: String, +} + +#[tokio::main] +async fn main() -> Result<()> { + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| "client=warn".into()), + ) + .init(); + + let args = Args::parse(); + let url = format!( + "ws://{}:{}/ws?username={}", + args.host, args.port, args.username + ); + connection::run(&url).await +} diff --git a/client/src/repl.rs b/client/src/repl.rs new file mode 100644 index 0000000..d62c8ec --- /dev/null +++ b/client/src/repl.rs @@ -0,0 +1,217 @@ +use std::{ + io::Write, + sync::{Arc, Mutex}, +}; + +use anyhow::Result; +use crossterm::{ + event::{Event, EventStream, KeyCode, KeyEvent, KeyModifiers}, + terminal, +}; +use futures_util::{SinkExt, StreamExt}; +use proto::{ClientMsg, encode_client}; +use tokio::io::AsyncBufReadExt; +use tokio_tungstenite::tungstenite::Message; + +struct RawModeGuard; +impl Drop for RawModeGuard { + fn drop(&mut self) { + let _ = terminal::disable_raw_mode(); + } +} + +pub async fn run_repl(write: &mut W, input_buf: Arc>) -> Result<()> +where + W: SinkExt + Unpin, +{ + terminal::enable_raw_mode()?; + let _guard = RawModeGuard; + repl_loop(write, &input_buf).await +} + +/// Non-TTY fallback: read lines from stdin and send them as commands. +pub async fn run_pipe(write: &mut W) -> Result<()> +where + W: SinkExt + Unpin, +{ + let stdin = tokio::io::BufReader::new(tokio::io::stdin()); + let mut lines = stdin.lines(); + while let Some(line) = lines.next_line().await? { + let line = line.trim().to_owned(); + if line.is_empty() { + continue; + } + match parse_command(&line) { + Some(msg @ ClientMsg::Leave) => { + write + .send(Message::Text(encode_client(&msg)?.into())) + .await + .ok(); + write.close().await.ok(); + return Ok(()); + } + Some(msg) => { + write + .send(Message::Text(encode_client(&msg)?.into())) + .await?; + } + None => {} + } + } + // stdin closed — send leave + let leave = encode_client(&ClientMsg::Leave)?; + write.send(Message::Text(leave.into())).await.ok(); + write.close().await.ok(); + Ok(()) +} + +async fn repl_loop(write: &mut W, input_buf: &Arc>) -> Result<()> +where + W: SinkExt + Unpin, +{ + let mut reader = EventStream::new(); + + while let Some(Ok(event)) = reader.next().await { + let Event::Key(KeyEvent { + code, modifiers, .. + }) = event + else { + continue; + }; + + match code { + KeyCode::Char('c') if modifiers.contains(KeyModifiers::CONTROL) => { + println!(); + break; + } + KeyCode::Enter => { + let line = { + let mut buf = input_buf.lock().unwrap(); + let line = buf.clone(); + buf.clear(); + line + }; + // Move to new line + print!("\r\n"); + std::io::stdout().flush()?; + + let line = line.trim().to_owned(); + if line.is_empty() { + continue; + } + match parse_command(&line) { + Some(msg @ ClientMsg::Leave) => { + write + .send(Message::Text(encode_client(&msg)?.into())) + .await + .ok(); + write.close().await.ok(); + break; + } + Some(msg) => { + write + .send(Message::Text(encode_client(&msg)?.into())) + .await?; + } + None => { + println!("unknown command. use: `send ` or `leave`\r"); + std::io::stdout().flush()?; + } + } + } + KeyCode::Backspace => { + let removed = input_buf.lock().unwrap().pop().is_some(); + if removed { + // erase character: backspace + space + backspace + print!("\x08 \x08"); + std::io::stdout().flush()?; + } + } + KeyCode::Char(c) => { + input_buf.lock().unwrap().push(c); + print!("{c}"); + std::io::stdout().flush()?; + } + _ => {} + } + } + + Ok(()) +} + +fn parse_command(line: &str) -> Option { + if line == "leave" { + Some(ClientMsg::Leave) + } else { + line.strip_prefix("send ").map(|text| ClientMsg::Send { + text: text.to_owned(), + }) + } +} + +#[cfg(test)] +mod tests { + use proto::{ClientMsg, decode_client, encode_client}; + + use super::parse_command; + + #[test] + fn send_encodes_correctly() { + let msg = ClientMsg::Send { + text: "hello world".into(), + }; + let json = encode_client(&msg).unwrap(); + assert_eq!(decode_client(&json).unwrap(), msg); + } + + #[test] + fn leave_encodes_correctly() { + let json = encode_client(&ClientMsg::Leave).unwrap(); + assert_eq!(decode_client(&json).unwrap(), ClientMsg::Leave); + } + + #[test] + fn unknown_type_is_rejected() { + assert!(decode_client(r#"{"type":"badcommand"}"#).is_err()); + } + + #[test] + fn parse_leave() { + assert_eq!(parse_command("leave"), Some(ClientMsg::Leave)); + } + + #[test] + fn parse_send_simple() { + assert_eq!( + parse_command("send hello"), + Some(ClientMsg::Send { + text: "hello".into() + }) + ); + } + + #[test] + fn parse_send_preserves_inner_spaces() { + assert_eq!( + parse_command("send hello world"), + Some(ClientMsg::Send { + text: "hello world".into() + }) + ); + } + + #[test] + fn parse_send_prefix_only_returns_none() { + assert_eq!(parse_command("send"), None); + } + + #[test] + fn parse_unknown_returns_none() { + assert_eq!(parse_command("foo"), None); + } + + #[test] + fn parse_empty_returns_none() { + assert_eq!(parse_command(""), None); + } +} diff --git a/proto/Cargo.toml b/proto/Cargo.toml new file mode 100644 index 0000000..4bd3598 --- /dev/null +++ b/proto/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "proto" +edition.workspace = true +version.workspace = true + +[dependencies] +serde = { workspace = true } +serde_json = { workspace = true } diff --git a/proto/src/lib.rs b/proto/src/lib.rs new file mode 100644 index 0000000..22e92d1 --- /dev/null +++ b/proto/src/lib.rs @@ -0,0 +1,125 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum ClientMsg { + Send { text: String }, + Leave, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum ServerMsg { + Welcome { username: String }, + UsernameTaken { username: String }, + Message { from: String, text: String }, + UserJoined { username: String }, + UserLeft { username: String }, + Error { reason: String }, +} + +pub fn encode_client(msg: &ClientMsg) -> Result { + serde_json::to_string(msg) +} + +pub fn decode_client(s: &str) -> Result { + serde_json::from_str(s) +} + +pub fn encode_server(msg: &ServerMsg) -> Result { + serde_json::to_string(msg) +} + +pub fn decode_server(s: &str) -> Result { + serde_json::from_str(s) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn client_send_roundtrip() { + let msg = ClientMsg::Send { + text: "hello world".into(), + }; + let json = encode_client(&msg).unwrap(); + assert_eq!(decode_client(&json).unwrap(), msg); + } + + #[test] + fn client_leave_roundtrip() { + let msg = ClientMsg::Leave; + let json = encode_client(&msg).unwrap(); + assert_eq!(decode_client(&json).unwrap(), msg); + } + + #[test] + fn server_message_roundtrip() { + let msg = ServerMsg::Message { + from: "alice".into(), + text: "hi".into(), + }; + let json = encode_server(&msg).unwrap(); + assert_eq!(decode_server(&json).unwrap(), msg); + } + + #[test] + fn server_welcome_roundtrip() { + let msg = ServerMsg::Welcome { + username: "alice".into(), + }; + let json = encode_server(&msg).unwrap(); + assert_eq!(decode_server(&json).unwrap(), msg); + } + + #[test] + fn server_username_taken_roundtrip() { + let msg = ServerMsg::UsernameTaken { + username: "bob".into(), + }; + let json = encode_server(&msg).unwrap(); + assert_eq!(decode_server(&json).unwrap(), msg); + } + + #[test] + fn server_user_joined_roundtrip() { + let msg = ServerMsg::UserJoined { + username: "charlie".into(), + }; + let json = encode_server(&msg).unwrap(); + assert_eq!(decode_server(&json).unwrap(), msg); + } + + #[test] + fn server_user_left_roundtrip() { + let msg = ServerMsg::UserLeft { + username: "dan".into(), + }; + let json = encode_server(&msg).unwrap(); + assert_eq!(decode_server(&json).unwrap(), msg); + } + + #[test] + fn client_send_json_shape() { + let json = encode_client(&ClientMsg::Send { + text: "test".into(), + }) + .unwrap(); + let v: serde_json::Value = serde_json::from_str(&json).unwrap(); + assert_eq!(v["type"], "send"); + assert_eq!(v["text"], "test"); + } + + #[test] + fn client_leave_json_shape() { + let json = encode_client(&ClientMsg::Leave).unwrap(); + let v: serde_json::Value = serde_json::from_str(&json).unwrap(); + assert_eq!(v["type"], "leave"); + } + + #[test] + fn rejects_unknown_client_msg() { + assert!(decode_client(r#"{"type":"unknown"}"#).is_err()); + } +} diff --git a/server/Cargo.toml b/server/Cargo.toml new file mode 100644 index 0000000..bb9a6f4 --- /dev/null +++ b/server/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "server" +edition.workspace = true +version.workspace = true + +[lib] +name = "server" +path = "src/lib.rs" + +[[bin]] +name = "server" +path = "src/main.rs" + +[dependencies] +proto = { path = "../proto" } +axum = { workspace = true } +tokio = { workspace = true } +futures-util = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +anyhow = { workspace = true } +tracing = { workspace = true } +tracing-subscriber = { workspace = true } +clap = { workspace = true } + +[dev-dependencies] +tokio-tungstenite = { workspace = true } diff --git a/server/src/error.rs b/server/src/error.rs new file mode 100644 index 0000000..bf30f6a --- /dev/null +++ b/server/src/error.rs @@ -0,0 +1,46 @@ +use axum::{ + http::StatusCode, + response::{IntoResponse, Response}, +}; + +pub struct AppError(pub anyhow::Error); + +impl IntoResponse for AppError { + fn into_response(self) -> Response { + (StatusCode::INTERNAL_SERVER_ERROR, self.0.to_string()).into_response() + } +} + +impl> From for AppError { + fn from(e: E) -> Self { + Self(e.into()) + } +} + +#[cfg(test)] +mod tests { + use axum::{http::StatusCode, response::IntoResponse}; + + use super::AppError; + + #[test] + fn error_into_response_is_500() { + let err = AppError(anyhow::anyhow!("boom")); + let response = err.into_response(); + assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR); + } + + #[tokio::test] + async fn error_body_contains_message() { + let err = AppError(anyhow::anyhow!("something went wrong")); + let response = err.into_response(); + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + assert!( + std::str::from_utf8(&body) + .unwrap() + .contains("something went wrong") + ); + } +} diff --git a/server/src/lib.rs b/server/src/lib.rs new file mode 100644 index 0000000..6228271 --- /dev/null +++ b/server/src/lib.rs @@ -0,0 +1,3 @@ +pub mod error; +pub mod state; +pub mod ws; diff --git a/server/src/main.rs b/server/src/main.rs new file mode 100644 index 0000000..f0bacfc --- /dev/null +++ b/server/src/main.rs @@ -0,0 +1,34 @@ +use axum::{Router, routing::get}; +use clap::Parser; + +use server::{state::AppState, ws::ws_handler}; + +#[derive(Parser)] +#[command(about = "simple chat server")] +struct Args { + #[arg(long, env = "CHAT_HOST", default_value = "0.0.0.0")] + host: String, + + #[arg(long, short, env = "CHAT_PORT", default_value_t = 3000u16)] + port: u16, +} + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| "server=info".into()), + ) + .init(); + + let args = Args::parse(); + let app = Router::new() + .route("/ws", get(ws_handler)) + .with_state(AppState::new()); + + let listener = tokio::net::TcpListener::bind(format!("{}:{}", args.host, args.port)).await?; + tracing::info!("listening on {}", listener.local_addr()?); + axum::serve(listener, app).await?; + Ok(()) +} diff --git a/server/src/state.rs b/server/src/state.rs new file mode 100644 index 0000000..36be56d --- /dev/null +++ b/server/src/state.rs @@ -0,0 +1,96 @@ +use std::{collections::HashSet, sync::Arc}; + +use proto::ServerMsg; +use tokio::sync::{Mutex, broadcast}; + +pub const BROADCAST_CAPACITY: usize = 512; + +#[derive(Clone)] +pub struct AppState { + pub inner: Arc, +} + +pub struct Inner { + pub users: Mutex>, + pub tx: broadcast::Sender>, +} + +impl AppState { + pub fn new() -> Self { + let (tx, _) = broadcast::channel(BROADCAST_CAPACITY); + Self { + inner: Arc::new(Inner { + users: Mutex::new(HashSet::new()), + tx, + }), + } + } + + pub async fn register(&self, username: &str) -> bool { + self.inner.users.lock().await.insert(username.to_owned()) + } + + pub async fn deregister(&self, username: &str) { + self.inner.users.lock().await.remove(username); + } + + pub fn broadcast(&self, msg: Arc) { + let _ = self.inner.tx.send(msg); + } + + pub fn subscribe(&self) -> broadcast::Receiver> { + self.inner.tx.subscribe() + } +} + +impl Default for AppState { + fn default() -> Self { + Self::new() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn register_new_username_returns_true() { + let state = AppState::new(); + assert!(state.register("alice").await); + } + + #[tokio::test] + async fn register_duplicate_username_returns_false() { + let state = AppState::new(); + state.register("alice").await; + assert!(!state.register("alice").await); + } + + #[tokio::test] + async fn deregister_allows_reregistration() { + let state = AppState::new(); + state.register("alice").await; + state.deregister("alice").await; + assert!(state.register("alice").await); + } + + #[tokio::test] + async fn broadcast_with_no_receivers_does_not_panic() { + let state = AppState::new(); + state.broadcast(Arc::new(ServerMsg::UserJoined { + username: "alice".into(), + })); + } + + #[tokio::test] + async fn subscribe_receives_broadcast() { + let state = AppState::new(); + let mut rx = state.subscribe(); + let msg = Arc::new(ServerMsg::UserJoined { + username: "alice".into(), + }); + state.broadcast(Arc::clone(&msg)); + let received = rx.recv().await.unwrap(); + assert_eq!(*received, *msg); + } +} diff --git a/server/src/ws.rs b/server/src/ws.rs new file mode 100644 index 0000000..2362aaf --- /dev/null +++ b/server/src/ws.rs @@ -0,0 +1,122 @@ +use std::sync::Arc; + +use axum::{ + extract::{ + Query, State, WebSocketUpgrade, + ws::{Message, WebSocket}, + }, + http::StatusCode, + response::IntoResponse, +}; +use futures_util::{SinkExt, StreamExt}; +use proto::{ClientMsg, ServerMsg, decode_client, encode_server}; +use serde::Deserialize; +use tokio::sync::broadcast::error::RecvError; + +use crate::state::AppState; + +#[derive(Deserialize)] +pub struct WsParams { + pub username: String, +} + +pub async fn ws_handler( + ws: WebSocketUpgrade, + Query(params): Query, + State(state): State, +) -> impl IntoResponse { + if params.username.trim().is_empty() { + return (StatusCode::BAD_REQUEST, "username required").into_response(); + } + ws.on_upgrade(move |socket| handle_socket(socket, params.username, state)) +} + +async fn handle_socket(socket: WebSocket, username: String, state: AppState) { + if !state.register(&username).await { + tracing::info!("{username} rejected: username taken"); + let mut socket = socket; + if let Ok(json) = encode_server(&ServerMsg::UsernameTaken { + username: username.clone(), + }) { + let _ = socket.send(Message::Text(json.into())).await; + } + return; + } + + let mut rx = state.subscribe(); + + let (mut sender, mut receiver) = socket.split(); + let welcome = ServerMsg::Welcome { + username: username.clone(), + }; + if let Ok(json) = encode_server(&welcome) + && sender.send(Message::Text(json.into())).await.is_err() + { + state.deregister(&username).await; + return; + } + + tracing::info!("{username} joined"); + state.broadcast(Arc::new(ServerMsg::UserJoined { + username: username.clone(), + })); + + let uname = username.clone(); + let send_task = async { + loop { + match rx.recv().await { + Ok(msg) => { + let skip = match msg.as_ref() { + ServerMsg::Message { from, .. } => from == &uname, + ServerMsg::UserJoined { username: u } => u == &uname, + ServerMsg::UserLeft { username: u } => u == &uname, + _ => false, + }; + if skip { + continue; + } + let Ok(json) = encode_server(&msg) else { + continue; + }; + if sender.send(Message::Text(json.into())).await.is_err() { + break; + } + } + Err(RecvError::Lagged(n)) => { + tracing::warn!("{uname} lagged by {n} messages"); + } + Err(RecvError::Closed) => break, + } + } + }; + + let uname = username.clone(); + let state_recv = state.clone(); + let recv_task = async { + while let Some(Ok(frame)) = receiver.next().await { + match frame { + Message::Text(text) => match decode_client(text.as_str()) { + Ok(ClientMsg::Send { text: body }) => { + state_recv.broadcast(Arc::new(ServerMsg::Message { + from: uname.clone(), + text: body, + })); + } + Ok(ClientMsg::Leave) => break, + Err(e) => tracing::warn!("bad msg from {uname}: {e}"), + }, + Message::Close(_) => break, + _ => {} + } + } + }; + + tokio::select! { + () = send_task => {} + () = recv_task => {} + } + + tracing::info!("{username} left"); + state.deregister(&username).await; + state.broadcast(Arc::new(ServerMsg::UserLeft { username })); +} diff --git a/server/tests/integration.rs b/server/tests/integration.rs new file mode 100644 index 0000000..76ca4b8 --- /dev/null +++ b/server/tests/integration.rs @@ -0,0 +1,223 @@ +use std::time::Duration; + +use futures_util::{SinkExt, StreamExt}; +use proto::{ClientMsg, ServerMsg, decode_server, encode_client}; +use tokio_tungstenite::{connect_async, tungstenite::Message}; + +async fn spawn_server() -> u16 { + use axum::{Router, routing::get}; + use server::{state::AppState, ws::ws_handler}; + + let app = Router::new() + .route("/ws", get(ws_handler)) + .with_state(AppState::new()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + port +} + +async fn connect( + port: u16, + username: &str, +) -> ( + impl futures_util::Sink + Unpin, + impl futures_util::Stream> + Unpin, +) { + let url = format!("ws://127.0.0.1:{port}/ws?username={username}"); + let (ws, _) = connect_async(&url).await.unwrap(); + ws.split() +} + +async fn recv_msg( + rx: &mut ( + impl futures_util::Stream> + + Unpin + ), +) -> ServerMsg { + let frame = rx.next().await.unwrap().unwrap(); + match frame { + Message::Text(t) => decode_server(t.as_str()).unwrap(), + other => panic!("expected text frame, got {other:?}"), + } +} + +async fn send_msg( + tx: &mut (impl futures_util::Sink + Unpin), + msg: &ClientMsg, +) { + let json = encode_client(msg).unwrap(); + tx.send(Message::Text(json.into())).await.unwrap(); +} + +#[tokio::test] +async fn empty_username_is_rejected() { + let port = spawn_server().await; + let url = format!("ws://127.0.0.1:{port}/ws?username="); + let result = connect_async(&url).await; + assert!(result.is_err(), "empty username should be rejected"); + assert!(matches!( + result.unwrap_err(), + tokio_tungstenite::tungstenite::Error::Http(_) + )); +} + +#[tokio::test] +async fn missing_username_param_is_rejected() { + let port = spawn_server().await; + let url = format!("ws://127.0.0.1:{port}/ws"); + let result = connect_async(&url).await; + assert!(result.is_err(), "missing username param should be rejected"); + assert!(matches!( + result.unwrap_err(), + tokio_tungstenite::tungstenite::Error::Http(_) + )); +} + +#[tokio::test] +async fn connect_sends_welcome() { + let port = spawn_server().await; + let (_, mut rx) = connect(port, "alice").await; + let msg = recv_msg(&mut rx).await; + assert_eq!( + msg, + ServerMsg::Welcome { + username: "alice".into() + } + ); +} + +#[tokio::test] +async fn duplicate_username_rejected() { + let port = spawn_server().await; + let (_tx1, mut rx1) = connect(port, "alice").await; + assert!(matches!( + recv_msg(&mut rx1).await, + ServerMsg::Welcome { .. } + )); + + let (_tx2, mut rx2) = connect(port, "alice").await; + let msg = recv_msg(&mut rx2).await; + assert_eq!( + msg, + ServerMsg::UsernameTaken { + username: "alice".into() + } + ); +} + +#[tokio::test] +async fn message_broadcast_to_others() { + let port = spawn_server().await; + + let (mut alice_tx, mut alice_rx) = connect(port, "alice").await; + assert!(matches!( + recv_msg(&mut alice_rx).await, + ServerMsg::Welcome { .. } + )); + + let (_bob_tx, mut bob_rx) = connect(port, "bob").await; + assert!(matches!( + recv_msg(&mut bob_rx).await, + ServerMsg::Welcome { .. } + )); + // alice gets UserJoined for bob + let _ = recv_msg(&mut alice_rx).await; + + send_msg( + &mut alice_tx, + &ClientMsg::Send { + text: "hello".into(), + }, + ) + .await; + + // bob gets the message + let msg = recv_msg(&mut bob_rx).await; + assert_eq!( + msg, + ServerMsg::Message { + from: "alice".into(), + text: "hello".into() + } + ); + + // alice does NOT get her own message within 200ms + let alice_received = + tokio::time::timeout(Duration::from_millis(200), recv_msg(&mut alice_rx)).await; + assert!( + alice_received.is_err(), + "alice should not receive her own message" + ); +} + +#[tokio::test] +async fn leave_removes_user() { + let port = spawn_server().await; + + let (mut alice_tx, mut alice_rx) = connect(port, "alice").await; + assert!(matches!( + recv_msg(&mut alice_rx).await, + ServerMsg::Welcome { .. } + )); + + let (_bob_tx, mut bob_rx) = connect(port, "bob").await; + assert!(matches!( + recv_msg(&mut bob_rx).await, + ServerMsg::Welcome { .. } + )); + // alice sees bob join + let _ = recv_msg(&mut alice_rx).await; + + send_msg(&mut alice_tx, &ClientMsg::Leave).await; + + // bob sees alice leave + let msg = recv_msg(&mut bob_rx).await; + assert_eq!( + msg, + ServerMsg::UserLeft { + username: "alice".into() + } + ); + + // re-connect as alice succeeds + let (_, mut rx3) = connect(port, "alice").await; + assert!(matches!( + recv_msg(&mut rx3).await, + ServerMsg::Welcome { .. } + )); +} + +#[tokio::test] +async fn disconnect_cleans_up_state() { + let port = spawn_server().await; + + let (alice_tx, mut alice_rx) = connect(port, "alice").await; + assert!(matches!( + recv_msg(&mut alice_rx).await, + ServerMsg::Welcome { .. } + )); + + let (_bob_tx, mut bob_rx) = connect(port, "bob").await; + assert!(matches!( + recv_msg(&mut bob_rx).await, + ServerMsg::Welcome { .. } + )); + // alice sees bob join + let _ = recv_msg(&mut alice_rx).await; + + // drop alice's connection without sending Leave + drop(alice_tx); + drop(alice_rx); + + // bob sees alice leave (may take a moment) + let msg = tokio::time::timeout(Duration::from_secs(2), recv_msg(&mut bob_rx)) + .await + .expect("timed out waiting for UserLeft"); + assert_eq!( + msg, + ServerMsg::UserLeft { + username: "alice".into() + } + ); +}