diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4fa1e70f..0c57bf46 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -36,12 +36,6 @@ jobs: - name: Test run: cargo test --workspace - # 桌面版不开 `bedrock`,上面两步就一行都不编它。企业版开,所以单独查 - - name: clippy + test (tw-upstream, bedrock) - run: | - cargo clippy -p tw-upstream --all-targets --features bedrock -- -D warnings - cargo test -p tw-upstream --features bedrock - - name: Build run: cargo build --release -p twcore @@ -51,6 +45,79 @@ jobs: - name: Smoke (real binary, real socket, real data plane) run: ./scripts/smoke.sh + # **第一层改了,企业版还编得过吗。**企业版钉 core 的 tag、只依赖第一层 + # (tw-dialect、tw-guard、tw-breaker)。以前要等 core 发版、企业版升级那天 + # 才知道某个改名或删掉的函数把它弄坏了,这里提前到 PR 上。 + # + # 企业版取和这个 PR 同名的分支 —— 要改接口的一方在企业版开一个同名分支 + # 把调用点跟上,两边一起绿;没有同名分支就取 dev。main 上的推送也对 dev。 + # 两个仓库都是公开的,不需要令牌。企业版没有 `sqlx::query!` 这类编译期 + # 连库的宏,`cargo check` 不需要数据库。 + enterprise: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + path: core + - uses: dorny/paths-filter@v3 + id: changed + with: + working-directory: core + filters: | + layer1: + - 'crates/tw-dialect/**' + - 'crates/tw-guard/**' + - 'crates/tw-breaker/**' + - 'Cargo.toml' + - '.github/workflows/ci.yml' + + - name: Pick the enterprise branch + if: steps.changed.outputs.layer1 == 'true' + id: branch + env: + HEAD_REF: ${{ github.head_ref }} + run: | + ref=dev + if [ -n "$HEAD_REF" ] && git ls-remote --exit-code --heads \ + https://github.com/ThinkWatchProject/ThinkWatch.git "$HEAD_REF" >/dev/null; then + ref="$HEAD_REF" + fi + echo "enterprise branch: $ref" + echo "ref=$ref" >> "$GITHUB_OUTPUT" + - uses: actions/checkout@v4 + if: steps.changed.outputs.layer1 == 'true' + with: + repository: ThinkWatchProject/ThinkWatch + ref: ${{ steps.branch.outputs.ref }} + path: enterprise + + - uses: dtolnay/rust-toolchain@stable + if: steps.changed.outputs.layer1 == 'true' + # 第一层全部指向这次的 core + - name: Point enterprise at this core + if: steps.changed.outputs.layer1 == 'true' + run: | + cat >> enterprise/Cargo.toml <<'TOML' + + [patch."https://github.com/ThinkWatchProject/ThinkWatch-Core.git"] + tw-dialect = { path = "../core/crates/tw-dialect" } + tw-guard = { path = "../core/crates/tw-guard" } + tw-breaker = { path = "../core/crates/tw-breaker" } + TOML + # 企业版的 Cargo.lock 锁着它钉的那个版本;版本号不同时补丁会被 + # 静默忽略(只报一条警告),编的还是旧的 core + cd enterprise && cargo update -p tw-dialect -p tw-guard -p tw-breaker + + - uses: Swatinem/rust-cache@v2 + if: steps.changed.outputs.layer1 == 'true' + with: + workspaces: enterprise -> target + + - name: cargo check (enterprise) + if: steps.changed.outputs.layer1 == 'true' + working-directory: enterprise + run: cargo check --workspace --all-targets + # **这台机器上没有 unix socket,也没有信号。**core 在这两件事上各有一套 # 平台实现,而在这个任务出现之前,Windows 那一半从来没有被编译过 —— # 一个 `#[cfg(windows)]` 模块「检查通过」和「根本没人看过它」长得一模一样。 diff --git a/Cargo.lock b/Cargo.lock index 39b1e04d..e2697c15 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8,41 +8,6 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" -[[package]] -name = "aead" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" -dependencies = [ - "crypto-common 0.1.7", - "generic-array", -] - -[[package]] -name = "aes" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" -dependencies = [ - "cfg-if", - "cipher", - "cpufeatures 0.2.17", -] - -[[package]] -name = "aes-gcm" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" -dependencies = [ - "aead", - "aes", - "cipher", - "ctr", - "ghash", - "subtle", -] - [[package]] name = "aho-corasick" version = "1.1.5" @@ -172,18 +137,6 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" -[[package]] -name = "aws-credential-types" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e93964ffdaf57857f544be3666a5f57570bb699e934700f11b49708f61bb556e" -dependencies = [ - "aws-smithy-async", - "aws-smithy-runtime-api", - "aws-smithy-types", - "zeroize", -] - [[package]] name = "aws-lc-rs" version = "1.18.1" @@ -207,123 +160,6 @@ dependencies = [ "pkg-config", ] -[[package]] -name = "aws-sigv4" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "723c2234ad7511ceef63eab016b7ba6ff7c55590fefb96fa8467af014a07309f" -dependencies = [ - "aws-credential-types", - "aws-smithy-http", - "aws-smithy-runtime-api", - "aws-smithy-types", - "bytes", - "form_urlencoded", - "hex", - "hmac", - "http 0.2.12", - "http 1.5.0", - "percent-encoding", - "sha2", - "time", - "tracing", -] - -[[package]] -name = "aws-smithy-async" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f02e407fb3b54891734224b9ffac8a71fdd35f542500fa1af95754a6b2beb316" -dependencies = [ - "futures-util", - "pin-project-lite", - "tokio", -] - -[[package]] -name = "aws-smithy-eventstream" -version = "0.60.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78d8391e65fcea47c586a22e1a41f173b38615b112b2c6b7a44e80cec3e6b706" -dependencies = [ - "aws-smithy-types", - "bytes", - "crc32fast", -] - -[[package]] -name = "aws-smithy-http" -version = "0.64.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37843d9add67c3aff5856f409c6dc315d3cdff60f9c0cb5b670dab1e9920306d" -dependencies = [ - "aws-smithy-runtime-api", - "aws-smithy-types", - "bytes", - "bytes-utils", - "futures-core", - "futures-util", - "http 1.5.0", - "http-body 1.1.0", - "http-body-util", - "percent-encoding", - "pin-project-lite", - "pin-utils", - "tracing", -] - -[[package]] -name = "aws-smithy-runtime-api" -version = "1.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c054752dd9e4dc73d0b75748c99ac2d0feafbf2f25c7b0516f03a3534161223" -dependencies = [ - "aws-smithy-async", - "aws-smithy-runtime-api-macros", - "aws-smithy-types", - "bytes", - "http 0.2.12", - "http 1.5.0", - "pin-project-lite", - "tokio", - "tracing", - "zeroize", -] - -[[package]] -name = "aws-smithy-runtime-api-macros" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "221eaa237ddf1ca79b60d1372aad77e47f9c0ea5b3ce5099da8c61d027dc77b3" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "aws-smithy-types" -version = "1.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f94d16e797ec62cd999fc9d5942b48fa7050c3093ddadff48e4d7528d16fcb9" -dependencies = [ - "base64-simd", - "bytes", - "bytes-utils", - "http 0.2.12", - "http 1.5.0", - "http-body 0.4.6", - "http-body 1.1.0", - "http-body-util", - "itoa", - "num-integer", - "pin-project-lite", - "pin-utils", - "ryu", - "serde", - "time", -] - [[package]] name = "axum" version = "0.8.9" @@ -336,8 +172,8 @@ dependencies = [ "bytes", "form_urlencoded", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "hyper", "hyper-util", @@ -369,8 +205,8 @@ checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" dependencies = [ "bytes", "futures-core", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "mime", "pin-project-lite", @@ -397,16 +233,6 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" -[[package]] -name = "base64-simd" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "339abbe78e73178762e23bea9dfd08e697eb3f3301cd4be981c0f78ba5859195" -dependencies = [ - "outref", - "vsimd", -] - [[package]] name = "bitflags" version = "2.13.1" @@ -456,16 +282,6 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" -[[package]] -name = "bytes-utils" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dafe3a8757b027e2be6e4e5601ed563c55989fcf1546e933c66c8eb3a058d35" -dependencies = [ - "bytes", - "either", -] - [[package]] name = "cc" version = "1.4.5" @@ -515,16 +331,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "cipher" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" -dependencies = [ - "crypto-common 0.1.7", - "inout", -] - [[package]] name = "clap" version = "4.6.6" @@ -574,12 +380,6 @@ dependencies = [ "cc", ] -[[package]] -name = "cmov" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" - [[package]] name = "colorchoice" version = "1.0.5" @@ -658,7 +458,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ "generic-array", - "rand_core 0.6.4", "typenum", ] @@ -671,36 +470,12 @@ dependencies = [ "hybrid-array", ] -[[package]] -name = "ctr" -version = "0.9.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" -dependencies = [ - "cipher", -] - -[[package]] -name = "ctutils" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e" -dependencies = [ - "cmov", -] - [[package]] name = "data-encoding" version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" -[[package]] -name = "deranged" -version = "0.5.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" - [[package]] name = "digest" version = "0.10.7" @@ -720,7 +495,6 @@ dependencies = [ "block-buffer 0.12.1", "const-oid", "crypto-common 0.2.2", - "ctutils", ] [[package]] @@ -740,12 +514,6 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" -[[package]] -name = "either" -version = "1.18.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" - [[package]] name = "equivalent" version = "1.0.2" @@ -970,16 +738,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "ghash" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" -dependencies = [ - "opaque-debug", - "polyval", -] - [[package]] name = "h2" version = "0.4.19" @@ -991,7 +749,7 @@ dependencies = [ "fnv", "futures-core", "futures-sink", - "http 1.5.0", + "http", "indexmap", "slab", "tokio", @@ -1032,32 +790,6 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" -[[package]] -name = "hex" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" - -[[package]] -name = "hmac" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" -dependencies = [ - "digest 0.11.3", -] - -[[package]] -name = "http" -version = "0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1" -dependencies = [ - "bytes", - "fnv", - "itoa", -] - [[package]] name = "http" version = "1.5.0" @@ -1068,17 +800,6 @@ dependencies = [ "itoa", ] -[[package]] -name = "http-body" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2" -dependencies = [ - "bytes", - "http 0.2.12", - "pin-project-lite", -] - [[package]] name = "http-body" version = "1.1.0" @@ -1086,7 +807,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" dependencies = [ "bytes", - "http 1.5.0", + "http", ] [[package]] @@ -1097,8 +818,8 @@ checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" dependencies = [ "bytes", "futures-core", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "pin-project-lite", ] @@ -1134,8 +855,8 @@ dependencies = [ "futures-channel", "futures-core", "h2", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "httparse", "httpdate", "itoa", @@ -1151,7 +872,7 @@ version = "0.27.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" dependencies = [ - "http 1.5.0", + "http", "hyper", "hyper-util", "rustls", @@ -1170,8 +891,8 @@ dependencies = [ "bytes", "futures-channel", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "hyper", "ipnet", "libc", @@ -1341,15 +1062,6 @@ dependencies = [ "libc", ] -[[package]] -name = "inout" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" -dependencies = [ - "generic-array", -] - [[package]] name = "ipnet" version = "2.12.2" @@ -1590,21 +1302,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "num-conv" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" - -[[package]] -name = "num-integer" -version = "0.1.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" -dependencies = [ - "num-traits", -] - [[package]] name = "num-traits" version = "0.2.19" @@ -1626,24 +1323,12 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" -[[package]] -name = "opaque-debug" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" - [[package]] name = "openssl-probe" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" -[[package]] -name = "outref" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e" - [[package]] name = "percent-encoding" version = "2.3.2" @@ -1656,30 +1341,12 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" -[[package]] -name = "pin-utils" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" - [[package]] name = "pkg-config" version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" -[[package]] -name = "polyval" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" -dependencies = [ - "cfg-if", - "cpufeatures 0.2.17", - "opaque-debug", - "universal-hash", -] - [[package]] name = "potential_utf" version = "0.1.6" @@ -1689,12 +1356,6 @@ dependencies = [ "zerovec", ] -[[package]] -name = "powerfmt" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" - [[package]] name = "ppv-lite86" version = "0.2.21" @@ -1822,15 +1483,6 @@ dependencies = [ "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]] name = "rand_core" version = "0.9.5" @@ -1895,8 +1547,8 @@ dependencies = [ "futures-core", "futures-util", "h2", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "hyper", "hyper-rustls", @@ -2422,36 +2074,6 @@ dependencies = [ "cfg-if", ] -[[package]] -name = "time" -version = "0.3.55" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" -dependencies = [ - "deranged", - "num-conv", - "powerfmt", - "serde_core", - "time-core", - "time-macros", -] - -[[package]] -name = "time-core" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" - -[[package]] -name = "time-macros" -version = "0.2.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" -dependencies = [ - "num-conv", - "time-core", -] - [[package]] name = "tinystr" version = "0.8.4" @@ -2626,8 +2248,8 @@ dependencies = [ "bitflags", "bytes", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "pin-project-lite", "tower", "tower-layer", @@ -2723,7 +2345,7 @@ checksum = "8628dcc84e5a09eb3d8423d6cb682965dea9133204e8fb3efee74c2a0c259442" dependencies = [ "bytes", "data-encoding", - "http 1.5.0", + "http", "httparse", "log", "rand 0.9.5", @@ -2740,7 +2362,7 @@ checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" dependencies = [ "bytes", "data-encoding", - "http 1.5.0", + "http", "httparse", "log", "rand 0.9.5", @@ -2842,22 +2464,9 @@ dependencies = [ "tw-secret", "tw-store", "tw-types", - "tw-wire", "tw-yaml", ] -[[package]] -name = "tw-crypto" -version = "0.41.0" -dependencies = [ - "aes-gcm", - "anyhow", - "hex", - "rand 0.10.2", - "serde_json", - "thiserror", -] - [[package]] name = "tw-dialect" version = "0.41.0" @@ -2891,7 +2500,7 @@ dependencies = [ "bytes", "chrono", "futures", - "http 1.5.0", + "http", "http-body-util", "hyper", "hyper-util", @@ -2920,8 +2529,6 @@ dependencies = [ "tw-pricing", "tw-secret", "tw-types", - "tw-upstream", - "tw-wire", "uuid", ] @@ -2936,7 +2543,6 @@ dependencies = [ "serde_yaml_ng", "thiserror", "tw-dialect", - "tw-secret", ] [[package]] @@ -3010,31 +2616,6 @@ version = "0.41.0" dependencies = [ "serde", "serde_json", - "thiserror", -] - -[[package]] -name = "tw-upstream" -version = "0.41.0" -dependencies = [ - "aws-credential-types", - "aws-sigv4", - "aws-smithy-eventstream", - "aws-smithy-types", - "bytes", - "http 1.5.0", - "reqwest", - "serde_json", - "tokio", - "tw-dialect", - "tw-wire", -] - -[[package]] -name = "tw-wire" -version = "0.41.0" -dependencies = [ - "serde_json", ] [[package]] @@ -3071,7 +2652,6 @@ dependencies = [ "tw-scan", "tw-secret", "tw-store", - "tw-wire", "tw-yaml", "windows-sys 0.61.2", ] @@ -3088,16 +2668,6 @@ version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" -[[package]] -name = "universal-hash" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" -dependencies = [ - "crypto-common 0.1.7", - "subtle", -] - [[package]] name = "unsafe-libyaml" version = "0.2.11" @@ -3170,12 +2740,6 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" -[[package]] -name = "vsimd" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64" - [[package]] name = "walkdir" version = "2.5.0" diff --git a/Cargo.toml b/Cargo.toml index da5aaa0a..4eef634e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,19 +1,17 @@ [workspace] resolver = "2" members = [ - # ── 第一层 · 共用(企业版依赖,含传递依赖)────────── - # 企业版直接用:tw-types、tw-upstream、tw-wire、tw-crypto、 - # tw-dialect、tw-guard、tw-breaker;tw-secret 经 tw-guard 带进去。 - # 改这一层要 grep 企业版。 - "crates/tw-types", - "crates/tw-upstream", - "crates/tw-wire", - "crates/tw-crypto", + # ── 第一层 · 共用(企业版依赖的只有这三个)────────── + # 只准依赖彼此和第三方 crate,不准依赖第二层 —— tw-dialect 里的 + # layer_one_depends_only_on_itself 测试守着这条。改这一层要 grep 企业版; + # CI 的 enterprise 任务会拿企业版对着这次改动编译一遍。 + # **只有一方在用的「共用件」搬回那一方**,不留在这里。 "crates/tw-dialect", "crates/tw-guard", - "crates/tw-secret", "crates/tw-breaker", # ── 第二层 · 桌面网关(企业版不依赖)──────────────── + "crates/tw-types", + "crates/tw-secret", "crates/tw-api", "crates/tw-config", "crates/tw-yaml", @@ -44,9 +42,6 @@ version = "0.41.0" [workspace.dependencies] # ── 内部 crate ─────────────────────────────────────────── tw-types = { path = "crates/tw-types" } -tw-upstream = { path = "crates/tw-upstream" } -tw-wire = { path = "crates/tw-wire" } -tw-crypto = { path = "crates/tw-crypto" } tw-api = { path = "crates/tw-api" } tw-secret = { path = "crates/tw-secret" } tw-config = { path = "crates/tw-config" } @@ -125,16 +120,7 @@ sha2 = "0.11" uuid = { version = "1", features = ["v4", "serde"] } rand = "0.10" -# 与企业版一样:加密相关一律精确锁定,防止 cargo update 悄悄换掉验证默认值 -aes-gcm = "=0.10.3" - clap = { version = "4", features = ["derive"] } -# ── Bedrock:SigV4 签名与 eventstream 拆帧(tw-upstream 的 bedrock feature)── -aws-sigv4 = "1" -aws-credential-types = { version = "1", features = ["hardcoded-credentials"] } -aws-smithy-eventstream = "0.60" -aws-smithy-types = "1" - [profile.release] # 桌面 sidecar:体积比极限吞吐重要。企业版用 lto = true + codegen-units = 1, diff --git a/README.md b/README.md index 97403493..0e87930b 100644 --- a/README.md +++ b/README.md @@ -43,18 +43,23 @@ Point a client (Claude Code, Codex, and friends) at a local port, and: ## Crate layers ``` -tw-types · tw-dialect · tw-wire · tw-upstream · tw-crypto ← shape fixed by the outside world -tw-engine · tw-pricing · tw-guard · tw-breaker · tw-yaml · tw-secret ← domain logic -tw-config · tw-store · tw-scan · tw-adopt · tw-observe ← assembly -tw-gateway · tw-control ← data plane / control plane +tw-dialect · tw-guard · tw-breaker ← shared with the server edition +tw-types · tw-engine · tw-pricing · tw-yaml · tw-secret ← domain logic +tw-config · tw-store · tw-scan · tw-adopt · tw-observe ← assembly +tw-gateway · tw-control ← data plane / control plane ``` -The top two layers are stable against external reality. The server edition -depends on tw-types, tw-dialect, tw-wire, tw-upstream, tw-crypto, tw-guard and -tw-breaker directly, and on tw-secret through tw-guard. The bottom two are the single-machine implementation -(SQLite, unix socket) and are deliberately **not** shared: single-machine SQLite -and multi-tenant Postgres are different enough that forcing one abstraction over -both would serve neither. +The server edition depends on the top layer and nothing else: format +conversion and usage parsing (tw-dialect), redaction and tool-call inspection +(tw-guard), and the circuit-breaker state machine (tw-breaker). Those three +depend only on each other — a test enforces it, and CI builds the server +edition against every change to them. A component only one side uses lives +on that side, not here. + +Everything below is the single-machine implementation (SQLite, unix socket) +and is deliberately **not** shared: single-machine SQLite and multi-tenant +Postgres are different enough that forcing one abstraction over both would +serve neither. ## Development diff --git a/README.zh-CN.md b/README.zh-CN.md index 851e1d66..d63675af 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -38,17 +38,19 @@ cargo run -p twcore -- serve # 起网关和控制面 ## crate 分层 ``` -tw-types · tw-dialect · tw-wire · tw-upstream · tw-crypto ← 形状由外部现实决定 -tw-engine · tw-pricing · tw-guard · tw-breaker · tw-yaml · tw-secret ← 领域逻辑 -tw-config · tw-store · tw-scan · tw-adopt · tw-observe ← 装配 -tw-gateway · tw-control ← 数据面 / 控制面 +tw-dialect · tw-guard · tw-breaker ← 与服务端版本共用 +tw-types · tw-engine · tw-pricing · tw-yaml · tw-secret ← 领域逻辑 +tw-config · tw-store · tw-scan · tw-adopt · tw-observe ← 装配 +tw-gateway · tw-control ← 数据面 / 控制面 ``` -上面两层对外部稳定。服务端版本直接依赖其中的 tw-types、tw-dialect、 -tw-wire、tw-upstream、tw-crypto、tw-guard、tw-breaker,tw-secret 经 -tw-guard 间接带进去。下面两层是单机的实现 -(SQLite、unix socket),**有意不共用** —— 单机 SQLite 和多租户 Postgres -差得太远,强行统一只会造出一个两边都别扭的抽象。 +服务端版本只依赖最上面一层:格式转换与用量解析(tw-dialect)、脱敏与工具调用 +审查(tw-guard)、熔断状态机(tw-breaker)。这三个只依赖彼此 —— 有测试守着, +CI 也会拿服务端版本对着每一次改动编译一遍。只有一方在用的东西住在那一方, +不放在这里。 + +下面三层是单机的实现(SQLite、unix socket),**有意不共用** —— 单机 SQLite +和多租户 Postgres 差得太远,强行统一只会造出一个两边都别扭的抽象。 ## 开发 diff --git a/bin/twcore/Cargo.toml b/bin/twcore/Cargo.toml index 8d4d5e7d..8a994508 100644 --- a/bin/twcore/Cargo.toml +++ b/bin/twcore/Cargo.toml @@ -23,7 +23,6 @@ clap = { workspace = true } tw-adopt = { workspace = true } tw-scan = { workspace = true } tw-guard = { workspace = true } -tw-wire = { workspace = true } serde_yaml_ng = { workspace = true } tokio = { workspace = true } tracing = { workspace = true } diff --git a/crates/tw-config/src/lib.rs b/crates/tw-config/src/lib.rs index 248d1817..ee8f5c66 100644 --- a/crates/tw-config/src/lib.rs +++ b/crates/tw-config/src/lib.rs @@ -17,6 +17,7 @@ mod probes; pub mod proxy; pub mod refs; pub mod reload; +mod retention; mod security; pub mod store; mod validate; @@ -82,7 +83,7 @@ pub struct Config { pub security: Security, /// 日志留多久。不写就是默认值。 #[serde(default, skip_serializing_if = "is_default")] - pub retention: tw_types::Retention, + pub retention: Retention, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub groups: Vec, /// 路由。一条路由是一组按顺序求值的规则。 @@ -120,7 +121,7 @@ impl Default for Config { pricing: tw_pricing::PricingConfig::default(), client_probes: ClientProbes::default(), security: Security::default(), - retention: tw_types::Retention::default(), + retention: Retention::default(), groups: Vec::new(), routes: Vec::new(), default_route: None, @@ -250,13 +251,18 @@ pub struct GatewayListen { pub allow_from: Vec, } +/// 放行网段的默认名单:RFC1918 的三个私网段和 IPv6 的唯一本地地址段。 +/// +/// **不含回环。**本机永远放行(见 tw-gateway 的 `AllowList::allows`),写进 +/// 名单只会在界面上多出两条删了也不起作用的条目。 +/// +/// 配置层用它填默认值,控制面把它交给界面「恢复默认」。 +pub const PRIVATE_RANGES: &[&str] = &["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"]; + /// 放行网段的默认名单:私网段。**不是放行所有** —— 想放开得手动写 /// `0.0.0.0/0`,那时他至少知道自己做了什么。 pub fn default_allow_from() -> Vec { - tw_types::PRIVATE_RANGES - .iter() - .map(|s| s.to_string()) - .collect() + PRIVATE_RANGES.iter().map(|s| s.to_string()).collect() } fn default_port() -> u16 { @@ -936,6 +942,7 @@ pub fn write(path: &Path, cfg: &Config) -> Result<(), WriteError> { pub use probes::{ClientProbes, ProbeAction}; pub use reload::{Rejected, Stage, try_parse}; +pub use retention::Retention; pub use security::{ CustomRedactRule, CustomToolRule, Mode as SecurityMode, RedactPolicy, Security, ToolAction, ToolPolicy, diff --git a/crates/tw-config/src/retention.rs b/crates/tw-config/src/retention.rs new file mode 100644 index 00000000..0e95d99b --- /dev/null +++ b/crates/tw-config/src/retention.rs @@ -0,0 +1,47 @@ +//! 日志留多久。 + +use serde::{Deserialize, Serialize}; + +/// 日志留多久。 +/// +/// **两个期限,因为两种东西的代价差三个数量级。**请求和响应的正文一条 +/// 几十 KB,一天就能堆出几百 MB;而一行记录(时刻、模型、用量、金额) +/// 只有几百字节,留一个季度也不过几十 MB。用一个期限管住两者,等于 +/// 要么早早丢掉「上个月花了多少」,要么让磁盘替正文买单。 +/// +/// **总量上限是给突发准备的。**按天数算出来的占用取决于用量,而用量 +/// 会有一周十倍于平时的时候 —— 没有上限的话,那一周会把磁盘吃光, +/// 而用户直到硬盘满了才知道。 +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Retention { + /// 请求和响应的正文留几天。**大头在这儿** + #[serde(default = "d_body_days")] + pub body_days: u64, + /// 一行记录留几天。它撑着「上个月花了多少」那类问题 + #[serde(default = "d_row_days")] + pub row_days: u64, + /// 正文总共最多占多少字节。超了从最旧的整天开始删 + #[serde(default = "d_body_max_bytes")] + pub body_max_bytes: u64, +} + +fn d_body_days() -> u64 { + 7 +} +fn d_row_days() -> u64 { + 90 +} +fn d_body_max_bytes() -> u64 { + 2 * 1024 * 1024 * 1024 +} + +impl Default for Retention { + fn default() -> Self { + Self { + body_days: d_body_days(), + row_days: d_row_days(), + body_max_bytes: d_body_max_bytes(), + } + } +} diff --git a/crates/tw-control/Cargo.toml b/crates/tw-control/Cargo.toml index 606f0d0c..576ece01 100644 --- a/crates/tw-control/Cargo.toml +++ b/crates/tw-control/Cargo.toml @@ -21,7 +21,6 @@ tw-guard = { workspace = true } bytes = { workspace = true } tw-engine = { workspace = true } tw-gateway = { workspace = true } -tw-wire = { workspace = true } tw-observe = { workspace = true } tw-secret = { workspace = true } tw-store = { workspace = true } diff --git a/crates/tw-crypto/Cargo.toml b/crates/tw-crypto/Cargo.toml deleted file mode 100644 index d40450ce..00000000 --- a/crates/tw-crypto/Cargo.toml +++ /dev/null @@ -1,16 +0,0 @@ -[package] -name = "tw-crypto" -version.workspace = true -edition.workspace = true -rust-version.workspace = true -license.workspace = true -repository.workspace = true -description = "AES-256-GCM envelope encryption and decryption" - -[dependencies] -aes-gcm = { workspace = true } -anyhow = { workspace = true } -hex = "0.4" -rand = { workspace = true } -serde_json = { workspace = true } -thiserror = { workspace = true } diff --git a/crates/tw-crypto/src/crypto.rs b/crates/tw-crypto/src/crypto.rs deleted file mode 100644 index 6f2b6d88..00000000 --- a/crates/tw-crypto/src/crypto.rs +++ /dev/null @@ -1,152 +0,0 @@ -use aes_gcm::{ - Aes256Gcm, Nonce, - aead::{Aead, KeyInit}, -}; - -/// Magic prefix for versioned ciphertexts. Every payload is parsed as -/// `MAGIC(4) || version(1) || nonce(12) || ciphertext + tag`. -const ENVELOPE_MAGIC: [u8; 4] = [0xfe, b'T', b'W', 0x01]; - -/// Current envelope version. Increment this when introducing a new -/// algorithm or KDF. -pub const CURRENT_KEY_VERSION: u8 = 1; - -/// Encrypt data using AES-256-GCM, emitting a versioned envelope: -/// -/// `[ENVELOPE_MAGIC (4)] [version (1)] [nonce (12)] [ciphertext + tag]` -pub fn encrypt(plaintext: &[u8], key: &[u8; 32]) -> anyhow::Result> { - let cipher = Aes256Gcm::new_from_slice(key).map_err(|e| anyhow::anyhow!("Invalid key: {e}"))?; - - let mut nonce_bytes = [0u8; 12]; - rand::fill(&mut nonce_bytes); - let nonce = Nonce::from_slice(&nonce_bytes); - - let ciphertext = cipher - .encrypt(nonce, plaintext) - .map_err(|e| anyhow::anyhow!("Encryption failed: {e}"))?; - - let mut result = Vec::with_capacity(4 + 1 + 12 + ciphertext.len()); - result.extend_from_slice(&ENVELOPE_MAGIC); - result.push(CURRENT_KEY_VERSION); - result.extend_from_slice(&nonce_bytes); - result.extend_from_slice(&ciphertext); - Ok(result) -} - -/// Decrypt data produced by `encrypt`. Only accepts the versioned envelope -/// format: `[ENVELOPE_MAGIC (4)] [version (1)] [nonce (12)] [ciphertext + tag]`. -pub fn decrypt(encrypted: &[u8], key: &[u8; 32]) -> anyhow::Result> { - if encrypted.len() < 4 + 1 + 12 { - return Err(anyhow::anyhow!("Ciphertext too short")); - } - if encrypted[..4] != ENVELOPE_MAGIC { - return Err(anyhow::anyhow!( - "Unrecognized ciphertext format (missing envelope magic)" - )); - } - let cipher = Aes256Gcm::new_from_slice(key).map_err(|e| anyhow::anyhow!("Invalid key: {e}"))?; - - let version = encrypted[4]; - match version { - 1 => { - let nonce = Nonce::from_slice(&encrypted[5..17]); - let ciphertext = &encrypted[17..]; - cipher - .decrypt(nonce, ciphertext) - .map_err(|e| anyhow::anyhow!("Decryption failed: {e}")) - } - other => Err(anyhow::anyhow!( - "Unknown ciphertext version: {other} (max supported: {CURRENT_KEY_VERSION})" - )), - } -} - -/// Parse a 32-byte hex-encoded encryption key. -pub fn parse_encryption_key(hex_key: &str) -> anyhow::Result<[u8; 32]> { - let bytes = hex::decode(hex_key)?; - if bytes.len() != 32 { - return Err(anyhow::anyhow!( - "Encryption key must be 32 bytes (64 hex chars), got {} bytes", - bytes.len() - )); - } - let mut key = [0u8; 32]; - key.copy_from_slice(&bytes); - Ok(key) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn test_key() -> [u8; 32] { - let mut key = [0u8; 32]; - rand::fill(&mut key); - key - } - - #[test] - fn encrypt_decrypt_roundtrip() { - let key = test_key(); - let plaintext = b"Hello, ThinkWatch!"; - let encrypted = encrypt(plaintext, &key).expect("encrypt should succeed"); - let decrypted = decrypt(&encrypted, &key).expect("decrypt should succeed"); - assert_eq!(decrypted, plaintext, "decrypted text must match original"); - } - - #[test] - fn wrong_key_fails_decrypt() { - let key1 = test_key(); - let mut key2 = test_key(); - // Ensure key2 differs from key1 - key2[0] ^= 0xFF; - - let encrypted = encrypt(b"secret data", &key1).expect("encrypt should succeed"); - let result = decrypt(&encrypted, &key2); - assert!(result.is_err(), "decryption with wrong key must fail"); - } - - #[test] - fn parse_encryption_key_valid() { - let hex_key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; - let key = parse_encryption_key(hex_key).expect("should parse valid 64-hex-char key"); - assert_eq!(key.len(), 32); - } - - #[test] - fn parse_encryption_key_too_short() { - let result = parse_encryption_key("abcdef"); - assert!(result.is_err(), "short key should be rejected"); - } - - #[test] - fn parse_encryption_key_invalid_hex() { - let result = parse_encryption_key( - "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz", - ); - assert!(result.is_err(), "non-hex chars should be rejected"); - } - - #[test] - fn versioned_envelope_starts_with_magic() { - let key = test_key(); - let encrypted = encrypt(b"hello", &key).unwrap(); - assert!(encrypted.starts_with(&ENVELOPE_MAGIC)); - assert_eq!(encrypted[4], CURRENT_KEY_VERSION); - } - - #[test] - fn unknown_version_rejected() { - let key = test_key(); - // Manually build a ciphertext with an unknown version byte - let mut bad = Vec::new(); - bad.extend_from_slice(&ENVELOPE_MAGIC); - bad.push(99); // unknown version - bad.extend_from_slice(&[0u8; 12]); // nonce - bad.extend_from_slice(&[0u8; 16]); // tag-only ciphertext (will fail anyway) - let result = decrypt(&bad, &key); - assert!(result.is_err()); - let msg = format!("{:#}", result.unwrap_err()); - assert!(msg.contains("Unknown ciphertext version")); - } -} diff --git a/crates/tw-crypto/src/json_secret.rs b/crates/tw-crypto/src/json_secret.rs deleted file mode 100644 index f2d29641..00000000 --- a/crates/tw-crypto/src/json_secret.rs +++ /dev/null @@ -1,187 +0,0 @@ -//! `JsonSecret` — at-rest representation of a sensitive string embedded -//! inside a JSONB column. -//! -//! Provider `config_json` carries multiple header values plus -//! `aws_secret_access_key`; each of those individual values is wrapped -//! as `{"$enc": ""}` in production rows. Centralising the wire -//! shape here means the next at-rest field added to a JSONB column -//! reuses the same envelope instead of inventing its own; tests can -//! ask `JsonSecret::is_encrypted` instead of reaching into -//! `value.get("$enc")` directly. -//! -//! This module covers the *JSON-nested* case only. Column-level -//! ciphertexts (mcp_oauth client secret, totp_secret, etc.) already use -//! [`crypto::encrypt`] / [`crypto::decrypt`] against a dedicated -//! `BYTEA`/`String` column; they don't carry a JSON wrapper, so they -//! don't go through this type. - -use crate::crypto; - -/// 本 crate 自己的错误类型。原来直接用企业版的 `AppError::Internal`, -/// 那会把整个错误枚举拖进共用层 —— core 不该认识调用方的错误分类。 -#[derive(Debug, thiserror::Error)] -#[error("{0}")] -pub struct SecretError(pub String); - -impl SecretError { - fn new(msg: impl std::fmt::Display) -> Self { - Self(msg.to_string()) - } -} - -/// Stored representation of a JSON-nested secret value. -#[derive(Debug, Clone, PartialEq)] -pub enum JsonSecret { - /// `{"$enc": ""}`. - Encrypted { hex: String }, - /// Missing key, null, empty string, or any other shape we treat as - /// "no value supplied". The loader fans this back into the empty - /// string at the consumer boundary. - Empty, -} - -/// JSON marker key — only exported because tests need to recognise -/// already-wrapped rows without a full round-trip decrypt. Production -/// read paths should call [`JsonSecret::from_json`] instead. -pub const ENC_MARKER: &str = "$enc"; - -impl JsonSecret { - /// Recognise the valid on-disk shapes. Returns `Err` for a bare - /// non-empty string — that shape is never written by any producer - /// in this codebase, so encountering one at read time signals a - /// corrupted row or a hand-edited DB. Surfacing the error stops - /// us from silently swallowing the cipher and serving a "no - /// credentials" downstream error that's much harder to trace. - pub fn from_json(value: &serde_json::Value) -> Result { - if let Some(obj) = value.as_object() - && let Some(hex_str) = obj.get(ENC_MARKER).and_then(|v| v.as_str()) - { - return Ok(JsonSecret::Encrypted { - hex: hex_str.to_string(), - }); - } - match value.as_str() { - Some("") | None => Ok(JsonSecret::Empty), - Some(_) => Err(SecretError::new(format!( - "config_json secret is a bare string; expected `{{\"{ENC_MARKER}\":...}}` or null", - ))), - } - } - - /// Encrypt `plaintext` and produce a value suitable for INSERT. - /// Empty input yields [`JsonSecret::Empty`] — burning AES on `""` - /// is wasteful and the loader treats missing/empty identically. - pub fn encrypt(plaintext: &str, encryption_key: &str) -> Result { - if plaintext.is_empty() { - return Ok(JsonSecret::Empty); - } - let key = crypto::parse_encryption_key(encryption_key) - .map_err(|e| SecretError::new(format!("Invalid encryption key: {e}")))?; - let bytes = crypto::encrypt(plaintext.as_bytes(), &key) - .map_err(|e| SecretError::new(format!("Secret encrypt failed: {e}")))?; - Ok(JsonSecret::Encrypted { - hex: hex::encode(bytes), - }) - } - - /// Resolve to plaintext. `Empty` resolves to `""`; `Encrypted` - /// decrypts via the workspace's at-rest key. - pub fn decrypt(&self, encryption_key: &str) -> Result { - match self { - JsonSecret::Encrypted { hex } => { - let bytes = hex::decode(hex) - .map_err(|e| SecretError::new(format!("Secret hex decode failed: {e}")))?; - let key = crypto::parse_encryption_key(encryption_key) - .map_err(|e| SecretError::new(format!("Invalid encryption key: {e}")))?; - let plain = crypto::decrypt(&bytes, &key) - .map_err(|e| SecretError::new(format!("Secret decrypt failed: {e}")))?; - String::from_utf8(plain) - .map_err(|e| SecretError::new(format!("Secret is not valid UTF-8: {e}"))) - } - JsonSecret::Empty => Ok(String::new()), - } - } - - /// Render to the JSON shape that goes into the DB. Empty stays as - /// `""` rather than `null` so downstream readers that expect a - /// string don't choke on a type change. - pub fn to_json(&self) -> serde_json::Value { - match self { - JsonSecret::Encrypted { hex } => serde_json::json!({ ENC_MARKER: hex }), - JsonSecret::Empty => serde_json::Value::String(String::new()), - } - } - - /// Cheap check used by tests: was this value stored with the - /// encryption envelope, or is it `Empty`? - pub fn is_encrypted(&self) -> bool { - matches!(self, JsonSecret::Encrypted { .. }) - } - - /// Convenience: classify a raw JSON value without holding the - /// intermediate `JsonSecret`. The write path uses this to skip - /// double-encrypting an `{"$enc":...}` shape that round-tripped - /// from a GET response. - pub fn json_is_encrypted(value: &serde_json::Value) -> bool { - value - .as_object() - .is_some_and(|o| o.contains_key(ENC_MARKER)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn test_key_hex() -> String { - // 32 zero bytes — fine for unit tests. - hex::encode([0u8; 32]) - } - - #[test] - fn round_trip_encrypt_decrypt() { - let key = test_key_hex(); - let enc = JsonSecret::encrypt("sk-secret", &key).unwrap(); - assert!(enc.is_encrypted()); - let plain = enc.decrypt(&key).unwrap(); - assert_eq!(plain, "sk-secret"); - } - - #[test] - fn empty_is_not_encrypted() { - let key = test_key_hex(); - let enc = JsonSecret::encrypt("", &key).unwrap(); - assert_eq!(enc, JsonSecret::Empty); - assert!(!enc.is_encrypted()); - assert_eq!(enc.to_json(), serde_json::Value::String(String::new())); - } - - #[test] - fn from_json_recognises_enc_envelope_and_empty() { - let key = test_key_hex(); - let enc = JsonSecret::encrypt("hello", &key).unwrap(); - let wire = enc.to_json(); - assert_eq!(JsonSecret::from_json(&wire).unwrap(), enc); - - let empty_str = serde_json::Value::String(String::new()); - assert_eq!( - JsonSecret::from_json(&empty_str).unwrap(), - JsonSecret::Empty - ); - assert_eq!( - JsonSecret::from_json(&serde_json::Value::Null).unwrap(), - JsonSecret::Empty - ); - } - - #[test] - fn from_json_rejects_bare_non_empty_string() { - // No producer in this codebase ever writes a bare string into - // a secret slot — encountering one at read time means the row - // is corrupted or hand-edited. The reader returns Err so the - // caller can surface the misconfig instead of silently - // treating it as Empty and falling through to "no credentials". - let bare = serde_json::Value::String("hand-typed-secret".into()); - assert!(JsonSecret::from_json(&bare).is_err()); - } -} diff --git a/crates/tw-crypto/src/lib.rs b/crates/tw-crypto/src/lib.rs deleted file mode 100644 index 0b9d2961..00000000 --- a/crates/tw-crypto/src/lib.rs +++ /dev/null @@ -1,10 +0,0 @@ -//! AES-256-GCM 信封加解密,以及「JSON 里的某个字段是密文」这一约定。 -//! -//! 桌面版当前不调用(密钥明文写在 config.yaml), -//! 但企业版依赖它,所以它住在共用层。 - -pub mod crypto; -pub mod json_secret; - -pub use crypto::{CURRENT_KEY_VERSION, decrypt, encrypt, parse_encryption_key}; -pub use json_secret::{ENC_MARKER, JsonSecret}; diff --git a/crates/tw-dialect/src/anthropic/response.rs b/crates/tw-dialect/src/anthropic/response.rs index c251b4b8..6c4ac067 100644 --- a/crates/tw-dialect/src/anthropic/response.rs +++ b/crates/tw-dialect/src/anthropic/response.rs @@ -36,10 +36,16 @@ pub fn stop_reason_str(s: &StopReason) -> Value { pub fn usage(u: &Value) -> Usage { let n = |k: &str| u64_of(u, k).unwrap_or(0); + // 1 小时缓存写。细分在 `cache_creation` 里;有它就整笔按 1 小时算 + let one_hour = u + .get("cache_creation") + .and_then(|d| u64_of(d, "ephemeral_1h_input_tokens")) + .unwrap_or(0); Usage { input: n("input_tokens"), cache_read: n("cache_read_input_tokens"), - cache_write: n("cache_creation_input_tokens"), + cache_write: n("cache_creation_input_tokens").max(one_hour), + cache_1h: one_hour > 0, output: n("output_tokens"), reasoning: u .get("output_tokens_details") @@ -49,12 +55,19 @@ pub fn usage(u: &Value) -> Usage { } pub fn usage_json(u: &Usage) -> Value { - json!({ + let mut v = json!({ "input_tokens": u.input, "output_tokens": u.output, "cache_read_input_tokens": u.cache_read, "cache_creation_input_tokens": u.cache_write, - }) + }); + if u.cache_1h { + v["cache_creation"] = json!({ + "ephemeral_5m_input_tokens": 0, + "ephemeral_1h_input_tokens": u.cache_write, + }); + } + v } /// 上游 Anthropic 的整包响应 → 中间表示。 @@ -178,6 +191,22 @@ pub fn error_message(v: &Value) -> Option { #[cfg(test)] mod tests { use super::*; + + #[test] + fn the_one_hour_cache_tier_survives_a_round_trip() { + let u = usage( + &json!({"input_tokens": 10, "cache_creation_input_tokens": 2000, + "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 2000}}), + ); + assert!(u.cache_1h); + assert_eq!(u.cache_write, 2000); + assert_eq!(usage(&usage_json(&u)), u); + // 5 分钟档不算 + let u = usage(&json!({"cache_creation_input_tokens": 2000, + "cache_creation": {"ephemeral_5m_input_tokens": 2000, "ephemeral_1h_input_tokens": 0}})); + assert!(!u.cache_1h); + assert!(usage_json(&u).get("cache_creation").is_none()); + } use crate::convert::Session; #[test] diff --git a/crates/tw-dialect/src/bedrock/response.rs b/crates/tw-dialect/src/bedrock/response.rs index 0ef0e6da..2e47d3a3 100644 --- a/crates/tw-dialect/src/bedrock/response.rs +++ b/crates/tw-dialect/src/bedrock/response.rs @@ -46,6 +46,7 @@ pub fn usage(u: &Value) -> Usage { input: n("inputTokens"), cache_read: n("cacheReadInputTokens"), cache_write: n("cacheWriteInputTokens"), + cache_1h: false, output: n("outputTokens"), reasoning: 0, } @@ -248,9 +249,8 @@ mod tests { usage: Some(Usage { input: 60, cache_read: 40, - cache_write: 0, output: 20, - reasoning: 0, + ..Default::default() }), }; let s = Session::for_test(Dialect::Bedrock, Dialect::Bedrock); diff --git a/crates/tw-dialect/src/chat/response.rs b/crates/tw-dialect/src/chat/response.rs index ba5fe660..b935aab6 100644 --- a/crates/tw-dialect/src/chat/response.rs +++ b/crates/tw-dialect/src/chat/response.rs @@ -36,6 +36,7 @@ pub fn usage(u: &Value) -> Usage { input: n("prompt_tokens").saturating_sub(cache_read + cache_write), cache_read, cache_write, + cache_1h: false, output: n("completion_tokens"), reasoning: u .get("completion_tokens_details") diff --git a/crates/tw-dialect/src/gemini/response.rs b/crates/tw-dialect/src/gemini/response.rs index 577dc82f..bd7f798a 100644 --- a/crates/tw-dialect/src/gemini/response.rs +++ b/crates/tw-dialect/src/gemini/response.rs @@ -41,6 +41,7 @@ pub fn usage(u: &Value) -> Usage { input: (n("promptTokenCount") + n("toolUsePromptTokenCount")).saturating_sub(cached), cache_read: cached, cache_write: 0, + cache_1h: false, output: n("candidatesTokenCount") + thoughts, reasoning: thoughts, } diff --git a/crates/tw-dialect/src/ir.rs b/crates/tw-dialect/src/ir.rs index b185f690..21f8a894 100644 --- a/crates/tw-dialect/src/ir.rs +++ b/crates/tw-dialect/src/ir.rs @@ -428,17 +428,27 @@ pub enum StopReason { /// 用量。**`input` 不含缓存读写**,和 Anthropic 的语义一致:三者不重叠, /// 加起来才是全部输入。`output` 含推理。 +/// +/// 方言转换和计费读的是同一个:各家响应里的 `usage` 由各自模块的 `usage()` 解析, +/// 旁路嗅探([`crate::usage::Sniffer`])也调它们,每条换算只写一处。 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct Usage { pub input: u64, pub cache_read: u64, pub cache_write: u64, + /// 缓存写用的是 1 小时 TTL 吗。**差价接近一倍**, + /// 而上游只在 Anthropic 那边给这个细分 + pub cache_1h: bool, pub output: u64, /// `output` 里有多少是推理 pub reasoning: u64, } impl Usage { + pub fn is_empty(&self) -> bool { + *self == Usage::default() + } + pub fn prompt_total(&self) -> u64 { self.input + self.cache_read + self.cache_write } @@ -449,6 +459,7 @@ impl Usage { self.input = self.input.max(other.input); self.cache_read = self.cache_read.max(other.cache_read); self.cache_write = self.cache_write.max(other.cache_write); + self.cache_1h |= other.cache_1h; self.output = self.output.max(other.output); self.reasoning = self.reasoning.max(other.reasoning); } diff --git a/crates/tw-dialect/src/lib.rs b/crates/tw-dialect/src/lib.rs index 6cd561e3..1ccf727b 100644 --- a/crates/tw-dialect/src/lib.rs +++ b/crates/tw-dialect/src/lib.rs @@ -4,6 +4,9 @@ //! 入口在 [`convert`]:[`convert::prepare`] 改写请求,它返回的 [`convert::Session`] //! 改写响应、流和错误。每种格式各一个模块,分请求、整包响应、流三部分,全部经过 //! [`ir`] 里的中间表示。这个 crate 只依赖 serde,不碰网络,企业版网关也可以直接用。 +//! +//! 同样两边都用的还有:从响应里旁路嗅出用量([`usage`],换算和转换共用各家的 +//! `usage()`),以及拼上游地址([`url`])。 pub mod anthropic; pub mod bedrock; @@ -15,3 +18,5 @@ pub mod ir; pub mod official; pub mod responses; pub mod think; +pub mod url; +pub mod usage; diff --git a/crates/tw-dialect/src/responses/response.rs b/crates/tw-dialect/src/responses/response.rs index 30888f89..1200547d 100644 --- a/crates/tw-dialect/src/responses/response.rs +++ b/crates/tw-dialect/src/responses/response.rs @@ -15,6 +15,7 @@ pub fn usage(u: &Value) -> Usage { input: n("input_tokens").saturating_sub(cache_read + cache_write), cache_read, cache_write, + cache_1h: false, output: n("output_tokens"), reasoning: u .get("output_tokens_details") diff --git a/crates/tw-dialect/src/url.rs b/crates/tw-dialect/src/url.rs new file mode 100644 index 00000000..a6bd5956 --- /dev/null +++ b/crates/tw-dialect/src/url.rs @@ -0,0 +1,84 @@ +//! 拼上游地址。两个网关都用:base_url 的尾斜杠、查询串里的网关密钥,处理 +//! 一处就够了。 + +/// 拼上游 URL。base_url 的尾斜杠在这里统一吃掉 —— 从浏览器地址栏粘一个 +/// URL 就会白送一个尾斜杠,而 `https://host//v1/messages` 换来的是一个 +/// 光秃秃的 404。查询串里的网关密钥去掉,见 [`without_gateway_key`]。 +pub fn upstream_url(base_url: &str, path: &str, query: Option<&str>) -> String { + let base = base_url.trim_end_matches('/'); + let path = path.trim_start_matches('/'); + let query = query.map(without_gateway_key); + match query { + Some(q) if !q.is_empty() => format!("{base}/{path}?{q}"), + _ => format!("{base}/{path}"), + } +} + +/// 去掉查询串里的 `key=`。 +/// +/// **那是网关密钥。**Gemini 的 REST 写法把密钥放在查询串里,网关认完身份之后 +/// 原样把整个查询串拼到上游地址上,等于把它发给了上游。上游的凭据走请求头, +/// 用不着这一项。凡是把客户端的查询串转给上游的地方(HTTP、WS 升级)都要过它。 +pub fn without_gateway_key(query: &str) -> String { + query + .split('&') + .filter(|pair| *pair != "key" && !pair.starts_with("key=")) + .collect::>() + .join("&") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn trailing_slash_in_base_url_does_not_double_up() { + // 从浏览器粘 URL 会白送一个尾斜杠,而 `//v1/messages` 换来 404。 + assert_eq!( + upstream_url("https://api.example.com/", "/v1/messages", None), + "https://api.example.com/v1/messages" + ); + assert_eq!( + upstream_url("https://api.example.com", "v1/messages", None), + "https://api.example.com/v1/messages" + ); + } + + #[test] + fn query_is_carried_through_but_empty_query_adds_no_question_mark() { + assert_eq!( + upstream_url("https://x.com", "/v1/m", Some("beta=true")), + "https://x.com/v1/m?beta=true" + ); + assert_eq!( + upstream_url("https://x.com", "/v1/m", Some("")), + "https://x.com/v1/m" + ); + } + + #[test] + fn the_gateway_key_in_the_query_never_reaches_the_upstream() { + assert_eq!( + upstream_url( + "https://g.example", + "/v1beta/models/m:generateContent", + Some("key=tw-secret&alt=sse") + ), + "https://g.example/v1beta/models/m:generateContent?alt=sse" + ); + assert_eq!( + upstream_url( + "https://g.example", + "/v1beta/models/m", + Some("key=tw-secret") + ), + "https://g.example/v1beta/models/m" + ); + // 名字只是以 key 开头的参数不受影响 + assert_eq!( + upstream_url("https://g.example", "/x", Some("keyword=a")), + "https://g.example/x?keyword=a" + ); + assert_eq!(without_gateway_key("alt=sse&key"), "alt=sse"); + } +} diff --git a/crates/tw-wire/src/usage.rs b/crates/tw-dialect/src/usage.rs similarity index 79% rename from crates/tw-wire/src/usage.rs rename to crates/tw-dialect/src/usage.rs index 5a0d2f39..631fd4d4 100644 --- a/crates/tw-wire/src/usage.rs +++ b/crates/tw-dialect/src/usage.rs @@ -14,17 +14,22 @@ //! | 非流式 | 末尾一个 `usage` | 同 | 同 | `usageMetadata` | 末尾一个 `usage` | //! | 流式 | `message_start` 给输入、`message_delta` 给输出 | 末尾一个带 `usage` 的 chunk | `response.completed` 里的 `usage` | 每一帧都带累计的 `usageMetadata` | `metadata` 事件里的 `usage` | //! -//! Bedrock 的流是二进制帧,要先经 `tw_upstream::eventstream` 转成 SSE 再喂进来。 +//! Bedrock 的流是二进制帧,要由调用方先转成 SSE(`:event-type` 进 `event:`, +//! 载荷进 `data:`)再喂进来。 //! //! 流式那一行决定了实现形状:usage **可能出现在流的任何位置,而且不止 //! 一次**,所以不能只看结尾。 //! -//! **几家对「输入」的定义不一样**:Anthropic 的 `input_tokens` 和 Bedrock 的 `inputTokens` 不含缓存命中; -//! OpenAI(两种格式)和 Gemini 的输入数**包含**缓存命中。不减掉的话,命中缓存的 -//! 那部分会按输入价再算一遍。 +//! **数字怎么换算不在这里。**找到的对象交给那一家的 `usage()`(和方言转换用的 +//! 是同一个),这里只负责「在字节流里找到它」和「认出它是哪一家的」。几家对 +//! 「输入」的定义不一样(OpenAI 和 Gemini 的输入数包含缓存命中),那些换算 +//! 各写在各家的模块里,只有一处。 use serde_json::Value; +pub use crate::ir::Usage; +use crate::{anthropic, bedrock, chat, gemini, responses}; + /// 跨 chunk 的接续窗口。 /// /// 一个 usage 对象几百字节,而 chunk 边界可能正好切在中间。留这么多 @@ -36,23 +41,6 @@ const CARRY: usize = 4096; /// 字段」那种情况。 const MAX_OBJECT: usize = 8192; -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct Usage { - pub input: u64, - pub output: u64, - pub cache_read: u64, - pub cache_write: u64, - /// 缓存写用的是 1 小时 TTL 吗。**差价接近一倍**, - /// 而上游只在 Anthropic 那边给这个细分 - pub cache_1h: bool, -} - -impl Usage { - pub fn is_empty(&self) -> bool { - *self == Usage::default() - } -} - /// 一边流一边嗅。 #[derive(Debug, Default)] pub struct Sniffer { @@ -138,11 +126,11 @@ impl Sniffer { continue; }; if let Ok(v) = serde_json::from_slice::(&buf[open..=end]) { - if gemini { - self.merge_gemini(&v); + self.merge(if gemini { + gemini::response::usage(&v) } else { - self.merge(&v); - } + read(&v) + }); } } } @@ -151,85 +139,14 @@ impl Sniffer { /// /// **每个字段取较大值。**Anthropic 的 `message_start` 给输入、 /// `message_delta` 给累计输出,两者都只带自己那部分;取较大值让 - /// 「后来的那个把前面的清零」不会发生。 - fn merge(&mut self, v: &Value) { - let n = |k: &str| v.get(k).and_then(Value::as_u64).unwrap_or(0); - let mut got = false; - // Anthropic、OpenAI、Bedrock 各叫各的名字,都认 - let mut take = |keys: &[&str], slot: &mut u64| { - for k in keys { - let x = n(k); - if x > 0 { - got = true; - *slot = (*slot).max(x); - } - } - }; - take( - &["input_tokens", "prompt_tokens", "inputTokens"], - &mut self.seen.input, - ); - take( - &["output_tokens", "completion_tokens", "outputTokens"], - &mut self.seen.output, - ); - take( - &["cache_read_input_tokens", "cacheReadInputTokens"], - &mut self.seen.cache_read, - ); - take( - &["cache_creation_input_tokens", "cacheWriteInputTokens"], - &mut self.seen.cache_write, - ); - // OpenAI 把缓存读写放在明细里(Chat 叫 `prompt_tokens_details`,Responses - // 叫 `input_tokens_details`),**而且它们是输入数的子集** —— 直接相加会 - // 重复计费。 - let details = v - .get("prompt_tokens_details") - .or_else(|| v.get("input_tokens_details")); - let detail = |k: &str| { - details - .and_then(|d| d.get(k)) - .and_then(Value::as_u64) - .unwrap_or(0) - }; - let (read, write) = (detail("cached_tokens"), detail("cache_write_tokens")); - if read + write > 0 { - got = true; - self.seen.cache_read = self.seen.cache_read.max(read); - self.seen.cache_write = self.seen.cache_write.max(write); - self.seen.input = self.seen.input.saturating_sub(read + write); - } - // 1 小时缓存写。Anthropic 在 `cache_creation` 里给细分 - if let Some(d) = v.get("cache_creation") { - let h = d - .get("ephemeral_1h_input_tokens") - .and_then(Value::as_u64) - .unwrap_or(0); - if h > 0 { - got = true; - self.seen.cache_1h = true; - self.seen.cache_write = self.seen.cache_write.max(h); - } - } - self.found |= got; - } - - /// 合并一个 Gemini 的 `usageMetadata`。**流里每一帧都带,数字是累计的**, - /// 取较大值就是最终数。`promptTokenCount` 包含缓存命中,`candidatesTokenCount` - /// 不含思考 - fn merge_gemini(&mut self, v: &Value) { - let n = |k: &str| v.get(k).and_then(Value::as_u64).unwrap_or(0); - let cached = n("cachedContentTokenCount"); - let input = (n("promptTokenCount") + n("toolUsePromptTokenCount")).saturating_sub(cached); - let output = n("candidatesTokenCount") + n("thoughtsTokenCount"); - if input + cached + output == 0 { + /// 「后来的那个把前面的清零」不会发生。Gemini 每一帧都带累计数, + /// 取较大值就是最终数。 + fn merge(&mut self, u: Usage) { + if u.is_empty() { return; } self.found = true; - self.seen.input = self.seen.input.max(input); - self.seen.cache_read = self.seen.cache_read.max(cached); - self.seen.output = self.seen.output.max(output); + self.seen.merge(&u); } /// 嗅到了什么。**没嗅到就是 None,不是零** —— 零会让一次真实的 @@ -239,6 +156,29 @@ impl Sniffer { } } +/// 读一个不知道是哪家的 `usage` 对象:按只有那一家才有的字段名认出来, +/// 交给那一家的解析器。 +/// +/// Anthropic 和 Responses 都叫 `input_tokens` / `output_tokens`,区别在明细: +/// Responses 有 `input_tokens_details` 和 `total_tokens`,而且它的输入数包含 +/// 缓存命中 —— 认错了,缓存那部分会按输入价再算一遍。 +pub fn read(v: &Value) -> Usage { + let has = |k: &str| v.get(k).is_some(); + if has("prompt_tokens") || has("completion_tokens") || has("prompt_tokens_details") { + chat::response::usage(v) + } else if has("inputTokens") + || has("outputTokens") + || has("cacheReadInputTokens") + || has("cacheWriteInputTokens") + { + bedrock::response::usage(v) + } else if has("input_tokens_details") || has("total_tokens") { + responses::response::usage(v) + } else { + anthropic::response::usage(v) + } +} + fn memfind(hay: &[u8], needle: &[u8]) -> bool { find_at(hay, needle, 0).is_some() } @@ -496,6 +436,39 @@ mod tests { assert_eq!((u.input, u.output), (11, 22)); } + #[test] + fn chat_cache_writes_are_also_part_of_the_prompt() { + let u = sniff(&[r#"{"usage":{"prompt_tokens":1000,"completion_tokens":50, + "prompt_tokens_details":{"cached_tokens":600,"cache_write_tokens":300}, + "completion_tokens_details":{"reasoning_tokens":20}}}"#]) + .unwrap(); + assert_eq!( + (u.input, u.cache_read, u.cache_write, u.output, u.reasoning), + (100, 600, 300, 50, 20) + ); + } + + #[test] + fn the_sniffer_and_the_dialect_read_a_usage_object_the_same_way() { + // 同一个对象,旁路嗅探和方言转换得出同一组数 —— 换算只有一处 + let anthropic = serde_json::json!({"input_tokens":10,"cache_creation_input_tokens":2000, + "cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":2000}}); + let responses = serde_json::json!({"input_tokens":5000,"output_tokens":300,"total_tokens":5300, + "input_tokens_details":{"cached_tokens":4000}}); + let bedrock = + serde_json::json!({"inputTokens":60,"outputTokens":20,"cacheReadInputTokens":40}); + for (v, parsed) in [ + (&anthropic, anthropic::response::usage(&anthropic)), + (&responses, responses::response::usage(&responses)), + (&bedrock, bedrock::response::usage(&bedrock)), + ] { + assert_eq!(read(v), parsed, "{v}"); + let sniffed = sniff(&[&format!(r#"{{"usage":{v}}}"#)]).unwrap(); + assert_eq!(sniffed, parsed, "{v}"); + } + assert!(read(&anthropic).cache_1h); + } + #[test] fn an_incomplete_usage_object_at_the_very_end_is_not_half_parsed() { // 上游中途断了。**半个 usage 比没有 usage 危险** —— 它会变成一个 diff --git a/crates/tw-dialect/tests/layer_one.rs b/crates/tw-dialect/tests/layer_one.rs new file mode 100644 index 00000000..ef35d5d7 --- /dev/null +++ b/crates/tw-dialect/tests/layer_one.rs @@ -0,0 +1,60 @@ +//! 第一层(企业版依赖的那几个 crate)只准依赖彼此。 +//! +//! 企业版钉 core 的 tag、只声明第一层。第一层里谁依赖了一个第二层的 crate, +//! 企业版就会连带编进桌面网关的东西 —— tw-guard 为了一个打码函数把 tw-secret +//! 带进企业版,就是这么发生的。名单和根 `Cargo.toml` 里的「第一层」一致。 + +use std::process::Command; + +use serde_json::Value; + +const LAYER_ONE: &[&str] = &["tw-dialect", "tw-guard", "tw-breaker"]; + +#[test] +fn layer_one_depends_only_on_itself() { + let out = Command::new(env!("CARGO")) + .args([ + "metadata", + "--format-version", + "1", + "--no-deps", + "--offline", + ]) + .current_dir(env!("CARGO_MANIFEST_DIR")) + .output() + .expect("run cargo metadata"); + assert!( + out.status.success(), + "cargo metadata failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + let meta: Value = serde_json::from_slice(&out.stdout).expect("cargo metadata is JSON"); + let packages = meta["packages"].as_array().expect("packages"); + + // 工作区里的每一个成员都是 core 自己的 crate + let ours: Vec<&str> = packages.iter().filter_map(|p| p["name"].as_str()).collect(); + for name in LAYER_ONE { + assert!( + ours.contains(name), + "{name} is no longer a workspace member" + ); + } + + let mut wrong = Vec::new(); + for p in packages { + let name = p["name"].as_str().unwrap_or_default(); + if !LAYER_ONE.contains(&name) { + continue; + } + for d in p["dependencies"].as_array().into_iter().flatten() { + let dep = d["name"].as_str().unwrap_or_default(); + if ours.contains(&dep) && !LAYER_ONE.contains(&dep) { + wrong.push(format!("{name} → {dep}")); + } + } + } + assert!( + wrong.is_empty(), + "layer one reaches into layer two: {wrong:?}" + ); +} diff --git a/crates/tw-gateway/Cargo.toml b/crates/tw-gateway/Cargo.toml index d4c09d13..cd2c752f 100644 --- a/crates/tw-gateway/Cargo.toml +++ b/crates/tw-gateway/Cargo.toml @@ -38,8 +38,6 @@ rand = { workspace = true } uuid = { workspace = true } tw-guard = { workspace = true } tw-dialect = { workspace = true } -tw-upstream = { workspace = true } -tw-wire = { workspace = true } thiserror = { workspace = true } tokio = { workspace = true } tracing = { workspace = true } diff --git a/crates/tw-gateway/src/access.rs b/crates/tw-gateway/src/access.rs index 5517d17f..fe5e0bf1 100644 --- a/crates/tw-gateway/src/access.rs +++ b/crates/tw-gateway/src/access.rs @@ -6,7 +6,7 @@ use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; -pub use tw_types::PRIVATE_RANGES; +pub use tw_config::PRIVATE_RANGES; /// 一条 CIDR。自己解析而不是引一个 crate —— 这里只需要「一个 IP 在不在 /// 这个段里」,而多一个依赖就多一份要跟着升级的东西。 diff --git a/crates/tw-gateway/src/ending.rs b/crates/tw-gateway/src/ending.rs index 67adb2f7..8661b31b 100644 --- a/crates/tw-gateway/src/ending.rs +++ b/crates/tw-gateway/src/ending.rs @@ -23,8 +23,8 @@ use std::time::Instant; use crate::bodies::{BodyKind, BodyRecord, BodySender, ResponseTap}; +use tw_dialect::usage::{Sniffer, Usage}; use tw_types::{Msg, msg}; -use tw_wire::usage::{Sniffer, Usage}; /// 一个还欠着结局的请求。 /// diff --git a/crates/tw-gateway/src/fixture.rs b/crates/tw-gateway/src/fixture.rs index f1d117d5..cc682ddf 100644 --- a/crates/tw-gateway/src/fixture.rs +++ b/crates/tw-gateway/src/fixture.rs @@ -112,7 +112,7 @@ pub fn extract(request: &Recorded, response: &Recorded) -> Extracted { } // ---- 响应侧:同样复用线上那个嗅探器 - let mut sniffer = tw_wire::usage::Sniffer::new(); + let mut sniffer = tw_dialect::usage::Sniffer::new(); sniffer.feed(response.body.as_bytes()); out.usage = sniffer .finish() diff --git a/crates/tw-gateway/src/forward.rs b/crates/tw-gateway/src/forward.rs index d688820e..63fa8227 100644 --- a/crates/tw-gateway/src/forward.rs +++ b/crates/tw-gateway/src/forward.rs @@ -6,11 +6,115 @@ //! 改写都可能是缓存杀手。 use bytes::Bytes; -pub use tw_upstream::*; +use http::{HeaderMap, HeaderName, HeaderValue}; +pub use tw_dialect::url::upstream_url; use crate::error::GatewayError; use tw_types::msg; +/// 这些头是「我们和客户端之间」的,不该转给上游。 +/// +/// `x-stainless-timeout` 那条不显然:客户端 SDK 自带的超时头传到上游, +/// 会让上游按客户端的超时提前断流,表现为莫名其妙的截断。 +pub const STRIP: &[&str] = &[ + "host", + "authorization", + "x-api-key", + "x-goog-api-key", + "content-length", + "connection", + "accept-encoding", + "x-stainless-timeout", +]; + +pub fn should_strip(name: &HeaderName) -> bool { + let n = name.as_str(); + // `x-thinkwatch-*` 是客户端写给网关的(接管 Codex 时写进去的 + // `X-ThinkWatch-Client`),上游不该看见 + STRIP.contains(&n) || n.starts_with("x-thinkwatch-") +} + +/// 把这家上游的请求头放上去。**凭据就在里面**(见 `tw_config::credential`)。 +/// +/// **WS 升级那条路也走同一份** `Provider::outbound_headers`:各写一份的话, +/// 两条路迟早会在「Gemini 用哪个头」这种事上不一致,而那时只有一条路是对的。 +pub fn apply_headers( + builder: reqwest::RequestBuilder, + headers: &[(String, String)], +) -> reqwest::RequestBuilder { + let mut b = builder; + for (name, value) in headers { + b = b.header(name.as_str(), value.as_str()); + } + b +} + +/// 客户端带来的这个头,是不是被这家上游配置的同名头盖掉了。 +/// +/// **盖掉,而不是并存。**配置里写的 `anthropic-version` 和客户端自己带的 +/// 那一个同时发出去,上游收到的是两个值 —— 有的取第一个、有的直接 400。 +pub fn overridden(headers: &[(String, String)], name: &str) -> bool { + headers.iter().any(|(n, _)| n.eq_ignore_ascii_case(name)) +} + +/// 把客户端的请求头搬到上游请求上,剔掉不该走的那些。 +pub fn forward_headers( + builder: reqwest::RequestBuilder, + incoming: &HeaderMap, +) -> reqwest::RequestBuilder { + forward_headers_filtered(builder, incoming, |_| true) +} + +/// 同上,但再过一道调用方给的筛子。 +/// +/// 方言互转要用它(M6+):翻译到另一边之后,方言专属的头全是 +/// 噪音,而有些 OpenAI 兼容实现会因为不认识的头直接 400。 +pub fn forward_headers_filtered( + builder: reqwest::RequestBuilder, + incoming: &HeaderMap, + keep: impl Fn(&str) -> bool, +) -> reqwest::RequestBuilder { + let mut b = builder; + for (name, value) in incoming.iter() { + if should_strip(name) || !keep(name.as_str()) { + continue; + } + b = b.header(name.clone(), value.clone()); + } + b +} + +/// 上游响应里也有不该原样回给客户端的头。 +pub fn response_headers(upstream: &reqwest::header::HeaderMap) -> HeaderMap { + let mut out = HeaderMap::new(); + for (name, value) in upstream.iter() { + let n = name.as_str(); + // content-length 会和我们重新分块的 body 对不上; + // transfer-encoding 由 axum 自己决定。 + if matches!(n, "content-length" | "transfer-encoding" | "connection") { + continue; + } + if let (Ok(k), Ok(v)) = ( + HeaderName::from_bytes(name.as_ref()), + HeaderValue::from_bytes(value.as_bytes()), + ) { + out.insert(k, v); + } + } + out +} + +/// Gemini 的模型写在路径里:`/v1beta/models/{model}:动作` 换成另一个模型 +pub fn gemini_path_with_model(path: &str, model: &str) -> String { + let Some((head, rest)) = path.split_once("/models/") else { + return path.to_string(); + }; + match rest.rsplit_once(':') { + Some((_, action)) => format!("{head}/models/{model}:{action}"), + None => path.to_string(), + } +} + /// 按规则改写直通的请求体。转换的请求改在中间表示上(见 `translate::apply_set`)。 /// /// **`set` 为空时原样返回,一个字节都不碰**。改写是用户显式要求 @@ -162,6 +266,63 @@ pub fn check_body_size(body: &Bytes, max: usize) -> Result<(), GatewayError> { mod tests { use super::*; + #[test] + fn headers_meant_for_the_gateway_never_reach_the_upstream() { + assert!(should_strip(&HeaderName::from_static( + "x-thinkwatch-client" + ))); + } + + #[test] + fn a_configured_header_replaces_the_one_the_client_sent() { + let configured = vec![("Anthropic-Version".to_string(), "2023-06-01".to_string())]; + assert!(overridden(&configured, "anthropic-version")); + assert!(!overridden(&configured, "anthropic-beta")); + } + + #[test] + fn our_own_auth_headers_never_reach_the_upstream() { + // 客户端带的是**我们的**网关密钥。原样转出去等于把它送给中转站。 + for h in ["authorization", "x-api-key", "x-goog-api-key"] { + assert!(should_strip(&HeaderName::from_static(h)), "{h} 应该被剔掉"); + } + } + + #[test] + fn client_sdk_timeout_headers_are_stripped() { + // 传给上游会让它按客户端的超时提前断流,表现为莫名其妙的截断。 + assert!(should_strip(&HeaderName::from_static( + "x-stainless-timeout" + ))); + } + + #[test] + fn dialect_headers_are_kept() { + // anthropic-version / anthropic-beta 是上游要认的,剔掉就废了。 + for h in ["anthropic-version", "anthropic-beta", "content-type"] { + assert!(!should_strip(&HeaderName::from_static(h)), "{h} 不该被剔掉"); + } + } + + #[test] + fn response_drops_length_and_framing_headers() { + let mut up = reqwest::header::HeaderMap::new(); + up.insert("content-length", HeaderValue::from_static("123")); + up.insert( + "content-type", + HeaderValue::from_static("text/event-stream"), + ); + up.insert( + "anthropic-ratelimit-unified-5h-utilization", + HeaderValue::from_static("0.62"), + ); + let out = response_headers(&up); + assert!(!out.contains_key("content-length")); + assert_eq!(out.get("content-type").unwrap(), "text/event-stream"); + // 订阅额度的头必须留着 —— 那是白捡的数据来源。 + assert!(out.contains_key("anthropic-ratelimit-unified-5h-utilization")); + } + #[test] fn an_empty_set_does_not_touch_a_single_byte() { // 出站直通。cc-switch 那次把缓存命中率从 99% 打到 20%, diff --git a/crates/tw-guard/Cargo.toml b/crates/tw-guard/Cargo.toml index 2dab9434..ad64a542 100644 --- a/crates/tw-guard/Cargo.toml +++ b/crates/tw-guard/Cargo.toml @@ -13,7 +13,6 @@ base64 = { workspace = true } serde_json = { workspace = true } regex = { workspace = true } thiserror = { workspace = true } -tw-secret = { workspace = true } serde_yaml_ng = { workspace = true } tw-dialect = { workspace = true } diff --git a/crates/tw-guard/src/redact/rules.rs b/crates/tw-guard/src/redact/rules.rs index 04920458..11bf40f8 100644 --- a/crates/tw-guard/src/redact/rules.rs +++ b/crates/tw-guard/src/redact/rules.rs @@ -800,7 +800,23 @@ pub fn masked(rule: &Rule, value: &str) -> String { if rule.kind() == Kind::Internal { return value.to_string(); } - tw_secret::mask_secret(value) + mask(value) +} + +/// 留头 5 尾 4,中间省略:`sk-a…7f9c`。 +/// +/// **按字符切,不按字节** —— 一个中文字符落在切口上,按字节切就是 panic。 +fn mask(s: &str) -> String { + const HEAD: usize = 5; + const TAIL: usize = 4; + let n = s.chars().count(); + // 太短的串留不出信息量,整串打掉。这也覆盖了空串。 + if n <= HEAD + TAIL + 1 { + return "…".repeat(n.min(3)); + } + let head: String = s.chars().take(HEAD).collect(); + let tail: String = s.chars().skip(n - TAIL).collect(); + format!("{head}…{tail}") } /// 一次扫描按「哪条规则 × 哪个值」合起来的结果,给事件和日志用。 @@ -837,6 +853,14 @@ pub fn findings(text: &str, hits: &[Hit]) -> Vec { mod tests { use super::*; + #[test] + fn a_reported_value_keeps_only_its_ends_and_never_splits_a_character() { + assert_eq!(mask("sk-ant-api03-abcdef7f9c"), "sk-an…7f9c"); + assert_eq!(mask("密钥密钥密钥密钥密钥密钥"), "密钥密钥密…密钥密钥"); + assert_eq!(mask("short"), "………"); + assert_eq!(mask(""), ""); + } + fn all() -> RuleSet { RuleSet::only(&BUILTINS.iter().map(|b| b.id).collect::>()) } diff --git a/crates/tw-types/Cargo.toml b/crates/tw-types/Cargo.toml index 904228ff..c2287d44 100644 --- a/crates/tw-types/Cargo.toml +++ b/crates/tw-types/Cargo.toml @@ -5,9 +5,10 @@ edition.workspace = true rust-version.workspace = true license.workspace = true repository.workspace = true -description = "Shared types: request and response DTOs, call context, gateway errors" +description = "A message for people: a stable code, its arguments, and the English sentence" [dependencies] serde = { workspace = true } + +[dev-dependencies] serde_json = { workspace = true } -thiserror = { workspace = true } diff --git a/crates/tw-types/src/lib.rs b/crates/tw-types/src/lib.rs index e65900ec..9489257b 100644 --- a/crates/tw-types/src/lib.rs +++ b/crates/tw-types/src/lib.rs @@ -1,7 +1,7 @@ -//! 共享类型:请求/响应 DTO、调用上下文、网关错误、给人看的话。 +//! 给人看的话:[`Msg`] 和造它的 [`msg!`]。 //! -//! 这一层刻意零业务依赖 —— 它是企业版和桌面版都要认的契约, -//! 任何在这里出现的第三方 crate 都会被两边同时背上。 +//! 桌面网关里会造消息的 crate 有一半够不着 tw-api,所以它单独住一个零业务 +//! 依赖的 crate。企业版不用它。 use std::collections::BTreeMap; @@ -74,422 +74,10 @@ macro_rules! msg { }}; } -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ChatCompletionRequest { - pub model: String, - pub messages: Vec, - #[serde(skip_serializing_if = "Option::is_none")] - pub temperature: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub max_tokens: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub stream: Option, - #[serde(flatten)] - pub extra: serde_json::Value, -} - -/// Per-call metadata that is *not* part of the request payload: caller -/// identity for header-template substitution, plus the trace id that -/// correlates the downstream request, the gateway log and the upstream -/// log line. -/// -/// This used to live on `ChatCompletionRequest` as three `#[serde(skip)]` -/// fields. That was wrong in a way that only shows up at the seams: -/// `ChatCompletionRequest` is the *wire format*, and a struct that -/// serializes to the upstream body should not also be the carrier for -/// "who is calling". Every construction site paid for it with three -/// lines of `None`, and anything that legitimately built a request -/// without a caller (cache probes, the protocol prober, Bedrock's -/// internal re-shaping) had to opt out of fields it never wanted. -/// -/// `attrs` is an open dictionary rather than named fields on purpose: -/// the substitution engine only does `{{key}}` → value and does not -/// understand what any key means. Adding `{{team_id}}` to a header -/// template becomes a caller-side change, not a signature change here. -#[derive(Debug, Clone, Default)] -pub struct CallCtx { - /// Forwarded upstream as `x-trace-id` when present (OBS-01). - pub trace_id: Option, - /// Values for `{{...}}` placeholders in custom header templates. - /// Conventional keys: `user_id`, `user_email`. - pub attrs: std::collections::HashMap, -} - -impl CallCtx { - /// Convenience for the common enterprise case: caller identity plus - /// a trace id. Empty/absent values are simply not inserted, so a - /// template referencing a missing key resolves to the empty string - /// (the previous behaviour). - pub fn new( - trace_id: Option, - user_id: Option, - user_email: Option, - ) -> Self { - let mut attrs = std::collections::HashMap::new(); - if let Some(v) = user_id { - attrs.insert("user_id".to_string(), v); - } - if let Some(v) = user_email { - attrs.insert("user_email".to_string(), v); - } - Self { trace_id, attrs } - } - - /// Trace-only context, for internal calls with no caller identity. - pub fn trace(trace_id: impl Into) -> Self { - Self { - trace_id: Some(trace_id.into()), - attrs: std::collections::HashMap::new(), - } - } -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub struct ChatMessage { - pub role: String, - pub content: serde_json::Value, - /// Pass-through bucket for the rest of the OpenAI / Anthropic - /// message envelope: `tool_call_id` (required when `role: "tool"`), - /// `tool_calls` (assistant-side function invocations), `name` - /// (legacy function-call / multi-user labelling), `refusal`, - /// vendor annotations. - /// - /// Without this flatten, serde quietly drops anything we don't - /// declare — the gateway then forwards a stripped message and - /// the upstream 400s with `missing field "tool_call_id"` the - /// first time the conversation uses tools, with no signal that - /// the gateway ate the field on the way through. - /// - /// Construct with `..Default::default()` if only role + content - /// matter so future additions to this struct don't ripple across - /// every literal in the codebase. - #[serde(flatten, default, skip_serializing_if = "is_empty_extras")] - pub extra: serde_json::Value, -} - -fn is_empty_extras(v: &serde_json::Value) -> bool { - matches!(v, serde_json::Value::Null) - || matches!(v, serde_json::Value::Object(o) if o.is_empty()) -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ChatCompletionResponse { - pub id: String, - pub object: String, - pub created: i64, - pub model: String, - pub choices: Vec, - pub usage: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Choice { - pub index: u32, - pub message: ChatMessage, - pub finish_reason: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Usage { - pub prompt_tokens: u32, - pub completion_tokens: u32, - pub total_tokens: u32, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ChatCompletionChunk { - pub id: String, - pub object: String, - pub created: i64, - pub model: String, - pub choices: Vec, - #[serde(skip_serializing_if = "Option::is_none")] - pub usage: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ChunkChoice { - pub index: u32, - pub delta: serde_json::Value, - pub finish_reason: Option, -} - -#[derive(Debug, thiserror::Error)] -pub enum GatewayError { - /// Catch-all upstream failure that doesn't fit one of the more - /// specific variants below. Prefer `ProviderHttpError` / - /// `ProviderTimeout` / `ProviderInvalidResponse` when the cause - /// is known so dashboards can split errors by class instead of - /// regex'ing the message. - #[error("Provider error: {0}")] - ProviderError(String), - /// Upstream returned a non-2xx, non-429, non-401 status. The - /// status is kept structured so error-classifier metrics stay - /// readable and the gateway can classify retry-eligible 5xx - /// versus poison 4xx without parsing the message. - #[error("Provider HTTP {status}: {message}")] - ProviderHttpError { status: u16, message: String }, - /// Upstream took longer than the configured timeout. Distinct - /// from a network drop because the request reached the upstream - /// — only the response was missing in time. - #[error("Provider timeout: {0}")] - ProviderTimeout(String), - /// Upstream responded but the body wasn't parseable as the - /// expected schema (chat completion / messages / etc.). Almost - /// always indicates an upstream incident or a model-specific - /// quirk, and is poison for retries — failover should still - /// happen but retry against the SAME upstream is pointless. - #[error("Provider returned invalid response: {0}")] - ProviderInvalidResponse(String), - #[error("Request transform error: {0}")] - TransformError(String), - #[error("Network error: {0}")] - NetworkError(String), - /// Upstream returned 429. `retry_after_secs` captures the value - /// parsed off the upstream's `Retry-After` header (delta-seconds - /// form per RFC 7231) so we can echo it to our client and stop - /// clients spinning into a tight retry loop while quota is still - /// burning. `None` means the upstream didn't tell us — we pick a - /// conservative default downstream. - #[error("Rate limited by upstream")] - UpstreamRateLimited { retry_after_secs: Option }, - #[error("Authentication failed with upstream")] - UpstreamAuthError, - /// Local rate limit / budget cap was hit. The String is the rule - /// label so the response body can tell the caller WHICH limit - /// fired (e.g. "user requests/5h", "api_key tokens/1d", - /// "monthly budget"). Maps to 429 in `IntoResponse`. - #[error("Rate limited: {0}")] - LocalRateLimited(String), - /// Refused by the gateway's own policy — a tool call the upstream - /// returned matched a rule set to cut it. Neither the caller's fault - /// (not 400) nor the upstream failing (not 502): the answer exists - /// and the gateway will not hand it over. Maps to 403. - #[error("Blocked by policy: {0}")] - PolicyBlocked(String), -} - -impl GatewayError { - /// Canonical HTTP status code for this error variant. Single source - /// of truth shared between the response wire status - /// (`GatewayErrorResponse::into_response`), the non-streaming log - /// row writer, and the streaming `StreamOutcome::UpstreamError` - /// path — drift between any of these would make the gateway_logs - /// `status_code` field disagree with what the client saw, leading - /// operators to chase phantom 502s for what was actually a 429. - pub fn status_code(&self) -> i64 { - match self { - GatewayError::ProviderError(_) => 502, - GatewayError::ProviderHttpError { status, .. } => i64::from(*status), - GatewayError::ProviderTimeout(_) => 504, - GatewayError::ProviderInvalidResponse(_) => 502, - GatewayError::TransformError(_) => 400, - GatewayError::NetworkError(_) => 502, - GatewayError::UpstreamRateLimited { .. } | GatewayError::LocalRateLimited(_) => 429, - GatewayError::UpstreamAuthError => 401, - GatewayError::PolicyBlocked(_) => 403, - } - } - - /// Short stable tag derived from the variant name. Used as a - /// dashboard-friendly label (Prometheus value, gateway_logs - /// `error_type` field). Never localize — operators grep on these. - pub fn error_tag(&self) -> &'static str { - match self { - GatewayError::ProviderError(_) => "ProviderError", - GatewayError::ProviderHttpError { .. } => "ProviderHttpError", - GatewayError::ProviderTimeout(_) => "ProviderTimeout", - GatewayError::ProviderInvalidResponse(_) => "ProviderInvalidResponse", - GatewayError::TransformError(_) => "TransformError", - GatewayError::NetworkError(_) => "NetworkError", - GatewayError::UpstreamRateLimited { .. } => "UpstreamRateLimited", - GatewayError::LocalRateLimited(_) => "LocalRateLimited", - GatewayError::UpstreamAuthError => "UpstreamAuthError", - GatewayError::PolicyBlocked(_) => "PolicyBlocked", - } - } - - /// Hint, in seconds, for `Retry-After` on a 429 response. For - /// upstream limits we echo the upstream's own header when present; - /// for local limits we fall back to a conservative 30s so naive - /// clients don't spin into a tight retry loop while the bucket is - /// still refilling. Capped at one hour to keep the header sane - /// even when an upstream returns an absurd value. - pub fn retry_after_secs(&self) -> Option { - const HARD_CAP_SECS: u32 = 3600; - const LOCAL_DEFAULT_SECS: u32 = 30; - match self { - GatewayError::UpstreamRateLimited { retry_after_secs } => { - retry_after_secs.map(|s| s.min(HARD_CAP_SECS)) - } - GatewayError::LocalRateLimited(_) => Some(LOCAL_DEFAULT_SECS), - _ => None, - } - } -} - -/// Parse RFC 7231 `Retry-After` (delta-seconds form). HTTP-date is -/// intentionally not supported — the absolute-time variant is -/// effectively unused by upstream LLM providers and would require -/// dragging in a date parser plus clock-skew handling for a vanishingly -/// rare path. Bad input silently maps to None, mirroring how a missing -/// header is treated; a malformed header is no better than no header. -pub fn parse_retry_after_seconds(value: &str) -> Option { - value.trim().parse::().ok() -} - -/// Replace every `{{key}}` occurrence in `template` with `attrs[key]`, -/// or with the empty string when the key is absent. -pub fn substitute_template( - template: &str, - attrs: &std::collections::HashMap, -) -> String { - // Fast path: most header values carry no placeholder at all. - if !template.contains("{{") { - return template.to_string(); - } - let mut out = String::with_capacity(template.len()); - let mut rest = template; - while let Some(start) = rest.find("{{") { - out.push_str(&rest[..start]); - let after = &rest[start + 2..]; - match after.find("}}") { - Some(end) => { - let key = after[..end].trim(); - if let Some(v) = attrs.get(key) { - out.push_str(v); - } - rest = &after[end + 2..]; - } - // Unterminated `{{` — emit the rest verbatim rather than - // silently truncating a header value. - None => { - out.push_str(&rest[start..]); - return out; - } - } - } - out.push_str(rest); - out -} - -/// 日志留多久。 -/// -/// **两个期限,因为两种东西的代价差三个数量级。**请求和响应的正文一条 -/// 几十 KB,一天就能堆出几百 MB;而一行记录(时刻、模型、用量、金额) -/// 只有几百字节,留一个季度也不过几十 MB。用一个期限管住两者,等于 -/// 要么早早丢掉「上个月花了多少」,要么让磁盘替正文买单。 -/// -/// **总量上限是给突发准备的。**按天数算出来的占用取决于用量,而用量 -/// 会有一周十倍于平时的时候 —— 没有上限的话,那一周会把磁盘吃光, -/// 而用户直到硬盘满了才知道。 -/// -/// 住在 tw-types 是因为配置和存储层都要认它。 -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct Retention { - /// 请求和响应的正文留几天。**大头在这儿** - #[serde(default = "d_body_days")] - pub body_days: u64, - /// 一行记录留几天。它撑着「上个月花了多少」那类问题 - #[serde(default = "d_row_days")] - pub row_days: u64, - /// 正文总共最多占多少字节。超了从最旧的整天开始删 - #[serde(default = "d_body_max_bytes")] - pub body_max_bytes: u64, -} - -fn d_body_days() -> u64 { - 7 -} -fn d_row_days() -> u64 { - 90 -} -fn d_body_max_bytes() -> u64 { - 2 * 1024 * 1024 * 1024 -} - -impl Default for Retention { - fn default() -> Self { - Self { - body_days: d_body_days(), - row_days: d_row_days(), - body_max_bytes: d_body_max_bytes(), - } - } -} - -/// 放行网段的默认名单:RFC1918 的三个私网段和 IPv6 的唯一本地地址段。 -/// -/// **不含回环。**本机永远放行(见 tw-gateway 的 `AllowList::allows`),写进 -/// 名单只会在界面上多出两条删了也不起作用的条目。 -/// -/// 住在这里是因为配置层要用它填默认值,控制面要把它交给界面「恢复默认」—— -/// 而它只是一组字符串。 -pub const PRIVATE_RANGES: &[&str] = &["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"]; - #[cfg(test)] -mod call_ctx_tests { +mod tests { use super::*; - fn attrs(pairs: &[(&str, &str)]) -> std::collections::HashMap { - pairs - .iter() - .map(|(k, v)| (k.to_string(), v.to_string())) - .collect() - } - - #[test] - fn a_policy_refusal_is_forbidden_not_a_bad_request_or_an_upstream_failure() { - let e = GatewayError::PolicyBlocked("the tool call matched a rule".into()); - assert_eq!(e.status_code(), 403); - assert_eq!(e.error_tag(), "PolicyBlocked"); - assert_eq!(e.retry_after_secs(), None); - } - - #[test] - fn substitutes_known_keys() { - let a = attrs(&[("user_id", "u1"), ("user_email", "a@b.c")]); - assert_eq!(substitute_template("{{user_id}}", &a), "u1"); - assert_eq!( - substitute_template("id={{user_id}};mail={{user_email}}", &a), - "id=u1;mail=a@b.c" - ); - } - - #[test] - fn missing_key_becomes_empty_not_literal() { - // The old implementation had the same behaviour via `unwrap_or("")`. - // Keeping it: a literal `{{user_id}}` reaching the upstream looks - // like a working config and is harder to diagnose than a blank. - assert_eq!(substitute_template("{{nope}}", &attrs(&[])), ""); - assert_eq!(substitute_template("x{{nope}}y", &attrs(&[])), "xy"); - } - - #[test] - fn passes_through_values_without_placeholders() { - let a = attrs(&[("user_id", "u1")]); - assert_eq!(substitute_template("plain", &a), "plain"); - assert_eq!(substitute_template("", &a), ""); - } - - #[test] - fn unterminated_placeholder_is_kept_verbatim() { - // Truncating here would silently shorten a header value. - assert_eq!(substitute_template("a{{user", &attrs(&[])), "a{{user"); - } - - #[test] - fn new_skips_absent_identity() { - let ctx = CallCtx::new(Some("t1".into()), None, Some("a@b.c".into())); - assert_eq!(ctx.trace_id.as_deref(), Some("t1")); - assert!(!ctx.attrs.contains_key("user_id")); - assert_eq!( - ctx.attrs.get("user_email").map(String::as_str), - Some("a@b.c") - ); - } - #[test] fn a_message_carries_its_arguments_beside_the_sentence() { // 界面要照自己的语序重写这句话,所以参数必须单独拿得到 —— diff --git a/crates/tw-upstream/Cargo.toml b/crates/tw-upstream/Cargo.toml deleted file mode 100644 index da344136..00000000 --- a/crates/tw-upstream/Cargo.toml +++ /dev/null @@ -1,42 +0,0 @@ -[package] -name = "tw-upstream" -version.workspace = true -edition.workspace = true -rust-version.workspace = true -license.workspace = true -repository.workspace = true -description = "Talking to an upstream: URL assembly and header handling, shared by both gateways" - -[dependencies] -# HeaderMap 和 HeaderName。**不要 axum 也不要 reqwest** —— 共享层不该 -# 规定下游用哪个 HTTP 框架,而两者的 HeaderMap 本来就都是这个 crate 的 -http = "1" -reqwest = { workspace = true } - -# ── Bedrock:SigV4 签名、eventstream 拆帧。桌面版不接它 ───────── -# 这一串会连同一个 http 0.2 一起进来,所以关在 feature 后面 -aws-sigv4 = { workspace = true, optional = true } -aws-credential-types = { workspace = true, optional = true } -aws-smithy-eventstream = { workspace = true, optional = true } -bytes = { workspace = true, optional = true } -serde_json = { workspace = true, optional = true } - -[features] -bedrock = [ - "dep:aws-sigv4", - "dep:aws-credential-types", - "dep:aws-smithy-eventstream", - "dep:bytes", - "dep:serde_json", -] - -[dev-dependencies] -tokio = { version = "1", features = ["rt", "macros"] } -aws-smithy-types = { workspace = true } -# 从线上的二进制帧一路走到客户端格式,证明拆帧和方言的约定对得上 -tw-dialect = { workspace = true } -tw-wire = { workspace = true } - -[[test]] -name = "bedrock_stream" -required-features = ["bedrock"] diff --git a/crates/tw-upstream/src/eventstream.rs b/crates/tw-upstream/src/eventstream.rs deleted file mode 100644 index c9e7df1f..00000000 --- a/crates/tw-upstream/src/eventstream.rs +++ /dev/null @@ -1,226 +0,0 @@ -//! AWS eventstream → SSE。 -//! -//! Bedrock 的 ConverseStream 不是 SSE,是 AWS eventstream 的二进制帧: -//! 每帧一段前导(总长、头长、前导 CRC)、一串带类型的头、载荷、整帧 CRC。 -//! 另外四种方言的流都是 SSE,下游的一切 —— 方言转换、usage 嗅探、流的 -//! 组装 —— 都按 SSE 读。所以**在字节进门的地方就把它转成 SSE**,后面 -//! 不需要知道 Bedrock 有什么不同。 -//! -//! 转出来的形状是 `tw-dialect` 约定好的:`:event-type` 头进 `event:`, -//! 载荷 JSON 进 `data:`。 -//! -//! **帧可能被切在任意一个字节上**,没收齐的那部分留到下一块。CRC 由 -//! `aws-smithy-eventstream` 校验 —— 校验不过就是坏了,不要猜着往下读。 - -use aws_smithy_eventstream::frame::{DecodedFrame, MessageFrameDecoder}; -use bytes::{Buf, BytesMut}; - -/// 流里出的错。 -/// -/// **这一层不认识调用方的错误体系**,理由同 [`crate::sigv4::SignError`]。 -#[derive(Debug)] -pub enum StreamError { - /// 帧坏了:长度不对、CRC 不对 - Malformed(String), - /// 上游在流里报了错(`:message-type` 是 `exception` 或 `error`), - /// 比如半路被限流。`kind` 是 AWS 的异常名 - Upstream { kind: String, message: String }, -} - -impl std::fmt::Display for StreamError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - StreamError::Malformed(m) => write!(f, "malformed AWS eventstream frame: {m}"), - StreamError::Upstream { kind, message } => write!(f, "{kind}: {message}"), - } - } -} - -impl std::error::Error for StreamError {} - -/// 一边收一边转。 -#[derive(Debug, Default)] -pub struct Transcoder { - buf: BytesMut, - decoder: MessageFrameDecoder, -} - -impl Transcoder { - pub fn new() -> Self { - Self::default() - } - - /// 喂一块,返回这一块里收齐了的所有帧,已经写成 SSE 文本。 - /// - /// 出错之后这个转码器就不该再用了:帧的边界已经对不上。 - pub fn feed(&mut self, chunk: &[u8]) -> Result, StreamError> { - self.buf.extend_from_slice(chunk); - let mut out = Vec::new(); - loop { - let before = self.buf.remaining(); - let frame = self - .decoder - .decode_frame(&mut self.buf) - .map_err(|e| StreamError::Malformed(e.to_string()))?; - match frame { - DecodedFrame::Complete(message) => { - let header = |name: &str| { - message - .headers() - .iter() - .find(|h| h.name().as_str() == name) - .and_then(|h| h.value().as_string().ok()) - .map(|s| s.as_str().to_string()) - }; - let payload = String::from_utf8_lossy(message.payload()); - match header(":message-type").as_deref() { - Some("event") | None => { - let event = header(":event-type").unwrap_or_default(); - write_frame(&mut out, &event, &payload); - } - Some("exception") => { - return Err(StreamError::Upstream { - kind: header(":exception-type").unwrap_or_default(), - message: message_of(&payload), - }); - } - Some(other) => { - return Err(StreamError::Upstream { - kind: header(":error-code").unwrap_or_else(|| other.to_string()), - message: header(":error-message").unwrap_or_default(), - }); - } - } - } - // 前导读走了但整帧没收齐时,缓冲区也会变短 —— 只有什么都没 - // 读走才是真的要等下一块 - DecodedFrame::Incomplete if self.buf.remaining() == before => return Ok(out), - DecodedFrame::Incomplete => {} - } - } - } -} - -/// 写一帧 SSE。载荷按行拆成多个 `data:` —— SSE 读回来会用换行拼上, -/// 多行 JSON 原样还原。 -fn write_frame(out: &mut Vec, event: &str, payload: &str) { - out.extend_from_slice(b"event: "); - out.extend_from_slice(event.as_bytes()); - out.push(b'\n'); - for line in payload.split('\n') { - out.extend_from_slice(b"data: "); - out.extend_from_slice(line.as_bytes()); - out.push(b'\n'); - } - out.push(b'\n'); -} - -/// 异常的载荷是 `{"message": "..."}`;不是的话原样给出。 -fn message_of(payload: &str) -> String { - serde_json::from_str::(payload) - .ok() - .and_then(|v| { - v.get("message") - .or_else(|| v.get("Message")) - .and_then(|m| m.as_str()) - .map(str::to_string) - }) - .unwrap_or_else(|| payload.to_string()) -} - -#[cfg(test)] -mod tests { - use super::*; - use aws_smithy_eventstream::frame::write_message_to; - use aws_smithy_types::event_stream::{Header, HeaderValue, Message}; - - fn event(kind: &str, payload: &str) -> Vec { - let m = Message::new(payload.as_bytes().to_vec()) - .add_header(Header::new( - ":message-type", - HeaderValue::String("event".into()), - )) - .add_header(Header::new( - ":event-type", - HeaderValue::String(kind.to_string().into()), - )) - .add_header(Header::new( - ":content-type", - HeaderValue::String("application/json".into()), - )); - let mut out = Vec::new(); - write_message_to(&m, &mut out).unwrap(); - out - } - - fn exception(kind: &str, message: &str) -> Vec { - let m = Message::new(format!(r#"{{"message":"{message}"}}"#).into_bytes()) - .add_header(Header::new( - ":message-type", - HeaderValue::String("exception".into()), - )) - .add_header(Header::new( - ":exception-type", - HeaderValue::String(kind.to_string().into()), - )); - let mut out = Vec::new(); - write_message_to(&m, &mut out).unwrap(); - out - } - - #[test] - fn each_frame_becomes_one_sse_event() { - let mut wire = event("messageStart", r#"{"role":"assistant"}"#); - wire.extend(event( - "contentBlockDelta", - r#"{"contentBlockIndex":0,"delta":{"text":"晴"}}"#, - )); - let sse = Transcoder::new().feed(&wire).unwrap(); - assert_eq!( - String::from_utf8(sse).unwrap(), - "event: messageStart\ndata: {\"role\":\"assistant\"}\n\n\ - event: contentBlockDelta\ndata: {\"contentBlockIndex\":0,\"delta\":{\"text\":\"晴\"}}\n\n" - ); - } - - #[test] - fn a_frame_cut_on_any_byte_comes_out_whole() { - let mut wire = event("messageStart", r#"{"role":"assistant"}"#); - wire.extend(event( - "metadata", - r#"{"usage":{"inputTokens":3,"outputTokens":5}}"#, - )); - let whole = Transcoder::new().feed(&wire).unwrap(); - // 逐字节喂:前导、头、载荷、CRC 每一处都会被切到 - let mut t = Transcoder::new(); - let mut pieced = Vec::new(); - for b in &wire { - pieced.extend(t.feed(std::slice::from_ref(b)).unwrap()); - } - assert_eq!(pieced, whole); - } - - #[test] - fn an_exception_in_the_stream_is_an_error_not_an_event() { - let mut wire = event("messageStart", r#"{"role":"assistant"}"#); - wire.extend(exception("throttlingException", "Too many requests")); - match Transcoder::new().feed(&wire) { - Err(StreamError::Upstream { kind, message }) => { - assert_eq!(kind, "throttlingException"); - assert_eq!(message, "Too many requests"); - } - other => panic!("expected an upstream error, got {other:?}"), - } - } - - #[test] - fn a_corrupted_frame_is_refused() { - let mut wire = event("messageStart", r#"{"role":"assistant"}"#); - let n = wire.len(); - wire[n - 6] ^= 0xff; // 载荷里改一个字节,整帧 CRC 就对不上 - assert!(matches!( - Transcoder::new().feed(&wire), - Err(StreamError::Malformed(_)) - )); - } -} diff --git a/crates/tw-upstream/src/lib.rs b/crates/tw-upstream/src/lib.rs deleted file mode 100644 index 603e5d84..00000000 --- a/crates/tw-upstream/src/lib.rs +++ /dev/null @@ -1,260 +0,0 @@ -//! 和上游之间这条线上的共用件:URL 怎么拼、头怎么传。 -//! -//! **出站直通**:请求体一个字节都不改。这不只是省事 —— -//! cc-switch 有一次为了兼容性把 `role=system` 消息提到顶层,结果上游的 -//! 前缀缓存命中率从 99% 掉到 20%,而且是静默的,只有账单会涨。任何 body -//! 改写都可能是缓存杀手。 -//! -//! 这一层刻意零业务依赖 —— 它不认识配置从哪来、谁在调用,所以企业版和 -//! 桌面版都能直接用。**不含 HTTP 客户端的构造**:两边的超时和重定向策略 -//! 是相反的(桌面版不设整体超时,因为一个跑六分钟的任务不该被中间层掐断; -//! 企业版设 300 秒并禁止重定向,因为它是多租户而且 base_url 由管理员填), -//! 那是各自的权衡,不是共用件。 - -#[cfg(feature = "bedrock")] -pub mod eventstream; -#[cfg(feature = "bedrock")] -pub mod sigv4; - -use http::{HeaderMap, HeaderName, HeaderValue}; - -/// 这些头是「我们和客户端之间」的,不该转给上游。 -/// -/// `x-stainless-timeout` 那条不显然:客户端 SDK 自带的超时头传到上游, -/// 会让上游按客户端的超时提前断流,表现为莫名其妙的截断。 -pub const STRIP: &[&str] = &[ - "host", - "authorization", - "x-api-key", - "x-goog-api-key", - "content-length", - "connection", - "accept-encoding", - "x-stainless-timeout", -]; - -pub fn should_strip(name: &HeaderName) -> bool { - let n = name.as_str(); - // `x-thinkwatch-*` 是客户端写给网关的(接管 Codex 时写进去的 - // `X-ThinkWatch-Client`),上游不该看见 - STRIP.contains(&n) || n.starts_with("x-thinkwatch-") -} - -/// 把这家上游的请求头放上去。**凭据就在里面**(见 `tw_config::credential`)。 -/// -/// **WS 升级那条路也走同一份** `Provider::outbound_headers`:各写一份的话, -/// 两条路迟早会在「Gemini 用哪个头」这种事上不一致,而那时只有一条路是对的。 -pub fn apply_headers( - builder: reqwest::RequestBuilder, - headers: &[(String, String)], -) -> reqwest::RequestBuilder { - let mut b = builder; - for (name, value) in headers { - b = b.header(name.as_str(), value.as_str()); - } - b -} - -/// 客户端带来的这个头,是不是被这家上游配置的同名头盖掉了。 -/// -/// **盖掉,而不是并存。**配置里写的 `anthropic-version` 和客户端自己带的 -/// 那一个同时发出去,上游收到的是两个值 —— 有的取第一个、有的直接 400。 -pub fn overridden(headers: &[(String, String)], name: &str) -> bool { - headers.iter().any(|(n, _)| n.eq_ignore_ascii_case(name)) -} - -/// 把客户端的请求头搬到上游请求上,剔掉不该走的那些。 -pub fn forward_headers( - builder: reqwest::RequestBuilder, - incoming: &HeaderMap, -) -> reqwest::RequestBuilder { - forward_headers_filtered(builder, incoming, |_| true) -} - -/// 同上,但再过一道调用方给的筛子。 -/// -/// 方言互转要用它(M6+):翻译到另一边之后,方言专属的头全是 -/// 噪音,而有些 OpenAI 兼容实现会因为不认识的头直接 400。 -pub fn forward_headers_filtered( - builder: reqwest::RequestBuilder, - incoming: &HeaderMap, - keep: impl Fn(&str) -> bool, -) -> reqwest::RequestBuilder { - let mut b = builder; - for (name, value) in incoming.iter() { - if should_strip(name) || !keep(name.as_str()) { - continue; - } - b = b.header(name.clone(), value.clone()); - } - b -} - -/// 拼上游 URL。base_url 的尾斜杠在这里统一吃掉 —— 从浏览器地址栏粘一个 -/// URL 就会白送一个尾斜杠,而 `https://host//v1/messages` 换来的是一个 -/// 光秃秃的 404。 -pub fn upstream_url(base_url: &str, path: &str, query: Option<&str>) -> String { - let base = base_url.trim_end_matches('/'); - let path = path.trim_start_matches('/'); - let query = query.map(without_gateway_key); - match query { - Some(q) if !q.is_empty() => format!("{base}/{path}?{q}"), - _ => format!("{base}/{path}"), - } -} - -/// 去掉查询串里的 `key=`。 -/// -/// **那是网关密钥。**Gemini 的 REST 写法把密钥放在查询串里,网关认完身份之后 -/// 原样把整个查询串拼到上游地址上,等于把它发给了上游。上游的凭据走请求头, -/// 用不着这一项。 -fn without_gateway_key(query: &str) -> String { - query - .split('&') - .filter(|pair| *pair != "key" && !pair.starts_with("key=")) - .collect::>() - .join("&") -} - -/// 上游响应里也有不该原样回给客户端的头。 -pub fn response_headers(upstream: &reqwest::header::HeaderMap) -> HeaderMap { - let mut out = HeaderMap::new(); - for (name, value) in upstream.iter() { - let n = name.as_str(); - // content-length 会和我们重新分块的 body 对不上; - // transfer-encoding 由 axum 自己决定。 - if matches!(n, "content-length" | "transfer-encoding" | "connection") { - continue; - } - if let (Ok(k), Ok(v)) = ( - HeaderName::from_bytes(name.as_ref()), - HeaderValue::from_bytes(value.as_bytes()), - ) { - out.insert(k, v); - } - } - out -} - -/// Gemini 的模型写在路径里:`/v1beta/models/{model}:动作` 换成另一个模型 -pub fn gemini_path_with_model(path: &str, model: &str) -> String { - let Some((head, rest)) = path.split_once("/models/") else { - return path.to_string(); - }; - match rest.rsplit_once(':') { - Some((_, action)) => format!("{head}/models/{model}:{action}"), - None => path.to_string(), - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn trailing_slash_in_base_url_does_not_double_up() { - // 从浏览器粘 URL 会白送一个尾斜杠,而 `//v1/messages` 换来 404。 - assert_eq!( - upstream_url("https://api.example.com/", "/v1/messages", None), - "https://api.example.com/v1/messages" - ); - assert_eq!( - upstream_url("https://api.example.com", "v1/messages", None), - "https://api.example.com/v1/messages" - ); - } - - #[test] - fn query_is_carried_through_but_empty_query_adds_no_question_mark() { - assert_eq!( - upstream_url("https://x.com", "/v1/m", Some("beta=true")), - "https://x.com/v1/m?beta=true" - ); - assert_eq!( - upstream_url("https://x.com", "/v1/m", Some("")), - "https://x.com/v1/m" - ); - } - - #[test] - fn the_gateway_key_in_the_query_never_reaches_the_upstream() { - assert_eq!( - upstream_url( - "https://g.example", - "/v1beta/models/m:generateContent", - Some("key=tw-secret&alt=sse") - ), - "https://g.example/v1beta/models/m:generateContent?alt=sse" - ); - assert_eq!( - upstream_url( - "https://g.example", - "/v1beta/models/m", - Some("key=tw-secret") - ), - "https://g.example/v1beta/models/m" - ); - // 名字只是以 key 开头的参数不受影响 - assert_eq!( - upstream_url("https://g.example", "/x", Some("keyword=a")), - "https://g.example/x?keyword=a" - ); - } - - #[test] - fn headers_meant_for_the_gateway_never_reach_the_upstream() { - assert!(should_strip(&HeaderName::from_static( - "x-thinkwatch-client" - ))); - } - - #[test] - fn a_configured_header_replaces_the_one_the_client_sent() { - let configured = vec![("Anthropic-Version".to_string(), "2023-06-01".to_string())]; - assert!(overridden(&configured, "anthropic-version")); - assert!(!overridden(&configured, "anthropic-beta")); - } - - #[test] - fn our_own_auth_headers_never_reach_the_upstream() { - // 客户端带的是**我们的**网关密钥。原样转出去等于把它送给中转站。 - for h in ["authorization", "x-api-key", "x-goog-api-key"] { - assert!(should_strip(&HeaderName::from_static(h)), "{h} 应该被剔掉"); - } - } - - #[test] - fn client_sdk_timeout_headers_are_stripped() { - // 传给上游会让它按客户端的超时提前断流,表现为莫名其妙的截断。 - assert!(should_strip(&HeaderName::from_static( - "x-stainless-timeout" - ))); - } - - #[test] - fn dialect_headers_are_kept() { - // anthropic-version / anthropic-beta 是上游要认的,剔掉就废了。 - for h in ["anthropic-version", "anthropic-beta", "content-type"] { - assert!(!should_strip(&HeaderName::from_static(h)), "{h} 不该被剔掉"); - } - } - - #[test] - fn response_drops_length_and_framing_headers() { - let mut up = reqwest::header::HeaderMap::new(); - up.insert("content-length", HeaderValue::from_static("123")); - up.insert( - "content-type", - HeaderValue::from_static("text/event-stream"), - ); - up.insert( - "anthropic-ratelimit-unified-5h-utilization", - HeaderValue::from_static("0.62"), - ); - let out = response_headers(&up); - assert!(!out.contains_key("content-length")); - assert_eq!(out.get("content-type").unwrap(), "text/event-stream"); - // 订阅额度的头必须留着 —— 那是白捡的数据来源。 - assert!(out.contains_key("anthropic-ratelimit-unified-5h-utilization")); - } -} diff --git a/crates/tw-upstream/src/sigv4.rs b/crates/tw-upstream/src/sigv4.rs deleted file mode 100644 index a47c8149..00000000 --- a/crates/tw-upstream/src/sigv4.rs +++ /dev/null @@ -1,244 +0,0 @@ -//! AWS SigV4 签名。 -//! -//! Bedrock 是唯一一家不用 bearer token 的上游:每个请求按内容签名,签的是 -//! 方法、URL、时间和请求体的哈希。所以**签名必须在请求体最终定稿之后**, -//! 改一个字节签名就失效。 -//! -//! 桌面版不接 Bedrock,所以这一整套在 `bedrock` feature 后面 —— 否则它会把 -//! `aws-sigv4`、`aws-credential-types`、`aws-smithy-*` 连同一个 `http 0.2` -//! 拖给每一个依赖这个 crate 的人。 - -use std::time::SystemTime; - -use aws_credential_types::Credentials; - -/// 签名过程里出的错。 -/// -/// **这一层不认识调用方的错误体系** —— 企业版有 `GatewayError`,桌面版有 -/// 自己的一套,共享层认识谁都是错的。调用方在边界上 `From` 一下。 -#[derive(Debug)] -pub enum SignError { - /// 拿不到凭据:环境里没有,IMDSv2 也问不出来 - Credentials(String), - /// 签名本身失败 - Signing(String), -} - -impl std::fmt::Display for SignError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - SignError::Credentials(m) => write!(f, "AWS credentials are unavailable: {m}"), - SignError::Signing(m) => write!(f, "SigV4 signing failed: {m}"), - } - } -} - -impl std::error::Error for SignError {} - -/// 一家 Bedrock 上游的签名身份。 -/// -/// 不带密钥时从 EC2 实例元数据(IMDSv2)现取 —— 那是在 AWS 里跑的部署 -/// 该有的样子:凭据由实例角色给,会自动轮换,不落在配置文件里。 -pub struct Signer { - pub region: String, - pub access_key_id: Option, - pub secret_access_key: Option, -} - -/// IMDS 的地址。**是个链路本地地址**,只有在 EC2 里才答得上来。 -const IMDS: &str = "http://169.254.169.254"; - -impl Signer { - /// 签一个请求,返回要加上去的头(`authorization` 和 `x-amz-*`)。 - /// - /// `body` 必须是**最终要发出去的那一份**:签名覆盖请求体的哈希。 - pub async fn sign( - &self, - client: &reqwest::Client, - url: &str, - body: &[u8], - ) -> Result, SignError> { - use aws_sigv4::http_request::{ - PayloadChecksumKind, SignableBody, SignableRequest, SignatureLocation, SigningSettings, - sign, - }; - use aws_sigv4::sign::v4; - - let credentials = match (&self.access_key_id, &self.secret_access_key) { - (Some(ak), Some(sk)) => Credentials::new(ak, sk, None, None, "think-watch"), - _ => self.imdsv2_credentials(client).await?, - }; - - let identity = credentials.into(); - let mut settings = SigningSettings::default(); - settings.payload_checksum_kind = PayloadChecksumKind::XAmzSha256; - settings.signature_location = SignatureLocation::Headers; - - let params = v4::SigningParams::builder() - .identity(&identity) - .region(&self.region) - .name("bedrock") - .time(SystemTime::now()) - .settings(settings) - .build() - .map_err(|e| SignError::Signing(e.to_string()))?; - - let signable = SignableRequest::new( - "POST", - url, - std::iter::once(("content-type", "application/json")), - SignableBody::Bytes(body), - ) - .map_err(|e| SignError::Signing(e.to_string()))?; - - let (instructions, _signature) = sign(signable, ¶ms.into()) - .map_err(|e| SignError::Signing(e.to_string()))? - .into_parts(); - - // 签名库只会往一个 http 请求上写,所以造一个空的接住它 - let mut req = http::Request::builder() - .method("POST") - .uri(url) - .header("content-type", "application/json") - .body(()) - .map_err(|e| SignError::Signing(e.to_string()))?; - instructions.apply_to_request_http1x(&mut req); - - // 只要签出来的那几个。**别的头是调用方的** —— 把整份头带走会 - // 盖掉它自己设的东西 - Ok(req - .headers() - .iter() - .filter(|(n, _)| { - let n = n.as_str(); - n == "authorization" || n.starts_with("x-amz-") - }) - .map(|(n, v)| (n.to_string(), v.to_str().unwrap_or_default().to_string())) - .collect()) - } - - /// 从 EC2 实例元数据取临时凭据。 - /// - /// IMDSv2 是三步:先拿一个有生存期的令牌,再问角色名,再用角色名换凭据。 - /// v1 一步就能问出来,也正因为如此,一个能发出 SSRF 的应用就能把凭据 - /// 读走 —— v2 的令牌要用 PUT 取,而 SSRF 通常只能发 GET。 - async fn imdsv2_credentials(&self, client: &reqwest::Client) -> Result { - let fail = |what: &str, e: reqwest::Error| SignError::Credentials(format!("{what}: {e}")); - - let token = client - .put(format!("{IMDS}/latest/api/token")) - .header("X-aws-ec2-metadata-token-ttl-seconds", "300") - .send() - .await - .map_err(|e| fail("IMDSv2 token request", e))? - .text() - .await - .map_err(|e| fail("IMDSv2 token read", e))?; - - let role = client - .get(format!("{IMDS}/latest/meta-data/iam/security-credentials/")) - .header("X-aws-ec2-metadata-token", &token) - .send() - .await - .map_err(|e| fail("IMDSv2 role lookup", e))? - .text() - .await - .map_err(|e| fail("IMDSv2 role read", e))?; - let role = role.trim(); - - let creds: serde_json::Value = client - .get(format!( - "{IMDS}/latest/meta-data/iam/security-credentials/{role}" - )) - .header("X-aws-ec2-metadata-token", &token) - .send() - .await - .map_err(|e| fail("IMDSv2 credentials fetch", e))? - .json() - .await - .map_err(|e| fail("IMDSv2 credentials parse", e))?; - - let field = |k: &str| { - creds[k] - .as_str() - .ok_or_else(|| SignError::Credentials(format!("IMDSv2 response has no {k}"))) - }; - Ok(Credentials::new( - field("AccessKeyId")?, - field("SecretAccessKey")?, - creds["Token"].as_str().map(str::to_string), - None, - "imdsv2", - )) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn signer() -> Signer { - Signer { - region: "us-east-1".into(), - access_key_id: Some("AKIAIOSFODNN7EXAMPLE".into()), - secret_access_key: Some("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY".into()), - } - } - - #[tokio::test] - async fn signing_produces_an_authorization_header_and_the_payload_hash() { - let headers = signer() - .sign( - &reqwest::Client::new(), - "https://bedrock-runtime.us-east-1.amazonaws.com/model/m/converse", - b"{}", - ) - .await - .expect("凭据是齐的,不该去问 IMDS"); - - let names: Vec<&str> = headers.iter().map(|(n, _)| n.as_str()).collect(); - assert!(names.contains(&"authorization"), "{names:?}"); - assert!( - names.contains(&"x-amz-content-sha256"), - "签名覆盖请求体的哈希,这个头必须在:{names:?}" - ); - assert!(names.contains(&"x-amz-date"), "{names:?}"); - } - - #[tokio::test] - async fn nothing_but_the_signed_headers_comes_back() { - // 把整份头带走会盖掉调用方自己设的东西 - let headers = signer() - .sign( - &reqwest::Client::new(), - "https://bedrock-runtime.us-east-1.amazonaws.com/model/m/converse", - b"{}", - ) - .await - .unwrap(); - for (n, _) in &headers { - assert!( - n == "authorization" || n.starts_with("x-amz-"), - "{n} 不是签出来的" - ); - } - } - - #[tokio::test] - async fn a_different_body_signs_differently() { - // 签名覆盖请求体 —— 改一个字节就该是另一个签名。 - // 这条不成立的话,重放一个改过的请求体就能通过 - let c = reqwest::Client::new(); - let url = "https://bedrock-runtime.us-east-1.amazonaws.com/model/m/converse"; - let a = signer().sign(&c, url, b"{}").await.unwrap(); - let b = signer().sign(&c, url, b"{\"x\":1}").await.unwrap(); - - let hash = |h: &[(String, String)]| { - h.iter() - .find(|(n, _)| n == "x-amz-content-sha256") - .map(|(_, v)| v.clone()) - .unwrap() - }; - assert_ne!(hash(&a), hash(&b)); - } -} diff --git a/crates/tw-upstream/tests/bedrock_stream.rs b/crates/tw-upstream/tests/bedrock_stream.rs deleted file mode 100644 index 6c80454b..00000000 --- a/crates/tw-upstream/tests/bedrock_stream.rs +++ /dev/null @@ -1,94 +0,0 @@ -//! 从线上的二进制帧一路走到客户端的格式。 -//! -//! 拆帧(这里)和读帧(`tw-dialect`)是分开写的,两边靠一个约定对接: -//! `:event-type` 进 `event:`,载荷进 `data:`。这条测试证明约定对得上 —— -//! 任何一边改了形状,它就断。 - -use aws_smithy_eventstream::frame::write_message_to; -use aws_smithy_types::event_stream::{Header, HeaderValue, Message}; -use tw_dialect::convert::decode; -use tw_dialect::ir::{Dialect, Target}; -use tw_upstream::eventstream::Transcoder; - -fn event(kind: &str, payload: &str) -> Vec { - let m = Message::new(payload.as_bytes().to_vec()) - .add_header(Header::new( - ":message-type", - HeaderValue::String("event".into()), - )) - .add_header(Header::new( - ":event-type", - HeaderValue::String(kind.to_string().into()), - )); - let mut out = Vec::new(); - write_message_to(&m, &mut out).unwrap(); - out -} - -fn converse_stream() -> Vec { - [ - event("messageStart", r#"{"role":"assistant"}"#), - event( - "contentBlockDelta", - r#"{"contentBlockIndex":0,"delta":{"text":"天气"}}"#, - ), - event( - "contentBlockDelta", - r#"{"contentBlockIndex":0,"delta":{"text":"晴"}}"#, - ), - event("contentBlockStop", r#"{"contentBlockIndex":0}"#), - event("messageStop", r#"{"stopReason":"end_turn"}"#), - event( - "metadata", - r#"{"usage":{"inputTokens":60,"cacheReadInputTokens":40,"outputTokens":20,"totalTokens":120}}"#, - ), - ] - .concat() -} - -#[test] -fn a_converse_stream_reaches_a_chat_client_with_its_text_and_usage() { - // 客户端说 Chat,路由到 Bedrock - let body = serde_json::json!({ - "model": "anthropic.claude", - "stream": true, - "messages": [{"role": "user", "content": "天气?"}], - }); - let converted = decode(Dialect::Chat, &body, "/v1/chat/completions", None) - .unwrap() - .encode(&Target { - dialect: Dialect::Bedrock, - official: true, - default_max_tokens: 4096, - }); - let mut to_client = converted.session.stream(); - let mut sniffer = tw_wire::Sniffer::new(); - - // 线上的字节七个一块地到,帧边界随便落在哪 - let mut transcoder = Transcoder::new(); - let mut chat = Vec::new(); - for chunk in converse_stream().chunks(7) { - let sse = transcoder.feed(chunk).unwrap(); - sniffer.feed(&sse); - chat.extend(to_client.process(&sse)); - } - chat.extend(to_client.finish()); - let chat = String::from_utf8(chat).unwrap(); - - let text: String = chat - .lines() - .filter_map(|l| l.strip_prefix("data: ")) - .filter_map(|d| serde_json::from_str::(d).ok()) - .filter_map(|v| { - v["choices"][0]["delta"]["content"] - .as_str() - .map(str::to_string) - }) - .collect(); - assert_eq!(text, "天气晴"); - assert!(chat.contains(r#""finish_reason":"stop""#), "{chat}"); - - // 用量从转出来的 SSE 里就嗅得到,不必等转成客户端格式 - let usage = sniffer.finish().expect("usage"); - assert_eq!((usage.input, usage.cache_read, usage.output), (60, 40, 20)); -} diff --git a/crates/tw-wire/Cargo.toml b/crates/tw-wire/Cargo.toml deleted file mode 100644 index 6dbec4a9..00000000 --- a/crates/tw-wire/Cargo.toml +++ /dev/null @@ -1,11 +0,0 @@ -[package] -name = "tw-wire" -version.workspace = true -edition.workspace = true -rust-version.workspace = true -license.workspace = true -repository.workspace = true -description = "Read the usage an upstream reports, alongside a response that keeps streaming" - -[dependencies] -serde_json = { workspace = true } diff --git a/crates/tw-wire/src/lib.rs b/crates/tw-wire/src/lib.rs deleted file mode 100644 index 7cbc9c31..00000000 --- a/crates/tw-wire/src/lib.rs +++ /dev/null @@ -1,16 +0,0 @@ -//! 从响应里嗅出上游报的用量。 -//! -//! **不缓冲**。响应是流着出去的,为了看一眼它而把它整块攒下来,会把 SSE -//! 变成一次性交付 —— 客户端看到的是「卡很久,然后一下全出来」。所以这里 -//! 是旁路的:字节照常流向客户端,同时喂它一份。 -//! -//! 这一层刻意零业务依赖 —— 它不认识配置从哪来、数据存哪里、谁在调用, -//! 所以企业版和桌面版都直接用它。 -//! -//! 以前这里还有订阅额度(`quota`)和正文留档(`bodies`)。两者只有桌面版 -//! 在用,已经搬回 tw-gateway:只有一方在用的「共用件」,是第二个要改的 -//! 地方,不是共用。 - -pub mod usage; - -pub use usage::{Sniffer, Usage};