Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
feat(rust): axum reverse proxy skeleton + http catch-all (phase-1)
chopratejas128a910ebb1b
diff --git a/Cargo.lock b/Cargo.lockindex 1254becd2..dddcb78a7 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2,6 +2,15 @@# It is not intended for manual editing.version = 3+[[package]]+name = "aho-corasick"+version = "1.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"+dependencies = [+ "memchr",+]+[[package]]name = "anstream"version = "1.0.0"@@ -58,6 +67,16 @@ version = "1.0.102"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"+[[package]]+name = "assert-json-diff"+version = "2.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47e4f2b81832e72834d7518d8487a0396a28cc408186a2e8854c0f98011faf12"+dependencies = [+ "serde",+ "serde_json",+]+[[package]]name = "async-trait"version = "0.1.89"@@ -89,6 +108,8 @@ checksum = "edca88bc138befd0323b20752846e6587272d3b03b0343c8ea28a6f819e6e71f"dependencies = ["async-trait","axum-core",+ "axum-macros",+ "base64","bytes","futures-util","http",@@ -107,8 +128,10 @@ dependencies = ["serde_json","serde_path_to_error","serde_urlencoded",+ "sha1","sync_wrapper","tokio",+ "tokio-tungstenite","tower","tower-layer","tower-service",@@ -136,6 +159,17 @@ dependencies = ["tracing",]+[[package]]+name = "axum-macros"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "57d123550fa8d071b7255cb0cc04dc302baa6c8c4a79f55701552684d8399bce"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]+[[package]]name = "base64"version = "0.22.1"@@ -148,18 +182,39 @@ version = "2.11.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3"+[[package]]+name = "block-buffer"+version = "0.10.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"+dependencies = [+ "generic-array",+]+[[package]]name = "bumpalo"version = "3.20.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb"+[[package]]+name = "byteorder"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"+[[package]]name = "bytes"version = "1.11.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"+[[package]]+name = "bytesize"+version = "1.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2e93abca9e28e0a1b9877922aacb20576e05d4679ffa78c3d6dc22a26a216659"+[[package]]name = "cc"version = "1.2.60"@@ -228,6 +283,59 @@ version = "1.0.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"+[[package]]+name = "cpufeatures"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"+dependencies = [+ "libc",+]++[[package]]+name = "crypto-common"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"+dependencies = [+ "generic-array",+ "typenum",+]++[[package]]+name = "data-encoding"+version = "2.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a4ae5f15dda3c708c0ade84bfee31ccab44a3da4f88015ed22f63732abe300c8"++[[package]]+name = "deadpool"+version = "0.12.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0be2b1d1d6ec8d846f05e137292d0b89133caf95ef33695424c09568bdd39b1b"+dependencies = [+ "deadpool-runtime",+ "lazy_static",+ "num_cpus",+ "tokio",+]++[[package]]+name = "deadpool-runtime"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b"++[[package]]+name = "digest"+version = "0.10.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"+dependencies = [+ "block-buffer",+ "crypto-common",+]+[[package]]name = "displaydoc"version = "0.2.5"@@ -239,6 +347,12 @@ dependencies = ["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"@@ -255,6 +369,18 @@ version = "0.1.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"+[[package]]+name = "fnv"+version = "1.0.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"++[[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"@@ -264,6 +390,21 @@ dependencies = ["percent-encoding",]+[[package]]+name = "futures"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d"+dependencies = [+ "futures-channel",+ "futures-core",+ "futures-executor",+ "futures-io",+ "futures-sink",+ "futures-task",+ "futures-util",+]+[[package]]name = "futures-channel"version = "0.3.32"@@ -271,6 +412,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"dependencies = ["futures-core",+ "futures-sink",][[package]]@@ -279,6 +421,40 @@ version = "0.3.32"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"+[[package]]+name = "futures-executor"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d"+dependencies = [+ "futures-core",+ "futures-task",+ "futures-util",+]++[[package]]+name = "futures-io"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718"++[[package]]+name = "futures-macro"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "futures-sink"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893"+[[package]]name = "futures-task"version = "0.3.32"@@ -291,12 +467,27 @@ version = "0.3.32"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"dependencies = [+ "futures-channel","futures-core",+ "futures-io",+ "futures-macro",+ "futures-sink","futures-task",+ "memchr","pin-project-lite","slab",]+[[package]]+name = "generic-array"+version = "0.14.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"+dependencies = [+ "typenum",+ "version_check",+]+[[package]]name = "getrandom"version = "0.2.17"@@ -319,11 +510,58 @@ dependencies = ["cfg-if","js-sys","libc",- "r-efi",+ "r-efi 5.3.0","wasip2","wasm-bindgen",]+[[package]]+name = "getrandom"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555"+dependencies = [+ "cfg-if",+ "libc",+ "r-efi 6.0.0",+ "wasip2",+ "wasip3",+]++[[package]]+name = "h2"+version = "0.4.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f44da3a8150a6703ed5d34e164b875fd14c2cdab9af1252a9a1020bde2bdc54"+dependencies = [+ "atomic-waker",+ "bytes",+ "fnv",+ "futures-core",+ "futures-sink",+ "http",+ "indexmap",+ "slab",+ "tokio",+ "tokio-util",+ "tracing",+]++[[package]]+name = "hashbrown"+version = "0.15.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"+dependencies = [+ "foldhash",+]++[[package]]+name = "hashbrown"+version = "0.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4f467dd6dccf739c208452f8014c75c18bb8301b050ad1cfb27153803edb0f51"+[[package]]name = "headroom-core"version = "0.1.0"@@ -352,13 +590,32 @@ name = "headroom-proxy"version = "0.1.0"dependencies = ["axum",+ "bytes",+ "bytesize",+ "clap",+ "futures",+ "futures-util","headroom-core",+ "http",+ "http-body-util",+ "humantime",+ "hyper",+ "hyper-util",+ "pin-project-lite","reqwest","serde","serde_json",+ "thiserror 1.0.69","tokio",+ "tokio-stream",+ "tokio-tungstenite","tower",+ "tower-http","tracing",+ "tracing-subscriber",+ "url",+ "uuid",+ "wiremock",][[package]]@@ -375,6 +632,12 @@ version = "0.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"+[[package]]+name = "hermit-abi"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c"+[[package]]name = "http"version = "1.4.0"@@ -420,6 +683,12 @@ version = "1.0.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"+[[package]]+name = "humantime"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "135b12329e5e3ce057a9f972339ea52bc954fe1e9358ef27f95e89716fbc5424"+[[package]]name = "hyper"version = "1.9.0"@@ -430,6 +699,7 @@ dependencies = ["bytes","futures-channel","futures-core",+ "h2","http","http-body","httparse",@@ -454,7 +724,7 @@ dependencies = ["tokio","tokio-rustls","tower-service",- "webpki-roots",+ "webpki-roots 1.0.7",][[package]]@@ -562,6 +832,12 @@ dependencies = ["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"@@ -583,6 +859,18 @@ dependencies = ["icu_properties",]+[[package]]+name = "indexmap"+version = "2.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"+dependencies = [+ "equivalent",+ "hashbrown 0.17.0",+ "serde",+ "serde_core",+]+[[package]]name = "indoc"version = "2.0.7"@@ -632,6 +920,18 @@ dependencies = ["wasm-bindgen",]+[[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.185"@@ -656,6 +956,15 @@ version = "0.1.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"+[[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.7.3"@@ -694,6 +1003,25 @@ dependencies = ["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_cpus"+version = "1.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b"+dependencies = [+ "hermit-abi",+ "libc",+]+[[package]]name = "once_cell"version = "1.21.4"@@ -742,6 +1070,16 @@ dependencies = ["zerocopy",]+[[package]]+name = "prettyplease"+version = "0.2.37"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"+dependencies = [+ "proc-macro2",+ "syn",+]+[[package]]name = "proc-macro2"version = "1.0.106"@@ -843,7 +1181,7 @@ dependencies = ["bytes","getrandom 0.3.4","lru-slab",- "rand",+ "rand 0.9.4","ring","rustc-hash","rustls",@@ -884,14 +1222,41 @@ version = "5.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"+[[package]]+name = "r-efi"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"++[[package]]+name = "rand"+version = "0.8.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a"+dependencies = [+ "libc",+ "rand_chacha 0.3.1",+ "rand_core 0.6.4",+]+[[package]]name = "rand"version = "0.9.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea"dependencies = [- "rand_chacha",- "rand_core",+ "rand_chacha 0.9.0",+ "rand_core 0.9.5",+]++[[package]]+name = "rand_chacha"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"+dependencies = [+ "ppv-lite86",+ "rand_core 0.6.4",][[package]]@@ -901,7 +1266,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"dependencies = ["ppv-lite86",- "rand_core",+ "rand_core 0.9.5",+]++[[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]]@@ -913,6 +1287,35 @@ dependencies = ["getrandom 0.3.4",]+[[package]]+name = "regex"+version = "1.12.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-automata",+ "regex-syntax",+]++[[package]]+name = "regex-automata"+version = "0.4.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-syntax",+]++[[package]]+name = "regex-syntax"+version = "0.8.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"+[[package]]name = "reqwest"version = "0.12.28"@@ -922,6 +1325,8 @@ dependencies = ["base64","bytes","futures-core",+ "futures-util",+ "h2","http","http-body","http-body-util",@@ -941,14 +1346,16 @@ dependencies = ["sync_wrapper","tokio","tokio-rustls",+ "tokio-util","tower","tower-http","tower-service","url","wasm-bindgen","wasm-bindgen-futures",+ "wasm-streams","web-sys",- "webpki-roots",+ "webpki-roots 1.0.7",][[package]]@@ -1018,6 +1425,12 @@ version = "1.0.23"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"+[[package]]+name = "semver"+version = "1.0.28"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"+[[package]]name = "serde"version = "1.0.228"@@ -1084,6 +1497,26 @@ dependencies = ["serde",]+[[package]]+name = "sha1"+version = "0.10.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"+dependencies = [+ "cfg-if",+ "cpufeatures",+ "digest",+]++[[package]]+name = "sharded-slab"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"+dependencies = [+ "lazy_static",+]+[[package]]name = "shlex"version = "1.3.0"@@ -1217,6 +1650,15 @@ dependencies = ["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 = "tinystr"version = "0.8.3"@@ -1279,6 +1721,46 @@ dependencies = ["tokio",]+[[package]]+name = "tokio-stream"+version = "0.1.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70"+dependencies = [+ "futures-core",+ "pin-project-lite",+ "tokio",+]++[[package]]+name = "tokio-tungstenite"+version = "0.24.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "edc5f74e248dc973e0dbb7b74c7e0d6fcc301c694ff50049504004ef4d0cdcd9"+dependencies = [+ "futures-util",+ "log",+ "rustls",+ "rustls-pki-types",+ "tokio",+ "tokio-rustls",+ "tungstenite",+ "webpki-roots 0.26.11",+]++[[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"@@ -1311,6 +1793,8 @@ dependencies = ["tower","tower-layer","tower-service",+ "tracing",+ "uuid",][[package]]@@ -1355,6 +1839,49 @@ 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-serde"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "704b1aeb7be0d0a84fc9828cae51dab5970fee5088f83d1dd7ee6f6246fc6ff1"+dependencies = [+ "serde",+ "tracing-core",+]++[[package]]+name = "tracing-subscriber"+version = "0.3.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319"+dependencies = [+ "matchers",+ "nu-ansi-term",+ "once_cell",+ "regex-automata",+ "serde",+ "serde_json",+ "sharded-slab",+ "smallvec",+ "thread_local",+ "tracing",+ "tracing-core",+ "tracing-log",+ "tracing-serde",][[package]]@@ -1363,12 +1890,44 @@ version = "0.2.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"+[[package]]+name = "tungstenite"+version = "0.24.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "18e5b8366ee7a95b16d32197d0b2604b43a0be89dc5fac9f8e96ccafbaedda8a"+dependencies = [+ "byteorder",+ "bytes",+ "data-encoding",+ "http",+ "httparse",+ "log",+ "rand 0.8.6",+ "rustls",+ "rustls-pki-types",+ "sha1",+ "thiserror 1.0.69",+ "utf-8",+]++[[package]]+name = "typenum"+version = "1.20.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de"+[[package]]name = "unicode-ident"version = "1.0.24"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"+[[package]]+name = "unicode-xid"+version = "0.2.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"+[[package]]name = "unindent"version = "0.2.4"@@ -1393,6 +1952,12 @@ dependencies = ["serde",]+[[package]]+name = "utf-8"+version = "0.7.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"+[[package]]name = "utf8_iter"version = "1.0.4"@@ -1405,6 +1970,29 @@ version = "0.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"+[[package]]+name = "uuid"+version = "1.23.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ddd74a9687298c6858e9b88ec8935ec45d22e8fd5e6394fa1bd4e99a87789c76"+dependencies = [+ "getrandom 0.4.2",+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "valuable"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"++[[package]]+name = "version_check"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"+[[package]]name = "want"version = "0.3.1"@@ -1426,7 +2014,16 @@ version = "1.0.3+wasi-0.2.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6"dependencies = [- "wit-bindgen",+ "wit-bindgen 0.57.1",+]++[[package]]+name = "wasip3"+version = "0.4.0+wasi-0.3.0-rc-2026-01-06"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5"+dependencies = [+ "wit-bindgen 0.51.0",][[package]]@@ -1484,6 +2081,53 @@ 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 = "wasm-streams"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65"+dependencies = [+ "futures-util",+ "js-sys",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+]++[[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 = "web-sys"version = "0.3.95"@@ -1504,6 +2148,15 @@ dependencies = ["wasm-bindgen",]+[[package]]+name = "webpki-roots"+version = "0.26.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"+dependencies = [+ "webpki-roots 1.0.7",+]+[[package]]name = "webpki-roots"version = "1.0.7"@@ -1675,12 +2328,123 @@ version = "0.53.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"+[[package]]+name = "wiremock"+version = "0.6.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08db1edfb05d9b3c1542e521aea074442088292f00b5f28e435c714a98f85031"+dependencies = [+ "assert-json-diff",+ "base64",+ "deadpool",+ "futures",+ "http",+ "http-body-util",+ "hyper",+ "hyper-util",+ "log",+ "once_cell",+ "regex",+ "serde",+ "serde_json",+ "tokio",+ "url",+]++[[package]]+name = "wit-bindgen"+version = "0.51.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"+dependencies = [+ "wit-bindgen-rust-macro",+]+[[package]]name = "wit-bindgen"version = "0.57.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"+[[package]]+name = "wit-bindgen-core"+version = "0.51.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc"+dependencies = [+ "anyhow",+ "heck",+ "wit-parser",+]++[[package]]+name = "wit-bindgen-rust"+version = "0.51.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21"+dependencies = [+ "anyhow",+ "heck",+ "indexmap",+ "prettyplease",+ "syn",+ "wasm-metadata",+ "wit-bindgen-core",+ "wit-component",+]++[[package]]+name = "wit-bindgen-rust-macro"+version = "0.51.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a"+dependencies = [+ "anyhow",+ "prettyplease",+ "proc-macro2",+ "quote",+ "syn",+ "wit-bindgen-core",+ "wit-bindgen-rust",+]++[[package]]+name = "wit-component"+version = "0.244.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"+dependencies = [+ "anyhow",+ "bitflags",+ "indexmap",+ "log",+ "serde",+ "serde_derive",+ "serde_json",+ "wasm-encoder",+ "wasm-metadata",+ "wasmparser",+ "wit-parser",+]++[[package]]+name = "wit-parser"+version = "0.244.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736"+dependencies = [+ "anyhow",+ "id-arena",+ "indexmap",+ "log",+ "semver",+ "serde",+ "serde_derive",+ "serde_json",+ "unicode-xid",+ "wasmparser",+]+[[package]]name = "writeable"version = "0.6.3"diff --git a/crates/headroom-proxy/Cargo.toml b/crates/headroom-proxy/Cargo.tomlindex d475ec365..87e7af660 100644--- a/crates/headroom-proxy/Cargo.toml+++ b/crates/headroom-proxy/Cargo.toml@@ -5,21 +5,50 @@ edition.workspace = truerust-version.workspace = truelicense.workspace = truerepository.workspace = true-description = "Headroom compression proxy (Rust, axum)."+description = "Headroom transparent reverse proxy (Rust, axum). Phase 1: drop-in passthrough in front of the Python proxy."[[bin]]name = "headroom-proxy"path = "src/main.rs"+[lib]+name = "headroom_proxy"+path = "src/lib.rs"+[dependencies]-axum = { workspace = true }-tokio = { workspace = true }+axum = { workspace = true, features = ["ws", "http2", "macros"] }+tokio = { workspace = true, features = ["macros", "rt-multi-thread", "signal", "net", "io-util", "time"] }tower = { workspace = true }+tower-http = { version = "0.6", features = ["trace", "request-id", "util"] }tracing = { workspace = true }-reqwest = { workspace = true }+tracing-subscriber = { version = "0.3", features = ["json", "env-filter", "fmt"] }+reqwest = { version = "0.12", default-features = false, features = ["stream", "rustls-tls", "http2"] }+tokio-tungstenite = { version = "0.24", default-features = false, features = ["connect", "rustls-tls-webpki-roots"] }+clap = { workspace = true, features = ["derive", "env"] }serde = { workspace = true }serde_json = { workspace = true }+thiserror = { workspace = true }+uuid = { version = "1", features = ["v4"] }+bytes = { workspace = true }+futures = "0.3"+futures-util = "0.3"+pin-project-lite = "0.2"+http = "1"+http-body-util = "0.1"+hyper = "1"+url = "2"+humantime = "2"+bytesize = "1"headroom-core = { path = "../headroom-core" }[dev-dependencies]tower = { workspace = true, features = ["util"] }+wiremock = "0.6"+reqwest = { version = "0.12", default-features = false, features = ["stream", "rustls-tls", "http2", "json"] }+tokio-tungstenite = { version = "0.24", default-features = false, features = ["connect", "rustls-tls-webpki-roots"] }+futures-util = "0.3"+tokio = { workspace = true, features = ["macros", "rt-multi-thread", "signal", "net", "io-util", "time", "test-util"] }+hyper = { version = "1", features = ["server", "http1", "http2"] }+hyper-util = { version = "0.1", features = ["tokio", "server-auto"] }+http-body-util = "0.1"+tokio-stream = "0.1"diff --git a/crates/headroom-proxy/src/config.rs b/crates/headroom-proxy/src/config.rsnew file mode 100644index 000000000..b0fe19032--- /dev/null+++ b/crates/headroom-proxy/src/config.rs@@ -0,0 +1,110 @@+//! Configuration for the proxy: CLI flags + env vars.++use clap::Parser;+use std::net::SocketAddr;+use std::time::Duration;+use url::Url;++#[derive(Debug, Clone, Parser)]+#[command(+ name = "headroom-proxy",+ version,+ about = "Headroom transparent reverse proxy"+)]+pub struct CliArgs {+ /// Address the proxy listens on (e.g. 0.0.0.0:8787).+ #[arg(long, env = "HEADROOM_PROXY_LISTEN", default_value = "0.0.0.0:8787")]+ pub listen: SocketAddr,++ /// Upstream base URL the proxy forwards to (e.g. http://127.0.0.1:8788).+ /// REQUIRED — there is no default; we want operators to be explicit.+ #[arg(long, env = "HEADROOM_PROXY_UPSTREAM")]+ pub upstream: Url,++ /// End-to-end timeout for a single upstream request (long, since LLM+ /// streams may run for many minutes).+ #[arg(long, default_value = "600s", value_parser = parse_duration)]+ pub upstream_timeout: Duration,++ /// TCP/TLS connect timeout for upstream.+ #[arg(long, default_value = "10s", value_parser = parse_duration)]+ pub upstream_connect_timeout: Duration,++ /// Max body size for buffered cases (does NOT bound streaming bodies).+ #[arg(long, default_value = "100MB", value_parser = parse_bytes)]+ pub max_body_bytes: u64,++ /// Log level / filter (RUST_LOG-style). Default: info.+ #[arg(long, default_value = "info")]+ pub log_level: String,++ /// Rewrite the outgoing Host header to the upstream host (default).+ /// Pair with --no-rewrite-host to preserve the client-supplied Host.+ #[arg(long, default_value_t = true, action = clap::ArgAction::Set)]+ pub rewrite_host: bool,++ /// Convenience flag matching the spec; sets rewrite_host=false when present.+ #[arg(long = "no-rewrite-host", default_value_t = false)]+ pub no_rewrite_host: bool,++ /// Maximum time to wait for in-flight requests to finish on shutdown.+ #[arg(long, default_value = "30s", value_parser = parse_duration)]+ pub graceful_shutdown_timeout: Duration,+}++fn parse_duration(s: &str) -> Result<Duration, String> {+ humantime::parse_duration(s).map_err(|e| format!("invalid duration `{s}`: {e}"))+}++fn parse_bytes(s: &str) -> Result<u64, String> {+ s.parse::<bytesize::ByteSize>()+ .map(|b| b.as_u64())+ .map_err(|e| format!("invalid byte size `{s}`: {e}"))+}++/// Resolved configuration used by the running server.+#[derive(Debug, Clone)]+pub struct Config {+ pub listen: SocketAddr,+ pub upstream: Url,+ pub upstream_timeout: Duration,+ pub upstream_connect_timeout: Duration,+ pub max_body_bytes: u64,+ pub log_level: String,+ pub rewrite_host: bool,+ pub graceful_shutdown_timeout: Duration,+}++impl Config {+ pub fn from_cli(args: CliArgs) -> Self {+ let rewrite_host = if args.no_rewrite_host {+ false+ } else {+ args.rewrite_host+ };+ Self {+ listen: args.listen,+ upstream: args.upstream,+ upstream_timeout: args.upstream_timeout,+ upstream_connect_timeout: args.upstream_connect_timeout,+ max_body_bytes: args.max_body_bytes,+ log_level: args.log_level,+ rewrite_host,+ graceful_shutdown_timeout: args.graceful_shutdown_timeout,+ }+ }++ /// Test/library helper.+ pub fn for_test(upstream: Url) -> Self {+ Self {+ listen: "127.0.0.1:0".parse().unwrap(),+ upstream,+ upstream_timeout: Duration::from_secs(60),+ upstream_connect_timeout: Duration::from_secs(5),+ max_body_bytes: 100 * 1024 * 1024,+ log_level: "warn".into(),+ rewrite_host: true,+ graceful_shutdown_timeout: Duration::from_secs(5),+ }+ }+}diff --git a/crates/headroom-proxy/src/error.rs b/crates/headroom-proxy/src/error.rsnew file mode 100644index 000000000..25add9a03--- /dev/null+++ b/crates/headroom-proxy/src/error.rs@@ -0,0 +1,45 @@+//! Error types for the proxy.++use axum::http::StatusCode;+use axum::response::{IntoResponse, Response};+use thiserror::Error;++#[derive(Debug, Error)]+pub enum ProxyError {+ #[error("upstream request failed: {0}")]+ Upstream(#[from] reqwest::Error),++ #[error("invalid upstream URL: {0}")]+ InvalidUpstream(String),++ #[error("invalid header: {0}")]+ InvalidHeader(String),++ #[error("websocket error: {0}")]+ WebSocket(String),++ #[error("io error: {0}")]+ Io(#[from] std::io::Error),+}++impl IntoResponse for ProxyError {+ fn into_response(self) -> Response {+ let (status, msg) = match &self {+ ProxyError::Upstream(e) if e.is_timeout() => (+ StatusCode::GATEWAY_TIMEOUT,+ format!("upstream timeout: {e}"),+ ),+ ProxyError::Upstream(e) if e.is_connect() => (+ StatusCode::BAD_GATEWAY,+ format!("upstream connect error: {e}"),+ ),+ ProxyError::Upstream(_) => (StatusCode::BAD_GATEWAY, self.to_string()),+ ProxyError::InvalidUpstream(_) => (StatusCode::BAD_GATEWAY, self.to_string()),+ ProxyError::InvalidHeader(_) => (StatusCode::BAD_REQUEST, self.to_string()),+ ProxyError::WebSocket(_) => (StatusCode::BAD_GATEWAY, self.to_string()),+ ProxyError::Io(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()),+ };+ tracing::warn!(error = %msg, "proxy error");+ (status, msg).into_response()+ }+}diff --git a/crates/headroom-proxy/src/lib.rs b/crates/headroom-proxy/src/lib.rsnew file mode 100644index 000000000..cc9c347a0--- /dev/null+++ b/crates/headroom-proxy/src/lib.rs@@ -0,0 +1,13 @@+//! headroom-proxy library: transparent reverse proxy in front of the Python+//! Headroom proxy. Used by both `main.rs` and the integration tests.++pub mod config;+pub mod error;+pub mod headers;+pub mod health;+pub mod proxy;+pub mod websocket;++pub use config::Config;+pub use error::ProxyError;+pub use proxy::{build_app, AppState};diff --git a/crates/headroom-proxy/src/main.rs b/crates/headroom-proxy/src/main.rsindex 4cce52647..dc5c2d47a 100644--- a/crates/headroom-proxy/src/main.rs+++ b/crates/headroom-proxy/src/main.rs@@ -1,57 +1,78 @@-//! headroom-proxy: Rust proxy binary (Phase 0 scaffolding).+//! headroom-proxy: transparent reverse proxy binary.//!-//! Currently exposes only `/healthz`. Provider routes land in Phase 2.+//! Drops in front of the existing Python proxy. End-users hit the public+//! port; this binary forwards every HTTP/SSE/WebSocket request verbatim to+//! `--upstream`. See RUST_DEV.md for the operator runbook.-use axum::{routing::get, Json, Router};-use serde_json::{json, Value};use std::net::SocketAddr;-async fn healthz() -> Json<Value> {- Json(json!({ "ok": true }))-}--fn app() -> Router {- Router::new().route("/healthz", get(healthz))-}+use clap::Parser;+use headroom_proxy::config::CliArgs;+use headroom_proxy::{build_app, AppState, Config};+use tracing_subscriber::layer::SubscriberExt;+use tracing_subscriber::util::SubscriberInitExt;+use tracing_subscriber::EnvFilter;#[tokio::main]-async fn main() -> Result<(), Box<dyn std::error::Error>> {- tracing_subscriber_init();- let addr: SocketAddr = "127.0.0.1:8787".parse()?;- tracing::info!(%addr, crate_hello = headroom_core::hello(), "starting headroom-proxy");- let listener = tokio::net::TcpListener::bind(addr).await?;- axum::serve(listener, app()).await?;+async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {+ let args = CliArgs::parse();+ let config = Config::from_cli(args);++ init_tracing(&config.log_level);++ tracing::info!(+ listen = %config.listen,+ upstream = %config.upstream,+ upstream_timeout_s = config.upstream_timeout.as_secs(),+ upstream_connect_timeout_s = config.upstream_connect_timeout.as_secs(),+ max_body_bytes = config.max_body_bytes,+ rewrite_host = config.rewrite_host,+ graceful_shutdown_timeout_s = config.graceful_shutdown_timeout.as_secs(),+ "headroom-proxy starting"+ );++ let state = AppState::new(config.clone())?;+ let app = build_app(state).into_make_service_with_connect_info::<SocketAddr>();++ let listener = tokio::net::TcpListener::bind(config.listen).await?;+ tracing::info!(addr = %listener.local_addr()?, "listening");++ axum::serve(listener, app)+ .with_graceful_shutdown(shutdown_signal())+ .await?;+Ok(())}-fn tracing_subscriber_init() {- // Minimal no-op initializer so we don't pull tracing-subscriber in Phase 0.- // Replace with tracing-subscriber in Phase 2 when richer logging is needed.+fn init_tracing(level: &str) {+ let filter = EnvFilter::try_new(level).unwrap_or_else(|_| EnvFilter::new("info"));+ let json_layer = tracing_subscriber::fmt::layer()+ .json()+ .with_current_span(false)+ .with_span_list(false);+ let _ = tracing_subscriber::registry()+ .with(filter)+ .with(json_layer)+ .try_init();}-#[cfg(test)]-mod tests {- use super::app;- use axum::body::Body;- use axum::http::{Request, StatusCode};- use tower::ServiceExt;-- #[tokio::test]- async fn healthz_returns_ok() {- let response = app()- .oneshot(- Request::builder()- .uri("/healthz")- .body(Body::empty())- .unwrap(),- )- .await- .unwrap();- assert_eq!(response.status(), StatusCode::OK);- let bytes = axum::body::to_bytes(response.into_body(), 1024)- .await- .unwrap();- let value: serde_json::Value = serde_json::from_slice(&bytes).unwrap();- assert_eq!(value, serde_json::json!({"ok": true}));+async fn shutdown_signal() {+ let ctrl_c = async {+ let _ = tokio::signal::ctrl_c().await;+ };+ #[cfg(unix)]+ let terminate = async {+ if let Ok(mut s) = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())+ {+ s.recv().await;+ }+ };+ #[cfg(not(unix))]+ let terminate = std::future::pending::<()>();++ tokio::select! {+ _ = ctrl_c => {},+ _ = terminate => {},}+ tracing::info!("shutdown signal received");}diff --git a/crates/headroom-proxy/src/proxy.rs b/crates/headroom-proxy/src/proxy.rsnew file mode 100644index 000000000..42ff2c560--- /dev/null+++ b/crates/headroom-proxy/src/proxy.rs@@ -0,0 +1,262 @@+//! Core reverse-proxy router and HTTP forwarding handler.++use std::net::SocketAddr;+use std::sync::Arc;+use std::time::Instant;++use axum::body::Body;+use axum::extract::{ConnectInfo, State, WebSocketUpgrade};+use axum::http::{HeaderMap, HeaderName, Request, Response, StatusCode, Uri};+use axum::response::IntoResponse;+use axum::routing::{any, get};+use axum::Router;+use bytes::Bytes;+use futures_util::TryStreamExt;+#[cfg(test)]+use http_body_util::BodyExt;++use crate::config::Config;+use crate::error::ProxyError;+use crate::headers::{build_forward_request_headers, filter_response_headers};+use crate::health::{healthz, healthz_upstream};+use crate::websocket::ws_handler;++/// Shared state passed to every handler.+#[derive(Clone)]+pub struct AppState {+ pub config: Arc<Config>,+ pub client: reqwest::Client,+}++impl AppState {+ pub fn new(config: Config) -> Result<Self, ProxyError> {+ let client = reqwest::Client::builder()+ .connect_timeout(config.upstream_connect_timeout)+ .timeout(config.upstream_timeout)+ // Don't auto-follow redirects: pass them through verbatim.+ .redirect(reqwest::redirect::Policy::none())+ // Pool needs to be allowed to be idle for long-lived streams.+ .pool_idle_timeout(std::time::Duration::from_secs(90))+ // Both HTTP/1.1 and HTTP/2 negotiated via ALPN.+ .build()+ .map_err(ProxyError::Upstream)?;+ Ok(Self {+ config: Arc::new(config),+ client,+ })+ }+}++/// Build the axum app. `/healthz` and `/healthz/upstream` are intercepted;+/// everything else hits the catch-all forwarder. WebSocket upgrades are+/// handled inside the catch-all handler when an `Upgrade: websocket` header+/// is present.+pub fn build_app(state: AppState) -> Router {+ Router::new()+ .route("/healthz", get(healthz))+ .route("/healthz/upstream", get(healthz_upstream))+ .fallback(any(catch_all))+ .with_state(state)+}++/// Catch-all handler. If the request is a WebSocket upgrade, hand off to the+/// ws module; otherwise forward as plain HTTP.+async fn catch_all(+ State(state): State<AppState>,+ ConnectInfo(client_addr): ConnectInfo<SocketAddr>,+ ws: Option<WebSocketUpgrade>,+ req: Request<Body>,+) -> Response<Body> {+ if is_websocket_upgrade(req.headers()) {+ if let Some(ws) = ws {+ return ws_handler(ws, state, client_addr, req).await;+ }+ // Header says websocket but axum didn't extract it (likely missing+ // Sec-WebSocket-Key) — fall through to HTTP forwarding which will+ // surface the upstream error.+ }+ forward_http(state, client_addr, req)+ .await+ .unwrap_or_else(|e| e.into_response())+}++fn is_websocket_upgrade(headers: &HeaderMap) -> bool {+ let upgrade = headers+ .get(http::header::UPGRADE)+ .and_then(|v| v.to_str().ok())+ .map(|s| s.eq_ignore_ascii_case("websocket"))+ .unwrap_or(false);+ let connection = headers+ .get(http::header::CONNECTION)+ .and_then(|v| v.to_str().ok())+ .map(|s| {+ s.split(',')+ .any(|t| t.trim().eq_ignore_ascii_case("upgrade"))+ })+ .unwrap_or(false);+ upgrade && connection+}++/// Build the upstream URL by joining the configured base with the incoming+/// path-and-query. Preserves '?' and the query string verbatim.+pub(crate) fn build_upstream_url(base: &url::Url, uri: &Uri) -> Result<url::Url, ProxyError> {+ let path = uri.path();+ let query = uri.query();++ // We treat the configured upstream as a base. Strip its trailing slash+ // when joining a path that starts with '/' so that "http://x:1/api" + "/v1/foo"+ // yields "http://x:1/api/v1/foo" rather than "http://x:1/v1/foo".+ let mut joined = base.clone();+ {+ let base_path = joined.path().trim_end_matches('/').to_string();+ let combined = if path.is_empty() || path == "/" {+ if base_path.is_empty() {+ "/".to_string()+ } else {+ base_path+ }+ } else if base_path.is_empty() {+ path.to_string()+ } else {+ format!("{base_path}{path}")+ };+ joined.set_path(&combined);+ }+ joined.set_query(query);+ Ok(joined)+}++/// Forward an HTTP request to the upstream and stream the response back.+async fn forward_http(+ state: AppState,+ client_addr: SocketAddr,+ req: Request<Body>,+) -> Result<Response<Body>, ProxyError> {+ let start = Instant::now();+ let request_id = ensure_request_id(req.headers());+ let method = req.method().clone();+ let uri = req.uri().clone();+ let path_for_log = uri.path().to_string();++ let upstream_url = build_upstream_url(&state.config.upstream, &uri)?;++ // Forwarded-Host: prefer client's Host. Forwarded-Proto: assume http for+ // now (we don't terminate TLS in this binary; if a TLS terminator is in+ // front, it should rewrite this — which we'd handle by not overwriting+ // an existing one in a future change).+ let forwarded_host = req+ .headers()+ .get(http::header::HOST)+ .and_then(|v| v.to_str().ok())+ .map(|s| s.to_string());++ // Build the outgoing headers off the incoming ones, then optionally drop+ // Host (rewrite_host=true => let reqwest set its own Host for the upstream).+ let mut outgoing_headers = build_forward_request_headers(+ req.headers(),+ client_addr.ip(),+ "http",+ forwarded_host.as_deref(),+ &request_id,+ );+ if !state.config.rewrite_host {+ if let Some(h) = req.headers().get(http::header::HOST) {+ outgoing_headers.insert(http::header::HOST, h.clone());+ }+ }++ // Stream the request body through to reqwest. We don't buffer.+ let body_stream =+ TryStreamExt::map_err(req.into_body().into_data_stream(), std::io::Error::other);+ let reqwest_body = reqwest::Body::wrap_stream(body_stream);++ let reqwest_method = reqwest::Method::from_bytes(method.as_str().as_bytes())+ .map_err(|e| ProxyError::InvalidHeader(e.to_string()))?;+ let upstream_resp = state+ .client+ .request(reqwest_method, upstream_url.clone())+ .headers(outgoing_headers)+ .body(reqwest_body)+ .send()+ .await?;++ let upstream_status = upstream_resp.status();+ let status = StatusCode::from_u16(upstream_status.as_u16()).unwrap_or(StatusCode::BAD_GATEWAY);+ let resp_headers = filter_response_headers(upstream_resp.headers());++ // Stream response body back without buffering.+ let resp_stream = upstream_resp.bytes_stream();+ let body = Body::from_stream(resp_stream.map_ok(Bytes::from));++ let mut response = Response::builder().status(status);+ {+ let h = response.headers_mut().expect("builder has headers");+ h.extend(resp_headers);+ // Echo X-Request-Id back to the client.+ if let Ok(v) = http::HeaderValue::from_str(&request_id) {+ h.insert(HeaderName::from_static("x-request-id"), v);+ }+ }+ let response = response+ .body(body)+ .map_err(|e| ProxyError::InvalidHeader(e.to_string()))?;++ tracing::info!(+ request_id = %request_id,+ method = %method,+ path = %path_for_log,+ upstream_status = upstream_status.as_u16(),+ latency_ms = start.elapsed().as_millis() as u64,+ protocol = "http",+ "forwarded"+ );++ Ok(response)+}++fn ensure_request_id(headers: &HeaderMap) -> String {+ headers+ .get("x-request-id")+ .and_then(|v| v.to_str().ok())+ .map(|s| s.to_string())+ .unwrap_or_else(|| uuid::Uuid::new_v4().to_string())+}++/// Test-only helper: drain a body to bytes (uses BodyExt).+#[cfg(test)]+pub async fn body_to_bytes(body: Body) -> Result<Bytes, axum::Error> {+ use axum::Error;+ body.collect()+ .await+ .map(|c| c.to_bytes())+ .map_err(Error::new)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn url_build_basic() {+ let base: url::Url = "http://up:8080".parse().unwrap();+ let uri: Uri = "/v1/messages?stream=true".parse().unwrap();+ let out = build_upstream_url(&base, &uri).unwrap();+ assert_eq!(out.as_str(), "http://up:8080/v1/messages?stream=true");+ }++ #[test]+ fn url_build_with_base_path() {+ let base: url::Url = "http://up:8080/api".parse().unwrap();+ let uri: Uri = "/v1/messages".parse().unwrap();+ let out = build_upstream_url(&base, &uri).unwrap();+ assert_eq!(out.as_str(), "http://up:8080/api/v1/messages");+ }++ #[test]+ fn url_build_root() {+ let base: url::Url = "http://up:8080/".parse().unwrap();+ let uri: Uri = "/".parse().unwrap();+ let out = build_upstream_url(&base, &uri).unwrap();+ assert_eq!(out.as_str(), "http://up:8080/");+ }+}