From 050dbc792af4c4f082afa6bed706cbf9171e5e3f Mon Sep 17 00:00:00 2001 From: L Date: Mon, 23 Feb 2026 23:18:56 +0000 Subject: [PATCH] feat: scaffold relay client auth workspace --- .gitignore | 5 + Cargo.lock | 1798 +++++++++++++++++++++++++++++++++++++++ Cargo.toml | 21 + Dockerfile.auth-api | 12 + MASTER_PROMPT.md | 311 +++++++ auth-api/Cargo.toml | 17 + auth-api/src/main.rs | 250 ++++++ client/Cargo.toml | 11 + client/src/main.rs | 254 ++++++ common/Cargo.toml | 11 + common/src/codec.rs | 42 + common/src/lib.rs | 3 + common/src/minecraft.rs | 106 +++ common/src/protocol.rs | 69 ++ db/schema.sql | 67 ++ docker-compose.yml | 32 + relay/Cargo.toml | 16 + relay/src/main.rs | 699 +++++++++++++++ 18 files changed, 3724 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 Dockerfile.auth-api create mode 100644 MASTER_PROMPT.md create mode 100644 auth-api/Cargo.toml create mode 100644 auth-api/src/main.rs create mode 100644 client/Cargo.toml create mode 100644 client/src/main.rs create mode 100644 common/Cargo.toml create mode 100644 common/src/codec.rs create mode 100644 common/src/lib.rs create mode 100644 common/src/minecraft.rs create mode 100644 common/src/protocol.rs create mode 100644 db/schema.sql create mode 100644 docker-compose.yml create mode 100644 relay/Cargo.toml create mode 100644 relay/src/main.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..af656a5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +target/ +.DS_Store +.env +.env.* +!.env.example diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..e6f6360 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1798 @@ +# 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 = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +version = "1.0.102" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" + +[[package]] +name = "arc-swap" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f3647c145568cec02c42054e07bdf9a5a698e15b466fb2341bfc393cd24aa5" +dependencies = [ + "rustversion", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "auth-api" +version = "0.1.0" +dependencies = [ + "anyhow", + "axum", + "chrono", + "fastrand", + "jsonwebtoken", + "redis", + "serde", + "serde_json", + "tokio", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "autocfg" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" + +[[package]] +name = "axum" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b52af3cb4058c895d37317bb27508dccc8e5f2d39454016b297bf4a400597b8" +dependencies = [ + "axum-core", + "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", + "sync_wrapper", + "tokio", + "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 = "backon" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cffb0e931875b666fc4fcb20fee52e9bbd1ef836fd9e9e04ec21555f9f85f7ef" +dependencies = [ + "fastrand", +] + +[[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.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af" + +[[package]] +name = "bumpalo" +version = "3.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" + +[[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.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aebf35691d1bfb0ac386a69bac2fde4dd276fb618cf8bf4f5318fe285e821bb2" +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 = "chrono" +version = "0.4.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "client" +version = "0.1.0" +dependencies = [ + "anyhow", + "common", + "tokio", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "combine" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd" +dependencies = [ + "bytes", + "futures-core", + "memchr", + "pin-project-lite", + "tokio", + "tokio-util", +] + +[[package]] +name = "common" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror", + "tokio", + "uuid", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +dependencies = [ + "powerfmt", +] + +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[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.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" + +[[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 = "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-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-sink", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139ef39800118c7683f2fd3c98c1b23c09ae076556b435f8e9064ae108aaeeec" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "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.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" + +[[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.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ab2d4f250c3d7b1c9fcdff1cece94ea4e2dfbec68614f7b87cb205f24ca9d11" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "pin-utils", + "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 = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" +dependencies = [ + "displaydoc", + "potential_utf", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" + +[[package]] +name = "icu_properties" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "020bfc02fe870ec3a66d93e677ccca0562506e5872c650f893269e08615d74ec" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "616c294cf8d725c6afcd8f55abc17c56464ef6211f9ed59cccffe534129c77af" + +[[package]] +name = "icu_provider" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017" +dependencies = [ + "equivalent", + "hashbrown 0.16.1", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2" + +[[package]] +name = "js-sys" +version = "0.3.88" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7e709f3e3d22866f9c25b3aff01af289b18422cc8b4262fb19103ee80fe513d" +dependencies = [ + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "jsonwebtoken" +version = "10.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0529410abe238729a60b108898784df8984c87f6054c9c4fcacc47e4803c1ce1" +dependencies = [ + "base64", + "getrandom 0.2.17", + "js-sys", + "pem", + "serde", + "serde_json", + "signature", + "simple_asn1", +] + +[[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.182" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6800badb6cb2082ffd7b6a67e6125bb39f18782f793520caee8cb8846be06112" + +[[package]] +name = "litemap" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77" + +[[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.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-bigint" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf97ec579c3c42f953ef76dbf8d55ac91fb219dde70e49aa4a6b7d74e9919050" + +[[package]] +name = "num-integer" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" + +[[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 = "pem" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +dependencies = [ + "base64", + "serde_core", +] + +[[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.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "potential_utf" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[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 = "quote" +version = "1.0.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4" +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 = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "redis" +version = "0.32.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "014cc767fefab6a3e798ca45112bccad9c6e0e218fbd49720042716c73cfef44" +dependencies = [ + "arc-swap", + "backon", + "bytes", + "cfg-if", + "combine", + "futures-channel", + "futures-util", + "itoa", + "num-bigint", + "percent-encoding", + "pin-project-lite", + "ryu", + "sha1_smol", + "socket2", + "tokio", + "tokio-util", + "url", +] + +[[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.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a96887878f22d7bad8a3b6dc5b7440e0ada9a245242924394987b21cf2210a4c" + +[[package]] +name = "relay" +version = "0.1.0" +dependencies = [ + "anyhow", + "chrono", + "common", + "fastrand", + "redis", + "serde_json", + "tokio", + "tracing", + "tracing-subscriber", + "uuid", +] + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "semver" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2" + +[[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 = "sha1_smol" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d" + +[[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-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "rand_core", +] + +[[package]] +name = "simple_asn1" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d" +dependencies = [ + "num-bigint", + "num-traits", + "thiserror", + "time", +] + +[[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.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86f4aa3ad99f2088c990dfa82d367e19cb29268ed67c574d10d0a4bfe71f07e0" +dependencies = [ + "libc", + "windows-sys 0.60.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[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 = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[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 = "time" +version = "0.3.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c" +dependencies = [ + "deranged", + "itoa", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca" + +[[package]] +name = "time-macros" +version = "0.2.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.49.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72a2903cd7736441aac9df9d7688bd0ce48edccaadf181c3b90be801e81d3d86" +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.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio-util" +version = "0.7.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[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.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f30143827ddab0d256fd843b7a66d164e9f271cfa0dde49142c5ca0ca291f1e" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[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 = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b672338555252d43fd2240c714dc444b8c6fb0a5c5335e65a07bba7742735ddb" +dependencies = [ + "getrandom 0.4.1", + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[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.2+wasi-0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5" +dependencies = [ + "wit-bindgen", +] + +[[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", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.111" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec1adf1535672f5b7824f817792b1afd731d7e843d2d04ec8f27e8cb51edd8ac" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.111" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19e638317c08b21663aed4d2b9a2091450548954695ff4efa75bff5fa546b3b1" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.111" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c64760850114d03d5f65457e96fc988f11f01d38fbaa51b254e4ab5809102af" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.111" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60eecd4fe26177cfa3339eb00b4a36445889ba3ad37080c2429879718e20ca41" +dependencies = [ + "unicode-ident", +] + +[[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 = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +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.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "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.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + +[[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-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 = "writeable" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9" + +[[package]] +name = "yoke" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3" +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..56f54b7 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,21 @@ +[workspace] +members = ["common", "relay", "client", "auth-api"] +resolver = "2" + +[workspace.package] +edition = "2024" + +[workspace.dependencies] +anyhow = "1.0" +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +tokio = { version = "1.44", features = ["full"] } +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] } +uuid = { version = "1.16", features = ["v4", "serde"] } +thiserror = "2.0" +fastrand = "2.3" +axum = "0.8" +redis = { version = "0.32", features = ["tokio-comp", "connection-manager"] } +jsonwebtoken = "10" +chrono = { version = "0.4", features = ["serde", "clock"] } diff --git a/Dockerfile.auth-api b/Dockerfile.auth-api new file mode 100644 index 0000000..88f6b95 --- /dev/null +++ b/Dockerfile.auth-api @@ -0,0 +1,12 @@ +FROM rust:1.86 as build +WORKDIR /app +COPY . . +RUN cargo build --release -p auth-api + +FROM debian:bookworm-slim +RUN useradd -r -u 10001 appuser +WORKDIR /app +COPY --from=build /app/target/release/auth-api /usr/local/bin/auth-api +USER appuser +EXPOSE 8080 +CMD ["auth-api"] diff --git a/MASTER_PROMPT.md b/MASTER_PROMPT.md new file mode 100644 index 0000000..27602ea --- /dev/null +++ b/MASTER_PROMPT.md @@ -0,0 +1,311 @@ +# ๐Ÿง  MASTER SYSTEM PROMPT + +## Distributed Minecraft Tunnel Platform (Railway-Scalable, Replica-Aware, Monetizable) + +--- + +## ROLE + +You are a senior distributed systems architect and Rust network engineer. + +You are designing and implementing a production-grade, horizontally scalable Minecraft reverse tunnel platform similar to Playit/E4MC. + +The system must: + +* Scale from 1k โ†’ 50k+ concurrent tunnels +* Support multi-region +* Support Railway auto-scaling +* Be replica-safe +* Be stateless at relay layer +* Be monetization-ready +* Be resilient to instance restarts +* Maintain low latency +* Be designed for high concurrency + +This is not a hobby project. +Design for real-world production constraints. + +--- +# ๐ŸŽฏ SYSTEM OBJECTIVE + +Users run a Rust client locally. +They receive a subdomain: + +``` +sleepy-creeper.eu.dvv.one +``` + +Players connect to that subdomain. +Traffic is routed through relay nodes to the userโ€™s home server. + +No port forwarding required. + +--- +# ๐Ÿ— GLOBAL ARCHITECTURE REQUIREMENTS + +You must design: + +1. Rust Relay Service (stateless) +2. Rust Client Agent +3. Redis cluster (shared tunnel state) +4. PostgreSQL (users + billing) +5. Auth API (minimal Rust HTTP service) +6. Stripe billing integration +7. Railway deployment topology +8. Multi-region support +9. Replica-aware routing +10. Graceful autoscaling logic + +--- +# ๐ŸŒ MULTI-REGION MODEL + +Regions: + +``` +eu +us +asia (optional) +``` + +Each region: + +* Has its own relay cluster +* Has its own Railway service group +* Shares central Redis + Postgres (or region-local Redis if specified) + +Subdomain format: + +``` +adjective-noun.{region}.dvv.one +``` + +--- +# ๐Ÿงฑ RELAY SERVICE REQUIREMENTS (RUST) + +Relay must: + +* Listen on: + * 7000 (tunnel registration) + * 25565 (Minecraft routing) +* Be async (Tokio) +* Be horizontally scalable +* NOT store tunnel state locally + +--- +## ๐Ÿ” TUNNEL STATE MODEL (REDIS) + +Redis stores: + +``` +subdomain โ†’ instance_id +instance_id โ†’ active tunnel metadata +user_id โ†’ plan tier +``` + +Relay instances must: + +* Register themselves in Redis on startup +* Maintain heartbeat key: + + ``` + instance:{id} โ†’ alive + ``` +* Remove stale instance data on startup + +--- +## ๐Ÿ”„ REPLICA SUPPORT + +If multiple relay replicas are running: + +* Any relay can receive player connection +* It checks Redis: + + ``` + subdomain โ†’ owning instance + ``` + +If tunnel owned by different instance: + +* Open internal TCP connection to that instance +* Forward traffic internally +* Do NOT reject connection + +Cross-instance routing must: + +* Be efficient +* Add minimal latency +* Avoid infinite routing loops +* Avoid recursive forwarding + +--- +# ๐Ÿš‚ RAILWAY COMPATIBILITY REQUIREMENTS + +You MUST design for: + +* Ephemeral containers +* No persistent disk +* Dynamic scaling up/down +* Instance restarts at any time +* Non-static internal IPs + +Therefore: + +* All state in Redis +* No reliance on local memory persistence +* Graceful shutdown support (SIGTERM handler) +* Drain active tunnels before shutdown + +--- +# ๐Ÿ“ˆ AUTOSCALING LOGIC + +When scaling up: + +* New instances register in Redis +* New tunnel registrations assigned to least-loaded instance +* Use Redis sorted set for load tracking + +When scaling down: + +* Instance marks itself as โ€œdrainingโ€ +* Stops accepting new tunnels +* Waits until active tunnels reach 0 +* Exits cleanly + +--- +# ๐Ÿง  CLIENT REQUIREMENTS (RUST) + +Client must: + +* Benchmark latency to all regions +* Connect to lowest-latency region +* Authenticate using token +* Maintain persistent tunnel +* Reconnect automatically +* Handle relay instance migration +* Support multiple concurrent forwarded connections +* Be under 10MB binary + +--- +# ๐Ÿ’ฐ SAAS & MONETIZATION LAYER + +Free tier: + +* 1 tunnel +* Random subdomain +* Idle timeout +* Limited bandwidth + +Paid tier: + +* Custom subdomain +* Multiple tunnels +* Higher bandwidth cap +* No idle timeout +* Priority routing + +--- +## ๐Ÿ” AUTH MODEL + +* JWT tokens +* Client must send token during registration +* Relay verifies token via Redis cache +* Plan limits enforced in real time + +--- +# ๐Ÿงฎ SCALING TARGETS + +Design must handle: + +| Level | Active Tunnels | Player Connections | +| ------ | -------------- | ------------------ | +| Small | 1,000 | 5,000 | +| Medium | 10,000 | 50,000 | +| Large | 50,000 | 200,000 | + +Include: + +* Memory usage estimates +* CPU usage estimates +* Redis throughput estimates +* Bandwidth estimates + +--- +# โšก PERFORMANCE CONSTRAINTS + +* No blocking I/O +* No global Mutex +* No heavy frameworks in relay +* Zero-copy forwarding +* Use `tokio::io::copy_bidirectional` +* Minimal allocations in hot path +* Avoid logging per packet + +--- +# ๐Ÿ›ก FAILURE SCENARIOS TO HANDLE + +* Relay instance crash +* Redis temporary outage +* Client reconnect storm +* Player connects during migration +* Instance scaling down mid-traffic +* Partial network partition + +Explain how each is handled safely. + +--- +# ๐Ÿ“ฆ REQUIRED OUTPUT FORMAT + +Return: + +1. Full system architecture diagram (text-based) +2. Component descriptions +3. Redis schema +4. Cross-instance routing design +5. Autoscaling algorithm +6. Graceful shutdown flow +7. Client architecture +8. SaaS enforcement model +9. Railway deployment layout +10. Cost estimates at 1k / 10k / 50k scale +11. Bottleneck analysis +12. Optimization opportunities + +Do NOT provide vague explanations. +Be concrete, structured, and technical. + +--- +# ๐Ÿ”ฅ ADVANCED MODE (MANDATORY) + +Include: + +* Replica-aware routing logic +* Load-based tunnel assignment +* Rate limiting strategy +* DDoS mitigation outline +* Observability plan (metrics + tracing) +* Suggested Prometheus metrics +* Suggested horizontal scaling thresholds + +--- +# ๐Ÿš€ DESIGN PRIORITY ORDER + +1. Correctness +2. Scalability +3. Low latency +4. Railway compatibility +5. Monetization enforcement +6. Cost efficiency + +--- + +This single prompt forces an AI agent to produce a **real distributed system blueprint**, not toy code. + +--- + +If you want next, I can: + +* Design the *ultra-low-latency no-Redis single-region version* +* Or design the *global Anycast + BGP version like major networks* +* Or help you decide whether Railway is actually the right choice for 50k tunnels* + +Youโ€™re now at infrastructure-architect level thinking. \ No newline at end of file diff --git a/auth-api/Cargo.toml b/auth-api/Cargo.toml new file mode 100644 index 0000000..5b8c2e9 --- /dev/null +++ b/auth-api/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "auth-api" +version = "0.1.0" +edition = "2024" + +[dependencies] +anyhow.workspace = true +axum.workspace = true +chrono.workspace = true +jsonwebtoken.workspace = true +redis.workspace = true +serde.workspace = true +serde_json.workspace = true +tokio.workspace = true +tracing.workspace = true +tracing-subscriber.workspace = true +fastrand.workspace = true diff --git a/auth-api/src/main.rs b/auth-api/src/main.rs new file mode 100644 index 0000000..a243eae --- /dev/null +++ b/auth-api/src/main.rs @@ -0,0 +1,250 @@ +use std::{net::SocketAddr, sync::Arc}; + +use anyhow::{Context, Result}; +use axum::{ + Json, Router, + extract::State, + http::StatusCode, + response::IntoResponse, + routing::{get, post}, +}; +use chrono::{Duration, Utc}; +use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, encode}; +use redis::AsyncCommands; +use serde::{Deserialize, Serialize}; +use tracing::{info, warn}; + +#[derive(Clone)] +struct AppState { + jwt_secret: Arc, + redis: Option, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +struct Claims { + sub: String, + tier: String, + max_tunnels: u32, + exp: usize, + iat: usize, + jti: String, +} + +#[derive(Debug, Deserialize)] +struct DevTokenRequest { + user_id: String, + #[serde(default = "default_tier")] + tier: String, + #[serde(default = "default_max_tunnels")] + max_tunnels: u32, +} + +#[derive(Debug, Serialize)] +struct TokenResponse { + token: String, + expires_at: i64, +} + +#[derive(Debug, Deserialize)] +struct ValidateRequest { + token: String, +} + +#[derive(Debug, Serialize)] +struct ValidateResponse { + valid: bool, + user_id: Option, + tier: Option, + max_tunnels: Option, +} + +#[derive(Debug, Deserialize)] +struct StripeWebhookEvent { + event_type: String, + user_id: String, + tier: String, + #[serde(default = "default_max_tunnels")] + max_tunnels: u32, +} + +#[tokio::main] +async fn main() -> Result<()> { + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| "auth_api=info".into()), + ) + .init(); + + let bind = std::env::var("AUTH_BIND").unwrap_or_else(|_| "0.0.0.0:8080".into()); + let jwt_secret = std::env::var("JWT_SECRET").unwrap_or_else(|_| "dev-secret-change-me".into()); + let redis = if let Ok(url) = std::env::var("REDIS_URL") { + let client = redis::Client::open(url.clone()).context("open redis client")?; + match redis::aio::ConnectionManager::new(client).await { + Ok(conn) => { + info!("auth-api connected to redis"); + Some(conn) + } + Err(e) => { + warn!(error = %e, "auth-api redis unavailable; continuing without cache"); + None + } + } + } else { + None + }; + + let state = AppState { + jwt_secret: Arc::new(jwt_secret), + redis, + }; + + let app = Router::new() + .route("/healthz", get(healthz)) + .route("/v1/token/dev", post(issue_dev_token)) + .route("/v1/token/validate", post(validate_token)) + .route("/v1/stripe/webhook", post(stripe_webhook)) + .with_state(state); + + let listener = tokio::net::TcpListener::bind(&bind) + .await + .with_context(|| format!("bind {bind}"))?; + let local_addr: SocketAddr = listener.local_addr()?; + info!(addr = %local_addr, "auth-api listening"); + axum::serve(listener, app).await?; + Ok(()) +} + +async fn healthz() -> &'static str { + "ok" +} + +async fn issue_dev_token( + State(state): State, + Json(req): Json, +) -> Result, ApiError> { + let now = Utc::now(); + let exp = now + Duration::hours(24); + let claims = Claims { + sub: req.user_id, + tier: req.tier, + max_tunnels: req.max_tunnels, + exp: exp.timestamp() as usize, + iat: now.timestamp() as usize, + jti: format!("jti-{}", fastrand::u64(..)), + }; + + let token = encode( + &Header::default(), + &claims, + &EncodingKey::from_secret(state.jwt_secret.as_bytes()), + ) + .map_err(ApiError::internal)?; + + if let Some(mut redis) = state.redis.clone() { + let key = format!("auth:jwt:jti:{}", claims.jti); + let ttl = (claims.exp as i64 - now.timestamp()).max(1); + let payload = serde_json::json!({ + "user_id": claims.sub, + "plan_tier": claims.tier, + "max_tunnels": claims.max_tunnels + }) + .to_string(); + let _: () = redis + .set_ex(key, payload, ttl as u64) + .await + .map_err(ApiError::internal)?; + } + + Ok(Json(TokenResponse { + token, + expires_at: exp.timestamp(), + })) +} + +async fn validate_token( + State(state): State, + Json(req): Json, +) -> Result, ApiError> { + let decoded = decode::( + &req.token, + &DecodingKey::from_secret(state.jwt_secret.as_bytes()), + &Validation::new(Algorithm::HS256), + ); + + match decoded { + Ok(tok) => { + let c = tok.claims; + if let Some(mut redis) = state.redis.clone() { + let key = format!("plan:user:{}", c.sub); + let payload = serde_json::json!({ + "tier": c.tier, + "max_tunnels": c.max_tunnels, + "source": "auth-api" + }) + .to_string(); + let _: () = redis.set_ex(key, payload, 300).await.map_err(ApiError::internal)?; + } + Ok(Json(ValidateResponse { + valid: true, + user_id: Some(c.sub), + tier: Some(c.tier), + max_tunnels: Some(c.max_tunnels), + })) + } + Err(_) => Ok(Json(ValidateResponse { + valid: false, + user_id: None, + tier: None, + max_tunnels: None, + })), + } +} + +async fn stripe_webhook( + State(state): State, + Json(event): Json, +) -> Result { + if let Some(mut redis) = state.redis.clone() { + let key = format!("plan:user:{}", event.user_id); + let payload = serde_json::json!({ + "tier": event.tier, + "max_tunnels": event.max_tunnels, + "source": "stripe_webhook", + "last_event_type": event.event_type, + "updated_at": Utc::now().timestamp(), + }) + .to_string(); + let _: () = redis.set_ex(key, payload, 300).await.map_err(ApiError::internal)?; + } + Ok(StatusCode::NO_CONTENT) +} + +#[derive(Debug)] +struct ApiError { + status: StatusCode, + message: String, +} + +impl ApiError { + fn internal(e: E) -> Self { + Self { + status: StatusCode::INTERNAL_SERVER_ERROR, + message: e.to_string(), + } + } +} + +impl IntoResponse for ApiError { + fn into_response(self) -> axum::response::Response { + (self.status, self.message).into_response() + } +} + +fn default_tier() -> String { + "free".to_string() +} + +fn default_max_tunnels() -> u32 { + 1 +} diff --git a/client/Cargo.toml b/client/Cargo.toml new file mode 100644 index 0000000..13f362a --- /dev/null +++ b/client/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "client" +version = "0.1.0" +edition = "2024" + +[dependencies] +anyhow.workspace = true +tokio.workspace = true +tracing.workspace = true +tracing-subscriber.workspace = true +common = { path = "../common" } diff --git a/client/src/main.rs b/client/src/main.rs new file mode 100644 index 0000000..fffc20a --- /dev/null +++ b/client/src/main.rs @@ -0,0 +1,254 @@ +use std::{collections::HashMap, sync::Arc, time::Duration}; + +use anyhow::{Context, Result}; +use common::{ + codec::{read_frame, write_frame}, + protocol::{ + ClientFrame, Heartbeat, RegisterRequest, ServerFrame, StreamClosed, StreamData, + }, +}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::TcpStream, + sync::{RwLock, mpsc}, + time::{MissedTickBehavior, sleep}, +}; +use tracing::{error, info, warn}; + +#[derive(Clone)] +struct ClientConfig { + relay_addr: String, + token: String, + region: String, + local_addr: String, + requested_subdomain: Option, +} + +impl ClientConfig { + fn from_env() -> Self { + Self { + relay_addr: std::env::var("DVV_RELAY_ADDR").unwrap_or_else(|_| "127.0.0.1:7000".into()), + token: std::env::var("DVV_TOKEN").unwrap_or_else(|_| "dev-token-local".into()), + region: std::env::var("DVV_REGION").unwrap_or_else(|_| "eu".into()), + local_addr: std::env::var("DVV_LOCAL_ADDR").unwrap_or_else(|_| "127.0.0.1:25565".into()), + requested_subdomain: std::env::var("DVV_SUBDOMAIN").ok(), + } + } +} + +type StreamSinkMap = Arc>>>>; + +#[tokio::main] +async fn main() -> Result<()> { + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| "client=info".into()), + ) + .init(); + + let cfg = ClientConfig::from_env(); + let mut backoff = Duration::from_millis(300); + + loop { + match run_session(cfg.clone()).await { + Ok(()) => warn!("session ended; reconnecting"), + Err(e) => error!(error = %e, "session failed"), + } + sleep(backoff).await; + backoff = (backoff * 2).min(Duration::from_secs(10)); + } +} + +async fn run_session(cfg: ClientConfig) -> Result<()> { + let stream = TcpStream::connect(&cfg.relay_addr) + .await + .with_context(|| format!("connect relay {}", cfg.relay_addr))?; + let (mut reader, mut writer) = stream.into_split(); + + write_frame( + &mut writer, + &ClientFrame::Register(RegisterRequest { + token: cfg.token.clone(), + region: cfg.region.clone(), + requested_subdomain: cfg.requested_subdomain.clone(), + local_addr: cfg.local_addr.clone(), + }), + ) + .await?; + + let accepted = match read_frame::<_, ServerFrame>(&mut reader) + .await + .context("read register response")? + { + ServerFrame::RegisterAccepted(ok) => ok, + ServerFrame::RegisterRejected { reason } => anyhow::bail!("register rejected: {reason}"), + other => anyhow::bail!("unexpected frame at register: {other:?}"), + }; + + info!( + fqdn = %accepted.fqdn, + session_id = %accepted.session_id, + owner = %accepted.owner_instance_id, + "registered tunnel" + ); + + let sinks: StreamSinkMap = Arc::new(RwLock::new(HashMap::new())); + let (out_tx, mut out_rx) = mpsc::channel::(1024); + + let writer_task = tokio::spawn(async move { + while let Some(frame) = out_rx.recv().await { + write_frame(&mut writer, &frame).await?; + } + Ok::<(), anyhow::Error>(()) + }); + + let hb_tx = out_tx.clone(); + let hb_sinks = sinks.clone(); + let hb_session_id = accepted.session_id.clone(); + let hb_interval = Duration::from_secs(accepted.heartbeat_interval_secs.max(1)); + let hb_task = tokio::spawn(async move { + let mut ticker = tokio::time::interval(hb_interval); + ticker.set_missed_tick_behavior(MissedTickBehavior::Delay); + loop { + ticker.tick().await; + let active_streams = hb_sinks.read().await.len() as u32; + let frame = ClientFrame::Heartbeat(Heartbeat { + session_id: hb_session_id.clone(), + active_streams, + bytes_in: 0, + bytes_out: 0, + }); + if hb_tx.send(frame).await.is_err() { + break; + } + } + }); + + loop { + let frame: ServerFrame = read_frame(&mut reader).await?; + match frame { + ServerFrame::Ping => { + let _ = out_tx.send(ClientFrame::Pong).await; + } + ServerFrame::IncomingTcp(incoming) => { + let cfg_clone = cfg.clone(); + let out_tx_clone = out_tx.clone(); + let sinks_clone = sinks.clone(); + tokio::spawn(async move { + if let Err(e) = handle_incoming_stream(cfg_clone, incoming, out_tx_clone, sinks_clone).await { + warn!(error = %e, "incoming stream handling failed"); + } + }); + } + ServerFrame::StreamData(StreamData { stream_id, data }) => { + if let Some(tx) = sinks.read().await.get(&stream_id).cloned() { + if tx.send(data).await.is_err() { + sinks.write().await.remove(&stream_id); + } + } + } + ServerFrame::StreamClosed(StreamClosed { stream_id, .. }) => { + sinks.write().await.remove(&stream_id); + } + ServerFrame::DrainNotice { retry_after_ms, reason } => { + warn!(retry_after_ms, reason = %reason, "relay draining"); + break; + } + ServerFrame::Error { message } => warn!(message = %message, "server error frame"), + ServerFrame::RegisterAccepted(_) | ServerFrame::RegisterRejected { .. } => { + warn!("ignoring unexpected register response after session start") + } + } + } + + hb_task.abort(); + writer_task.abort(); + Ok(()) +} + +async fn handle_incoming_stream( + cfg: ClientConfig, + incoming: common::protocol::IncomingTcp, + out_tx: mpsc::Sender, + sinks: StreamSinkMap, +) -> Result<()> { + let mut local = TcpStream::connect(&cfg.local_addr) + .await + .with_context(|| format!("connect local mc {}", cfg.local_addr))?; + + if !incoming.initial_data.is_empty() { + local.write_all(&incoming.initial_data).await?; + } + + let (local_read, local_write) = local.into_split(); + let (to_local_tx, to_local_rx) = mpsc::channel::>(128); + sinks.write().await.insert(incoming.stream_id.clone(), to_local_tx); + + let stream_id = incoming.stream_id.clone(); + let sinks_clone = sinks.clone(); + tokio::spawn(async move { + if let Err(e) = run_local_writer(local_write, to_local_rx).await { + warn!(stream_id = %stream_id, error = %e, "local writer ended"); + } + sinks_clone.write().await.remove(&stream_id); + }); + + let stream_id = incoming.stream_id.clone(); + let out_tx_clone = out_tx.clone(); + let sinks_clone = sinks.clone(); + tokio::spawn(async move { + if let Err(e) = run_local_reader(local_read, out_tx_clone.clone(), stream_id.clone()).await { + warn!(stream_id = %stream_id, error = %e, "local reader ended"); + } + let _ = out_tx_clone + .send(ClientFrame::StreamClosed(StreamClosed { + stream_id: stream_id.clone(), + reason: Some("local_reader_closed".into()), + })) + .await; + sinks_clone.write().await.remove(&stream_id); + }); + + info!( + stream_id = %incoming.stream_id, + peer = %incoming.peer_addr, + hostname = %incoming.hostname, + local = %cfg.local_addr, + "connected relay stream to local minecraft" + ); + Ok(()) +} + +async fn run_local_reader( + mut reader: tokio::net::tcp::OwnedReadHalf, + out_tx: mpsc::Sender, + stream_id: String, +) -> Result<()> { + let mut buf = vec![0u8; 16 * 1024]; + loop { + let n = reader.read(&mut buf).await?; + if n == 0 { + break; + } + out_tx + .send(ClientFrame::StreamData(StreamData { + stream_id: stream_id.clone(), + data: buf[..n].to_vec(), + })) + .await + .context("send local data to relay")?; + } + Ok(()) +} + +async fn run_local_writer( + mut writer: tokio::net::tcp::OwnedWriteHalf, + mut rx: mpsc::Receiver>, +) -> Result<()> { + while let Some(chunk) = rx.recv().await { + writer.write_all(&chunk).await?; + } + writer.shutdown().await.ok(); + Ok(()) +} diff --git a/common/Cargo.toml b/common/Cargo.toml new file mode 100644 index 0000000..5e9bb7a --- /dev/null +++ b/common/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "common" +version = "0.1.0" +edition = "2024" + +[dependencies] +serde.workspace = true +serde_json.workspace = true +tokio.workspace = true +thiserror.workspace = true +uuid.workspace = true diff --git a/common/src/codec.rs b/common/src/codec.rs new file mode 100644 index 0000000..a6c5d98 --- /dev/null +++ b/common/src/codec.rs @@ -0,0 +1,42 @@ +use std::io; + +use serde::{Serialize, de::DeserializeOwned}; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; + +const MAX_FRAME_SIZE: usize = 1024 * 1024; + +pub async fn write_frame(writer: &mut W, value: &T) -> io::Result<()> +where + W: AsyncWrite + Unpin, + T: Serialize, +{ + let payload = serde_json::to_vec(value) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?; + if payload.len() > MAX_FRAME_SIZE { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "frame exceeds max size", + )); + } + writer.write_u32(payload.len() as u32).await?; + writer.write_all(&payload).await?; + writer.flush().await +} + +pub async fn read_frame(reader: &mut R) -> io::Result +where + R: AsyncRead + Unpin, + T: DeserializeOwned, +{ + let len = reader.read_u32().await? as usize; + if len > MAX_FRAME_SIZE { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "frame too large", + )); + } + let mut payload = vec![0u8; len]; + reader.read_exact(&mut payload).await?; + serde_json::from_slice(&payload) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string())) +} diff --git a/common/src/lib.rs b/common/src/lib.rs new file mode 100644 index 0000000..008971e --- /dev/null +++ b/common/src/lib.rs @@ -0,0 +1,3 @@ +pub mod codec; +pub mod minecraft; +pub mod protocol; diff --git a/common/src/minecraft.rs b/common/src/minecraft.rs new file mode 100644 index 0000000..e7f98f5 --- /dev/null +++ b/common/src/minecraft.rs @@ -0,0 +1,106 @@ +use std::io; + +use tokio::io::{AsyncRead, AsyncReadExt}; + +pub async fn read_handshake_hostname(reader: &mut R) -> io::Result +where + R: AsyncRead + Unpin, +{ + let (hostname, _) = read_handshake_hostname_and_bytes(reader).await?; + Ok(hostname) +} + +pub async fn read_handshake_hostname_and_bytes(reader: &mut R) -> io::Result<(String, Vec)> +where + R: AsyncRead + Unpin, +{ + let (packet_len, packet_len_bytes) = read_varint_async_with_bytes(reader).await?; + let packet_len = packet_len as usize; + if packet_len == 0 || packet_len > 2048 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "invalid minecraft handshake packet length", + )); + } + + let mut buf = vec![0u8; packet_len]; + reader.read_exact(&mut buf).await?; + let mut cur = &buf[..]; + + let packet_id = read_varint_slice(&mut cur)?; + if packet_id != 0 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "expected handshake packet id 0", + )); + } + + let _protocol_version = read_varint_slice(&mut cur)?; + let host = read_string_slice(&mut cur, 255)?; + if cur.len() < 2 { + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "missing port")); + } + let _port = u16::from_be_bytes([cur[0], cur[1]]); + cur = &cur[2..]; + let _next_state = read_varint_slice(&mut cur)?; + + let mut raw = packet_len_bytes; + raw.extend_from_slice(&buf); + Ok((host, raw)) +} + +async fn read_varint_async_with_bytes(reader: &mut R) -> io::Result<(i32, Vec)> +where + R: AsyncRead + Unpin, +{ + let mut num_read = 0; + let mut result = 0i32; + let mut raw = Vec::with_capacity(5); + loop { + let byte = reader.read_u8().await?; + raw.push(byte); + let value = (byte & 0x7F) as i32; + result |= value << (7 * num_read); + num_read += 1; + if num_read > 5 { + return Err(io::Error::new(io::ErrorKind::InvalidData, "varint too big")); + } + if (byte & 0x80) == 0 { + break; + } + } + Ok((result, raw)) +} + +fn read_varint_slice(input: &mut &[u8]) -> io::Result { + let mut num_read = 0; + let mut result = 0i32; + loop { + if input.is_empty() { + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "eof")); + } + let byte = input[0]; + *input = &input[1..]; + let value = (byte & 0x7F) as i32; + result |= value << (7 * num_read); + num_read += 1; + if num_read > 5 { + return Err(io::Error::new(io::ErrorKind::InvalidData, "varint too big")); + } + if (byte & 0x80) == 0 { + break; + } + } + Ok(result) +} + +fn read_string_slice(input: &mut &[u8], max_len: usize) -> io::Result { + let len = read_varint_slice(input)? as usize; + if len > max_len || input.len() < len { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad string len")); + } + let bytes = &input[..len]; + *input = &input[len..]; + String::from_utf8(bytes.to_vec()) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string())) +} diff --git a/common/src/protocol.rs b/common/src/protocol.rs new file mode 100644 index 0000000..c5e1700 --- /dev/null +++ b/common/src/protocol.rs @@ -0,0 +1,69 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RegisterRequest { + pub token: String, + pub region: String, + pub requested_subdomain: Option, + pub local_addr: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RegisterAccepted { + pub session_id: String, + pub fqdn: String, + pub heartbeat_interval_secs: u64, + pub owner_instance_id: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Heartbeat { + pub session_id: String, + pub active_streams: u32, + pub bytes_in: u64, + pub bytes_out: u64, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct IncomingTcp { + pub stream_id: String, + pub session_id: String, + pub peer_addr: String, + pub hostname: String, + pub initial_data: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct StreamData { + pub stream_id: String, + pub data: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct StreamClosed { + pub stream_id: String, + pub reason: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "type", content = "data")] +pub enum ClientFrame { + Register(RegisterRequest), + Heartbeat(Heartbeat), + StreamData(StreamData), + StreamClosed(StreamClosed), + Pong, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "type", content = "data")] +pub enum ServerFrame { + RegisterAccepted(RegisterAccepted), + RegisterRejected { reason: String }, + IncomingTcp(IncomingTcp), + StreamData(StreamData), + StreamClosed(StreamClosed), + Ping, + DrainNotice { retry_after_ms: u64, reason: String }, + Error { message: String }, +} diff --git a/db/schema.sql b/db/schema.sql new file mode 100644 index 0000000..13b4f79 --- /dev/null +++ b/db/schema.sql @@ -0,0 +1,67 @@ +-- PostgreSQL schema scaffold for dvv tunnel SaaS platform. + +create extension if not exists pgcrypto; + +create table if not exists users ( + id uuid primary key default gen_random_uuid(), + email text unique not null, + password_hash text, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now() +); + +create table if not exists plans ( + id text primary key, + name text not null, + max_tunnels integer not null, + custom_subdomain boolean not null default false, + idle_timeout_seconds integer, + bandwidth_cap_kbps integer, + priority_routing boolean not null default false, + created_at timestamptz not null default now() +); + +create table if not exists subscriptions ( + id uuid primary key default gen_random_uuid(), + user_id uuid not null references users(id) on delete cascade, + plan_id text not null references plans(id), + provider text not null default 'stripe', + provider_customer_id text, + provider_subscription_id text, + status text not null, + current_period_end timestamptz, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now() +); + +create index if not exists subscriptions_user_id_idx on subscriptions(user_id); + +create table if not exists tunnels ( + id uuid primary key default gen_random_uuid(), + user_id uuid not null references users(id) on delete cascade, + region text not null check (region in ('eu', 'us', 'asia')), + subdomain text not null, + custom_domain boolean not null default false, + active boolean not null default true, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + unique (region, subdomain) +); + +create index if not exists tunnels_user_id_idx on tunnels(user_id); + +create table if not exists usage_rollups_hourly ( + user_id uuid not null references users(id) on delete cascade, + hour_bucket timestamptz not null, + bytes_in bigint not null default 0, + bytes_out bigint not null default 0, + player_connections integer not null default 0, + primary key (user_id, hour_bucket) +); + +insert into plans (id, name, max_tunnels, custom_subdomain, idle_timeout_seconds, bandwidth_cap_kbps, priority_routing) +values + ('free', 'Free', 1, false, 900, 512, false), + ('pro', 'Pro', 5, true, null, 8192, true), + ('team', 'Team', 25, true, null, null, true) +on conflict (id) do nothing; diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..8eaab64 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,32 @@ +version: "3.9" + +services: + redis: + image: redis:7-alpine + ports: + - "6379:6379" + + postgres: + image: postgres:16-alpine + environment: + POSTGRES_USER: dvv + POSTGRES_PASSWORD: dvv + POSTGRES_DB: dvv + ports: + - "5432:5432" + volumes: + - ./db/schema.sql:/docker-entrypoint-initdb.d/001-schema.sql:ro + + auth-api: + build: + context: . + dockerfile: Dockerfile.auth-api + environment: + AUTH_BIND: 0.0.0.0:8080 + JWT_SECRET: dev-secret-change-me + REDIS_URL: redis://redis:6379 + depends_on: + - redis + ports: + - "8080:8080" + diff --git a/relay/Cargo.toml b/relay/Cargo.toml new file mode 100644 index 0000000..ee1ed0a --- /dev/null +++ b/relay/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "relay" +version = "0.1.0" +edition = "2024" + +[dependencies] +anyhow.workspace = true +tokio.workspace = true +tracing.workspace = true +tracing-subscriber.workspace = true +uuid.workspace = true +fastrand.workspace = true +redis.workspace = true +serde_json.workspace = true +chrono.workspace = true +common = { path = "../common" } diff --git a/relay/src/main.rs b/relay/src/main.rs new file mode 100644 index 0000000..2d8e34e --- /dev/null +++ b/relay/src/main.rs @@ -0,0 +1,699 @@ +use std::{ + collections::HashMap, + net::SocketAddr, + sync::Arc, + time::{Duration, Instant}, +}; + +use anyhow::{Context, Result}; +use common::{ + codec::{read_frame, write_frame}, + minecraft::read_handshake_hostname_and_bytes, + protocol::{ + ClientFrame, Heartbeat, IncomingTcp, RegisterAccepted, RegisterRequest, ServerFrame, + StreamClosed, StreamData, + }, +}; +use redis::AsyncCommands; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::{TcpListener, TcpStream}, + sync::{Notify, RwLock, mpsc}, + time::{MissedTickBehavior, interval, timeout}, +}; +use tracing::{debug, info, warn}; +use uuid::Uuid; + +#[derive(Clone)] +struct RelayConfig { + instance_id: String, + region: String, + control_bind: String, + player_bind: String, + domain: String, + heartbeat_timeout: Duration, + registry_ttl_secs: u64, +} + +impl RelayConfig { + fn from_env() -> Self { + Self { + instance_id: std::env::var("RELAY_INSTANCE_ID") + .unwrap_or_else(|_| format!("relay-{}", Uuid::new_v4())), + region: std::env::var("RELAY_REGION").unwrap_or_else(|_| "eu".to_string()), + control_bind: std::env::var("RELAY_CONTROL_BIND") + .unwrap_or_else(|_| "0.0.0.0:7000".to_string()), + player_bind: std::env::var("RELAY_PLAYER_BIND") + .unwrap_or_else(|_| "0.0.0.0:25565".to_string()), + domain: std::env::var("RELAY_BASE_DOMAIN").unwrap_or_else(|_| "dvv.one".to_string()), + heartbeat_timeout: Duration::from_secs( + std::env::var("RELAY_HEARTBEAT_TIMEOUT_SECS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(30), + ), + registry_ttl_secs: std::env::var("RELAY_REGISTRY_TTL_SECS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(20), + } + } +} + +#[derive(Clone)] +struct SessionHandle { + session_id: String, + tx: mpsc::Sender, + stream_sinks: Arc>>>>, + last_heartbeat: Instant, +} + +struct RelayState { + by_fqdn: HashMap, + by_session: HashMap, +} + +impl RelayState { + fn new() -> Self { + Self { + by_fqdn: HashMap::new(), + by_session: HashMap::new(), + } + } + + fn session_count(&self) -> usize { + self.by_session.len() + } +} + +type SharedState = Arc>; + +#[derive(Clone)] +struct RedisRegistry { + conn: Option, + instance_id: String, + region: String, + control_addr: String, + player_addr: String, + ttl_secs: u64, +} + +impl RedisRegistry { + async fn from_env(cfg: &RelayConfig) -> Self { + let conn = match std::env::var("REDIS_URL") { + Ok(url) => match redis::Client::open(url.clone()) { + Ok(client) => match redis::aio::ConnectionManager::new(client).await { + Ok(cm) => { + info!("connected to redis"); + Some(cm) + } + Err(e) => { + warn!(error = %e, "redis connection manager failed; continuing without redis"); + None + } + }, + Err(e) => { + warn!(error = %e, "invalid REDIS_URL; continuing without redis"); + None + } + }, + Err(_) => None, + }; + + Self { + conn, + instance_id: cfg.instance_id.clone(), + region: cfg.region.clone(), + control_addr: cfg.control_bind.clone(), + player_addr: cfg.player_bind.clone(), + ttl_secs: cfg.registry_ttl_secs, + } + } + + async fn register_instance(&self) { + let Some(mut conn) = self.conn.clone() else { + return; + }; + let key = format!("relay:instance:{}", self.instance_id); + let payload = serde_json::json!({ + "instance_id": self.instance_id, + "region": self.region, + "status": "active", + "control_addr": self.control_addr, + "player_addr": self.player_addr, + "started_at": chrono::Utc::now().timestamp(), + }) + .to_string(); + + let res: redis::RedisResult<()> = async { + let _: usize = conn.sadd("relay:instances", &self.instance_id).await?; + let _: () = conn.set_ex(&key, payload, self.ttl_secs).await?; + let hb_key = format!("relay:heartbeat:{}", self.instance_id); + let _: () = conn.set_ex(hb_key, "1", self.ttl_secs).await?; + Ok(()) + } + .await; + if let Err(e) = res { + warn!(error = %e, "failed to register instance in redis"); + } + } + + async fn heartbeat_instance(&self, tunnel_count: usize) { + let Some(mut conn) = self.conn.clone() else { + return; + }; + let hb_key = format!("relay:heartbeat:{}", self.instance_id); + let load_key = format!("relay:load:{}", self.region); + let score = tunnel_count as f64; + let key = format!("relay:instance:{}", self.instance_id); + let payload = serde_json::json!({ + "instance_id": self.instance_id, + "region": self.region, + "status": "active", + "control_addr": self.control_addr, + "player_addr": self.player_addr, + "tunnel_count": tunnel_count, + "updated_at": chrono::Utc::now().timestamp(), + }) + .to_string(); + let res: redis::RedisResult<()> = async { + let _: () = conn.set_ex(hb_key, "1", self.ttl_secs).await?; + let _: () = conn.set_ex(key, payload, self.ttl_secs).await?; + let _: () = conn.zadd(load_key, &self.instance_id, score).await?; + Ok(()) + } + .await; + if let Err(e) = res { + warn!(error = %e, "redis instance heartbeat failed"); + } + } + + async fn set_draining(&self) { + let Some(mut conn) = self.conn.clone() else { + return; + }; + let key = format!("relay:instance:{}", self.instance_id); + let payload = serde_json::json!({ + "instance_id": self.instance_id, + "region": self.region, + "status": "draining", + "control_addr": self.control_addr, + "player_addr": self.player_addr, + "updated_at": chrono::Utc::now().timestamp(), + }) + .to_string(); + let _: redis::RedisResult<()> = async { + let _: () = conn.set_ex(key, payload, self.ttl_secs).await?; + let load_key = format!("relay:load:{}", self.region); + let _: () = conn.zadd(load_key, &self.instance_id, 1e12f64).await?; + Ok(()) + } + .await; + } + + async fn register_tunnel(&self, fqdn: &str, session_id: &str, user_id: &str) { + let Some(mut conn) = self.conn.clone() else { + return; + }; + let key = format!("tunnel:sub:{fqdn}"); + let session_key = format!("tunnel:session:{session_id}"); + let payload = serde_json::json!({ + "instance_id": self.instance_id, + "session_id": session_id, + "user_id": user_id, + "region": self.region, + "fqdn": fqdn, + }) + .to_string(); + let _: redis::RedisResult<()> = async { + let _: () = conn.set_ex(key, &payload, self.ttl_secs).await?; + let _: () = conn.set_ex(session_key, payload, self.ttl_secs).await?; + Ok(()) + } + .await; + } + + async fn refresh_tunnel_session(&self, fqdn: &str, session_id: &str, user_id: &str) { + self.register_tunnel(fqdn, session_id, user_id).await; + } + + async fn remove_tunnel(&self, fqdn: &str, session_id: &str) { + let Some(mut conn) = self.conn.clone() else { + return; + }; + let _: redis::RedisResult<()> = async { + let _: usize = conn.del(format!("tunnel:sub:{fqdn}")).await?; + let _: usize = conn.del(format!("tunnel:session:{session_id}")).await?; + Ok(()) + } + .await; + } +} + +#[tokio::main] +async fn main() -> Result<()> { + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| "relay=info".into()), + ) + .init(); + + let cfg = RelayConfig::from_env(); + let registry = RedisRegistry::from_env(&cfg).await; + registry.register_instance().await; + + let control_listener = TcpListener::bind(&cfg.control_bind) + .await + .with_context(|| format!("bind control {}", cfg.control_bind))?; + let player_listener = TcpListener::bind(&cfg.player_bind) + .await + .with_context(|| format!("bind player {}", cfg.player_bind))?; + + info!(instance_id = %cfg.instance_id, region = %cfg.region, "relay started"); + + let shutdown = Arc::new(Notify::new()); + let state: SharedState = Arc::new(RwLock::new(RelayState::new())); + + let heartbeat_task = tokio::spawn(run_registry_heartbeat( + state.clone(), + registry.clone(), + shutdown.clone(), + )); + let control_task = tokio::spawn(run_control_accept_loop( + control_listener, + cfg.clone(), + state.clone(), + registry.clone(), + shutdown.clone(), + )); + let player_task = tokio::spawn(run_player_accept_loop( + player_listener, + state.clone(), + shutdown.clone(), + )); + tokio::pin!(heartbeat_task); + tokio::pin!(control_task); + tokio::pin!(player_task); + + tokio::select! { + _ = tokio::signal::ctrl_c() => info!("shutdown signal received"), + res = &mut control_task => warn!("control accept loop ended: {:?}", res), + res = &mut player_task => warn!("player accept loop ended: {:?}", res), + res = &mut heartbeat_task => warn!("registry heartbeat task ended: {:?}", res), + } + + registry.set_draining().await; + shutdown.notify_waiters(); + info!("draining relay"); + tokio::time::sleep(Duration::from_secs(1)).await; + Ok(()) +} + +async fn run_registry_heartbeat(state: SharedState, registry: RedisRegistry, shutdown: Arc) { + let mut ticker = interval(Duration::from_secs(5)); + ticker.set_missed_tick_behavior(MissedTickBehavior::Skip); + loop { + tokio::select! { + _ = shutdown.notified() => break, + _ = ticker.tick() => { + let count = state.read().await.session_count(); + registry.heartbeat_instance(count).await; + } + } + } +} + +async fn run_control_accept_loop( + listener: TcpListener, + cfg: RelayConfig, + state: SharedState, + registry: RedisRegistry, + shutdown: Arc, +) -> Result<()> { + loop { + tokio::select! { + _ = shutdown.notified() => break, + res = listener.accept() => { + let (stream, addr) = match res { + Ok(v) => v, + Err(e) => { warn!(error = %e, "control accept failed"); continue; } + }; + let cfg = cfg.clone(); + let state = state.clone(); + let registry = registry.clone(); + tokio::spawn(async move { + if let Err(e) = handle_control_conn(stream, addr, cfg, state, registry).await { + warn!(peer = %addr, error = %e, "control connection ended with error"); + } + }); + } + } + } + Ok(()) +} + +async fn run_player_accept_loop( + listener: TcpListener, + state: SharedState, + shutdown: Arc, +) -> Result<()> { + loop { + tokio::select! { + _ = shutdown.notified() => break, + res = listener.accept() => { + let (stream, addr) = match res { + Ok(v) => v, + Err(e) => { warn!(error = %e, "player accept failed"); continue; } + }; + let state = state.clone(); + tokio::spawn(async move { + if let Err(e) = handle_player_conn(stream, addr, state).await { + debug!(peer = %addr, error = %e, "player connection closed"); + } + }); + } + } + } + Ok(()) +} + +async fn handle_control_conn( + stream: TcpStream, + addr: SocketAddr, + cfg: RelayConfig, + state: SharedState, + registry: RedisRegistry, +) -> Result<()> { + let (mut reader, mut writer) = stream.into_split(); + let first: ClientFrame = read_frame(&mut reader).await.context("read initial frame")?; + let register = match first { + ClientFrame::Register(req) => req, + _ => { + write_frame( + &mut writer, + &ServerFrame::RegisterRejected { reason: "expected Register frame".to_string() }, + ).await.ok(); + anyhow::bail!("expected register frame"); + } + }; + + if !token_looks_valid(®ister.token) { + write_frame( + &mut writer, + &ServerFrame::RegisterRejected { reason: "invalid token".to_string() }, + ).await.ok(); + anyhow::bail!("invalid token"); + } + + let (tx, mut rx) = mpsc::channel::(512); + let session_id = Uuid::new_v4().to_string(); + let fqdn = assign_fqdn(&cfg, ®ister); + let user_id = fake_user_id_from_token(®ister.token); + let stream_sinks = Arc::new(RwLock::new(HashMap::>>::new())); + + { + let mut guard = state.write().await; + let handle = SessionHandle { + session_id: session_id.clone(), + tx: tx.clone(), + stream_sinks: stream_sinks.clone(), + last_heartbeat: Instant::now(), + }; + guard.by_session.insert(session_id.clone(), fqdn.clone()); + guard.by_fqdn.insert(fqdn.clone(), handle); + } + registry.register_tunnel(&fqdn, &session_id, &user_id).await; + + write_frame( + &mut writer, + &ServerFrame::RegisterAccepted(RegisterAccepted { + session_id: session_id.clone(), + fqdn: fqdn.clone(), + heartbeat_interval_secs: 5, + owner_instance_id: cfg.instance_id.clone(), + }), + ) + .await?; + info!(peer = %addr, user_id = %user_id, fqdn = %fqdn, session_id = %session_id, "client registered"); + + let write_task = tokio::spawn(async move { + while let Some(frame) = rx.recv().await { + write_frame(&mut writer, &frame).await?; + } + Ok::<(), anyhow::Error>(()) + }); + + let read_result = control_read_loop( + &mut reader, + &state, + ®istry, + &session_id, + &fqdn, + &user_id, + cfg.heartbeat_timeout, + ) + .await; + + if let Err(e) = &read_result { + warn!(session_id = %session_id, error = %e, "control read loop error"); + } + + { + let mut guard = state.write().await; + if let Some(fqdn) = guard.by_session.remove(&session_id) { + guard.by_fqdn.remove(&fqdn); + } + } + registry.remove_tunnel(&fqdn, &session_id).await; + write_task.abort(); + info!(session_id = %session_id, "client session removed"); + read_result +} + +async fn control_read_loop( + reader: &mut tokio::net::tcp::OwnedReadHalf, + state: &SharedState, + registry: &RedisRegistry, + session_id: &str, + fqdn: &str, + user_id: &str, + heartbeat_timeout: Duration, +) -> Result<()> { + loop { + let frame: ClientFrame = timeout(heartbeat_timeout, read_frame(reader)) + .await + .context("heartbeat timeout")??; + match frame { + ClientFrame::Heartbeat(Heartbeat { session_id: hb_id, .. }) => { + if hb_id != session_id { + anyhow::bail!("heartbeat session mismatch"); + } + let mut guard = state.write().await; + if let Some(route_fqdn) = guard.by_session.get(session_id).cloned() + && let Some(handle) = guard.by_fqdn.get_mut(&route_fqdn) + { + handle.last_heartbeat = Instant::now(); + } + drop(guard); + registry.refresh_tunnel_session(fqdn, session_id, user_id).await; + } + ClientFrame::StreamData(StreamData { stream_id, data }) => { + let sink = lookup_stream_sink(state, session_id, &stream_id).await; + if let Some(tx) = sink { + if tx.send(data).await.is_err() { + remove_stream_sink(state, session_id, &stream_id).await; + } + } + } + ClientFrame::StreamClosed(StreamClosed { stream_id, .. }) => { + remove_stream_sink(state, session_id, &stream_id).await; + } + ClientFrame::Pong => {} + ClientFrame::Register(_) => anyhow::bail!("unexpected Register frame after registration"), + } + } +} + +async fn handle_player_conn( + mut stream: TcpStream, + addr: SocketAddr, + state: SharedState, +) -> Result<()> { + let (hostname, initial_data) = read_handshake_hostname_and_bytes(&mut stream) + .await + .context("parse minecraft handshake")?; + + let session = { + let guard = state.read().await; + guard.by_fqdn.get(&hostname).cloned() + }; + let Some(session) = session else { + debug!(peer = %addr, hostname = %hostname, "no tunnel for hostname"); + return Ok(()); + }; + + let stream_id = Uuid::new_v4().to_string(); + let (player_read, player_write) = stream.into_split(); + let (to_player_tx, to_player_rx) = mpsc::channel::>(128); + session + .stream_sinks + .write() + .await + .insert(stream_id.clone(), to_player_tx); + + session + .tx + .send(ServerFrame::IncomingTcp(IncomingTcp { + stream_id: stream_id.clone(), + session_id: session.session_id.clone(), + peer_addr: addr.to_string(), + hostname: hostname.clone(), + initial_data, + })) + .await + .context("send IncomingTcp to client")?; + + let tx_control = session.tx.clone(); + let stream_id_clone = stream_id.clone(); + let session_id_clone = session.session_id.clone(); + let sinks = session.stream_sinks.clone(); + tokio::spawn(async move { + if let Err(e) = run_player_writer(player_write, to_player_rx).await { + debug!(stream_id = %stream_id_clone, error = %e, "player writer ended"); + } + let _ = tx_control + .send(ServerFrame::StreamClosed(StreamClosed { + stream_id: stream_id_clone.clone(), + reason: Some("player_writer_closed".into()), + })) + .await; + let _ = remove_stream_sink_by_store(sinks, &stream_id_clone).await; + let _ = session_id_clone; + }); + + let tx_control = session.tx.clone(); + let stream_id_clone = stream_id.clone(); + let sinks = session.stream_sinks.clone(); + tokio::spawn(async move { + if let Err(e) = run_player_reader(player_read, tx_control.clone(), stream_id_clone.clone()).await { + debug!(stream_id = %stream_id_clone, error = %e, "player reader ended"); + } + let _ = tx_control + .send(ServerFrame::StreamClosed(StreamClosed { + stream_id: stream_id_clone.clone(), + reason: Some("player_reader_closed".into()), + })) + .await; + let _ = remove_stream_sink_by_store(sinks, &stream_id_clone).await; + }); + + info!(peer = %addr, hostname = %hostname, session_id = %session.session_id, stream_id = %stream_id, "player proxied via client stream"); + Ok(()) +} + +async fn run_player_reader( + mut reader: tokio::net::tcp::OwnedReadHalf, + tx_control: mpsc::Sender, + stream_id: String, +) -> Result<()> { + let mut buf = vec![0u8; 16 * 1024]; + loop { + let n = reader.read(&mut buf).await?; + if n == 0 { + break; + } + tx_control + .send(ServerFrame::StreamData(StreamData { + stream_id: stream_id.clone(), + data: buf[..n].to_vec(), + })) + .await + .context("send stream data to client")?; + } + Ok(()) +} + +async fn run_player_writer( + mut writer: tokio::net::tcp::OwnedWriteHalf, + mut rx: mpsc::Receiver>, +) -> Result<()> { + while let Some(chunk) = rx.recv().await { + writer.write_all(&chunk).await?; + } + writer.shutdown().await.ok(); + Ok(()) +} + +async fn lookup_stream_sink( + state: &SharedState, + session_id: &str, + stream_id: &str, +) -> Option>> { + let store = { + let guard = state.read().await; + let fqdn = guard.by_session.get(session_id)?.clone(); + guard.by_fqdn.get(&fqdn)?.stream_sinks.clone() + }; + store.read().await.get(stream_id).cloned() +} + +async fn remove_stream_sink(state: &SharedState, session_id: &str, stream_id: &str) { + let store = { + let guard = state.read().await; + let Some(fqdn) = guard.by_session.get(session_id).cloned() else { + return; + }; + let Some(handle) = guard.by_fqdn.get(&fqdn) else { + return; + }; + handle.stream_sinks.clone() + }; + let _ = remove_stream_sink_by_store(store, stream_id).await; +} + +async fn remove_stream_sink_by_store( + store: Arc>>>>, + stream_id: &str, +) -> Option>> { + store.write().await.remove(stream_id) +} + +fn token_looks_valid(token: &str) -> bool { + !token.trim().is_empty() +} + +fn fake_user_id_from_token(token: &str) -> String { + let suffix: String = token.chars().rev().take(6).collect(); + format!("user-{}", suffix.chars().rev().collect::()) +} + +fn assign_fqdn(cfg: &RelayConfig, req: &RegisterRequest) -> String { + let label = req + .requested_subdomain + .as_ref() + .filter(|s| !s.trim().is_empty()) + .cloned() + .unwrap_or_else(random_label); + format!("{}.{}.{}", sanitize_label(&label), cfg.region, cfg.domain) +} + +fn random_label() -> String { + const ADJ: &[&str] = &["sleepy", "swift", "brave", "quiet", "mossy"]; + const NOUN: &[&str] = &["creeper", "ghast", "axolotl", "wolf", "beacon"]; + format!( + "{}-{}-{}", + ADJ[fastrand::usize(..ADJ.len())], + NOUN[fastrand::usize(..NOUN.len())], + fastrand::u16(..9999) + ) +} + +fn sanitize_label(input: &str) -> String { + input + .chars() + .filter(|c| c.is_ascii_alphanumeric() || *c == '-') + .collect::() + .trim_matches('-') + .to_ascii_lowercase() +}