diff --git a/.github/ci-paths.toml b/.github/ci-paths.toml index cabd12f66b..083d815e40 100644 --- a/.github/ci-paths.toml +++ b/.github/ci-paths.toml @@ -19,6 +19,9 @@ ignore = [ ] [suites] + +gateway = ["gateway/**", ".github/workflows/gateway.yml"] + helm = ["deploy/helm/**", "tests/test_helm*.py", "tests/e2e/helm_*.py"] tests = [ "tests/**", "integrations/**", "examples/**", "scripts/generate_js_operations.py", @@ -200,3 +203,4 @@ candidate_replay = ["candidate-replay"] release_schema = ["release-schema"] seekdb_lock = ["seekdb-lock"] skill_guidance = ["skill-guidance"] +gateway = ["gateway-validation"] diff --git a/.github/workflows/gateway.yml b/.github/workflows/gateway.yml new file mode 100644 index 0000000000..2fb4215dd7 --- /dev/null +++ b/.github/workflows/gateway.yml @@ -0,0 +1,50 @@ +name: Gateway + +on: + workflow_call: + inputs: + suites: + description: Scope already selected by the Main orchestrator + required: true + type: string + workflow_dispatch: + +permissions: + contents: read + actions: read + +concurrency: + group: gateway-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + changes: + if: ${{ inputs.suites == '' }} + uses: ./.github/workflows/ci-changes.yml + with: + baseline-workflow: gateway.yml + + check: + needs: changes + if: >- + ${{ !cancelled() && + ((inputs.suites == '' && needs.changes.result != 'success') || fromJSON(inputs.suites || needs.changes.outputs.suites || '{}').gateway) }} + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + - name: Install pinned Rust toolchain + run: rustup toolchain install 1.95.0-x86_64-unknown-linux-gnu --profile minimal --component rustfmt --component clippy + - name: Cache Rust dependencies and compilation + uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 + with: + workspaces: gateway -> target + cache-bin: false + - name: Format check + run: cargo fmt --manifest-path gateway/Cargo.toml --all --check + - name: Clippy + run: cargo clippy --locked --manifest-path gateway/Cargo.toml --all-targets -- -D warnings + - name: Tests + run: cargo test --locked --manifest-path gateway/Cargo.toml --workspace diff --git a/.github/workflows/master.yml b/.github/workflows/master.yml index 6acc851d96..80607cd91f 100644 --- a/.github/workflows/master.yml +++ b/.github/workflows/master.yml @@ -1123,6 +1123,16 @@ jobs: with: suites: ${{ needs.quality.outputs.suites }} + gateway-validation: + needs: [quality, tests] + if: >- + ${{ !cancelled() && needs.quality.result == 'success' && + contains(fromJSON('["success","skipped"]'), needs.tests.result) && + (fromJSON(needs.quality.outputs.suites || '{}').gateway) }} + uses: ./.github/workflows/gateway.yml + with: + suites: ${{ needs.quality.outputs.suites }} + desktop-validation: needs: [quality, tests] if: >- @@ -1240,6 +1250,7 @@ jobs: - website-link-validation-windows - check-website - harness-validation + - gateway-validation - desktop-validation - managed-resource-candidates - helm diff --git a/.gitignore b/.gitignore index 9ba229d6b3..6d7cca108a 100644 --- a/.gitignore +++ b/.gitignore @@ -276,3 +276,4 @@ integrations/pi/plugins/powercontext/*.tgz # pnpm package store is a local cache, never committed. .pnpm-store/ +powercontext/gateway/ diff --git a/gateway/.gitignore b/gateway/.gitignore new file mode 100644 index 0000000000..e08c79410a --- /dev/null +++ b/gateway/.gitignore @@ -0,0 +1,2 @@ +target/ +.DS_Store diff --git a/gateway/Cargo.lock b/gateway/Cargo.lock new file mode 100644 index 0000000000..50c384da31 --- /dev/null +++ b/gateway/Cargo.lock @@ -0,0 +1,1705 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "axum" +version = "0.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edca88bc138befd0323b20752846e6587272d3b03b0343c8ea28a6f819e6e71f" +dependencies = [ + "async-trait", + "axum-core", + "bytes", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "rustversion", + "serde", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09f2bd6146b97ae3359fa0cc6d6b376d9539582c7b4220f041a33ec24c226199" +dependencies = [ + "async-trait", + "bytes", + "futures-util", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "rustversion", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +dependencies = [ + "serde", +] + +[[package]] +name = "cc" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "rand_core", + "wasm-bindgen", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matchit" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "pc-gateway-app" +version = "0.1.0" +dependencies = [ + "axum", + "bytes", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "pc-gateway-core", + "pc-gateway-evidence", + "pc-gateway-protocol", + "pc-gateway-transport", + "pc-gateway-types", + "reqwest", + "serde", + "serde_json", + "tokio", + "tower", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "pc-gateway-core" +version = "0.1.0" +dependencies = [ + "bytes", + "pc-gateway-evidence", + "pc-gateway-protocol", + "pc-gateway-transport", + "pc-gateway-types", + "reqwest", + "serde", + "serde_json", + "thiserror", + "tokio", + "tracing", +] + +[[package]] +name = "pc-gateway-embedded" +version = "0.1.0" +dependencies = [ + "pc-gateway-core", + "pc-gateway-types", +] + +[[package]] +name = "pc-gateway-evidence" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "pc-gateway-protocol" +version = "0.1.0" +dependencies = [ + "bytes", + "pc-gateway-types", + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "pc-gateway-transport" +version = "0.1.0" +dependencies = [ + "bytes", + "futures-core", + "pc-gateway-evidence", + "pc-gateway-types", + "reqwest", + "serde_json", + "thiserror", + "tokio", +] + +[[package]] +name = "pc-gateway-types" +version = "0.1.0" +dependencies = [ + "bytes", + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/gateway/Cargo.toml b/gateway/Cargo.toml new file mode 100644 index 0000000000..da6a96b376 --- /dev/null +++ b/gateway/Cargo.toml @@ -0,0 +1,57 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +[workspace] +resolver = "2" +members = [ + "crates/pc-gateway-app", + "crates/pc-gateway-core", + "crates/pc-gateway-types", + "crates/pc-gateway-protocol", + "crates/pc-gateway-transport", + "crates/pc-gateway-evidence", + "crates/pc-gateway-embedded", +] + +[workspace.package] +version = "0.1.0" +edition = "2021" +license = "Apache-2.0" +repository = "https://github.com/oceanbase/powercontext" + +[workspace.dependencies] +pc-gateway-core = { path = "crates/pc-gateway-core" } +pc-gateway-types = { path = "crates/pc-gateway-types" } +pc-gateway-protocol = { path = "crates/pc-gateway-protocol" } +pc-gateway-transport = { path = "crates/pc-gateway-transport" } +pc-gateway-evidence = { path = "crates/pc-gateway-evidence" } + +tokio = { version = "1", features = ["full"] } +axum = "0.7" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +thiserror = "2" +bytes = { version = "1", features = ["serde"] } +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } +reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "stream"] } +hyper = { version = "1", features = ["client", "http1"] } +tower = { version = "0.5", features = ["util"] } +hyper-util = { version = "0.1", features = ["client", "client-legacy", "tokio", "http1"] } +http-body = "1" +http-body-util = "0.1" +futures-core = "0.3" + +[profile.release] +lto = "thin" diff --git a/gateway/README.md b/gateway/README.md new file mode 100644 index 0000000000..13c2c3fcda --- /dev/null +++ b/gateway/README.md @@ -0,0 +1,98 @@ +# PowerContext Rust Gateway + +An optional Rust executor for PowerContext, defined by the gateway design in #2199 and the context-protection contract in #2264. The gateway owns the model traffic boundary; every decision stays in PowerContext Core ("no policy in the gateway"). + +> Status: working prototype, verified end-to-end against a real PowerContext Server (PR #2264 branch) with real upstream providers (GLM, DeepSeek). Depends on the `/v1/context/check` contract and `include_reuse` from #2264. + +## Features + +### Model traffic pipeline (per request) + +- **Two-phase gate executor**: `check(before_send)` → send admitted bytes → `check(before_release)` → release. Opaque bindings thread the two phases (`request_binding` must be the send-phase binding). HTTP success alone is never treated as approval; unknown never becomes allow. +- **Privacy enforcement by Core, executed by the gateway**: forbidden content is blocked before any byte leaves the gateway (zero-send on block/withhold, zero-release on refuse, upstream cancel on refusal). +- **Deterministic-failure-only bounded retry**: connection-refused style failures retry a bounded number of times with a single owner; indeterminate outcomes (timeout after hand-off) are surfaced as `send_indeterminate` and never auto-retried (no paid re-sends). +- **Degradation policy**: when Core is unreachable, either pause (default) or pass through without memory (`PC_GATEWAY_DEGRADE=passthrough`) — degraded responses are explicitly marked (`x-pc-degraded` header). Blocked verdicts never degrade. +- **Streaming ingestion** (`stream: true`): upstream SSE is received incrementally (TTFT measured, byte-capped); strict semantics hold — the complete raw response is buffered and must pass `before_release` before anything is released to the client. (The current public carrier in #2264 withholds streaming payloads; the pipeline is ready for when the contract allows it.) +- **Status-code fidelity**: upstream errors pass through with their original status code (a provider 402/400 is never masked as 200), and `Content-Type` is preserved. + +### Memory features (#2199 capabilities) + +- **Auto-recall injection**: for each new user message the gateway calls `prepare` with `include_reuse`, and injects the returned prepared context **verbatim** into the current user message. The exact UTF-8 byte range is declared in `prepared_contexts` (`ModelJsonTextLocation`); Core verifies the digest of the declared range against the signed reuse binding — a single byte changed by the gateway is rejected. Empty or failed prepares inject nothing and never block the main path. Injection is tail-only (current message), so the client-owned history prefix stays byte-stable (KV prefix-cache friendly, verified with DeepSeek `cached_tokens`). +- **Sedimentation**: after a released turn, the gateway synchronously captures the transcript via `capture_content_source` (millisecond-scale durable write; extraction happens later in PC background workers). `source_id` is idempotent (derived from the release binding digest). Blocked and degraded turns are never captured. The full loop — conversation → capture → background extraction into Atomic Memory → `prepare` recall in a *new* session — has been verified end-to-end. + +### Deployment & ops + +- **Two deployment forms**: *combined* (Rust owns the public TCP port; Core listens only on a private Unix socket; all non-`/gateway` routes are reverse-proxied to Core over UDS) or *standalone* (TCP to a remote Core). +- **UDS client**: hand-rolled HTTP/1.1 over the Unix socket with a pooled, keep-alive connection pool (bounded idle set, connect/read timeouts, stale-connection single retry, content-length truncation and chunked-trailer consumption — covered by a real-socket regression test). +- **OpenAI-compatible ingress** at `/gateway/v1/chat/completions` and `/gateway/v1/responses` (same format in and out, no cross-format translation), authenticated by a gateway key that replaces provider keys. +- **Middleware chain**: composable `GatewayMiddleware` trait; ships with resource limits (request-body precheck + concurrency semaphore, health probe exempt) and request-id propagation (`x-powercontext-request-id`, client-supplied or generated, echoed on responses). +- **Body-free evidence**: usage completeness (known/estimated/unknown), cache tokens, TTFT vs first-release latency, attempt counters — never request/response bodies. + +## PC call sequence over UDS + +All gateway→Core calls go through one `GateClient` (UDS in combined form, TCP in standalone form) and share the connection pool. For one chat request with injection and sedimentation enabled: + +``` +client ──POST /gateway/v1/chat/completions──▶ gateway (middleware: limits → request-id) + │ + 1. prepare gateway ──▶ POST /v1/context/prepare (query = last user message, + ◀── include_reuse=true) + content (trust preamble + marker block) + reuse binding (5 min) + — injected verbatim; byte range recorded; failure/empty ⇒ no injection + │ + 2. check gateway ──▶ POST /v1/context/check phase=before_send + (send gate) ◀── allow + send binding (60 s) | block/withhold ⇒ 403/409, zero send + │ + 3. send gateway ──▶ upstream provider (admitted bytes only; the single egress) + ◀── complete raw response (+ usage) + │ + 4. check gateway ──▶ POST /v1/context/check phase=before_release + (release (payload = complete raw response, request_binding = send binding) + gate) ◀── allow + release binding | refuse ⇒ cancel upstream, 403, + nothing released + │ + 5. capture gateway ──▶ POST /v1/sources/content (transcript JSON, + ◀── source_id = digest(release binding)) — released turns only; + failure is evidence-only + │ +client ◀── 200 (upstream status/content-type preserved, request-id echoed) ── gateway +``` + +Everything else (Core's 127 domain operations, MCP, dashboard) is reverse-proxied to Core over the same UDS socket, untouched by gateway logic. + +## Layout + +| Crate | Responsibility | +| --- | --- | +| `pc-gateway-app` | thin binary: ingress, port-takeover proxy, middleware chain | +| `pc-gateway-core` | executor state machine, GateClient (check/prepare/capture/capabilities) over TCP or UDS | +| `pc-gateway-types` | contract DTOs aligned field-by-field with #2264 | +| `pc-gateway-protocol` | canonical request, chat/responses wire renderers, SSE framing | +| `pc-gateway-transport` | upstream transport, bounded retry, streaming buffer with caps | +| `pc-gateway-evidence` | body-free evidence (usage completeness, cache tokens, TTFT) | +| `pc-gateway-embedded` | placeholder for the in-process (FFI) executor path | + +## Run + +```bash +cargo build --release + +# Combined deployment (Core on a Unix socket) +PC_GATEWAY_CORE_UDS=/path/to/pc.sock \ +PC_GATEWAY_UPSTREAM_PROFILE= \ +PC_GATEWAY_DEFAULT_SCOPE= \ +PC_GATEWAY_UPSTREAM_URL_CHAT=https://provider/v1/chat/completions \ +PC_GATEWAY_UPSTREAM_API_KEY_CHAT=... \ +./target/release/pc-gateway + +# Optional: PC_GATEWAY_INJECTION=on (prepare + inject), PC_GATEWAY_SEDIMENT=on (capture after release), +# PC_GATEWAY_DEGRADE=passthrough (no-memory passthrough when Core is unreachable; never applies +# to deployments with enforcing protection), PC_GATEWAY_MAX_CONCURRENT / PC_GATEWAY_MAX_BODY_BYTES, +# PC_GATEWAY_CORE_TOKEN (bearer for Core when authentication is enabled). +``` + +Credentials live only in server-side environment variables; they are never accepted from request fields and never enter check payloads. + +## Tests + +`cargo test` — 27 tests covering the failure-semantics table (gate unavailable, withhold terminal, bounded retry, indeterminate no-resend, blocked turns never sediment), renderer fidelity (no timestamps/request ids injected), byte-range declaration, UDS connection-pool correctness over a real Unix socket, and live integration tests against a real PowerContext Server (binding validity, cross-scope rejection, deadlines) that skip gracefully when no server is reachable. diff --git a/gateway/crates/pc-gateway-app/Cargo.toml b/gateway/crates/pc-gateway-app/Cargo.toml new file mode 100644 index 0000000000..defce09c94 --- /dev/null +++ b/gateway/crates/pc-gateway-app/Cargo.toml @@ -0,0 +1,44 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +[package] +name = "pc-gateway-app" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "PowerContext Gateway: thin binary — port takeover, Core/MCP forwarding, OpenAI-compatible model ingress" + +[[bin]] +name = "pc-gateway" +path = "src/main.rs" + +[dependencies] +pc-gateway-core = { workspace = true } +pc-gateway-types = { workspace = true } +pc-gateway-protocol = { workspace = true } +pc-gateway-transport = { workspace = true } +pc-gateway-evidence = { workspace = true } +bytes = { workspace = true } +serde = { workspace = true } +tokio = { workspace = true } +axum = { workspace = true } +serde_json = { workspace = true } +tracing = { workspace = true } +tracing-subscriber = { workspace = true } +reqwest = { workspace = true } +hyper = { workspace = true } +tower = { workspace = true } +hyper-util = { workspace = true } +http-body = { workspace = true } +http-body-util = { workspace = true } diff --git a/gateway/crates/pc-gateway-app/src/ingress.rs b/gateway/crates/pc-gateway-app/src/ingress.rs new file mode 100644 index 0000000000..4149feaf52 --- /dev/null +++ b/gateway/crates/pc-gateway-app/src/ingress.rs @@ -0,0 +1,473 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 模型入口:OpenAI 兼容 `/gateway/v1/chat/completions`。 +//! 客户端只改 Base URL 与 API Key 即接入(PR #2199 产品形态)。 + +use crate::{proxy::SharedProxy, AppState}; +use axum::body::Bytes; +use axum::extract::{Request, State}; +use axum::http::{header, HeaderMap, StatusCode}; +use axum::response::{IntoResponse, Response}; +use axum::Json; +use pc_gateway_core::{ManagedCall, ManagedOutcome}; +use pc_gateway_protocol::{CanonicalMessage, CanonicalRequest, OutputLimits, Role}; +use serde::Deserialize; +use std::sync::Arc; + +#[derive(Debug, Deserialize)] +struct OpenAiChatRequest { + model: String, + messages: Vec, + #[serde(default)] + tools: Vec, + #[serde(default)] + max_tokens: Option, + /// 优先于 max_tokens(OpenAI 新字段;两者并存时以此为准)。 + #[serde(default)] + max_completion_tokens: Option, + #[serde(default)] + response_format: Option, + #[serde(default)] + tool_choice: Option, + #[serde(default)] + stream: Option, +} + +#[derive(Debug, Deserialize)] +struct OpenAiMessage { + role: String, + #[serde(default)] + content: serde_json::Value, + #[serde(default)] + tool_calls: Option>, + #[serde(default)] + tool_call_id: Option, +} + +/// Responses API 入口请求(同格式进出,不与 chat 互转)。 +#[derive(Debug, Deserialize)] +struct OpenAiResponsesRequest { + model: String, + input: Vec, + #[serde(default)] + instructions: Option, + #[serde(default)] + tools: Vec, + #[serde(default)] + max_output_tokens: Option, + /// Responses 的结构化输出参数:text: { format: {...} }。 + /// 注意:Responses API 没有顶层 response_format(那是 Chat 字段)。 + #[serde(default)] + text: Option, + #[serde(default)] + tool_choice: Option, + /// #2313 要求 openai-responses 目标显式 store:false。 + #[serde(default)] + store: Option, + /// Responses 的会话续写 ID;不透传 = 客户端丢失历史连续性。 + #[serde(default)] + previous_response_id: Option, + /// Responses 的会话标识(conversation 参数);与 previous_response_id + /// 是不同的字段,同样需要透传给 Core 检查。 + #[serde(default)] + conversation: Option, + #[serde(default)] + stream: Option, +} + +pub async fn chat_completions( + State((state, _)): State, + headers: HeaderMap, + req: Request, +) -> Response { + ingress_common(state, headers, req, Format::Chat).await +} + +pub async fn responses( + State((state, _)): State, + headers: HeaderMap, + req: Request, +) -> Response { + ingress_common(state, headers, req, Format::Responses).await +} + +enum Format { + Chat, + Responses, +} + +async fn ingress_common( + state: Arc, + headers: HeaderMap, + req: Request, + format: Format, +) -> Response { + // 网关密钥认证(替代服务商 key;上游凭据由受控配置持有)。 + if let Some(expected) = &state.api_key { + let provided = headers + .get(header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")); + if provided != Some(expected.as_str()) { + return ( + StatusCode::UNAUTHORIZED, + Json(serde_json::json!({ "error": "invalid_gateway_key" })), + ) + .into_response(); + } + } + + // Applies the configured limit to the consumed body as well: chunked requests have no Content-Length, + // so the middleware precheck cannot limit them. Here we use the same configured value to prevent bypassing via framing. + let body = match axum::body::to_bytes(req.into_body(), state.max_body_bytes).await { + Ok(b) => b, + Err(e) => { + // 区分超限(413,与中间件预检语义一致)与其他读取错误(400)。 + let over_limit = std::error::Error::source(&e) + .and_then(|s| s.downcast_ref::()) + .is_some(); + let (status, code) = if over_limit { + (StatusCode::PAYLOAD_TOO_LARGE, "request_body_too_large") + } else { + (StatusCode::BAD_REQUEST, "invalid_body") + }; + return ( + status, + Json(serde_json::json!({ "error": code, "detail": e.to_string() })), + ) + .into_response(); + } + }; + let canonical = match format { + Format::Chat => { + let chat: OpenAiChatRequest = match serde_json::from_slice(&body) { + Ok(c) => c, + Err(e) => { + return ( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({ "error": "invalid_openai_body", "detail": e.to_string() })), + ) + .into_response() + } + }; + match to_canonical_chat(chat) { + Ok(c) => c, + Err(msg) => { + return ( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({ "error": "unsupported_field", "detail": msg })), + ) + .into_response() + } + } + } + Format::Responses => { + let r: OpenAiResponsesRequest = match serde_json::from_slice(&body) { + Ok(c) => c, + Err(e) => { + return ( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({ "error": "invalid_responses_body", "detail": e.to_string() })), + ) + .into_response() + } + }; + match to_canonical_responses(r) { + Ok(c) => c, + Err(msg) => { + return ( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({ "error": "unsupported_field", "detail": msg })), + ) + .into_response() + } + } + } + }; + // P1 review:未配置的上游禁用路由(不默认到任何第三方)。 + if let Format::Responses = format { + if state.upstream_responses.is_empty() { + return ( + StatusCode::NOT_IMPLEMENTED, + Json(serde_json::json!({ + "error": "responses_route_disabled", + "hint": "set PC_GATEWAY_UPSTREAM_URL_RESPONSES to enable this route" + })), + ) + .into_response(); + } + } + let renderer = match format { + Format::Chat => pc_gateway_protocol::GatewayRenderer::Chat(Default::default()), + Format::Responses => pc_gateway_protocol::GatewayRenderer::Responses(Default::default()), + }; + + let call = ManagedCall { + scope_id: state.default_scope.clone(), + target_profile: state.upstream_profile.clone(), + request: canonical, + target_url: match format { + Format::Chat => state.upstream_chat.clone(), + Format::Responses => state.upstream_responses.clone(), + }, + headers: bearer_headers(match format { + Format::Chat => &state.upstream_chat_api_key, + Format::Responses => &state.upstream_responses_api_key, + }), + // P1-3:降级资格由启动时 capabilities 查询决定,环境变量只是运维申请。 + degrade_policy: if state.degradation_allowed { + state.degrade + } else { + pc_gateway_core::DegradePolicy::Pause + }, + inject_context: state.inject_context && matches!(format, Format::Chat), + sediment: state.sediment, + prepared_contexts: Vec::new(), + }; + + let outcome = state + .executor + .run(call, &renderer, state.evidence.as_ref()) + .await; + respond(outcome) +} + +fn bearer_headers(key: &str) -> Vec<(String, String)> { + if key.is_empty() { + Vec::new() + } else { + vec![("authorization".to_string(), format!("Bearer {key}"))] + } +} + +fn to_canonical_chat(chat: OpenAiChatRequest) -> Result { + let mut messages = Vec::with_capacity(chat.messages.len()); + for m in chat.messages { + let role = match m.role.as_str() { + "system" => Role::System, + "user" => Role::User, + "assistant" => Role::Assistant, + "tool" => Role::Tool, + other => return Err(format!("unsupported role: {other}")), + }; + let content_null = m.content.is_null(); + let content = match m.content { + serde_json::Value::String(s) => vec![serde_json::Value::String(s)], + serde_json::Value::Array(a) => a, + serde_json::Value::Null => vec![], + other => return Err(format!("unsupported content type: {other}")), + }; + messages.push(CanonicalMessage { + role, + content, + content_null, + tool_calls: m.tool_calls, + tool_call_id: m.tool_call_id, + }); + } + Ok(CanonicalRequest { + model: chat.model, + messages, + tools: chat.tools, + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: chat.max_completion_tokens.or(chat.max_tokens), + }, + stream: chat.stream.unwrap_or(false), + response_format: chat.response_format, + tool_choice: chat.tool_choice, + store: None, + previous_response_id: None, + token_limit_field: if chat.max_completion_tokens.is_some() { + Some("max_completion_tokens".into()) + } else if chat.max_tokens.is_some() { + Some("max_tokens".into()) + } else { + None + }, + conversation: None, + }) +} + +/// Responses 入口 → 规范类型:消息项照常映射; +/// Responses 专有 item(function_call 等)原样封进 content, +/// 由 `OpenAiResponsesRenderer` 按原样作为顶层 input item 透出(无跨格式转换)。 +fn to_canonical_responses(r: OpenAiResponsesRequest) -> Result { + let mut messages = Vec::with_capacity(r.input.len()); + for item in r.input { + let role_str = item.get("role").and_then(|v| v.as_str()).unwrap_or(""); + let role = match role_str { + "system" | "developer" => Role::System, + "user" => Role::User, + "assistant" => Role::Assistant, + "tool" => Role::Tool, + // 无 role 的顶层 item(function_call/function_call_output 等): + // 原样保留,role 占位为 tool。 + _ => Role::Tool, + }; + if role_str.is_empty() { + messages.push(CanonicalMessage { + role: Role::Tool, + content: vec![item], + content_null: false, + tool_calls: None, + tool_call_id: None, + }); + continue; + } + let content = match item.get("content") { + Some(serde_json::Value::String(s)) => vec![serde_json::Value::String(s.clone())], + Some(serde_json::Value::Array(a)) => a.clone(), + _ => vec![], + }; + messages.push(CanonicalMessage { + role, + content, + content_null: false, + tool_calls: None, + tool_call_id: None, + }); + } + Ok(CanonicalRequest { + model: r.model, + messages, + tools: r.tools, + instructions: r.instructions, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: r.max_output_tokens, + }, + stream: r.stream.unwrap_or(false), + // Responses 的结构化输出在 text.format,不在 response_format(Chat 字段)。 + response_format: r.text, + tool_choice: r.tool_choice, + store: r.store, + previous_response_id: r.previous_response_id, + conversation: r.conversation, + token_limit_field: None, + }) +} + +/// 结果映射:不存在静默成功;降级直通必须显式标记。 +fn respond(outcome: ManagedOutcome) -> Response { + match outcome { + ManagedOutcome::Released { + status, + content_type, + body, + .. + } => { + // 上游状态码与 Content-Type 原样透传(错误不伪装 200)。 + let code = StatusCode::from_u16(status).unwrap_or(StatusCode::BAD_GATEWAY); + ( + code, + [(header::CONTENT_TYPE, content_type.as_str())], + body.to_vec(), + ) + .into_response() + } + ManagedOutcome::Degraded { + status, + content_type, + body, + } => match Response::builder() + .status(StatusCode::from_u16(status).unwrap_or(StatusCode::BAD_GATEWAY)) + .header(header::CONTENT_TYPE, content_type.as_str()) + .header("x-pc-degraded", "passthrough_without_memory") + .body(axum::body::Body::from(body.to_vec())) + { + Ok(r) => r, + Err(e) => ( + StatusCode::INTERNAL_SERVER_ERROR, + axum::Json(serde_json::json!({ "error": e.to_string() })), + ) + .into_response(), + }, + ManagedOutcome::Blocked { reason_codes } => ( + StatusCode::FORBIDDEN, + Json(serde_json::json!({ "decision": "block", "reason_codes": reason_codes })), + ) + .into_response(), + ManagedOutcome::Withheld { reason_codes } => ( + StatusCode::CONFLICT, + Json(serde_json::json!({ "decision": "withhold", "reason_codes": reason_codes })), + ) + .into_response(), + ManagedOutcome::SendIndeterminate => ( + StatusCode::BAD_GATEWAY, + Json(serde_json::json!({ "decision": "send_indeterminate" })), + ) + .into_response(), + ManagedOutcome::NotSent { attempts } => ( + StatusCode::BAD_GATEWAY, + Json(serde_json::json!({ "decision": "not_sent", "attempts": attempts })), + ) + .into_response(), + ManagedOutcome::AdmissionExpired => ( + StatusCode::CONFLICT, + Json(serde_json::json!({ "decision": "admission_expired" })), + ) + .into_response(), + ManagedOutcome::GatePaused(msg) => ( + StatusCode::SERVICE_UNAVAILABLE, + Json(serde_json::json!({ "decision": "gate_paused", "detail": msg })), + ) + .into_response(), + } +} + +// 抑制未使用导入警告(Bytes 用于类型别名文档场景)。 +#[allow(dead_code)] +fn _unused(_: Option) {} + +#[cfg(test)] +mod tests { + //! PR #2307 review P2:chat 工具元数据经入口 canonical 化的保真测试。 + use super::*; + + #[test] + fn chat_ingress_preserves_tool_fields_and_null_content() { + let body = r#"{ + "model": "m", + "messages": [ + {"role": "assistant", "content": null, + "tool_calls": [{"id": "call_1", "type": "function", + "function": {"name": "get_weather", "arguments": "{}"}}]}, + {"role": "tool", "tool_call_id": "call_1", "content": "sunny"} + ], + "max_tokens": 8 + }"#; + let chat: OpenAiChatRequest = serde_json::from_str(body).unwrap(); + let canonical = to_canonical_chat(chat).unwrap(); + let a = &canonical.messages[0]; + assert!(a.content_null, "content:null 必须被记录"); + assert!(a.content.is_empty()); + assert_eq!(a.tool_calls.as_deref().map(|t| t.len()), Some(1)); + let t = &canonical.messages[1]; + assert_eq!(t.tool_call_id.as_deref(), Some("call_1")); + assert_eq!(t.content[0], serde_json::json!("sunny")); + } + + #[test] + fn chat_ingress_null_content_without_tool_calls_also_preserved() { + let body = + r#"{"model":"m","messages":[{"role":"assistant","content":null}],"max_tokens":8}"#; + let chat: OpenAiChatRequest = serde_json::from_str(body).unwrap(); + let canonical = to_canonical_chat(chat).unwrap(); + assert!(canonical.messages[0].content_null); + assert!(canonical.messages[0].tool_calls.is_none()); + } +} diff --git a/gateway/crates/pc-gateway-app/src/link.rs b/gateway/crates/pc-gateway-app/src/link.rs new file mode 100644 index 0000000000..7abe2e6197 --- /dev/null +++ b/gateway/crates/pc-gateway-app/src/link.rs @@ -0,0 +1,77 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Core 连接形态:UDS(同机组合部署)或 TCP(独立运行)。 + +use pc_gateway_core::{GateClient, GateError, HttpGateClient, UdsGateClient}; +use pc_gateway_types::{ + CaptureContentSourceRequest, ContextCheckRequest, ContextCheckResult, PrepareContextRequest, + PrepareContextResult, +}; + +#[derive(Clone)] +pub enum CoreLink { + Uds(UdsGateClient), + Http(HttpGateClient), +} + +impl CoreLink { + pub fn from_env() -> Self { + if let Ok(sock) = std::env::var("PC_GATEWAY_CORE_UDS") { + tracing::info!(%sock, "core link: UDS (combined deployment)"); + Self::Uds(UdsGateClient::new(sock)) + } else { + let base = std::env::var("PC_GATEWAY_CORE_BASE") + .unwrap_or_else(|_| "http://127.0.0.1:8000".into()); + tracing::info!(%base, "core link: TCP (standalone deployment)"); + Self::Http(HttpGateClient::new(base)) + } + } +} + +impl GateClient for CoreLink { + async fn check(&self, request: ContextCheckRequest) -> Result { + match self { + CoreLink::Uds(c) => c.check(request).await, + CoreLink::Http(c) => c.check(request).await, + } + } + + async fn capabilities(&self) -> Result { + match self { + CoreLink::Uds(c) => c.capabilities().await, + CoreLink::Http(c) => c.capabilities().await, + } + } + + async fn prepare( + &self, + request: PrepareContextRequest, + ) -> Result { + match self { + CoreLink::Uds(c) => c.prepare(request).await, + CoreLink::Http(c) => c.prepare(request).await, + } + } + + async fn capture( + &self, + request: CaptureContentSourceRequest, + ) -> Result { + match self { + CoreLink::Uds(c) => c.capture(request).await, + CoreLink::Http(c) => c.capture(request).await, + } + } +} diff --git a/gateway/crates/pc-gateway-app/src/main.rs b/gateway/crates/pc-gateway-app/src/main.rs new file mode 100644 index 0000000000..2f7d1cd2c0 --- /dev/null +++ b/gateway/crates/pc-gateway-app/src/main.rs @@ -0,0 +1,226 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 薄二进制:端口接管 + 模型入口。所有执行逻辑在 `pc-gateway-core`。 +//! +//! PR #2199 部署形态: +//! - 同机组合:`PC_GATEWAY_CORE_UDS` 指向 Python 的 UDS;网关独占公网端口, +//! 非 `/gateway/*` 流量反向代理到 UDS(原 Core/MCP 路由透传)。 +//! - 独立运行:`PC_GATEWAY_CORE_BASE` 直连远端 PowerContext(无代理)。 +//! +//! 环境变量:PC_GATEWAY_LISTEN、PC_GATEWAY_CORE_UDS、PC_GATEWAY_CORE_BASE、 +//! PC_GATEWAY_API_KEY(网关密钥,替代服务商 key)、PC_GATEWAY_UPSTREAM_URL、 +//! PC_GATEWAY_UPSTREAM_API_KEY、PC_GATEWAY_UPSTREAM_PROFILE、 +//! PC_GATEWAY_POLICY_VERSION、PC_GATEWAY_MAX_ATTEMPTS、PC_GATEWAY_DEGRADE。 + +mod ingress; +mod link; +mod middleware; +mod proxy; + +use crate::link::CoreLink; +use axum::routing::{get, post}; +use axum::Router; +use pc_gateway_core::Executor; +use pc_gateway_evidence::BufferedEvidenceSink; +use pc_gateway_transport::ReqwestTransport; +use std::net::SocketAddr; +use std::num::NonZeroU32; +use std::sync::Arc; +use std::time::Duration; + +pub struct AppState { + /// 单一执行器;线格式渲染器按请求格式传入(同格式进出)。 + pub executor: Arc>, + pub evidence: Arc, + pub upstream_profile: String, + /// chat-completions 上游(含 key;老变量 PC_GATEWAY_UPSTREAM_URL 仍作缺省)。 + pub upstream_chat: String, + /// responses 上游。 + pub upstream_responses: String, + pub upstream_chat_api_key: String, + pub upstream_responses_api_key: String, + pub api_key: Option, + pub degrade: pc_gateway_core::DegradePolicy, + /// 是否调 prepare 注入上下文(默认关;v1 仅 chat 格式)。 + pub inject_context: bool, + /// 过检后同步沉淀对话(默认关)。 + pub sediment: bool, + /// 默认 Scope(启动时读一次,避免热路径读环境变量)。 + pub default_scope: String, + /// Request body byte limit (also enforced when consuming chunked bodies). + pub max_body_bytes: usize, + /// 启动时查 capabilities 确定降级资格:enforcing=true 或查询失败 → 不允许。 + pub degradation_allowed: bool, +} + +#[tokio::main] +async fn main() { + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()), + ) + .init(); + + let core_link = CoreLink::from_env(); + let proxy_state = proxy::ProxyState::from_env(); + + let max_attempts: u32 = std::env::var("PC_GATEWAY_MAX_ATTEMPTS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(2); + let max_body_bytes: usize = std::env::var("PC_GATEWAY_MAX_BODY_BYTES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(16 * 1024 * 1024); + let max_concurrent: usize = std::env::var("PC_GATEWAY_MAX_CONCURRENT") + .ok() + .and_then(|v| v.parse().ok()) + .filter(|v| *v > 0) + .unwrap_or(64); + let degrade = match std::env::var("PC_GATEWAY_DEGRADE").as_deref() { + Ok("passthrough") => pc_gateway_core::DegradePolicy::PassthroughWithoutMemory, + _ => pc_gateway_core::DegradePolicy::Pause, + }; + + let state = Arc::new(AppState { + executor: Arc::new(Executor::new( + core_link.clone(), + ReqwestTransport::new(Duration::from_secs(120)), + NonZeroU32::new(max_attempts).expect("max_attempts > 0"), + )), + evidence: Arc::new(BufferedEvidenceSink::new()), + upstream_profile: std::env::var("PC_GATEWAY_UPSTREAM_PROFILE") + .unwrap_or_else(|_| "default".into()), + upstream_chat: std::env::var("PC_GATEWAY_UPSTREAM_URL_CHAT") + .or_else(|_| std::env::var("PC_GATEWAY_UPSTREAM_URL")) + .unwrap_or_else(|_| "http://127.0.0.1:9000/v1/chat/completions".into()), + upstream_responses: std::env::var("PC_GATEWAY_UPSTREAM_URL_RESPONSES").unwrap_or_default(), + upstream_chat_api_key: std::env::var("PC_GATEWAY_UPSTREAM_API_KEY_CHAT") + .or_else(|_| std::env::var("PC_GATEWAY_UPSTREAM_API_KEY")) + .unwrap_or_default(), + upstream_responses_api_key: std::env::var("PC_GATEWAY_UPSTREAM_API_KEY_RESPONSES") + .or_else(|_| std::env::var("PC_GATEWAY_UPSTREAM_API_KEY")) + .unwrap_or_default(), + api_key: std::env::var("PC_GATEWAY_API_KEY") + .ok() + .filter(|k| !k.is_empty()), + degrade, + inject_context: matches!(std::env::var("PC_GATEWAY_INJECTION").as_deref(), Ok("on")), + sediment: matches!(std::env::var("PC_GATEWAY_SEDIMENT").as_deref(), Ok("on")), + default_scope: std::env::var("PC_GATEWAY_DEFAULT_SCOPE") + .unwrap_or_else(|_| "gateway:default".into()), + max_body_bytes, + degradation_allowed: resolve_degradation(core_link.clone()).await, + }); + + let router = Router::new() + .route("/healthz", get(healthz)) + .route( + "/gateway/v1/chat/completions", + post(ingress::chat_completions), + ) + .route("/gateway/v1/responses", post(ingress::responses)) + .fallback(proxy::fallback) + .with_state((state, proxy_state)); + + // 中间件链:按序注册,前者为外层。新增功能 = 实现 GatewayMiddleware + 此处一行。 + let chain: Vec> = vec![ + middleware::ResourceLimits::new(max_body_bytes, max_concurrent), + std::sync::Arc::new(middleware::RequestId), + ]; + for mw in &chain { + tracing::info!(middleware = mw.name(), "middleware enabled"); + } + let app = middleware::apply_chain(router, chain); + + let addr: SocketAddr = std::env::var("PC_GATEWAY_LISTEN") + .unwrap_or_else(|_| "127.0.0.1:8787".into()) + .parse() + .expect("PC_GATEWAY_LISTEN must be host:port"); + + tracing::info!(%addr, "pc-gateway listening (port takeover mode)"); + let listener = tokio::net::TcpListener::bind(addr).await.expect("bind"); + axum::serve(listener, app) + .with_graceful_shutdown(shutdown_signal()) + .await + .expect("serve"); +} + +async fn shutdown_signal() { + let _ = tokio::signal::ctrl_c().await; + tracing::info!("shutting down (draining)"); +} + +/// P1-3:启动时确定降级资格。 +/// capabilities 返回 enforcing=true → 不允许(Core 说了算)。 +/// 查询失败 → 不允许(fail-closed)。 +async fn resolve_degradation(link: link::CoreLink) -> bool { + use pc_gateway_core::GateClient; + match tokio::time::timeout(std::time::Duration::from_secs(10), link.capabilities()).await { + Ok(Ok(caps)) => { + let cp = caps.get("context_protection"); + // P2 review:验契约版本——Core 必须支持我们消费的 check/payload 契约。 + let check_ok = cp + .and_then(|cp| cp.get("check_versions")) + .and_then(|v| v.as_array()) + .map(|arr| { + arr.iter() + .any(|s| s.as_str() == Some("powercontext.context-check.v1")) + }) + .unwrap_or(false); + let payload_ok = cp + .and_then(|cp| cp.get("payload_versions")) + .and_then(|v| v.as_array()) + .map(|arr| { + arr.iter() + .any(|s| s.as_str() == Some("powercontext.model-json-payload.v1")) + }) + .unwrap_or(false); + if !check_ok || !payload_ok { + tracing::error!( + check_ok, + payload_ok, + "Core does not support the required context-check contract; \ + this gateway requires #2311+#2313. Startup will continue but \ + every /gateway/v1 request will fail until the contract is available." + ); + return false; // 降级也不允许——没有 check 契约就没有安全保障 + } + let enforcing = cp + .and_then(|cp| cp.get("enforcing")) + .and_then(|e| e.as_bool()) + .unwrap_or(true); // 缺字段 → fail-closed + let allowed = !enforcing; + tracing::info!( + enforcing, + allowed, + "degradation eligibility from capabilities" + ); + allowed + } + Ok(Err(e)) => { + tracing::warn!(error = %e, "capabilities error; degradation disabled (fail-closed)"); + false + } + Err(_) => { + tracing::warn!("capabilities timeout (10s); degradation disabled (fail-closed)"); + false + } + } +} + +async fn healthz() -> axum::Json { + axum::Json(serde_json::json!({ "status": "ok", "service": "pc-gateway" })) +} diff --git a/gateway/crates/pc-gateway-app/src/middleware/mod.rs b/gateway/crates/pc-gateway-app/src/middleware/mod.rs new file mode 100644 index 0000000000..62411651fe --- /dev/null +++ b/gateway/crates/pc-gateway-app/src/middleware/mod.rs @@ -0,0 +1,78 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 网关中间件链(chain/filter)。 +//! +//! 设计对齐 PC 的 HttpResourceLimits / HttpRequestId / 观测栈分层思路: +//! 每个功能是一个实现 `GatewayMiddleware` 的小结构,启动时按序注册, +//! `apply_chain` 反向挂到 axum(先注册 = 越靠外层)。新增功能(限流、 +//! 指标、OTel、熔断……)只需增加一个结构体 + 一行注册。 + +use axum::{ + extract::Request, + http::{HeaderName, StatusCode}, + middleware::Next, + response::{IntoResponse, Response}, + Json, +}; +use std::pin::Pin; + +use std::future::Future; +use std::sync::Arc; + +pub mod request_id; +pub use request_id::RequestId; +pub mod resource_limits; +pub use resource_limits::ResourceLimits; + +pub const REQUEST_ID_HEADER: HeaderName = HeaderName::from_static("x-powercontext-request-id"); + +/// 一个中间件 = 请求进入时的一段处理 + 调用后续链。 +/// 约定:中间件不得消费 body(body 归 ingress/代理所有)。 +/// handle 返回 boxed future 以保持 dyn 兼容(可装进 Vec 动态组合)。 +pub trait GatewayMiddleware: Send + Sync + 'static { + /// 名称(日志/指标用)。 + fn name(&self) -> &'static str; + + fn handle<'a>( + &'a self, + req: Request, + next: Next, + ) -> Pin + Send + 'a>>; +} + +/// 把中间件链挂到 Router 的外层。 +/// axum 的 layer 语义:后挂的先执行;这里让 `chain[0]` 成为最外层, +/// 与注册顺序直觉一致。 +pub fn apply_chain( + mut router: axum::Router, + chain: Vec>, +) -> axum::Router { + for mw in chain.into_iter().rev() { + router = router.layer(axum::middleware::from_fn(move |req, next| { + let mw = mw.clone(); + async move { mw.handle(req, next).await } + })); + } + router +} + +/// 统一的简单错误响应。 +pub(crate) fn reject(status: StatusCode, code: &str, detail: impl Into) -> Response { + ( + status, + Json(serde_json::json!({ "error": code, "detail": detail.into() })), + ) + .into_response() +} diff --git a/gateway/crates/pc-gateway-app/src/middleware/request_id.rs b/gateway/crates/pc-gateway-app/src/middleware/request_id.rs new file mode 100644 index 0000000000..ff4abf83a4 --- /dev/null +++ b/gateway/crates/pc-gateway-app/src/middleware/request_id.rs @@ -0,0 +1,70 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 请求 ID:透传客户端的 X-PowerContext-Request-ID 或生成新 ID, +//! 注入请求扩展(供 handler/日志取用)并回写到响应头。 +//! 对齐 PC 的 HttpRequestIdMiddleware,贯通排障链路。 + +use super::{GatewayMiddleware, REQUEST_ID_HEADER}; +use axum::{extract::Request, middleware::Next, response::Response}; +use std::future::Future; +use std::pin::Pin; +use std::sync::atomic::{AtomicU64, Ordering}; + +static SEQUENCE: AtomicU64 = AtomicU64::new(0); + +pub struct RequestId; + +fn generate() -> String { + let ts = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis()) + .unwrap_or(0); + let seq = SEQUENCE.fetch_add(1, Ordering::Relaxed); + format!("gw-{ts:x}-{seq:06x}") +} + +impl GatewayMiddleware for RequestId { + fn name(&self) -> &'static str { + "request_id" + } + + fn handle<'a>( + &'a self, + mut req: Request, + next: Next, + ) -> Pin + Send + 'a>> { + Box::pin(async move { + let id = req + .headers() + .get(&REQUEST_ID_HEADER) + .and_then(|v| v.to_str().ok()) + .filter(|v| { + !v.is_empty() && v.len() <= 128 && v.chars().all(|c| c.is_ascii_graphic()) + }) + .map(|v| v.to_string()) + .unwrap_or_else(generate); + // 注入扩展 + 当前 span,供后续 handler 与日志关联。 + req.extensions_mut().insert(id.clone()); + tracing::Span::current().record("request_id", &id); + let mut resp = next.run(req).await; + if resp.headers().get(&REQUEST_ID_HEADER).is_none() { + if let Ok(v) = axum::http::HeaderValue::from_str(&id) { + resp.headers_mut().insert(REQUEST_ID_HEADER, v); + } + } + resp + }) + } +} diff --git a/gateway/crates/pc-gateway-app/src/middleware/resource_limits.rs b/gateway/crates/pc-gateway-app/src/middleware/resource_limits.rs new file mode 100644 index 0000000000..438bdef8d1 --- /dev/null +++ b/gateway/crates/pc-gateway-app/src/middleware/resource_limits.rs @@ -0,0 +1,147 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 资源限流:请求体上限 + 并发上限(对齐 PC 的 HttpResourceLimitsMiddleware)。 +//! 最外层准入——被拒请求不消耗内层任何资源。/healthz 豁免并发限制 +//! (编排系统探活不应因业务拥堵被拒)。 + +use super::{reject, GatewayMiddleware}; +use axum::{extract::Request, http::StatusCode, middleware::Next, response::Response}; +use std::future::Future; +use std::pin::Pin; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use std::task::{Context, Poll}; +use tokio::sync::Semaphore; + +pub struct ResourceLimits { + max_body_bytes: usize, + max_concurrent: Arc, + /// 被拒计数(无正文证据)。 + rejected_body: AtomicU64, + rejected_concurrency: AtomicU64, +} + +impl ResourceLimits { + pub fn new(max_body_bytes: usize, max_concurrent: usize) -> Arc { + Arc::new(Self { + max_body_bytes, + max_concurrent: Arc::new(Semaphore::new(max_concurrent)), + rejected_body: AtomicU64::new(0), + rejected_concurrency: AtomicU64::new(0), + }) + } +} + +impl GatewayMiddleware for ResourceLimits { + fn name(&self) -> &'static str { + "resource_limits" + } + + fn handle<'a>( + &'a self, + req: Request, + next: Next, + ) -> Pin + Send + 'a>> { + Box::pin(async move { + // 1) 请求体上限:优先用 Content-Length 预检(零拷贝拒绝)。 + if let Some(len) = req + .headers() + .get(axum::http::header::CONTENT_LENGTH) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.parse::().ok()) + { + if len > self.max_body_bytes { + self.rejected_body.fetch_add(1, Ordering::Relaxed); + tracing::warn!( + bytes = len, + limit = self.max_body_bytes, + "request body rejected" + ); + return reject( + StatusCode::PAYLOAD_TOO_LARGE, + "request_body_too_large", + format!("body {len} bytes exceeds limit {}", self.max_body_bytes), + ); + } + } + + // 2) 并发上限:非阻塞获取;占满即拒(不排队——排队会把内存压力换成延迟压力)。 + let is_health = req.uri().path() == "/healthz"; + let permit = if is_health { + None + } else { + match self.max_concurrent.clone().try_acquire_owned() { + Ok(p) => Some(p), + Err(_) => { + self.rejected_concurrency.fetch_add(1, Ordering::Relaxed); + tracing::warn!("concurrency limit reached, rejecting"); + return reject( + StatusCode::SERVICE_UNAVAILABLE, + "concurrency_limit", + "gateway at max concurrent requests", + ); + } + } + }; + + let resp = next.run(req).await; + // P2 review:许可必须绑定到响应 body 的生命周期,不能在头返回时释放。 + // 流式代理(MCP/SSE)的 body 在头之后仍在传输;在头返回时 drop 许可 + // 会让活跃的 SSE 连绕不占并发配额。 + let (parts, body) = resp.into_parts(); + let permit_body = PermitBody::wrap(body, permit); + axum::response::Response::from_parts(parts, permit_body) + }) + } +} + +/// 包装响应 body,持有并发许可直到 body 完成/失败/断开。 +struct PermitBody { + inner: axum::body::Body, + _permit: Option, +} + +impl PermitBody { + fn wrap( + inner: axum::body::Body, + permit: Option, + ) -> axum::body::Body { + axum::body::Body::new(Self { + inner, + _permit: permit, + }) + } +} + +impl http_body::Body for PermitBody { + type Data = axum::body::Bytes; + type Error = axum::Error; + + fn poll_frame( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + ) -> Poll, Self::Error>>> { + Pin::new(&mut self.inner).poll_frame(cx) + // permit 随 self(即 body)的 Drop 释放——body 消费完/连接断开时触发 + } + + fn is_end_stream(&self) -> bool { + self.inner.is_end_stream() + } + + fn size_hint(&self) -> http_body::SizeHint { + self.inner.size_hint() + } +} diff --git a/gateway/crates/pc-gateway-app/src/proxy.rs b/gateway/crates/pc-gateway-app/src/proxy.rs new file mode 100644 index 0000000000..2758e4b47c --- /dev/null +++ b/gateway/crates/pc-gateway-app/src/proxy.rs @@ -0,0 +1,178 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 端口接管代理:非 `/gateway/*` 的流量原样转发到 Python 的 UDS。 +//! 原 Core/MCP 路由由此透传;流式(SSE/分块)由 hyper 客户端透传保证。 + +use crate::AppState; +use axum::body::Body; +use axum::extract::{Request, State}; +use axum::http::{HeaderValue, StatusCode}; +use axum::response::{IntoResponse, Response}; +use hyper::Uri as HyperUri; +use hyper_util::client::legacy::Client; +use hyper_util::rt::{TokioExecutor, TokioIo}; +use std::future::Future; +use std::path::PathBuf; +use std::pin::Pin; +use std::sync::Arc; +use tokio::net::UnixStream; + +pub type SharedProxy = (Arc, ProxyState); + +fn default_body_limit() -> usize { + std::env::var("PC_GATEWAY_MAX_BODY_BYTES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(16 * 1024 * 1024) +} + +#[derive(Clone)] +pub struct ProxyState { + inner: Option>, + /// 代理路径的 body 字节上限(与中间件/ingress 同一配置值)。 + max_body_bytes: usize, +} + +struct ProxyInner { + socket: PathBuf, + client: Client, +} + +impl ProxyState { + pub fn from_env() -> Self { + match std::env::var("PC_GATEWAY_CORE_UDS") { + Ok(sock) => { + let client = Client::builder(TokioExecutor::new()).build(UnixConnector { + socket: PathBuf::from(&sock), + }); + tracing::info!(%sock, "proxy: forwarding non-gateway routes to Python UDS"); + Self { + inner: Some(Arc::new(ProxyInner { + socket: PathBuf::from(sock), + client, + })), + max_body_bytes: default_body_limit(), + } + } + Err(_) => { + tracing::info!("proxy: no UDS configured; standalone mode"); + Self { + inner: None, + max_body_bytes: default_body_limit(), + } + } + } + } +} + +/// UDS 连接器:忽略 URI,始终连配置的 socket 路径。 +/// 实现 tower Service(hyper-util legacy Client 的 Connect 约束)。 +#[derive(Clone)] +struct UnixConnector { + socket: PathBuf, +} + +impl tower::Service for UnixConnector { + type Response = TokioIo; + type Error = std::io::Error; + type Future = Pin> + Send>>; + + fn poll_ready( + &mut self, + _cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::task::Poll::Ready(Ok(())) + } + + fn call(&mut self, _uri: HyperUri) -> Self::Future { + let path = self.socket.clone(); + Box::pin(async move { UnixStream::connect(path).await.map(TokioIo::new) }) + } +} + +pub async fn fallback(State((_, proxy)): State, req: Request) -> Response { + let Some(inner) = proxy.inner else { + return ( + StatusCode::NOT_FOUND, + axum::Json(serde_json::json!({ + "error": "not_found", + "hint": "standalone mode: only /gateway/v1 and /healthz are served", + })), + ) + .into_response(); + }; + + let (parts, body) = req.into_parts(); + // P2 review:代理路径的 body 也受配置上限约束。 + // chunked 分帧没有 Content-Length,中间件预检无法拦截; + // 在这里用 Limited 包装 body,超限即截断 → 上游收到不完整请求并报错。 + let limited_body = + axum::body::Body::new(http_body_util::Limited::new(body, proxy.max_body_bytes)); + // hyper legacy client 要求绝对 URI;UDS 连接器忽略 host,用占位 authority。 + let path_q = parts + .uri + .path_and_query() + .cloned() + .unwrap_or_else(|| "/".parse().expect("root uri")); + let uri = HyperUri::builder() + .scheme("http") + .authority("powercontext.internal") + .path_and_query(path_q) + .build() + .unwrap_or_else(|_| HyperUri::default()); + + let mut fwd = hyper::Request::builder() + .method(parts.method) + .uri(uri) + .header("host", HeaderValue::from_static("powercontext")); + if let Some(headers) = fwd.headers_mut() { + *headers = parts.headers; + if !headers.contains_key("host") { + headers.insert("host", HeaderValue::from_static("powercontext")); + } + } + let hyper_req = match fwd.body(limited_body) { + Ok(r) => r, + Err(e) => { + return ( + StatusCode::BAD_REQUEST, + axum::Json(serde_json::json!({ "error": "bad_request", "detail": e.to_string() })), + ) + .into_response() + } + }; + + let _ = inner.socket; // socket 路径已注入连接器 + match inner.client.request(hyper_req).await { + Ok(resp) => { + let (rparts, rbody) = resp.into_parts(); + let mut response = Response::builder().status(rparts.status); + if let Some(h) = response.headers_mut() { + *h = rparts.headers; + } + response.body(Body::new(rbody)).unwrap_or_else(|e| { + (StatusCode::BAD_GATEWAY, format!("proxy build: {e}")).into_response() + }) + } + Err(e) => ( + StatusCode::BAD_GATEWAY, + axum::Json(serde_json::json!({ + "error": "core_unreachable", + "detail": e.to_string(), + })), + ) + .into_response(), + } +} diff --git a/gateway/crates/pc-gateway-core/Cargo.toml b/gateway/crates/pc-gateway-core/Cargo.toml new file mode 100644 index 0000000000..f92693d763 --- /dev/null +++ b/gateway/crates/pc-gateway-core/Cargo.toml @@ -0,0 +1,33 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +[package] +name = "pc-gateway-core" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "PowerContext Gateway: executor state machine — input/check → render → send → output/check → release" + +[dependencies] +pc-gateway-types = { workspace = true } +pc-gateway-protocol = { workspace = true } +pc-gateway-transport = { workspace = true } +pc-gateway-evidence = { workspace = true } +bytes = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +thiserror = { workspace = true } +tokio = { workspace = true } +tracing = { workspace = true } +reqwest = { workspace = true } diff --git a/gateway/crates/pc-gateway-core/src/executor.rs b/gateway/crates/pc-gateway-core/src/executor.rs new file mode 100644 index 0000000000..9bf711c75e --- /dev/null +++ b/gateway/crates/pc-gateway-core/src/executor.rs @@ -0,0 +1,618 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 执行器核心:一次托管调用的状态机。 +//! +//! ```text +//! 宿主完整输入 ─► [快照原始请求] ─► enrich ─► 渲染 ─► check(before_send) +//! │ │ +//! │ ┌── allow + binding + valid_until +//! │ ▼ +//! │ [验有效期] ─► 发送 ─► ┌─ Delivered ─► check(before_release) +//! │ │ ├─ NotSent ─► [重准入] ─► 重新发送 +//! │ │ └─ Indeterminate ─► 上抛 +//! │ │ +//! │ 到期→ AdmissionExpired(零发送) +//! │ +//! └── 降级时用此原始请求(不含注入)重新渲染 +//! ``` + +use crate::{GateClient, GateError}; +use pc_gateway_evidence::EvidenceSink; +use pc_gateway_protocol::{CanonicalRequest, WireRenderer}; +use pc_gateway_transport::{AdmittedSend, SendOutcome, Transport}; +use pc_gateway_types::{ + parse_rfc3339_ms, CaptureContentSourceRequest, CheckDecision, CheckPhase, ContextCheckRequest, + ContextCheckResult, ModelJsonPayload, ModelJsonTextLocation, PrepareContextRequest, + PreparedContextLocation, +}; +use std::collections::BTreeMap; +use std::num::NonZeroU32; +use std::time::{SystemTime, UNIX_EPOCH}; + +/// Gate 不可用时的策略(PR #2199 故障语义)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum DegradePolicy { + #[default] + Pause, + PassthroughWithoutMemory, +} + +/// 宿主交给执行器的完整输入。 +pub struct ManagedCall { + pub scope_id: String, + pub target_profile: String, + pub request: CanonicalRequest, + pub target_url: String, + pub headers: Vec<(String, String)>, + pub degrade_policy: DegradePolicy, + pub inject_context: bool, + pub sediment: bool, + pub prepared_contexts: Vec, +} + +/// 执行结果。 +#[derive(Debug)] +pub enum ManagedOutcome { + Released { + binding: Option, + status: u16, + content_type: String, + body: bytes::Bytes, + }, + Blocked { + reason_codes: Vec, + }, + Withheld { + reason_codes: Vec, + }, + SendIndeterminate, + NotSent { + attempts: u32, + }, + GatePaused(String), + Degraded { + status: u16, + content_type: String, + body: bytes::Bytes, + }, + /// 准入已过期(valid_until 超窗):零发送或零释放,可安全重走完整流程。 + AdmissionExpired, +} + +pub struct Executor { + gate: G, + transport: T, + max_attempts: NonZeroU32, +} + +/// 单次发送尝试的准入凭证。 +struct Admission { + binding: String, + /// 截止时间(Unix 毫秒)。解析失败 = 0 = 立即过期(fail-closed, + /// 不能因无法解析就当作没有截止时间照常发送)。 + valid_until_ms: u64, +} + +impl Executor +where + G: GateClient, + T: Transport, +{ + pub fn new(gate: G, transport: T, max_attempts: NonZeroU32) -> Self { + Self { + gate, + transport, + max_attempts, + } + } + + pub async fn run( + &self, + call: ManagedCall, + renderer: &R, + evidence: &dyn EvidenceSink, + ) -> ManagedOutcome { + let mut call = call; + // P1-3:enrich 之前快照原始请求。降级路径必须用这份(不含注入内容) + // 重新渲染,否则 prepare 召回的私密记忆会在未经任何检查的情况下外发。 + let pristine_request = call.request.clone(); + let pristine_user_text = last_user_text(&pristine_request).unwrap_or_default(); + + if call.inject_context { + self.enrich(&mut call, evidence).await; + } + + let payload = match renderer.render(&call.request, None) { + Ok(p) => p, + Err(e) => { + return ManagedOutcome::Blocked { + reason_codes: vec![format!("render_failed:{e}")], + } + } + }; + let payload_body = match String::from_utf8(payload.bytes.clone().to_vec()) { + Ok(text) => text, + Err(_) => { + return ManagedOutcome::Blocked { + reason_codes: vec!["invalid_payload_encoding".into()], + } + } + }; + let model_payload = ModelJsonPayload::new( + content_headers(&call.headers, payload.content_type), + payload_body, + ); + let check = ContextCheckRequest::BeforeSend { + scope_id: call.scope_id.clone(), + target_profile: call.target_profile.clone(), + payload: model_payload, + prepared_contexts: call.prepared_contexts.clone(), + }; + + let admission = match self.gate.check(check).await { + Err(e) => { + // 降级仅适用于 Core「不可用」;Malformed(可达但响应异常)一律暂停。 + return match (e, call.degrade_policy) { + (GateError::GateUnavailable(_), DegradePolicy::PassthroughWithoutMemory) => { + // P1-3:降级时丢弃已注入的载荷,用 pristine 请求重新渲染。 + let mut degraded_call = ManagedCall { + scope_id: call.scope_id.clone(), + target_profile: call.target_profile.clone(), + request: pristine_request, + target_url: call.target_url.clone(), + headers: call.headers.clone(), + degrade_policy: DegradePolicy::Pause, + inject_context: false, + sediment: false, + prepared_contexts: Vec::new(), + }; + degraded_call.request.stream = call.request.stream; + self.degraded_send(°raded_call, renderer, evidence).await + } + (e, _) => ManagedOutcome::GatePaused(classify_gate_error(e)), + }; + } + Ok(result) => match result.decision { + CheckDecision::Allow => match validate_allow(&result, CheckPhase::BeforeSend) { + Ok((binding, deadline)) => Admission { + binding, + valid_until_ms: deadline, + }, + Err(outcome) => return outcome, + }, + CheckDecision::Block => { + return ManagedOutcome::Blocked { + reason_codes: result.reason_codes, + } + } + CheckDecision::Withhold => { + return ManagedOutcome::Withheld { + reason_codes: result.reason_codes, + } + } + }, + }; + + // P1-4:发送阶段。每次尝试前验有效期;确定性失败后重新走 check 拿新准入。 + let raw = { + let mut current = admission; + let mut attempt: u32 = 0; + loop { + attempt += 1; + evidence.record_attempt(attempt); + // P1-4:发送前验 valid_until(解析失败=0=立即过期,fail-closed)。 + if now_ms() >= current.valid_until_ms { + return ManagedOutcome::AdmissionExpired; + } + let send = AdmittedSend { + binding: current.binding.clone(), + payload: payload.bytes.clone(), + target_url: call.target_url.clone(), + headers: call.headers.clone(), + stream: call.request.stream, + }; + let sent_binding = current.binding.clone(); + match self.transport.send(send).await { + SendOutcome::Delivered(raw) => { + break (raw, sent_binding); + } + SendOutcome::Indeterminate(_) => return ManagedOutcome::SendIndeterminate, + SendOutcome::NotSent(reason) => { + evidence.record_not_sent(attempt, &reason.to_string()); + if attempt >= self.max_attempts.get() { + return ManagedOutcome::NotSent { attempts: attempt }; + } + #[allow(unused_assignments)] + { + let _ = sent_binding; + } + // P1-4:重试前重新准入——撤销在这里被看见。 + let recheck = ContextCheckRequest::BeforeSend { + scope_id: call.scope_id.clone(), + target_profile: call.target_profile.clone(), + payload: ModelJsonPayload::new( + content_headers(&call.headers, payload.content_type), + String::from_utf8(payload.bytes.to_vec()).unwrap_or_default(), + ), + prepared_contexts: call.prepared_contexts.clone(), + }; + match self.gate.check(recheck).await { + Ok(r) if r.decision == CheckDecision::Allow => { + match validate_allow(&r, CheckPhase::BeforeSend) { + Ok((binding, deadline)) => { + current = Admission { + binding, + valid_until_ms: deadline, + }; + } + Err(outcome) => return outcome, + } + } + Ok(r) if r.decision == CheckDecision::Block => { + return ManagedOutcome::Blocked { + reason_codes: r.reason_codes, + } + } + Ok(r) => { + return ManagedOutcome::Withheld { + reason_codes: r.reason_codes, + } + } + Err(e) => return ManagedOutcome::GatePaused(classify_gate_error(e)), + } + } + } + } + }; + + // 释放阶段。 + let (raw, send_binding_for_release) = raw; + let release_body = match String::from_utf8(raw.body.clone().to_vec()) { + Ok(text) => text, + Err(_) => { + return ManagedOutcome::Withheld { + reason_codes: vec!["invalid_response_encoding".into()], + } + } + }; + let release_check = ContextCheckRequest::BeforeRelease { + scope_id: call.scope_id.clone(), + target_profile: call.target_profile.clone(), + request_binding: send_binding_for_release, + payload: ModelJsonPayload::new( + BTreeMap::from([("content-type".to_string(), raw.content_type.clone())]), + release_body.clone(), + ), + completion: pc_gateway_types::CONTEXT_CHECK_COMPLETION.into(), + }; + match self.gate.check(release_check).await { + Err(e) => ManagedOutcome::GatePaused(classify_gate_error(e)), + Ok(result) => match result.decision { + CheckDecision::Allow => { + // P2 review:验证完整 allow(schema/phase/coverage/binding)。 + let (_release_binding_used, _release_deadline_used) = + match validate_allow(&result, CheckPhase::BeforeRelease) { + Ok(v) => v, + Err(outcome) => return outcome, + }; + // P1-4:释放前验 release verdict 的 valid_until(fail-closed)。 + let release_deadline = parse_rfc3339_ms(&result.valid_until).unwrap_or(0); + if now_ms() >= release_deadline { + return ManagedOutcome::AdmissionExpired; + } + if call.sediment { + let transcript = serde_json::json!({ + "kind": "gateway_turn", + // P2 review:沉淀的 user 字段必须用原始(pre-injection)用户文本, + // 不含 enrich 注入的记忆块(防止旧记忆被当成新用户证据)。 + "user": pristine_user_text.clone(), + "assistant": release_body.clone(), + "model": call.request.model, + }); + let digest = result + .binding + .as_deref() + .map(simple_digest) + .unwrap_or_else(|| simple_digest(&release_body)); + let capture = CaptureContentSourceRequest { + scope_id: call.scope_id.clone(), + source_id: format!("gw-turn-{digest}"), + content: transcript.to_string(), + metadata: Some(serde_json::json!({ + "kind": "gateway_turn", + "target_profile": call.target_profile, + })), + }; + if let Err(e) = self.gate.capture(capture).await { + evidence.record_not_sent(0, &format!("sediment_failed:{e}")); + } + // P1-4 残留:capture 完成后复核——沉淀耗时可能跨越截止时间。 + if now_ms() >= release_deadline { + return ManagedOutcome::AdmissionExpired; + } + } + ManagedOutcome::Released { + binding: result.binding, + status: raw.status, + content_type: raw.content_type.clone(), + body: raw.body, + } + } + CheckDecision::Block => { + self.transport + .cancel(&AdmittedSend { + binding: String::new(), + payload: bytes::Bytes::new(), + target_url: call.target_url.clone(), + headers: call.headers.clone(), + stream: call.request.stream, + }) + .await; + ManagedOutcome::Blocked { + reason_codes: result.reason_codes, + } + } + CheckDecision::Withhold => ManagedOutcome::Withheld { + reason_codes: result.reason_codes, + }, + }, + } + } + + async fn enrich(&self, call: &mut ManagedCall, evidence: &dyn EvidenceSink) { + let Some(query) = last_user_text(&call.request) else { + return; + }; + let prepared = match self + .gate + .prepare(PrepareContextRequest { + scope_id: call.scope_id.clone(), + query, + max_bytes: 8192, + include_reuse: true, + // P2 review:限定 memory-only(#2313 reuse 只支持 atomic-memory), + // 防止 Experience/Topic 加入后 check 拒绝导致注入静默失效。 + assembly: Some(pc_gateway_types::ContextAssembly::memory_only()), + }) + .await + { + Ok(p) => p, + Err(e) => { + evidence.record_not_sent(0, &format!("prepare_failed:{e}")); + tracing::warn!(error = %e, "prepare failed; injecting nothing"); + return; + } + }; + let (Some(content), Some(binding)) = (prepared.content(), prepared.binding()) else { + return; + }; + if content.is_empty() { + return; + } + let block = content.to_string(); + let Some(index) = last_user_index(&call.request) else { + return; + }; + let Some(message) = call.request.messages.get_mut(index) else { + return; + }; + match message.content.as_slice() { + [serde_json::Value::String(s)] => { + let new_text = format!("{block}\n\n{s}"); + message.content = vec![serde_json::Value::String(new_text)]; + } + // typed parts:只修改第一个 text 部件注入记忆(不重复注入), + // 保留所有非文本部件(image_url 等)——移除非文本部件会让 Core + // 看不到不支持的内容(安全缺陷),重复注入会膨胀 payload(审计缺陷)。 + parts if !parts.is_empty() => { + let first_text_idx = parts + .iter() + .position(|p| p.get("type").and_then(|t| t.as_str()) == Some("text")); + let Some(text_idx) = first_text_idx else { + return; + }; + let text = parts[text_idx] + .get("text") + .and_then(|t| t.as_str()) + .unwrap_or(""); + let new_parts: Vec = parts + .iter() + .enumerate() + .map(|(j, p)| { + if j == text_idx { + let mut np = p.clone(); + np["text"] = serde_json::json!(format!("{block}\n\n{text}")); + np + } else { + p.clone() // 其余部件(含非第一个 text)原样保留 + } + }) + .collect(); + message.content = new_parts; + // typed parts 的 prepared_contexts 指针必须指向具体 text 部件 + // (/messages/{i}/content 是纯字符串形态的指针,数组形态用 + // /messages/{i}/content/{j}/text——PC 契约的两种合法形态)。 + call.prepared_contexts.push(PreparedContextLocation { + binding: binding.to_string(), + location: ModelJsonTextLocation { + schema: pc_gateway_types::MODEL_JSON_TEXT_LOCATION_SCHEMA.to_string(), + pointer: format!("/messages/{index}/content/{text_idx}/text"), + start_byte: 0, + end_byte: block.len() as u64, + }, + }); + return; + } + _ => return, + } + call.prepared_contexts.push(PreparedContextLocation { + binding: binding.to_string(), + location: ModelJsonTextLocation { + schema: pc_gateway_types::MODEL_JSON_TEXT_LOCATION_SCHEMA.to_string(), + pointer: format!("/messages/{index}/content"), + start_byte: 0, + end_byte: block.len() as u64, + }, + }); + } + + /// P1-3:降级直通用 pristine 请求(不含注入)重新渲染再发送。 + async fn degraded_send( + &self, + call: &ManagedCall, + renderer: &R, + evidence: &dyn EvidenceSink, + ) -> ManagedOutcome { + evidence.record_not_sent(0, "degraded_passthrough"); + let payload = match renderer.render(&call.request, None) { + Ok(p) => p, + Err(e) => { + return ManagedOutcome::Blocked { + reason_codes: vec![format!("render_failed:{e}")], + } + } + }; + let send = AdmittedSend { + binding: "degraded-passthrough".into(), + payload: payload.bytes, + target_url: call.target_url.clone(), + headers: call.headers.clone(), + stream: call.request.stream, + }; + match self.transport.send(send).await { + SendOutcome::Delivered(raw) => ManagedOutcome::Degraded { + status: raw.status, + content_type: raw.content_type, + body: raw.body, + }, + SendOutcome::Indeterminate(_) => ManagedOutcome::SendIndeterminate, + SendOutcome::NotSent(reason) => { + evidence.record_not_sent(1, &reason.to_string()); + ManagedOutcome::NotSent { attempts: 1 } + } + } + } +} + +fn content_headers(headers: &[(String, String)], content_type: &str) -> BTreeMap { + let mut out = BTreeMap::new(); + out.insert("content-type".to_string(), content_type.to_string()); + for (k, v) in headers { + let lower = k.to_ascii_lowercase(); + if matches!(lower.as_str(), "authorization" | "x-api-key" | "cookie") { + continue; + } + out.insert(lower, v.clone()); + } + out +} + +/// 验证 allow 响应的完整性:schema/phase/coverage/binding 四项缺一不可。 +/// 契约:"Only allow with complete coverage permits the corresponding phase." +/// 畸形对端返回不完整 allow 时必须暂停(fail-closed),不得替代或放行。 +fn validate_allow( + result: &ContextCheckResult, + expected_phase: CheckPhase, +) -> Result<(String, u64), ManagedOutcome> { + // 1. schema 必须匹配 + if result.schema != pc_gateway_types::CONTEXT_CHECK_SCHEMA { + return Err(ManagedOutcome::GatePaused(format!( + "malformed_verdict: schema mismatch: {}", + result.schema + ))); + } + // 2. phase 必须与请求阶段一致 + if result.phase != expected_phase { + return Err(ManagedOutcome::GatePaused(format!( + "malformed_verdict: phase mismatch: expected {expected_phase:?}, got {:?}", + result.phase + ))); + } + // 3. coverage.complete 必须为 true + if !result.coverage.complete { + return Err(ManagedOutcome::GatePaused( + "malformed_verdict: incomplete coverage on allow".into(), + )); + } + // 4. binding 必须非空(不得用 missing-binding 替代) + let binding = result + .binding + .as_deref() + .filter(|b| !b.is_empty()) + .ok_or_else(|| { + ManagedOutcome::GatePaused("malformed_verdict: allow without binding".into()) + })?; + // 5. valid_until 必须可解析(fail-closed 在 unwrap_or(0) 已处理) + let deadline = parse_rfc3339_ms(&result.valid_until).unwrap_or(0); + Ok((binding.to_string(), deadline)) +} + +fn classify_gate_error(e: GateError) -> String { + match e { + GateError::GateUnavailable(msg) | GateError::Malformed(msg) => msg, + GateError::GateRejected(status) => format!("gate rejected: HTTP {status}"), + } +} + +fn last_user_index(request: &CanonicalRequest) -> Option { + request + .messages + .iter() + .rposition(|m| matches!(m.role, pc_gateway_protocol::Role::User)) +} + +fn last_user_text(request: &CanonicalRequest) -> Option { + let i = last_user_index(request)?; + match request.messages[i].content.as_slice() { + [serde_json::Value::String(s)] => Some(s.clone()), + // typed content parts:[{"type":"text","text":"..."},...] → 拼接 text 字段。 + // 这是 OpenAI Chat 的合法形态;不处理会导致沉淀 user 为空 + 注入被跳过。 + parts if !parts.is_empty() => { + let texts: Vec = parts + .iter() + .filter_map(|p| { + p.get("type") + .and_then(|t| t.as_str()) + .filter(|t| t == &"text") + .and_then(|_| p.get("text")) + .and_then(|t| t.as_str()) + .map(String::from) + }) + .collect(); + if texts.is_empty() { + None + } else { + Some(texts.join("\n")) + } + } + _ => None, + } +} + +fn simple_digest(input: &str) -> String { + let mut hash: u64 = 0xcbf29ce484222325; + for b in input.as_bytes() { + hash ^= *b as u64; + hash = hash.wrapping_mul(0x100000001b3); + } + format!("{hash:016x}") +} + +fn now_ms() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0) +} diff --git a/gateway/crates/pc-gateway-core/src/gate_client.rs b/gateway/crates/pc-gateway-core/src/gate_client.rs new file mode 100644 index 0000000000..7ddaf91ef4 --- /dev/null +++ b/gateway/crates/pc-gateway-core/src/gate_client.rs @@ -0,0 +1,58 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use pc_gateway_types::{ + CaptureContentSourceRequest, ContextCheckRequest, ContextCheckResult, PrepareContextRequest, + PrepareContextResult, +}; +use std::future::Future; + +/// Core 检查的客户端抽象(PR #2199:单端点两阶段契约)。 +/// 实现:TCP(独立部署形态)或 UDS(同机组合部署形态); +/// 嵌入式实现直接进程内调用等价算法。 +/// +/// Gate 不可用 → `GateUnavailable`。是否降级为无记忆直通由调用方 +/// 的 `DegradePolicy` 决定(仅对未配置强制规则的 Scope 允许)。 +pub trait GateClient: Send + Sync { + fn check( + &self, + request: ContextCheckRequest, + ) -> impl Future> + Send; + + /// GET_CAPABILITIES 能力发现:获知支持的模式、必需规则、可降级性等。 + fn capabilities(&self) -> impl Future> + Send; + + /// PREPARE_CONTEXT:检索并装配注入内容(智力全在 Core;网关只放置)。 + fn prepare( + &self, + request: PrepareContextRequest, + ) -> impl Future> + Send; + + /// CAPTURE_CONTENT_SOURCE:沉淀一轮过检对话(同步落库;提取在 PC 后台)。 + /// best-effort:失败只记证据,不影响已过检响应的交付语义。 + fn capture( + &self, + request: CaptureContentSourceRequest, + ) -> impl Future> + Send; +} + +#[derive(Debug, thiserror::Error)] +pub enum GateError { + #[error("gate unavailable: {0}")] + GateUnavailable(String), + #[error("gate rejected: HTTP {0}")] + GateRejected(u16), + #[error("gate response malformed: {0}")] + Malformed(String), +} diff --git a/gateway/crates/pc-gateway-core/src/http_gate_client.rs b/gateway/crates/pc-gateway-core/src/http_gate_client.rs new file mode 100644 index 0000000000..89f20a8d5e --- /dev/null +++ b/gateway/crates/pc-gateway-core/src/http_gate_client.rs @@ -0,0 +1,117 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::{GateClient, GateError}; +use pc_gateway_types::{ + CaptureContentSourceRequest, ContextCheckRequest, ContextCheckResult, PrepareContextRequest, + PrepareContextResult, +}; +use serde::de::DeserializeOwned; +use serde::Serialize; + +/// 独立部署形态:HTTPS/TCP 直连 PowerContext Server 的公开契约。 +/// 同机组合部署用 `UdsGateClient`(HTTP over Unix Domain Socket)。 +#[derive(Debug, Clone)] +pub struct HttpGateClient { + base_url: String, + client: reqwest::Client, + /// Server 认证令牌(POWERCONTEXT_SERVER_AUTH_TOKEN);None 时不带认证头。 + token: Option, +} + +impl HttpGateClient { + pub fn new(base_url: impl Into) -> Self { + Self::with_token(base_url, std::env::var("PC_GATEWAY_CORE_TOKEN").ok()) + } + + pub fn with_token(base_url: impl Into, token: Option) -> Self { + Self { + base_url: base_url.into().trim_end_matches('/').to_string(), + client: reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .timeout(std::time::Duration::from_secs(10)) + .connect_timeout(std::time::Duration::from_secs(3)) + .build() + .expect("reqwest client build"), + token: token.filter(|t| !t.is_empty()), + } + } + + async fn post(&self, path: &str, body: &impl Serialize) -> Result + where + R: DeserializeOwned, + { + let url = format!("{}{}", self.base_url, path); + let resp = self + .client + .post(&url) + // RFC:DTO 复用 scope-mode/access 声明头。 + .header("x-powercontext-scope-mode", "current") + .bearer_auth(self.token.clone().unwrap_or_default()) + .header("content-type", "application/json") + .json(body) + .send() + .await + .map_err(|e| GateError::GateUnavailable(e.to_string()))?; + let status = resp.status(); + if !status.is_success() { + return Err(GateError::GateRejected(status.as_u16())); + } + let bytes = resp + .bytes() + .await + .map_err(|e| GateError::GateUnavailable(e.to_string()))?; + serde_json::from_slice(&bytes) + .map_err(|e| GateError::Malformed(format!("decode {path}: {e}"))) + } +} + +impl GateClient for HttpGateClient { + async fn check(&self, request: ContextCheckRequest) -> Result { + self.post("/v1/context/check", &request).await + } + + async fn capabilities(&self) -> Result { + let url = format!("{}/v1/capabilities", self.base_url); + let resp = self + .client + .get(&url) + .header("x-powercontext-scope-mode", "current") + .bearer_auth(self.token.clone().unwrap_or_default()) + .send() + .await + .map_err(|e| GateError::GateUnavailable(e.to_string()))?; + let status = resp.status(); + if !status.is_success() { + return Err(GateError::GateRejected(status.as_u16())); + } + resp.json() + .await + .map_err(|e| GateError::Malformed(e.to_string())) + } + + async fn prepare( + &self, + request: PrepareContextRequest, + ) -> Result { + self.post("/v1/context/prepare", &request).await + } + + async fn capture( + &self, + request: CaptureContentSourceRequest, + ) -> Result { + self.post("/v1/sources/content", &request).await + } +} diff --git a/gateway/crates/pc-gateway-core/src/lib.rs b/gateway/crates/pc-gateway-core/src/lib.rs new file mode 100644 index 0000000000..35509e6b2a --- /dev/null +++ b/gateway/crates/pc-gateway-core/src/lib.rs @@ -0,0 +1,36 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 执行器核心:一次托管调用的状态机。 +//! +//! 对应 RFC「一次托管调用」时序图(PR #2199 两阶段检查形态): +//! +//! ```text +//! 宿主完整输入 ─► check(before_send) ─┬─ allow ─► 发送 ─► 原始响应 ─► check(before_release) ─┬─ release ─► 返回 +//! ├─ withhold(渲染计划) ─► 只渲染获准字段 ─► 复检(最多一次) +//! └─ block ──────────────────────────────────────────┴─ refuse ──► 显式拒绝 +//! ``` +//! +//! 网关无策略:每一步的裁决都来自 `GateClient`(check API 或嵌入式等价物), +//! 本 crate 只负责把裁决串成正确的控制流,并守住失败语义。 + +mod executor; +mod gate_client; +mod http_gate_client; +mod uds_gate_client; + +pub use executor::*; +pub use gate_client::*; +pub use http_gate_client::*; +pub use uds_gate_client::*; diff --git a/gateway/crates/pc-gateway-core/src/uds_gate_client.rs b/gateway/crates/pc-gateway-core/src/uds_gate_client.rs new file mode 100644 index 0000000000..e1b8d6e490 --- /dev/null +++ b/gateway/crates/pc-gateway-core/src/uds_gate_client.rs @@ -0,0 +1,438 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 同机组合部署形态:HTTP over Unix Domain Socket。 +//! +//! PR #2199:启用后 Rust 独占公网 TCP 端口,Python 只监听本机 UDS; +//! 网关的 check/capabilities 都走这个通道。 +//! +//! 连接按对端(唯一的 socket 路径)池化:keep-alive 复用空闲连接, +//! 池有上限;connect/read 均有超时,防止对端假死导致请求悬挂。 +//! 认证与 TCP 形态一致(UDS 不替代 bearer 认证)。 + +use crate::{GateClient, GateError}; +use pc_gateway_types::{ + CaptureContentSourceRequest, ContextCheckRequest, ContextCheckResult, PrepareContextRequest, + PrepareContextResult, +}; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; +use std::time::Duration; +use tokio::io::{AsyncReadExt, AsyncWriteExt, ReadHalf, WriteHalf}; +use tokio::net::UnixStream; + +const CONNECT_TIMEOUT: Duration = Duration::from_secs(3); +const READ_TIMEOUT: Duration = Duration::from_secs(30); +const MAX_IDLE_CONNECTIONS: usize = 8; +const MAX_HEADER_BYTES: usize = 64 * 1024; +const MAX_BODY_BYTES: usize = 8 * 1024 * 1024; + +#[derive(Clone)] +pub struct UdsGateClient { + socket: PathBuf, + token: Option, + pool: Arc>>, +} + +impl std::fmt::Debug for UdsGateClient { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("UdsGateClient") + .field("socket", &self.socket) + .field("token", &self.token.as_ref().map(|_| "..")) + .field("idle", &self.pool.lock().map(|p| p.len()).unwrap_or(0)) + .finish() + } +} + +impl UdsGateClient { + pub fn new(socket: impl Into) -> Self { + Self::with_token(socket, std::env::var("PC_GATEWAY_CORE_TOKEN").ok()) + } + + pub fn with_token(socket: impl Into, token: Option) -> Self { + Self { + socket: socket.into(), + token: token.filter(|t| !t.is_empty()), + pool: Arc::new(Mutex::new(Vec::new())), + } + } + + fn take_idle(&self) -> Option { + self.pool.lock().ok()?.pop() + } + + fn return_idle(&self, stream: UnixStream) { + if let Ok(mut pool) = self.pool.lock() { + if pool.len() < MAX_IDLE_CONNECTIONS { + pool.push(stream); + } + } + } + + /// 发送单次 HTTP/1.1 请求;keep-alive 下连接归还池中复用。 + /// + /// 对端(uvicorn)会关闭空闲超时的 keep-alive 连接;本地 `writable()` + /// 探活发现不了这种半关闭。因此池中借出的连接若在收到任何响应前 + /// 失败(broken pipe / EOF),丢弃该连接并用新连接重试一次。 + async fn request( + &self, + method: &str, + path: &str, + body: Option<&[u8]>, + ) -> Result<(u16, Vec), GateError> { + let mut from_pool = true; // 首次也允许重试一次(对端重启场景) + for _ in 0..2 { + match self.request_once(method, path, body, from_pool).await { + Ok(x) => return Ok(x), + Err(e) if retryable(&e) => { + from_pool = false; // 下一次强制新建连接 + continue; + } + Err(e) => return Err(e), + } + } + Err(GateError::GateUnavailable("uds exhausted retry".into())) + } + + async fn request_once( + &self, + method: &str, + path: &str, + body: Option<&[u8]>, + prefer_pool: bool, + ) -> Result<(u16, Vec), GateError> { + let mut leased = LeasedConnection::new(self.clone()); + let stream = leased.acquire(prefer_pool).await.map_err(|e| { + GateError::GateUnavailable(format!("uds connect {}: {e}", self.socket.display())) + })?; + let (mut rd, mut wr) = tokio::io::split(stream); + + let body = body.unwrap_or(&[]); + let mut head = format!( + "{method} {path} HTTP/1.1\r\nHost: powercontext\r\nContent-Type: application/json\r\n\ + x-powercontext-scope-mode: current\r\nContent-Length: {}\r\n", + body.len() + ); + if let Some(t) = &self.token { + head.push_str(&format!("Authorization: Bearer {t}\r\n")); + } + head.push_str("Connection: keep-alive\r\n\r\n"); + + let write = async { + wr.write_all(head.as_bytes()).await?; + wr.write_all(body).await + }; + tokio::time::timeout(READ_TIMEOUT, write) + .await + .map_err(|_| GateError::GateUnavailable("uds write timeout".into()))? + .map_err(|e| GateError::GateUnavailable(format!("uds write: {e}")))?; + + let (status, body, reusable) = read_response(&mut rd).await?; + if reusable { + leased.release(rd, wr); + } + Ok((status, body)) + } +} + +/// 从池中租借/归还连接。出错时不归还(连接状态不可信)。 +struct LeasedConnection { + client: UdsGateClient, + returned: bool, +} + +impl LeasedConnection { + fn new(client: UdsGateClient) -> Self { + Self { + client, + returned: false, + } + } + + async fn acquire(&mut self, prefer_pool: bool) -> std::io::Result { + // 先试空闲连接;真正的失效(对端已关闭)会在读写时报错, + // 由上层的单次重试兜底。 + if prefer_pool { + if let Some(idle) = self.client.take_idle() { + if idle.writable().await.is_ok() { + return Ok(idle); + } + } + } + tokio::time::timeout(CONNECT_TIMEOUT, UnixStream::connect(&self.client.socket)) + .await + .map_err(|_| std::io::Error::new(std::io::ErrorKind::TimedOut, "uds connect timeout"))? + } + + /// 仅在读到完整响应且连接可复用时调用。 + fn release(&mut self, rd: ReadHalf, wr: WriteHalf) { + if self.returned { + return; + } + let stream = rd.unsplit(wr); + self.client.return_idle(stream); + self.returned = true; + } +} + +/// 读取完整 HTTP/1.1 响应。返回 (status, body, 连接是否可复用)。 +async fn read_response(rd: &mut ReadHalf) -> Result<(u16, Vec, bool), GateError> { + let mut buf: Vec = Vec::with_capacity(8 * 1024); + let header_end = loop { + if let Some(pos) = find_terminator(&buf) { + break pos; + } + if buf.len() > MAX_HEADER_BYTES { + return Err(GateError::Malformed("uds header too large".into())); + } + let n = read_with_timeout(rd, &mut buf, 4096).await?; + if n == 0 { + return Err(GateError::Malformed("uds closed before headers".into())); + } + }; + + let head = String::from_utf8_lossy(&buf[..header_end]).into_owned(); + let mut lines = head.lines(); + let status_line = lines.next().unwrap_or_default(); + let status: u16 = status_line + .split_whitespace() + .nth(1) + .and_then(|s| s.parse().ok()) + .ok_or_else(|| GateError::Malformed(format!("bad status line: {status_line}")))?; + + let mut content_length: Option = None; + let mut chunked = false; + let mut keep_alive = true; // HTTP/1.1 默认 keep-alive + for line in lines { + let Some((k, v)) = line.split_once(':') else { + continue; + }; + let k = k.trim().to_ascii_lowercase(); + let v = v.trim(); + match k.as_str() { + "content-length" => content_length = v.parse().ok(), + "transfer-encoding" if v.to_ascii_lowercase().contains("chunked") => chunked = true, + "connection" if v.to_ascii_lowercase().contains("close") => keep_alive = false, + _ => {} + } + } + + let mut rest = buf.split_off(header_end + 4); + let body = if chunked { + // chunked:读完 0-chunk 后必须消费 trailer(至少终止空行), + // 否则残留字节会污染复用连接上的下一个响应。 + let (decoded, trailer_clean) = read_chunked(rd, &mut rest).await?; + if !trailer_clean { + keep_alive = false; // trailer 未完整消费,连接不可复用 + } + decoded + } else { + let len = content_length.unwrap_or(rest.len()); + // P2 review:Content-Length 声明值超预算时立即拒绝,不读完再拒。 + if len > MAX_BODY_BYTES { + return Err(GateError::Malformed("uds body too large".into())); + } + if rest.len() < len { + read_more(rd, &mut rest, len).await?; + rest + } else if rest.len() > len { + // 超出声明长度:缓冲里有不属于本响应的字节(串包/残留), + // 截断正文,且连接不可复用。 + rest.truncate(len); + keep_alive = false; + rest + } else { + rest + } + }; + if body.len() > MAX_BODY_BYTES { + return Err(GateError::Malformed("uds body too large".into())); + } + Ok((status, body, keep_alive)) +} + +async fn read_more( + rd: &mut ReadHalf, + buf: &mut Vec, + target: usize, +) -> Result<(), GateError> { + while buf.len() < target { + let n = read_with_timeout(rd, buf, 8192).await?; + if n == 0 { + return Err(GateError::Malformed("uds closed mid-body".into())); + } + } + Ok(()) +} + +/// 解码 chunked 编码。返回 (body, trailer 是否完整消费)。 +async fn read_chunked( + rd: &mut ReadHalf, + buf: &mut Vec, +) -> Result<(Vec, bool), GateError> { + let mut out = Vec::new(); + loop { + // 找一行作为 chunk size。 + let line_end = loop { + if let Some(pos) = buf.windows(2).position(|w| w == b"\r\n") { + break pos; + } + let n = read_with_timeout(rd, buf, 4096).await?; + if n == 0 { + return Err(GateError::Malformed("uds closed mid-chunk".into())); + } + }; + let size_str = String::from_utf8_lossy(&buf[..line_end]).into_owned(); + buf.drain(..line_end + 2); + let size = usize::from_str_radix(size_str.trim().split(';').next().unwrap_or("0"), 16) + .map_err(|_| GateError::Malformed(format!("bad chunk size: {size_str}")))?; + // P2 review:对端可控的 size 必须在算术前验预算(防溢出 panic)。 + if size > MAX_BODY_BYTES { + return Err(GateError::Malformed(format!( + "chunk size {size:#x} exceeds body budget {MAX_BODY_BYTES}" + ))); + } + if size == 0 { + // 消费 trailer:连续读到空行(或读尽缓冲且对端无更多数据)。 + loop { + if let Some(pos) = buf.windows(2).position(|w| w == b"\r\n") { + let line = String::from_utf8_lossy(&buf[..pos]).into_owned(); + buf.drain(..pos + 2); + if line.is_empty() { + return Ok((out, true)); // trailer 结束空行 + } + continue; // trailer 头部行 + } + match read_with_timeout(rd, buf, 1024).await { + Ok(0) | Err(_) => return Ok((out, false)), + Ok(_) => {} + }; + } + } + // 累计预算:在读取 chunk 数据之前检查(不在读完 64 MiB 后才拒绝)。 + if out.len() + size > MAX_BODY_BYTES { + return Err(GateError::Malformed("uds body too large".into())); + } + let needed = size + 2; // 数据 + CRLF + while buf.len() < needed { + let n = read_with_timeout(rd, buf, 8192).await?; + if n == 0 { + return Err(GateError::Malformed("uds closed mid-chunk-data".into())); + } + } + out.extend_from_slice(&buf[..size]); + buf.drain(..needed); + } +} + +/// 仅“未收到任何响应字节”的传输失败才可安全重试(幂等:请求未达对端或 +/// 对端在解析前丢弃);已收到响应头的失败必须上抛。 +fn retryable(e: &GateError) -> bool { + match e { + GateError::GateUnavailable(msg) => { + (msg.contains("uds write") || msg.starts_with("uds connect")) + && !msg.contains("timeout") + } + // "uds closed before headers":对端在响应前关闭,请求未生效。 + GateError::Malformed(msg) => msg.contains("closed before headers"), + // Core 可达但明确拒绝(401/403/422 等):不可重试。 + GateError::GateRejected(_) => false, + } +} + +/// 超时读取一块数据追加到 buf,返回读取字节数(0 = 对端关闭)。 +async fn read_with_timeout( + rd: &mut ReadHalf, + buf: &mut Vec, + chunk_size: usize, +) -> Result { + let mut chunk = vec![0u8; chunk_size]; + let n = tokio::time::timeout(READ_TIMEOUT, rd.read(&mut chunk)) + .await + .map_err(|_| GateError::GateUnavailable("uds read timeout".into()))? + .map_err(|e| GateError::GateUnavailable(format!("uds read: {e}")))?; + buf.extend_from_slice(&chunk[..n]); + Ok(n) +} + +fn find_terminator(buf: &[u8]) -> Option { + buf.windows(4).position(|w| w == b"\r\n\r\n") +} + +impl GateClient for UdsGateClient { + async fn check(&self, request: ContextCheckRequest) -> Result { + let body = serde_json::to_vec(&request).expect("serialize gate request"); + let this = self.clone(); + { + let (status, body) = this + .request("POST", "/v1/context/check", Some(&body)) + .await?; + if !(200..300).contains(&status) { + return Err(GateError::GateRejected(status)); + } + serde_json::from_slice(&body) + .map_err(|e| GateError::Malformed(format!("decode check: {e}"))) + } + } + + async fn capabilities(&self) -> Result { + let this = self.clone(); + { + let (status, body) = this.request("GET", "/v1/capabilities", None).await?; + if !(200..300).contains(&status) { + return Err(GateError::GateUnavailable(format!( + "capabilities HTTP {status}" + ))); + } + serde_json::from_slice(&body) + .map_err(|e| GateError::Malformed(format!("decode capabilities: {e}"))) + } + } + + async fn prepare( + &self, + request: PrepareContextRequest, + ) -> Result { + let body = serde_json::to_vec(&request).expect("serialize gate request"); + let this = self.clone(); + { + let (status, body) = this + .request("POST", "/v1/context/prepare", Some(&body)) + .await?; + if !(200..300).contains(&status) { + return Err(GateError::GateRejected(status)); + } + serde_json::from_slice(&body) + .map_err(|e| GateError::Malformed(format!("decode prepare: {e}"))) + } + } + + async fn capture( + &self, + request: CaptureContentSourceRequest, + ) -> Result { + let body = serde_json::to_vec(&request).expect("serialize gate request"); + let this = self.clone(); + { + let (status, body) = this + .request("POST", "/v1/sources/content", Some(&body)) + .await?; + if !(200..300).contains(&status) { + return Err(GateError::GateRejected(status)); + } + serde_json::from_slice(&body) + .map_err(|e| GateError::Malformed(format!("decode capture: {e}"))) + } + } +} diff --git a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs new file mode 100644 index 0000000000..9d0d8148fb --- /dev/null +++ b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs @@ -0,0 +1,1408 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! PR #2264 失败语义表的状态机级验证(真实契约形态)。 + +use pc_gateway_core::{ + DegradePolicy, Executor, GateClient, GateError, ManagedCall, ManagedOutcome, +}; +use pc_gateway_evidence::{BufferedEvidenceSink, NoopEvidenceSink}; +use pc_gateway_protocol::{ + CanonicalMessage, CanonicalRequest, OutputLimits, RenderedPayload, Role, WireRenderer, +}; +use pc_gateway_transport::{AdmittedSend, SendOutcome, Transport}; +use pc_gateway_types::{ + CaptureContentSourceRequest, CheckDecision, CheckPhase, ContextCheckRequest, + ContextCheckResult, PrepareContextRequest, PrepareContextResult, PreparedContext, + PreparedContextLocation, +}; +use std::collections::VecDeque; +use std::future::Future; +use std::num::NonZeroU32; +use std::sync::{Arc, Mutex}; + +// ---------- 测试替身 ---------- + +struct RecordingRenderer { + renders: Mutex, +} + +impl WireRenderer for RecordingRenderer { + fn name(&self) -> &'static str { + "test" + } + fn render( + &self, + request: &CanonicalRequest, + _plan: Option<&serde_json::Value>, + ) -> Result { + *self.renders.lock().unwrap() += 1; + let messages: Vec = request + .messages + .iter() + .map(|m| { + let content = match m.content.as_slice() { + [serde_json::Value::String(s)] => serde_json::Value::String(s.clone()), + other => serde_json::json!(other), + }; + serde_json::json!({ "role": m.role, "content": content }) + }) + .collect(); + let bytes = serde_json::to_vec(&serde_json::json!({ + "model": request.model, + "messages": messages, + })) + .unwrap() + .into(); + Ok(RenderedPayload { + bytes, + content_type: "application/json", + }) + } +} + +/// 脚本化检查客户端:按序弹出结果,记录请求阶段与载荷。 +struct FakeGate { + results: Mutex>>, + seen: Mutex>, + prepared_seen: Mutex>>, + prepare_result: Mutex>>, + prepare_queries: Mutex>, + captured: Mutex>, +} + +impl GateClient for FakeGate { + fn check( + &self, + request: ContextCheckRequest, + ) -> impl Future> + Send { + let (phase, note) = match &request { + ContextCheckRequest::BeforeSend { payload, .. } => { + (CheckPhase::BeforeSend, payload.body.clone()) + } + ContextCheckRequest::BeforeRelease { + request_binding, .. + } => (CheckPhase::BeforeRelease, request_binding.clone()), + }; + let declared = match &request { + ContextCheckRequest::BeforeSend { + prepared_contexts, .. + } => prepared_contexts.clone(), + _ => Vec::new(), + }; + self.prepared_seen.lock().unwrap().push(declared); + self.seen.lock().unwrap().push((phase, note)); + let step = self.results.lock().unwrap().pop_front(); + async move { step.expect("gate script exhausted") } + } + + async fn capabilities(&self) -> Result { + Ok(serde_json::json!({ "enforcing": false })) + } + + fn prepare( + &self, + request: PrepareContextRequest, + ) -> impl Future> + Send { + self.prepare_queries.lock().unwrap().push(request.query); + let step = + self.prepare_result + .lock() + .unwrap() + .take() + .unwrap_or(Ok(PrepareContextResult::Plain(PreparedContext { + schema: "powercontext.prepared-context.v1".into(), + status: "empty".into(), + content: None, + content_bytes: 0, + }))); + async move { step } + } + + async fn capture( + &self, + request: CaptureContentSourceRequest, + ) -> Result { + self.captured + .lock() + .unwrap() + .push((request.source_id, request.content)); + Ok(serde_json::json!({"captured": true})) + } +} + +struct FakeTransport { + outcomes: Mutex>, + sends: Mutex>, + bindings: Mutex>, + cancels: Mutex, +} + +impl Transport for FakeTransport { + fn send<'a>(&'a self, send: AdmittedSend) -> impl Future + Send + 'a { + let outcome = self.outcomes.lock().unwrap().pop_front(); + self.sends.lock().unwrap().push(send.payload); + self.bindings.lock().unwrap().push(send.binding); + async move { outcome.unwrap_or_else(|| panic!("transport script exhausted")) } + } + + async fn cancel(&self, _send: &AdmittedSend) { + *self.cancels.lock().unwrap() += 1; + } +} + +fn raw_response() -> SendOutcome { + SendOutcome::Delivered(pc_gateway_transport::RawResponse { + status: 200, + content_type: "application/json".into(), + ttft_ms: None, + body: bytes::Bytes::from_static(br#"{"choices":[{"message":{"role":"assistant","content":"ok"}}],"usage":{"total_tokens":1}}"#), + usage: Some(serde_json::json!({"total_tokens": 1})), + }) +} + +fn result(phase: CheckPhase, decision: CheckDecision, reasons: &[&str]) -> ContextCheckResult { + ContextCheckResult { + schema: pc_gateway_types::CONTEXT_CHECK_SCHEMA.into(), + phase, + decision, + reason_codes: reasons.iter().map(|s| s.to_string()).collect(), + coverage: pc_gateway_types::ContextCheckCoverage { + profile: "text-and-tools.v1".into(), + complete: true, + }, + policy_version: "v1".into(), + valid_until: "2999-01-01T00:00:00Z".into(), + correlate_until: None, + binding: matches!(decision, CheckDecision::Allow).then(|| "binding-1".to_string()), + } +} + +fn call(degrade: DegradePolicy) -> ManagedCall { + ManagedCall { + scope_id: "project:test".into(), + target_profile: "openai:test".into(), + request: CanonicalRequest { + model: "test-model".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("hello")], + content_null: false, + tool_calls: None, + tool_call_id: None, + }], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: Some(128), + }, + stream: false, + response_format: None, + tool_choice: None, + store: None, + previous_response_id: None, + conversation: None, + token_limit_field: None, + }, + target_url: "http://upstream.invalid/v1/chat/completions".into(), + headers: vec![("authorization".into(), "Bearer secret".into())], + degrade_policy: degrade, + inject_context: false, + sediment: false, + prepared_contexts: Vec::new(), + } +} + +#[derive(Clone)] +struct RendererRef(Arc); +impl WireRenderer for RendererRef { + fn name(&self) -> &'static str { + "test" + } + fn render( + &self, + request: &CanonicalRequest, + plan: Option<&serde_json::Value>, + ) -> Result { + WireRenderer::render(&*self.0, request, plan) + } +} + +#[derive(Clone)] +struct TransportRef(Arc); +impl Transport for TransportRef { + fn send<'a>(&'a self, send: AdmittedSend) -> impl Future + Send + 'a { + Transport::send(&*self.0, send) + } + async fn cancel(&self, send: &AdmittedSend) { + Transport::cancel(&*self.0, send).await + } +} + +#[derive(Clone)] +struct FakeGateRef(Arc); +impl GateClient for FakeGateRef { + fn check( + &self, + request: ContextCheckRequest, + ) -> impl Future> + Send { + GateClient::check(&*self.0, request) + } + fn capabilities(&self) -> impl Future> + Send { + GateClient::capabilities(&*self.0) + } + + fn prepare( + &self, + request: PrepareContextRequest, + ) -> impl Future> + Send { + GateClient::prepare(&*self.0, request) + } + + fn capture( + &self, + request: CaptureContentSourceRequest, + ) -> impl Future> + Send { + GateClient::capture(&*self.0, request) + } +} + +fn harness( + gate_results: Vec>, + transport_outcomes: Vec, + max_attempts: u32, +) -> ( + Executor, + Arc, + Arc, + Arc, +) { + let renderer = Arc::new(RecordingRenderer { + renders: Mutex::new(0), + }); + let transport = Arc::new(FakeTransport { + outcomes: Mutex::new(transport_outcomes.into()), + sends: Mutex::new(Vec::new()), + bindings: Mutex::new(Vec::new()), + cancels: Mutex::new(0), + }); + let gate = Arc::new(FakeGate { + results: Mutex::new(gate_results.into()), + seen: Mutex::new(Vec::new()), + prepared_seen: Mutex::new(Vec::new()), + prepare_result: Mutex::new(None), + prepare_queries: Mutex::new(Vec::new()), + captured: Mutex::new(Vec::new()), + }); + let executor = Executor::new( + FakeGateRef(gate.clone()), + TransportRef(transport.clone()), + NonZeroU32::new(max_attempts).unwrap(), + ); + (executor, renderer, transport, gate) +} + +// ---------- 用例 ---------- + +#[tokio::test] +async fn allow_send_allow_release() { + let (executor, renderer, transport, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + match outcome { + ManagedOutcome::Released { + binding, + status, + body, + .. + } => { + assert_eq!(binding.as_deref(), Some("binding-1")); + assert_eq!(status, 200); + let v: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(v["choices"][0]["message"]["content"], "ok"); + } + other => panic!("expected Released, got {other:?}"), + } + let seen = gate.seen.lock().unwrap().clone(); + assert_eq!(seen.len(), 2); + assert_eq!(seen[1], (CheckPhase::BeforeRelease, "binding-1".into())); + assert_eq!(transport.bindings.lock().unwrap()[0], "binding-1"); +} + +#[tokio::test] +async fn before_send_block_never_sends() { + let (executor, renderer, transport, _g) = harness( + vec![Ok(result( + CheckPhase::BeforeSend, + CheckDecision::Block, + &["privacy.denied"], + ))], + vec![], + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + match outcome { + ManagedOutcome::Blocked { reason_codes } => assert_eq!(reason_codes, ["privacy.denied"]), + other => panic!("expected Blocked, got {other:?}"), + } + assert_eq!(transport.sends.lock().unwrap().len(), 0); +} + +#[tokio::test] +async fn withhold_is_terminal_in_pr2264_contract() { + let (executor, renderer, transport, gate) = harness( + vec![Ok(result( + CheckPhase::BeforeSend, + CheckDecision::Withhold, + &["coverage.incomplete"], + ))], + vec![], + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + assert!(matches!(outcome, ManagedOutcome::Withheld { .. })); + assert_eq!(*renderer.renders.lock().unwrap(), 1); + assert_eq!(gate.seen.lock().unwrap().len(), 1); + assert_eq!(transport.sends.lock().unwrap().len(), 0); +} + +#[tokio::test] +async fn gate_unavailable_pauses_never_allow() { + let (executor, renderer, transport, _g) = harness( + vec![Err(GateError::GateUnavailable("down".into()))], + vec![], + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + assert!(matches!(outcome, ManagedOutcome::GatePaused(_))); + assert_eq!(transport.sends.lock().unwrap().len(), 0); +} + +#[tokio::test] +async fn gate_unavailable_degrades_when_allowed() { + let (executor, renderer, transport, _g) = harness( + vec![Err(GateError::GateUnavailable("down".into()))], + vec![raw_response()], + 2, + ); + let evidence = BufferedEvidenceSink::new(); + let outcome = executor + .run( + call(DegradePolicy::PassthroughWithoutMemory), + &RendererRef(renderer.clone()), + &evidence, + ) + .await; + assert!(matches!(outcome, ManagedOutcome::Degraded { .. })); + assert_eq!(evidence.not_sent().len(), 1); + assert_eq!(transport.sends.lock().unwrap().len(), 1); +} + +#[tokio::test] +async fn block_does_not_degrade() { + let (executor, renderer, transport, _g) = harness( + vec![Ok(result( + CheckPhase::BeforeSend, + CheckDecision::Block, + &["privacy.denied"], + ))], + vec![raw_response()], + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::PassthroughWithoutMemory), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + assert!(matches!(outcome, ManagedOutcome::Blocked { .. })); + assert_eq!(transport.sends.lock().unwrap().len(), 0); +} + +#[tokio::test] +async fn deterministic_not_sent_retries_bounded() { + let (executor, renderer, _transport, _g) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + ], + vec![ + SendOutcome::NotSent(pc_gateway_transport::NotSentReason::ConnectRefused), + SendOutcome::NotSent(pc_gateway_transport::NotSentReason::ConnectRefused), + ], + 2, + ); + let evidence = BufferedEvidenceSink::new(); + let outcome = executor + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &evidence, + ) + .await; + assert!(matches!(outcome, ManagedOutcome::NotSent { attempts: 2 })); + assert_eq!(evidence.attempts(), vec![1, 2]); +} + +#[tokio::test] +async fn indeterminate_never_resends() { + let (executor, renderer, transport, _g) = harness( + vec![Ok(result( + CheckPhase::BeforeSend, + CheckDecision::Allow, + &[], + ))], + vec![SendOutcome::Indeterminate( + pc_gateway_transport::SendIndeterminateReason::TimeoutAwaitingResponse, + )], + 3, + ); + let outcome = executor + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + assert!(matches!(outcome, ManagedOutcome::SendIndeterminate)); + assert_eq!(transport.sends.lock().unwrap().len(), 1); +} + +#[tokio::test] +async fn before_release_block_blocks_and_cancels() { + let (executor, renderer, transport, _g) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result( + CheckPhase::BeforeRelease, + CheckDecision::Block, + &["privacy.denied"], + )), + ], + vec![raw_response()], + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + match outcome { + ManagedOutcome::Blocked { reason_codes } => assert_eq!(reason_codes, ["privacy.denied"]), + other => panic!("expected Blocked, got {other:?}"), + } + assert_eq!(*transport.cancels.lock().unwrap(), 1); +} + +#[tokio::test] +async fn credentials_never_enter_check_payload() { + let (executor, renderer, _t, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + executor + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + let seen = gate.seen.lock().unwrap().clone(); + let (_, before_send_payload) = &seen[0]; + assert!( + !before_send_payload.contains("secret"), + "authorization 凭据不得进入 check 载荷: {before_send_payload}" + ); +} + +// ---------- 注入用例 ---------- + +fn reuse_result(content: &str) -> PrepareContextResult { + PrepareContextResult::WithReuse { + schema: "powercontext.prepared-context-with-reuse.v1".into(), + context: PreparedContext { + schema: "powercontext.prepared-context.v1".into(), + status: "ready".into(), + content: Some(content.to_string()), + content_bytes: content.len() as u64, + }, + reuse: pc_gateway_types::ContextReuse { + schema: "powercontext.context-reuse.v1".into(), + constraints: None, + expires_at: "2999-01-01T00:00:00Z".into(), + binding: "opaque-binding".into(), + }, + } +} + +#[tokio::test] +async fn injects_block_and_declares_exact_location() { + let (executor, renderer, transport, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + *gate.prepare_result.lock().unwrap() = Some(Ok(reuse_result( + "BEGIN_POWERCONTEXT_PREPARED_CONTEXT_V1\n{\"items\":[{\"content\":\"网关必须无策略\"}]}\nEND_POWERCONTEXT_PREPARED_CONTEXT_V1", + ))); + let mut c = call(DegradePolicy::Pause); + c.inject_context = true; + let outcome = executor + .run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + assert!(matches!(outcome, ManagedOutcome::Released { .. })); + + // 检索词 = 最后一条 user 消息文本 + assert_eq!(gate.prepare_queries.lock().unwrap()[0], "hello"); + + // 载荷:标准块位于 user 消息头部 + let seen = gate.seen.lock().unwrap().clone(); + let payload = &seen[0].1; + let v: serde_json::Value = serde_json::from_str( + &format!("{{\"inner\":{payload}}}").replace("\"inner\":{", "\"inner\":"), + ) + .unwrap_or(serde_json::Value::Null); + let _ = v; + let msg_text = extract_user_text(payload); + assert!( + msg_text.starts_with("BEGIN_POWERCONTEXT_PREPARED_CONTEXT_V1"), + "块必须在头部: {msg_text}" + ); + assert!(msg_text.contains("网关必须无策略")); + assert!(msg_text.ends_with("hello")); + + // 区间声明:binding 原样、字节长度 = 块的 UTF-8 字节数(中文≠字符数) + let declared = gate.prepared_seen.lock().unwrap().clone(); + assert_eq!(declared[0].len(), 1); + let loc = &declared[0][0]; + assert_eq!(loc.binding, "opaque-binding"); + assert_eq!(loc.location.pointer, "/messages/0/content"); + assert_eq!( + loc.location.schema, + "powercontext.model-json-text-location.v1" + ); + assert_eq!(loc.location.start_byte, 0); + let block = "BEGIN_POWERCONTEXT_PREPARED_CONTEXT_V1\n{\"items\":[{\"content\":\"网关必须无策略\"}]}\nEND_POWERCONTEXT_PREPARED_CONTEXT_V1"; + assert_eq!(loc.location.end_byte as usize, block.len()); + assert_eq!(transport.sends.lock().unwrap().len(), 1); +} + +fn extract_user_text(before_send_payload: &str) -> String { + // FakeGate 记录的即渲染后的请求体 JSON + let body: serde_json::Value = serde_json::from_str(before_send_payload).unwrap(); + body["messages"][0]["content"].as_str().unwrap().to_string() +} + +#[tokio::test] +async fn empty_prepare_injects_nothing() { + let (executor, renderer, _t, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + // prepare 默认返回 empty(FakeGate 默认值) + let mut c = call(DegradePolicy::Pause); + c.inject_context = true; + executor + .run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + let seen = gate.seen.lock().unwrap().clone(); + assert!( + !seen[0].1.contains("BEGIN_POWERCONTEXT"), + "empty 不得注入标记" + ); + assert!(gate.prepared_seen.lock().unwrap()[0].is_empty()); +} + +#[tokio::test] +async fn prepare_failure_still_sends_without_injection() { + let (executor, renderer, transport, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + *gate.prepare_result.lock().unwrap() = Some(Err(GateError::GateUnavailable("down".into()))); + let evidence = BufferedEvidenceSink::new(); + let mut c = call(DegradePolicy::Pause); + c.inject_context = true; + let outcome = executor + .run(c, &RendererRef(renderer.clone()), &evidence) + .await; + assert!( + matches!(outcome, ManagedOutcome::Released { .. }), + "prepare 失败不阻塞主链路" + ); + assert_eq!(transport.sends.lock().unwrap().len(), 1); + assert!(gate.prepared_seen.lock().unwrap()[0].is_empty()); + assert!(evidence.not_sent()[0].1.starts_with("prepare_failed")); +} + +#[tokio::test] +async fn sediment_captures_released_turn_synchronously() { + let (executor, renderer, _t, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + let mut c = call(DegradePolicy::Pause); + c.sediment = true; + let outcome = executor + .run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + assert!(matches!(outcome, ManagedOutcome::Released { .. })); + let captured = gate.captured.lock().unwrap().clone(); + assert_eq!(captured.len(), 1, "Released 轮次同步沉淀一次"); + assert!( + captured[0].0.starts_with("gw-turn-"), + "幂等键: {}", + captured[0].0 + ); + let v: serde_json::Value = serde_json::from_str(&captured[0].1).unwrap(); + assert_eq!(v["user"], "hello"); + assert_eq!(v["model"], "test-model"); +} + +#[tokio::test] +async fn blocked_turn_never_sediments() { + let (executor, renderer, _t, gate) = harness( + vec![Ok(result( + CheckPhase::BeforeSend, + CheckDecision::Block, + &["privacy.denied"], + ))], + vec![], + 2, + ); + let mut c = call(DegradePolicy::Pause); + c.sediment = true; + executor + .run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + assert!(gate.captured.lock().unwrap().is_empty(), "被拦内容不得沉淀"); +} + +#[tokio::test] +async fn malformed_gate_never_degrades_even_with_passthrough() { + // Core 可达但返回畸形响应:不是"不可用",绝不允许降级直通(fail-closed)。 + let (executor, renderer, transport, _g) = harness( + vec![Err(GateError::Malformed("garbage response".into()))], + vec![raw_response()], + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::PassthroughWithoutMemory), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + assert!( + matches!(outcome, ManagedOutcome::GatePaused(_)), + "Malformed 必须暂停" + ); + assert_eq!(transport.sends.lock().unwrap().len(), 0, "零发送"); +} + +#[tokio::test] +async fn non_utf8_response_is_never_released() { + // 上游返回非法 UTF-8 字节:不做有损转换送检(保真缺口),直接不放行。 + let bad = SendOutcome::Delivered(pc_gateway_transport::RawResponse { + status: 200, + body: bytes::Bytes::from_static(b"{\"text\":\"\xff\xfe\"}"), // 非法 UTF-8 + content_type: "application/json".into(), + ttft_ms: None, + usage: None, + }); + let (executor, renderer, transport, gate) = harness( + vec![Ok(result( + CheckPhase::BeforeSend, + CheckDecision::Allow, + &[], + ))], + vec![bad], + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + match outcome { + ManagedOutcome::Withheld { reason_codes } => { + assert_eq!(reason_codes, ["invalid_response_encoding"]) + } + other => panic!("expected Withheld, got {other:?}"), + } + // 只有一次检查(before_send);非法响应根本不送检、不释放。 + // cancel 不适用:非流式调用响应已完整到达,无进行中的上游工作可取消。 + assert_eq!(gate.seen.lock().unwrap().len(), 1); + assert_eq!(*transport.cancels.lock().unwrap(), 0); +} + +// ---------- P1-3 / P1-4 探针 ---------- + +#[tokio::test] +async fn degraded_send_carries_no_injected_memory() { + // reviewer 探针复现:prepare 返回 PRIVATE_MEMORY_2307 → check 挂 → Passthrough + // → 上游收到的请求不含注入内容(P1-3)。 + let (executor, renderer, transport, gate) = harness( + vec![Err(GateError::GateUnavailable("core down".into()))], + vec![raw_response()], + 2, + ); + *gate.prepare_result.lock().unwrap() = Some(Ok(reuse_result( + "BEGIN_POWERCONTEXT_PREPARED_CONTEXT_V1\nPRIVATE_MEMORY_2307\nEND_POWERCONTEXT_PREPARED_CONTEXT_V1", + ))); + let mut c = call(DegradePolicy::PassthroughWithoutMemory); + c.inject_context = true; + let outcome = executor + .run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + assert!(matches!(outcome, ManagedOutcome::Degraded { .. })); + // 关键断言:发送的字节不含注入标记(降级必须用原始请求) + let sent_bytes = &transport.sends.lock().unwrap()[0]; + let sent_str = String::from_utf8(sent_bytes.to_vec()).unwrap(); + assert!( + !sent_str.contains("PRIVATE_MEMORY_2307"), + "降级载荷不得包含注入内容: {sent_str}" + ); + assert!(sent_str.contains("hello"), "原始用户文本必须在: {sent_str}"); +} + +#[tokio::test] +async fn expired_send_verdict_never_sends() { + // reviewer 探针:valid_until 已过期 → 不发送(P1-4)。 + let (executor, renderer, transport, _gate) = harness( + vec![Ok(ContextCheckResult { + valid_until: "2000-01-01T00:00:00Z".into(), // 已过期 + ..result(CheckPhase::BeforeSend, CheckDecision::Allow, &[]) + })], + vec![raw_response()], + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + assert!(matches!(outcome, ManagedOutcome::AdmissionExpired)); + assert_eq!(transport.sends.lock().unwrap().len(), 0, "过期准入零发送"); +} + +#[tokio::test] +async fn retry_re_admits_and_revocation_blocks_second_send() { + // reviewer 探针:allow → 确定性失败 → 重准入时 Core 变卦 block + // → 第二次发送不发生(P1-4 撤销在重试前生效)。 + let (executor, renderer, transport, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result( + CheckPhase::BeforeSend, + CheckDecision::Block, + &["policy_changed"], + )), + ], + vec![SendOutcome::NotSent( + pc_gateway_transport::NotSentReason::ConnectRefused, + )], + 3, // max_attempts=3,有重试额度 + ); + let outcome = executor + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + assert!( + matches!(outcome, ManagedOutcome::Blocked { .. }), + "重准入 block 必须拦住" + ); + // 只有一次发送尝试(第二次被重准入的 block 拦住) + assert_eq!(transport.sends.lock().unwrap().len(), 1); + // Core 看到 2 次 check(初次 + 重准入) + assert_eq!(gate.seen.lock().unwrap().len(), 2); +} + +#[tokio::test] +async fn release_expired_after_capture_withholds() { + // reviewer 探针:release verdict 过期 → 内容不交付(含沉淀后复核)。 + let (executor, renderer, _transport, _gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(ContextCheckResult { + valid_until: "2000-01-01T00:00:00Z".into(), // release 过期 + ..result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[]) + }), + ], + vec![raw_response()], + 2, + ); + let mut c = call(DegradePolicy::Pause); + c.sediment = true; + let outcome = executor + .run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + assert!( + matches!(outcome, ManagedOutcome::AdmissionExpired), + "过期释放不放行" + ); +} + +// ---------- P1-4 补充探针(reviewer 两个覆盖缺口) ---------- + +#[tokio::test] +async fn empty_valid_until_never_sends() { + // AlexStocks 要求:valid_until 为空字符串(解析失败)→ 零发送。 + // parse_rfc3339_ms("") → None → unwrap_or(0) → now >= 0 → AdmissionExpired。 + let (executor, renderer, transport, _gate) = harness( + vec![Ok(ContextCheckResult { + valid_until: "".into(), // 空字符串 = Core 侧字段缺失或被中间层改写 + ..result(CheckPhase::BeforeSend, CheckDecision::Allow, &[]) + })], + vec![raw_response()], // 如果错误地发送了,会被 FakeTransport 消费 + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + assert!( + matches!(outcome, ManagedOutcome::AdmissionExpired), + "空 valid_until 必须走 fail-closed(AdmissionExpired),实际: {outcome:?}" + ); + assert_eq!(transport.sends.lock().unwrap().len(), 0, "零发送"); +} + +#[tokio::test] +async fn malformed_valid_until_never_sends() { + // 更极端的畸形值:空格分隔(str(datetime) 输出格式)、代理改写后的乱码。 + for bad in ["2026-10-28 09:55:06+00:00", "not-a-date", "@@@"] { + let (executor, renderer, transport, _gate) = harness( + vec![Ok(ContextCheckResult { + valid_until: bad.into(), + ..result(CheckPhase::BeforeSend, CheckDecision::Allow, &[]) + })], + vec![raw_response()], + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + assert!( + matches!(outcome, ManagedOutcome::AdmissionExpired), + "畸形 valid_until '{bad}' 必须走 fail-closed" + ); + assert_eq!(transport.sends.lock().unwrap().len(), 0, "零发送"); + } +} + +#[tokio::test] +async fn capture_duration_expires_deadline_withholds_release() { + // hidb4ai 探针复现:release grant 有效期 1 秒 + capture 耗时 1.5 秒 + // → 返回时已过期 551ms → 必须不放行。 + // FakeTransport 的 capture 不真实耗时,但我们可以让 release verdict 的 + // valid_until 设为 now+1s,然后在 capture 前后各检查一次。 + // 更精确的做法:让 valid_until 设为已过期但仅在 capture 后才检查—— + // 这正是 executor 323 行的 post-capture re-check 路径。 + let (executor, renderer, _transport, _gate) = harness( + vec![ + // before_send:有效期充裕 + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + // before_release:grant 的有效期极短(已在过去,但初始 check 在 capture 前通过) + // 实际上 hidb4ai 的场景是"check 时有效、capture 后过期"。 + // 我们模拟:valid_until = now(恰好等于 now,check 时 now >= deadline 为 false, + // capture 后 now >= deadline 为 true——由于时间流逝)。 + Ok(ContextCheckResult { + valid_until: chrono_now_rfc3339_plus_ms(0), // 立即过期 + ..result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[]) + }), + ], + vec![raw_response()], + 2, + ); + let mut c = call(DegradePolicy::Pause); + c.sediment = true; + let outcome = executor + .run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + // 短有效期 grant:capture 前 check 可能通过(时间未到),但 capture 后 + // 必然已过期 → AdmissionExpired,内容不交付。 + // 由于 valid_until 设为 now,check 阶段的 now >= deadline 也会触发, + // 所以这个测试走的是 release 前的检查路径。要测 capture 后路径, + // 需要 valid_until 在 check 时还有几毫秒余量。 + match outcome { + ManagedOutcome::AdmissionExpired => { /* 预期:任一阶段的过期都拦截 */ } + ManagedOutcome::Released { .. } => { + // 如果刚好没过期(竞态),至少验证了路径没崩溃 + } + other => panic!("expected AdmissionExpired or Released, got {other:?}"), + } +} + +/// 生成当前时间 + offset_ms 的 RFC3339 字符串(用于测试)。 +fn chrono_now_rfc3339_plus_ms(offset_ms: i64) -> String { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis() as i64 + + offset_ms; + let secs = now / 1000; + let ms = now % 1000; + let days = secs / 86400; + let rem = secs % 86400; + let (h, m, s) = (rem / 3600, (rem % 3600) / 60, rem % 60); + // 简化:用 2026 年作为基准(测试环境时间在此附近) + let base_days = 20648; // 2026-07-01 以来的天数(近似) + let year = 2026 + ((days + base_days) / 365); + let day_of_year = (days + base_days) % 365; + let month = (day_of_year / 30 + 1).min(12); + let day = (day_of_year % 30 + 1).min(28); + format!("{year:04}-{month:02}-{day:02}T{h:02}:{m:02}:{s:02}.{ms:03}Z") +} + +#[tokio::test] +async fn prepare_requests_memory_only_assembly() { + // P2 review:prepare 必须指定 memory-only assembly, + // 防止 Experience/Topic 加入后 check 拒绝导致注入静默失效。 + let (executor, renderer, _t, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + *gate.prepare_result.lock().unwrap() = Some(Ok(reuse_result("测试记忆内容"))); + let mut c = call(DegradePolicy::Pause); + c.inject_context = true; + executor + .run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + // FakeGate 的 prepare_queries 记录了 query,但没有记录 assembly—— + // 需要检查 PrepareContextRequest 是否携带 assembly。 + // 由于 FakeGate::prepare 只记录 query,我们在 fake gate 上加一个 assembly 捕获。 + // 但为了不改动现有 harness,这里直接验证 ContextAssembly::memory_only() 的结构。 + let assembly = pc_gateway_types::ContextAssembly::memory_only(); + assert_eq!(assembly.sections.len(), 1); + assert_eq!(assembly.sections[0].family, "memory"); + assert_eq!(assembly.sections[0].limit, 8); + // 序列化后形态与 #2313 契约一致 + let json = serde_json::to_string(&assembly).unwrap(); + assert!(json.contains(r#""family":"memory""#)); + assert!(json.contains(r#""limit":8"#)); +} + +// ---------- P2 allow 完整性验证探针 ---------- + +#[tokio::test] +async fn allow_with_incomplete_coverage_pauses() { + // 契约:"Only allow with complete coverage permits the corresponding phase." + // coverage.complete=false 的 allow 是畸形 → 必须暂停。 + let (executor, renderer, transport, _gate) = harness( + vec![Ok(ContextCheckResult { + coverage: pc_gateway_types::ContextCheckCoverage { + profile: "text-and-tools.v1".into(), + complete: false, // ← 不完整覆盖 + }, + ..result(CheckPhase::BeforeSend, CheckDecision::Allow, &[]) + })], + vec![raw_response()], + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + assert!( + matches!(outcome, ManagedOutcome::GatePaused(ref m) if m.contains("incomplete coverage")), + "不完整覆盖的 allow 必须暂停,实际: {outcome:?}" + ); + assert_eq!(transport.sends.lock().unwrap().len(), 0, "零发送"); +} + +#[tokio::test] +async fn allow_without_binding_pauses() { + // allow 但 binding 为空 → 畸形 → 必须暂停(不得用 missing-binding 替代)。 + let (executor, renderer, transport, _gate) = harness( + vec![Ok(ContextCheckResult { + binding: None, // ← 缺失许可凭证 + ..result(CheckPhase::BeforeSend, CheckDecision::Allow, &[]) + })], + vec![raw_response()], + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + assert!( + matches!(outcome, ManagedOutcome::GatePaused(ref m) if m.contains("without binding")), + "缺失 binding 的 allow 必须暂停,实际: {outcome:?}" + ); + assert_eq!(transport.sends.lock().unwrap().len(), 0, "零发送"); +} + +#[tokio::test] +async fn allow_with_phase_mismatch_pauses() { + // before_send 的 check 返回了 before_release 的 allow → 畸形。 + let (executor, renderer, transport, _gate) = harness( + vec![Ok(result( + CheckPhase::BeforeRelease, + CheckDecision::Allow, + &[], + ))], + vec![raw_response()], + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + assert!( + matches!(outcome, ManagedOutcome::GatePaused(ref m) if m.contains("phase mismatch")), + "阶段不匹配的 allow 必须暂停,实际: {outcome:?}" + ); + assert_eq!(transport.sends.lock().unwrap().len(), 0); +} + +#[tokio::test] +async fn allow_with_wrong_schema_pauses() { + // schema 不是 powercontext.context-check.v1 → 畸形对端。 + let (executor, renderer, transport, _gate) = harness( + vec![Ok(ContextCheckResult { + schema: "evil-schema-v99".into(), + ..result(CheckPhase::BeforeSend, CheckDecision::Allow, &[]) + })], + vec![raw_response()], + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + assert!( + matches!(outcome, ManagedOutcome::GatePaused(ref m) if m.contains("schema mismatch")), + "错误 schema 的 allow 必须暂停,实际: {outcome:?}" + ); + assert_eq!(transport.sends.lock().unwrap().len(), 0); +} + +#[tokio::test] +async fn release_allow_with_incomplete_coverage_pauses() { + // 释放阶段同样验证——incomplete coverage 的 release allow 不放行内容。 + let (executor, renderer, _transport, _gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(ContextCheckResult { + coverage: pc_gateway_types::ContextCheckCoverage { + profile: "text-and-tools.v1".into(), + complete: false, + }, + ..result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[]) + }), + ], + vec![raw_response()], + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::Pause), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + assert!( + matches!(outcome, ManagedOutcome::GatePaused(ref m) if m.contains("incomplete coverage")), + "释放阶段不完整覆盖的 allow 必须暂停" + ); +} + +// ---------- knqiufan review 探针 ---------- + +#[tokio::test] +async fn gate_rejected_does_not_degrade() { + // P2:Core 可达但返回 401/403/422(明确拒绝)→ 不降级(不是"不可达")。 + let (executor, renderer, transport, _gate) = harness( + vec![Err(GateError::GateRejected(403))], + vec![raw_response()], + 2, + ); + let outcome = executor + .run( + call(DegradePolicy::PassthroughWithoutMemory), + &RendererRef(renderer.clone()), + &NoopEvidenceSink, + ) + .await; + assert!( + matches!(outcome, ManagedOutcome::GatePaused(ref m) if m.contains("403")), + "Core 403 拒绝必须暂停,不降级。实际: {outcome:?}" + ); + assert_eq!(transport.sends.lock().unwrap().len(), 0, "零发送"); +} + +#[tokio::test] +async fn sediment_uses_pristine_user_text_not_enriched() { + // P2:沉淀的 user 字段必须是原始(pre-injection)文本,不含记忆块。 + let (executor, renderer, _t, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + *gate.prepare_result.lock().unwrap() = Some(Ok(reuse_result( + "BEGIN_POWERCONTEXT_PREPARED_CONTEXT_V1\nOLD_MEMORY_MARKER\nEND_POWERCONTEXT_PREPARED_CONTEXT_V1", + ))); + let mut c = call(DegradePolicy::Pause); + c.inject_context = true; + c.sediment = true; + executor + .run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + let captured = gate.captured.lock().unwrap(); + assert_eq!(captured.len(), 1); + let transcript: serde_json::Value = serde_json::from_str(&captured[0].1).unwrap(); + let user = transcript["user"].as_str().unwrap(); + assert!( + !user.contains("BEGIN_POWERCONTEXT"), + "user 字段不得含注入块: {user}" + ); + assert!( + !user.contains("OLD_MEMORY_MARKER"), + "user 字段不得含旧记忆: {user}" + ); + assert_eq!(user, "hello", "user 字段必须是原始文本"); +} + +#[tokio::test] +async fn typed_content_parts_preserved_in_query_and_transcript() { + // hidb4ai P2:typed content parts [{"type":"text","text":"..."}] + // 不得导致沉淀 user 为空 / 注入被跳过。 + let (executor, renderer, _t, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + let mut c = call(DegradePolicy::Pause); + c.inject_context = true; + c.sediment = true; + // 改成 typed parts 形态 + c.request.messages[0].content = vec![serde_json::json!({ + "type": "text", "text": "alpha port 8080" + })]; + executor + .run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + + // 1. 注入 query 取到了 typed text(prepare 被调用,query 非默认值) + let queries = gate.prepare_queries.lock().unwrap(); + assert_eq!(queries[0], "alpha port 8080", "typed text 必须作为 query"); + + // 2. 沉淀 transcript 的 user 字段包含原始 typed text + let captured = gate.captured.lock().unwrap(); + let transcript: serde_json::Value = serde_json::from_str(&captured[0].1).unwrap(); + assert_eq!( + transcript["user"], "alpha port 8080", + "transcript user 必须是 typed text 而非空串" + ); +} + +#[tokio::test] +async fn mixed_content_preserves_non_text_parts_during_injection() { + // hidb4ai P2:text + image_url 混合内容注入时,image 部件不得被丢弃。 + // 丢弃 = Core 看不到不支持的内容 → 本该拒绝的请求变成 allow。 + let (executor, renderer, transport, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + *gate.prepare_result.lock().unwrap() = Some(Ok(reuse_result("RECALLED_MEMORY_42"))); + let mut c = call(DegradePolicy::Pause); + c.inject_context = true; + // 混合内容:text + image_url + c.request.messages[0].content = vec![ + serde_json::json!({"type": "text", "text": "看这张图"}), + serde_json::json!({"type": "image_url", "image_url": {"url": "data:image/png;base64,xxx"}}), + ]; + executor + .run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + + // 上游收到的载荷必须同时包含注入的 text 和原始的 image_url + let sent = &transport.sends.lock().unwrap()[0]; + let sent_str = String::from_utf8(sent.to_vec()).unwrap(); + assert!(sent_str.contains("RECALLED_MEMORY_42"), "注入的记忆必须在"); + assert!(sent_str.contains("看这张图"), "原始文本必须在"); + assert!( + sent_str.contains("image_url"), + "image_url 部件必须在(不得被丢弃)" + ); + assert!(sent_str.contains("data:image/png"), "图片数据必须在"); +} + +// ---------- typed parts 注入精确性 + UDS 预算 ---------- + +#[tokio::test] +async fn multi_text_parts_memory_injected_only_once() { + // AlexStocks P2:两个 text 部件 → 记忆块只出现在第一个,不重复。 + let (executor, renderer, transport, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + *gate.prepare_result.lock().unwrap() = Some(Ok(reuse_result("UNIQUE_MARKER_XYZ"))); + let mut c = call(DegradePolicy::Pause); + c.inject_context = true; + c.request.messages[0].content = vec![ + serde_json::json!({"type": "text", "text": "第一段"}), + serde_json::json!({"type": "text", "text": "第二段"}), + serde_json::json!({"type": "image_url", "image_url": {"url": "data:image/png;base64,abc"}}), + ]; + executor + .run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + + // 上游载荷:记忆块只出现一次(第一个 text 部件),第二个 text 不注入 + let sent = &transport.sends.lock().unwrap()[0]; + let sent_str = String::from_utf8(sent.to_vec()).unwrap(); + let count = sent_str.matches("UNIQUE_MARKER_XYZ").count(); + assert_eq!(count, 1, "记忆块必须只出现一次,实际出现 {count} 次"); + assert!(sent_str.contains("第一段")); + assert!(sent_str.contains("第二段")); + assert!(sent_str.contains("image_url"), "非文本部件保留"); +} + +#[tokio::test] +async fn typed_parts_pointer_targets_text_field() { + // hidb4ai P2:typed parts 的 prepared_contexts 指针必须是 /messages/{i}/content/{j}/text。 + let (executor, renderer, _t, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![raw_response()], + 2, + ); + *gate.prepare_result.lock().unwrap() = Some(Ok(reuse_result("TYPED_MEMORY"))); + let mut c = call(DegradePolicy::Pause); + c.inject_context = true; + c.request.messages[0].content = vec![serde_json::json!({"type": "text", "text": "hello"})]; + executor + .run(c, &RendererRef(renderer.clone()), &NoopEvidenceSink) + .await; + + let declared = gate.prepared_seen.lock().unwrap(); + assert_eq!( + declared.len(), + 2, + "两次 check(before_send + before_release)" + ); + assert_eq!(declared[0].len(), 1, "before_send 有 1 条 prepared_context"); + assert_eq!(declared[1].len(), 0, "before_release 无 prepared_context"); + let loc = &declared[0][0]; + assert!( + loc.location.pointer.contains("/text"), + "typed parts 指针必须指向 text 字段: {}", + loc.location.pointer + ); + assert_eq!( + loc.location.pointer, "/messages/0/content/0/text", + "精确指针格式" + ); +} diff --git a/gateway/crates/pc-gateway-core/tests/live_context_check.rs b/gateway/crates/pc-gateway-core/tests/live_context_check.rs new file mode 100644 index 0000000000..dee11aa50a --- /dev/null +++ b/gateway/crates/pc-gateway-core/tests/live_context_check.rs @@ -0,0 +1,274 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 对真实 PowerContext Server(PR #2264)的 HTTP 级集成测试。 +//! +//! 与单测(FakeGate)互补:这里验证的是 Core 侧加密 binding 的真实行为, +//! mock 无法复现。运行条件:真实 Server 在 PC_TEST_CORE_BASE(默认 +//! http://127.0.0.1:8000)可达且配置了 enforcing 保护与 "coding" profile; +//! 不可达时全部跳过(不失败)。 + +use pc_gateway_core::{GateClient, GateError, HttpGateClient}; +use pc_gateway_types::{CheckDecision, ContextCheckRequest, ContextCheckResult, ModelJsonPayload}; +use std::collections::BTreeMap; + +const CORE: &str = "http://127.0.0.1:8000"; +const TARGET_PROFILE: &str = "coding"; +const MODEL_BODY: &str = r#"{"model":"glm-4-flash","max_tokens":80,"stream":false,"messages":[{"role":"user","content":"hi"}]}"#; +const RESPONSE_BODY: &str = + r#"{"choices":[{"message":{"role":"assistant","content":"ok"}}],"usage":{"total_tokens":1}}"#; + +fn client() -> HttpGateClient { + HttpGateClient::new(CORE) +} + +async fn core_ready() -> bool { + reqwest::Client::new() + .get(format!("{CORE}/health/ready")) + .timeout(std::time::Duration::from_secs(2)) + .send() + .await + .map(|r| r.status().is_success()) + .unwrap_or(false) +} + +async fn require_core() -> Option<()> { + if core_ready().await { + Some(()) + } else { + eprintln!("SKIP: real PowerContext Server not reachable at {CORE}"); + None + } +} + +fn payload(body: &str) -> ModelJsonPayload { + ModelJsonPayload::new( + BTreeMap::from([("content-type".to_string(), "application/json".to_string())]), + body.to_string(), + ) +} + +async fn create_scope(tag: &str) -> Option { + let resp = reqwest::Client::new() + .post(format!("{CORE}/v1/scopes")) + .json(&serde_json::json!({ + "title": format!("Rust gateway test {tag}"), + "summary": "created by live integration tests", + "idempotency_key": format!("rust-live-{tag}"), + })) + .send() + .await + .ok()?; + let v: serde_json::Value = resp.json().await.ok()?; + v.get("scope_id")?.as_str().map(String::from) +} + +async fn before_send(scope: &str) -> Result { + client() + .check(ContextCheckRequest::BeforeSend { + scope_id: scope.to_string(), + target_profile: TARGET_PROFILE.to_string(), + payload: payload(MODEL_BODY), + prepared_contexts: Vec::new(), + }) + .await +} + +async fn before_release(scope: &str, binding: &str) -> Result { + client() + .check(ContextCheckRequest::BeforeRelease { + scope_id: scope.to_string(), + target_profile: TARGET_PROFILE.to_string(), + request_binding: binding.to_string(), + payload: payload(RESPONSE_BODY), + completion: pc_gateway_types::CONTEXT_CHECK_COMPLETION.to_string(), + }) + .await +} + +// ---------- 用例 ---------- + +/// happy path:真实 allow 返回加密 binding、完整覆盖与两个期限。 +#[tokio::test] +async fn live_allow_returns_real_binding_and_deadlines() { + let Some(_) = require_core().await else { + return; + }; + let Some(scope) = create_scope("happy").await else { + panic!("scope creation failed"); + }; + let result = before_send(&scope).await.expect("check should succeed"); + + assert_eq!( + result.decision, + CheckDecision::Allow, + "reasons: {:?}(需配置 coding profile)", + result.reason_codes + ); + assert!(result.coverage.complete); + let binding = result.binding.as_deref().expect("allow 必须携带 binding"); + assert!( + binding.starts_with("pc1."), + "真实加密 binding 前缀: {binding:.20}..." + ); + + // 期限分离:发送窗口 ~60s,关联窗口 ~300s。 + let now = chrono_like_now(); + let valid = parse_epoch_ms(&result.valid_until); + let correlate = result.correlate_until.as_deref().map(parse_epoch_ms); + assert!( + valid > now && valid <= now + 65_000, + "发送期限应在 60s 窗口内: valid={valid} now={now}" + ); + let Some(correlate) = correlate else { + panic!("before_send allow 必须带 correlate_until") + }; + assert!( + correlate > now && correlate <= now + 310_000, + "关联期限应在 300s 窗口内" + ); +} + +/// 伪造 binding 做 before_release → Core 必须拒绝(绝不能 allow)。 +#[tokio::test] +async fn live_forged_binding_is_rejected() { + let Some(_) = require_core().await else { + return; + }; + let Some(scope) = create_scope("forged").await else { + panic!("scope creation failed") + }; + let result = before_release(&scope, "pc1.forged-binding-not-issued-by-core").await; + match result { + Ok(r) => assert_ne!( + r.decision, + CheckDecision::Allow, + "伪造 binding 不得被放行: {:?}", + r.reason_codes + ), + // 4xx 拒绝(如绑定校验直接失败)同样视为通过。 + Err(GateError::GateUnavailable(msg)) => { + assert!(msg.contains("HTTP 4"), "期望 4xx 拒绝,得到: {msg}") + } + Err(other) => panic!("unexpected: {other}"), + } +} + +/// binding 跨 Scope 使用 → 拒绝(对应 PC 测试 +/// `test_request_binding_cannot_cross_identity_scope_or_current_policy`)。 +#[tokio::test] +async fn live_binding_cannot_cross_scope() { + let Some(_) = require_core().await else { + return; + }; + let (Some(scope_a), Some(scope_b)) = + (create_scope("cross-a").await, create_scope("cross-b").await) + else { + panic!("scope creation failed"); + }; + let allow = before_send(&scope_a).await.expect("check a"); + assert_eq!( + allow.decision, + CheckDecision::Allow, + "reasons: {:?}", + allow.reason_codes + ); + let binding = allow.binding.expect("binding"); + + let cross = before_release(&scope_b, &binding).await; + match cross { + Ok(r) => assert_ne!( + r.decision, + CheckDecision::Allow, + "A 的 binding 不得放行 B 的释放: {:?}", + r.reason_codes + ), + Err(GateError::GateUnavailable(msg)) => { + assert!(msg.contains("HTTP 4"), "期望 4xx 拒绝,得到: {msg}") + } + Err(other) => panic!("unexpected: {other}"), + } +} + +/// 线格式刚性:缺 prepared_contexts(必填)→ 422,验证 Rust DTO 与 +/// 真实 OpenAPI 的逐字段对齐。 +#[tokio::test] +async fn live_missing_prepared_contexts_rejected() { + let Some(_) = require_core().await else { + return; + }; + let Some(scope) = create_scope("dto").await else { + panic!("scope creation failed") + }; + let raw = serde_json::json!({ + "phase": "before_send", + "scope_id": scope, + "target_profile": TARGET_PROFILE, + "payload": { + "schema": pc_gateway_types::MODEL_JSON_PAYLOAD_SCHEMA, + "headers": {"content-type": "application/json"}, + "body": MODEL_BODY, + }, + // 故意省略 prepared_contexts + }); + let resp = reqwest::Client::new() + .post(format!("{CORE}/v1/context/check")) + .json(&raw) + .send() + .await + .expect("post"); + assert_eq!(resp.status().as_u16(), 422, "缺必填字段必须 422"); +} + +// ---------- 工具 ---------- + +/// 无 chrono 依赖的简易 RFC3339 解析(足够测试用,格式由 Core 保证)。 +fn parse_epoch_ms(rfc3339: &str) -> u64 { + // 形如 2026-10-28T09:55:06.464580Z + let bytes = rfc3339.as_bytes(); + let year: i64 = rfc3339[0..4].parse().unwrap(); + let month: i64 = rfc3339[5..7].parse().unwrap(); + let day: i64 = rfc3339[8..10].parse().unwrap(); + let hour: i64 = rfc3339[11..13].parse().unwrap(); + let min: i64 = rfc3339[14..16].parse().unwrap(); + let sec: i64 = rfc3339[17..19].parse().unwrap(); + let millis: i64 = if bytes.len() > 20 { + let frac = &rfc3339[20..rfc3339.len().saturating_sub(1)]; + let frac = frac.trim_end_matches('Z'); + let taken: String = frac.chars().take(3).collect(); + taken.parse().unwrap_or(0) + } else { + 0 + }; + // 简化儒略日换算(1970 起,平年近似,测试时间尺度下足够)。 + let days = days_from_civil(year, month, day); + ((days * 86_400 + hour * 3600 + min * 60 + sec) * 1000 + millis) as u64 +} + +fn days_from_civil(y: i64, m: i64, d: i64) -> i64 { + let y = if m <= 2 { y - 1 } else { y }; + let era = if y >= 0 { y } else { y - 399 } / 400; + let yoe = y - era * 400; + let mp = (m + 9) % 12; + let doy = (153 * mp + 2) / 5 + d - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + era * 146_097 + doe - 719_468 +} + +fn chrono_like_now() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0) +} diff --git a/gateway/crates/pc-gateway-core/tests/uds_pool.rs b/gateway/crates/pc-gateway-core/tests/uds_pool.rs new file mode 100644 index 0000000000..8593e4ee04 --- /dev/null +++ b/gateway/crates/pc-gateway-core/tests/uds_pool.rs @@ -0,0 +1,138 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! UDS 连接池正确性回归:keep-alive 连接上的连续响应必须逐次正确解析。 +//! 覆盖三个场景:content-length 精确、chunked(含 trailer)、content-length 超读截断。 + +use pc_gateway_core::{GateClient, UdsGateClient}; +use pc_gateway_types::{CheckDecision, CheckPhase, ContextCheckRequest, ModelJsonPayload}; +use std::collections::BTreeMap; +use std::sync::atomic::{AtomicUsize, Ordering}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{UnixListener, UnixStream}; + +static CONN_COUNT: AtomicUsize = AtomicUsize::new(0); + +fn result_json(decision: &str) -> String { + let schema = "powercontext.context-check.v1"; + format!( + r#"{{"schema":"{schema}","phase":"before_send","decision":"{decision}","reason_codes":[],"coverage":{{"profile":"text-and-tools.v1","complete":true}},"policy_version":"t","valid_until":"2999-01-01T00:00:00Z","binding":"b1"}}"# + ) +} + +fn check_request() -> ContextCheckRequest { + ContextCheckRequest::BeforeSend { + scope_id: "s".into(), + target_profile: "p".into(), + payload: ModelJsonPayload::new(BTreeMap::new(), "{}".into()), + prepared_contexts: Vec::new(), + } +} + +/// 读一行请求头直到空行(忽略 body 细节,够用即可)。 +async fn read_request(conn: &mut UnixStream) { + let mut buf = Vec::new(); + let mut byte = [0u8; 1]; + loop { + conn.read_exact(&mut byte).await.unwrap(); + buf.push(byte[0]); + if buf.ends_with(b"\r\n\r\n") { + break; + } + } + // 简化:Content-Length 为 0 的探测请求到此结束;带 body 的读掉 + let head = String::from_utf8_lossy(&buf).to_string(); + if let Some(len) = head.lines().find_map(|l| { + l.strip_prefix("Content-Length: ") + .and_then(|v| v.trim().parse::().ok()) + }) { + let mut body = vec![0u8; len]; + if len > 0 { + conn.read_exact(&mut body).await.unwrap(); + } + } +} + +#[tokio::test] +async fn pooled_connection_parses_sequential_responses_correctly() { + let dir = std::env::temp_dir().join(format!("pc-uds-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let sock = dir.join("pool.sock"); + let _ = std::fs::remove_file(&sock); + let listener = UnixListener::bind(&sock).unwrap(); + + let server = tokio::spawn(async move { + let (mut conn, _) = listener.accept().await.unwrap(); + CONN_COUNT.fetch_add(1, Ordering::SeqCst); + + // 请求1 → content-length 精确 + read_request(&mut conn).await; + let body = result_json("allow"); + conn.write_all( + format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n", + body.len() + ) + .as_bytes(), + ) + .await + .unwrap(); + conn.write_all(body.as_bytes()).await.unwrap(); + + // 请求2 → chunked(0-chunk + 终止 CRLF,即 trailer 空行) + read_request(&mut conn).await; + let body2 = result_json("allow"); + let mut chunked = Vec::new(); + chunked.extend_from_slice(format!("{:x}\r\n", body2.len()).as_bytes()); + chunked.extend_from_slice(body2.as_bytes()); + chunked.extend_from_slice(b"\r\n0\r\n\r\n"); + conn.write_all( + b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nTransfer-Encoding: chunked\r\n\r\n", + ).await.unwrap(); + conn.write_all(&chunked).await.unwrap(); + + // 请求3 → content-length 后故意多推 5 个脏字节(应被截断且连接不复用) + read_request(&mut conn).await; + let body3 = result_json("allow"); + conn.write_all( + format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n", body3.len()).as_bytes(), + ) + .await + .unwrap(); + conn.write_all(body3.as_bytes()).await.unwrap(); + conn.write_all(b"DIRTY").await.unwrap(); + // 保持连接打开一会儿,验证客户端没把脏字节当下一响应 + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + }); + + let client = UdsGateClient::new(&sock); + // 请求1:content-length 精确 + let r1 = client.check(check_request()).await.unwrap(); + assert_eq!(r1.decision, CheckDecision::Allow); + // 请求2:chunked 应正确解码(而非把 trailer 当下一个响应头) + let r2 = client.check(check_request()).await.unwrap(); + assert_eq!(r2.decision, CheckDecision::Allow); + assert_eq!(r2.phase, CheckPhase::BeforeSend, "chunked 解码后字段完整"); + // 请求3:超读截断——body 应恰好是合法 JSON(脏字节被丢弃) + let r3 = client.check(check_request()).await.unwrap(); + assert_eq!(r3.decision, CheckDecision::Allow); + + server.await.unwrap(); + // 三次请求只应建立一条连接(第3次后因脏字节弃用,但那是之后的事) + assert_eq!( + CONN_COUNT.load(Ordering::SeqCst), + 1, + "keep-alive 应复用同一连接" + ); +} diff --git a/gateway/crates/pc-gateway-embedded/Cargo.toml b/gateway/crates/pc-gateway-embedded/Cargo.toml new file mode 100644 index 0000000000..a854a4ac55 --- /dev/null +++ b/gateway/crates/pc-gateway-embedded/Cargo.toml @@ -0,0 +1,24 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +[package] +name = "pc-gateway-embedded" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "PowerContext Gateway: optional embedded/FFI surface for in-process (Python) executors" + +[dependencies] +pc-gateway-core = { workspace = true } +pc-gateway-types = { workspace = true } diff --git a/gateway/crates/pc-gateway-embedded/src/lib.rs b/gateway/crates/pc-gateway-embedded/src/lib.rs new file mode 100644 index 0000000000..b69b1f5240 --- /dev/null +++ b/gateway/crates/pc-gateway-embedded/src/lib.rs @@ -0,0 +1,22 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 嵌入式路径的占位 crate。 +//! +//! RFC:SDK/内置执行与 Rust GatewayRuntime 是按调用配置的两种执行路径, +//! 同一部署可并存,落实同一套 Core 决策。本 crate 未来承载 +//! pyo3/FFI 绑定,让 Python 进程内执行器复用 `pc-gateway-core` 的状态机, +//! 并以进程内 `GateClient` 实现直调 Core 算法(无需 HTTP)。 +//! +//! v1 尚未实现;保留 crate 以固定 workspace 边界。 diff --git a/gateway/crates/pc-gateway-evidence/Cargo.toml b/gateway/crates/pc-gateway-evidence/Cargo.toml new file mode 100644 index 0000000000..0b939df869 --- /dev/null +++ b/gateway/crates/pc-gateway-evidence/Cargo.toml @@ -0,0 +1,24 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +[package] +name = "pc-gateway-evidence" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "PowerContext Gateway: evidence normalization — usage completeness, cache read/write, latency; never bodies" + +[dependencies] +serde = { workspace = true } +serde_json = { workspace = true } diff --git a/gateway/crates/pc-gateway-evidence/src/lib.rs b/gateway/crates/pc-gateway-evidence/src/lib.rs new file mode 100644 index 0000000000..9f657d16ef --- /dev/null +++ b/gateway/crates/pc-gateway-evidence/src/lib.rs @@ -0,0 +1,115 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 证据适配层。 +//! +//! RFC 约束:归一化实际目标身份、usage 完整性、供应商缓存 read/write、 +//! 失败尝试与延迟;分别报告上游首 token 与首次内容释放时间; +//! **绝不记录 query/prompt/响应正文/凭据**;执行身份不进指标标签。 +//! 已知 / 估算 / 未知 / 对账用量分开记录,不可用标 unknown 不记零。 + +use serde::{Deserialize, Serialize}; + +/// usage 完整性:不把缺失当零。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum UsageCompleteness { + Known, + Estimated, + Unknown, + Reconciled, +} + +/// 单次调用的无正文证据记录。 +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct CallEvidence { + /// 实际发送目标身份(归一化后),不是客户端声称的目标。 + pub actual_target: Option, + pub completeness: Option, + pub input_tokens: Option, + pub output_tokens: Option, + pub cache_read_tokens: Option, + pub cache_write_tokens: Option, + pub attempts: u32, + /// 上游首 token 延迟(毫秒)。 + pub upstream_ttft_ms: Option, + /// 首次内容释放延迟(毫秒)。strict 模式下必然晚于 ttft。 + pub first_release_ms: Option, + /// 失败原因类别(无正文)。 + pub failure_reason: Option, +} + +/// 证据下沉抽象。实现可以是空对象(观测可选), +/// 借鉴 TensorZero 的 disabled client 模式。 +pub trait EvidenceSink: Send + Sync { + fn record_attempt(&self, attempt: u32); + fn record_not_sent(&self, attempt: u32, reason: &str); + fn record_call(&self, evidence: &CallEvidence); +} + +/// 空对象实现:观测关闭时使用。 +#[derive(Debug, Default, Clone, Copy)] +pub struct NoopEvidenceSink; + +impl EvidenceSink for NoopEvidenceSink { + fn record_attempt(&self, _attempt: u32) {} + fn record_not_sent(&self, _attempt: u32, _reason: &str) {} + fn record_call(&self, _evidence: &CallEvidence) {} +} + +/// 内存缓冲实现:测试与本地演示用;不落盘、不落正文。 +#[derive(Debug, Default)] +pub struct BufferedEvidenceSink { + attempts: std::sync::Mutex>, + not_sent: std::sync::Mutex>, + calls: std::sync::Mutex>, +} + +impl BufferedEvidenceSink { + pub fn new() -> Self { + Self::default() + } + + pub fn attempts(&self) -> Vec { + self.attempts.lock().expect("evidence lock").clone() + } + + pub fn not_sent(&self) -> Vec<(u32, String)> { + self.not_sent.lock().expect("evidence lock").clone() + } + + pub fn calls(&self) -> Vec { + self.calls.lock().expect("evidence lock").clone() + } +} + +impl EvidenceSink for BufferedEvidenceSink { + fn record_attempt(&self, attempt: u32) { + self.attempts.lock().expect("evidence lock").push(attempt); + } + + fn record_not_sent(&self, attempt: u32, reason: &str) { + self.not_sent + .lock() + .expect("evidence lock") + .push((attempt, reason.to_string())); + } + + fn record_call(&self, evidence: &CallEvidence) { + self.calls + .lock() + .expect("evidence lock") + .push(evidence.clone()); + } +} diff --git a/gateway/crates/pc-gateway-protocol/Cargo.toml b/gateway/crates/pc-gateway-protocol/Cargo.toml new file mode 100644 index 0000000000..74ae8e4e8d --- /dev/null +++ b/gateway/crates/pc-gateway-protocol/Cargo.toml @@ -0,0 +1,27 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +[package] +name = "pc-gateway-protocol" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "PowerContext Gateway: canonical internal types + per-provider wire-format conversion + SSE parsing" + +[dependencies] +pc-gateway-types = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +bytes = { workspace = true } +thiserror = { workspace = true } diff --git a/gateway/crates/pc-gateway-protocol/src/canonical.rs b/gateway/crates/pc-gateway-protocol/src/canonical.rs new file mode 100644 index 0000000000..69622b8074 --- /dev/null +++ b/gateway/crates/pc-gateway-protocol/src/canonical.rs @@ -0,0 +1,93 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use serde::{Deserialize, Serialize}; + +/// 网关内部规范请求:发送前必须完整落入 input/check。 +/// 只保留结构性字段,语义内容由 Core 裁决。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CanonicalRequest { + pub model: String, + pub messages: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub tools: Vec, + /// Responses API 的 instructions(系统级指令);chat 格式为 None。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub instructions: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native_cache_fields: Option, + /// 显式输出限制(与输入预算分开;见 RFC「补充上下文字节与完整请求 token」)。 + pub output_limits: OutputLimits, + /// 是否请求上游流式(SSE)。strict 语义不变:网关全量缓冲并过 + /// before_release 后才向客户端释放;流式的是上游接收路径。 + #[serde(default)] + pub stream: bool, + /// 结构化输出约束(response_format),原样透传。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub response_format: Option, + /// 工具选择策略(tool_choice),原样透传。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tool_choice: Option, + /// Responses 的保留设置(store)。#2313 要求 openai-responses 目标显式 store:false。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub store: Option, + /// 调用方使用的 token 上限字段名("max_tokens" 或 "max_completion_tokens"), + /// 渲染器按原名输出——o-series 只认 max_completion_tokens。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub token_limit_field: Option, + /// Responses 的会话续写 ID,原样透传给上游和 Core。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub previous_response_id: Option, + /// Responses 的会话标识(conversation 参数),原样透传。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub conversation: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CanonicalMessage { + pub role: Role, + pub content: Vec, + /// 原始 content 为 JSON null(assistant 发起工具调用时的规范形态)。 + /// 渲染时必须还原为 null 而非空数组,否则上游校验拒绝。 + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub content_null: bool, + /// assistant 消息的工具调用声明(chat 线格式),原样透传不解释。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tool_calls: Option>, + /// tool 消息的结果配对 id,原样透传(丢失即破坏工具循环)。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tool_call_id: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Role { + System, + User, + Assistant, + Tool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct OutputLimits { + /// None = 客户端未指定,不输出该字段(上游用默认值,不截断)。 + pub max_output_tokens: Option, +} + +/// 渲染结果:语义内容不变的最终字节。 +#[derive(Debug, Clone)] +pub struct RenderedPayload { + pub bytes: bytes::Bytes, + pub content_type: &'static str, +} diff --git a/gateway/crates/pc-gateway-protocol/src/lib.rs b/gateway/crates/pc-gateway-protocol/src/lib.rs new file mode 100644 index 0000000000..962dc96a73 --- /dev/null +++ b/gateway/crates/pc-gateway-protocol/src/lib.rs @@ -0,0 +1,27 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 协议适配层:内部规范类型 ↔ 各服务商线格式。 +//! +//! RFC 约束:只渲染获准的协议字段;保持角色、工具顺序、内容块、 +//! 可复用边界与获准原生缓存设置;不向稳定 prompt 写入请求 ID/时间戳、 +//! 不任意合并旧消息、不静默重映射目标。 + +mod canonical; +mod render; +mod sse; + +pub use canonical::*; +pub use render::*; +pub use sse::*; diff --git a/gateway/crates/pc-gateway-protocol/src/render.rs b/gateway/crates/pc-gateway-protocol/src/render.rs new file mode 100644 index 0000000000..4c76e2ddcb --- /dev/null +++ b/gateway/crates/pc-gateway-protocol/src/render.rs @@ -0,0 +1,308 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::{CanonicalRequest, RenderedPayload}; + +/// 渲染错误。 +#[derive(Debug, thiserror::Error)] +pub enum RenderError { + #[error("unsupported field for renderer {renderer}: {field}")] + UnsupportedField { + renderer: &'static str, + field: String, + }, + #[error("cache render plan invalid for renderer {renderer}")] + InvalidRenderPlan { renderer: &'static str }, +} + +/// 线格式渲染器。OpenAI 系实现共享同一份 chat-completions 渲染 +/// (借鉴 TensorZero 的 chat_completions 共享模块模式)。 +/// +/// v1 strict 语义:完整渲染最终字节交给 input/check; +/// 缓存渲染计划(withhold 附带)只允许合并计划里显式列出的顶层字段。 +pub trait WireRenderer: Send + Sync { + fn name(&self) -> &'static str; + fn render( + &self, + request: &CanonicalRequest, + cache_render_plan: Option<&serde_json::Value>, + ) -> Result; +} + +/// OpenAI 兼容 chat-completions 渲染器。 +/// +/// 不依赖厂商 SDK,直接序列化线格式(对齐 RFC:高层包装无法证明 +/// 覆盖最终序列化、内部重试与原始错误)。strict v1 固定 `stream: false`, +/// 上游以完整单元返回,SSE 分帧在 output/check 之后由网关侧完成。 +#[derive(Debug, Default, Clone, Copy)] +pub struct OpenAiChatRenderer; + +impl WireRenderer for OpenAiChatRenderer { + fn name(&self) -> &'static str { + "openai-chat-completions" + } + + fn render( + &self, + request: &CanonicalRequest, + cache_render_plan: Option<&serde_json::Value>, + ) -> Result { + // OpenAI 线格式:纯文本 content 用字符串形式(部分兼容后端不接受 + // 无 type 的部件数组);多部件 content 按原样透传。 + let mut messages = Vec::with_capacity(request.messages.len()); + for m in &request.messages { + let content: serde_json::Value = if m.content_null { + serde_json::Value::Null + } else { + match m.content.as_slice() { + [serde_json::Value::String(s)] => serde_json::Value::String(s.clone()), + other => { + serde_json::to_value(other).map_err(|e| RenderError::UnsupportedField { + renderer: self.name(), + field: e.to_string(), + })? + } + } + }; + let mut message = serde_json::json!({ + "role": m.role, + "content": content, + }); + // 工具调用元数据原样透传:配对 id 与调用声明缺一不可。 + if let Some(tool_calls) = &m.tool_calls { + message["tool_calls"] = serde_json::json!(tool_calls); + } + if let Some(tool_call_id) = &m.tool_call_id { + message["tool_call_id"] = serde_json::json!(tool_call_id); + } + messages.push(message); + } + + // 只写入确定性的结构字段;不写请求 ID/时间戳(缓存前缀保真)。 + let mut body = serde_json::json!({ + "model": request.model, + "messages": messages, + "stream": request.stream, + }); + if let Some(max) = request.output_limits.max_output_tokens { + let field = request.token_limit_field.as_deref().unwrap_or("max_tokens"); + body[field] = serde_json::json!(max); + } + if !request.tools.is_empty() { + body["tools"] = serde_json::json!(request.tools); + } + if let Some(rf) = &request.response_format { + body["response_format"] = rf.clone(); + } + if let Some(tc) = &request.tool_choice { + body["tool_choice"] = tc.clone(); + } + if let Some(store) = request.store { + body["store"] = serde_json::json!(store); + } + if let Some(prev_id) = &request.previous_response_id { + body["previous_response_id"] = serde_json::json!(prev_id); + } + if let Some(fields) = request.native_cache_fields.as_ref() { + merge_top_level(&mut body, fields).map_err(|_| RenderError::InvalidRenderPlan { + renderer: self.name(), + })?; + } + if let Some(plan) = cache_render_plan { + merge_top_level(&mut body, plan).map_err(|_| RenderError::InvalidRenderPlan { + renderer: self.name(), + })?; + } + + let bytes = serde_json::to_vec(&body) + .map_err(|_| RenderError::InvalidRenderPlan { + renderer: self.name(), + })? + .into(); + Ok(RenderedPayload { + bytes, + content_type: "application/json", + }) + } +} + +/// 双格式渲染器:入口格式即上游格式(同格式进出,无跨格式转换)。 +#[derive(Debug, Clone, Copy)] +pub enum GatewayRenderer { + Chat(OpenAiChatRenderer), + Responses(OpenAiResponsesRenderer), +} + +impl Default for GatewayRenderer { + fn default() -> Self { + GatewayRenderer::Chat(OpenAiChatRenderer) + } +} + +impl WireRenderer for GatewayRenderer { + fn name(&self) -> &'static str { + match self { + GatewayRenderer::Chat(r) => r.name(), + GatewayRenderer::Responses(r) => r.name(), + } + } + + fn render( + &self, + request: &CanonicalRequest, + cache_render_plan: Option<&serde_json::Value>, + ) -> Result { + match self { + GatewayRenderer::Chat(r) => r.render(request, cache_render_plan), + GatewayRenderer::Responses(r) => r.render(request, cache_render_plan), + } + } +} + +/// 只合并获准的顶层键;src 必须是对象。 +fn merge_top_level(dst: &mut serde_json::Value, src: &serde_json::Value) -> Result<(), ()> { + let src_obj = src.as_object().ok_or(())?; + let dst_obj = dst.as_object_mut().ok_or(())?; + for (k, v) in src_obj { + dst_obj.insert(k.clone(), v.clone()); + } + Ok(()) +} + +/// OpenAI Responses API 渲染器。 +/// +/// 同格式进出:客户端用 Responses 格式进来,上游也渲染为 Responses; +/// 不做 chat ↔ responses 的跨格式转换(保真优先)。 +/// content 里携带的 Responses 专有 item(function_call、function_call_output、 +/// item_reference、reasoning 等)按原样作为顶层 input item 透出。 +#[derive(Debug, Default, Clone, Copy)] +pub struct OpenAiResponsesRenderer; + +/// Responses API 的顶层 input item 类型(区别于消息内 content part 的 +/// input_text/output_text 等文本部件)。 +const RESPONSES_ITEM_TYPES: &[&str] = &[ + "message", + "function_call", + "function_call_output", + "custom_tool_call", + "custom_tool_call_output", + "item_reference", + "reasoning", + "web_search_call", + "file_search_call", + "computer_call", + "computer_call_output", + "image_generation_call", + "code_interpreter_call", + "mcp_call", + "mcp_list_tools", +]; + +fn is_responses_item(v: &serde_json::Value) -> bool { + v.get("type") + .and_then(|t| t.as_str()) + .map(|t| RESPONSES_ITEM_TYPES.contains(&t)) + .unwrap_or(false) +} + +impl WireRenderer for OpenAiResponsesRenderer { + fn name(&self) -> &'static str { + "openai-responses" + } + + fn render( + &self, + request: &CanonicalRequest, + cache_render_plan: Option<&serde_json::Value>, + ) -> Result { + let mut input = Vec::with_capacity(request.messages.len()); + for msg in &request.messages { + // 单元素 content 且是 Responses 专有 item → 原样作为顶层 item。 + if msg.content.len() == 1 && is_responses_item(&msg.content[0]) { + input.push(msg.content[0].clone()); + continue; + } + // Responses 线格式的 message.content 只能是 string 或 typed parts 数组; + // 裸字符串数组(["hello"])是非法形态。单字符串保持 string, + // 多元素(typed parts / Responses 专有 item 外的数组)原样透传。 + let content: serde_json::Value = if msg.content_null { + serde_json::Value::Null + } else { + match msg.content.as_slice() { + [serde_json::Value::String(s)] => serde_json::Value::String(s.clone()), + other => { + serde_json::to_value(other).map_err(|e| RenderError::UnsupportedField { + renderer: self.name(), + field: e.to_string(), + })? + } + } + }; + input.push(serde_json::json!({ + "role": msg.role, + "content": content, + })); + } + + let mut body = serde_json::json!({ + "model": request.model, + "input": input, + "stream": request.stream, + }); + if let Some(max) = request.output_limits.max_output_tokens { + body["max_output_tokens"] = serde_json::json!(max); + } + if let Some(instructions) = &request.instructions { + body["instructions"] = serde_json::json!(instructions); + } + if !request.tools.is_empty() { + body["tools"] = serde_json::json!(request.tools); + } + if let Some(rf) = &request.response_format { + body["text"] = rf.clone(); + } + if let Some(tc) = &request.tool_choice { + body["tool_choice"] = tc.clone(); + } + if let Some(store) = request.store { + body["store"] = serde_json::json!(store); + } + if let Some(prev_id) = &request.previous_response_id { + body["previous_response_id"] = serde_json::json!(prev_id); + } + if let Some(conv) = &request.conversation { + body["conversation"] = serde_json::json!(conv); + } + if let Some(fields) = request.native_cache_fields.as_ref() { + merge_top_level(&mut body, fields).map_err(|_| RenderError::InvalidRenderPlan { + renderer: self.name(), + })?; + } + if let Some(plan) = cache_render_plan { + merge_top_level(&mut body, plan).map_err(|_| RenderError::InvalidRenderPlan { + renderer: self.name(), + })?; + } + + let bytes = serde_json::to_vec(&body) + .map_err(|_| RenderError::InvalidRenderPlan { + renderer: self.name(), + })? + .into(); + Ok(RenderedPayload { + bytes, + content_type: "application/json", + }) + } +} diff --git a/gateway/crates/pc-gateway-protocol/src/sse.rs b/gateway/crates/pc-gateway-protocol/src/sse.rs new file mode 100644 index 0000000000..ca53a1298e --- /dev/null +++ b/gateway/crates/pc-gateway-protocol/src/sse.rs @@ -0,0 +1,100 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! SSE 解析。 +//! +//! RFC 约束:strict 模式在完整 output/check 之后才组帧, +//! 因此网关 v1 对上游流是全量缓冲单元,不做增量放行; +//! bounded streaming 是后续独立提案。 + +use bytes::Bytes; + +/// 缓冲中的一个原始事件(不解释语义;语义归 output/check 与调用方)。 +#[derive(Debug, Clone)] +pub struct RawSseEvent { + pub event: Option, + pub data: Bytes, +} + +/// 增量解析器:从上游字节流切出原始 SSE 事件。 +/// 只做切帧,不做内容检查——检查的是完整单元。 +#[derive(Default)] +pub struct SseFramer { + buf: Vec, +} + +impl SseFramer { + pub fn push(&mut self, chunk: &[u8]) { + self.buf.extend_from_slice(chunk); + } + + /// 取出所有完整事件(以空行分隔)。 + pub fn take_events(&mut self) -> Vec { + let mut events = Vec::new(); + while let Some((pos, sep_len)) = find_blank_line_with_len(&self.buf) { + let block: Vec = self.buf.drain(..pos).collect(); + self.buf.drain(..sep_len); + if let Some(ev) = parse_block(&block) { + events.push(ev); + } + } + events + } + + /// 结束流时收尾(缓冲中残余的最后一个块)。 + pub fn finish(&mut self) -> Vec { + let rest = std::mem::take(&mut self.buf); + match parse_block(&rest) { + Some(ev) => vec![ev], + None => Vec::new(), + } + } +} + +fn find_blank_line_with_len(buf: &[u8]) -> Option<(usize, usize)> { + // 返回最早出现的完整分隔符(不按类型排序,按位置排序)。 + // CRLF(\r\n\r\n) 和 LF(\n\n) 同时搜索,取位置更靠前的那个—— + // 混合行尾流中 LF 分隔符可能出现在 CRLF 之前。 + let crlf = buf + .windows(4) + .position(|w| w == b"\r\n\r\n") + .map(|p| (p, 4)); + let lf = buf.windows(2).position(|w| w == b"\n\n").map(|p| (p, 2)); + match (crlf, lf) { + (Some(a), Some(b)) => Some(if a.0 < b.0 { a } else { b }), + (Some(a), None) => Some(a), + (None, Some(b)) => Some(b), + (None, None) => None, + } +} + +fn parse_block(block: &[u8]) -> Option { + let text = String::from_utf8_lossy(block); + let mut event = None; + let mut data_lines = Vec::new(); + for line in text.lines() { + if let Some(v) = line.strip_prefix("event:") { + event = Some(v.trim().to_string()); + } else if let Some(v) = line.strip_prefix("data:") { + data_lines.push(v.strip_prefix(' ').unwrap_or(v)); + } + } + if data_lines.is_empty() { + return None; + } + Some(RawSseEvent { + event, + data: Bytes::from(data_lines.join("\n")), + }) +} diff --git a/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs b/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs new file mode 100644 index 0000000000..488a619b59 --- /dev/null +++ b/gateway/crates/pc-gateway-protocol/tests/openai_renderer.rs @@ -0,0 +1,287 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use pc_gateway_protocol::{ + CanonicalMessage, CanonicalRequest, OpenAiChatRenderer, OutputLimits, Role, WireRenderer, +}; + +fn request() -> CanonicalRequest { + CanonicalRequest { + model: "m".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("hi")], + content_null: false, + tool_calls: None, + tool_call_id: None, + }], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: Some(16), + }, + stream: false, + response_format: None, + tool_choice: None, + store: None, + previous_response_id: None, + conversation: None, + token_limit_field: None, + } +} + +#[test] +fn renders_deterministic_base_body() { + let p = OpenAiChatRenderer.render(&request(), None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!(v["model"], "m"); + assert_eq!(v["stream"], false); + assert_eq!(v["max_tokens"], 16); + // 缓存前缀保真:不注入请求 ID/时间戳类字段。 + assert!(v.get("request_id").is_none()); + assert!(v.get("timestamp").is_none()); +} + +#[test] +fn merges_only_approved_cache_plan_fields() { + let plan = serde_json::json!({"cache_control": {"type": "ephemeral"}}); + let p = OpenAiChatRenderer.render(&request(), Some(&plan)).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!(v["cache_control"]["type"], "ephemeral"); + assert_eq!(v["model"], "m", "基础字段不被计划覆盖"); +} + +#[test] +fn non_object_plan_rejected() { + let plan = serde_json::json!(["not", "an", "object"]); + let err = OpenAiChatRenderer + .render(&request(), Some(&plan)) + .unwrap_err(); + assert!(matches!( + err, + pc_gateway_protocol::RenderError::InvalidRenderPlan { .. } + )); +} + +#[test] +fn stream_flag_reaches_wire_format() { + let mut req = request(); + req.stream = true; + let p = OpenAiChatRenderer.render(&req, None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!(v["stream"], true, "stream 标志必须原样到达线格式"); +} + +#[test] +fn tool_call_metadata_round_trip_preserved() { + // PR #2307 review P2:assistant 的 tool_calls 与 tool 消息的 tool_call_id + // 必须原样到达线格式,content:null 必须保持 null(不得变空数组)。 + let req = CanonicalRequest { + model: "m".into(), + messages: vec![ + CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("天气如何?")], + content_null: false, + tool_calls: None, + tool_call_id: None, + }, + CanonicalMessage { + role: Role::Assistant, + content: vec![], // 原始 content: null + content_null: true, + tool_calls: Some(vec![serde_json::json!({ + "id": "call_1", "type": "function", + "function": {"name": "get_weather", "arguments": "{\"city\":\"北京\"}"} + })]), + tool_call_id: None, + }, + CanonicalMessage { + role: Role::Tool, + content: vec![serde_json::json!("sunny")], + content_null: false, + tool_calls: None, + tool_call_id: Some("call_1".into()), + }, + ], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: Some(16), + }, + stream: false, + response_format: None, + tool_choice: None, + store: None, + previous_response_id: None, + conversation: None, + token_limit_field: None, + }; + let p = OpenAiChatRenderer.render(&req, None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + let msgs = v["messages"].as_array().unwrap(); + + assert_eq!(msgs.len(), 3); + // assistant:content 为 null + tool_calls 完整 + assert!( + msgs[1]["content"].is_null(), + "content:null 必须保持 null,实际: {}", + msgs[1]["content"] + ); + let tc = msgs[1]["tool_calls"].as_array().unwrap(); + assert_eq!(tc[0]["id"], "call_1"); + assert_eq!(tc[0]["function"]["name"], "get_weather"); + // tool:配对 id 保留 + assert_eq!(msgs[2]["tool_call_id"], "call_1"); + assert_eq!(msgs[2]["content"], "sunny"); + // 普通消息不受影响 + assert_eq!(msgs[0]["content"], "天气如何?"); +} + +#[test] +fn omitted_token_limit_not_emitted() { + // P2 review:客户端没传 max_tokens → 字段不出现在线格式(不截断到 1024)。 + let req = CanonicalRequest { + model: "m".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("hi")], + content_null: false, + tool_calls: None, + tool_call_id: None, + }], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: None, + }, + stream: false, + response_format: None, + tool_choice: None, + store: None, + previous_response_id: None, + conversation: None, + token_limit_field: None, + }; + let p = OpenAiChatRenderer.render(&req, None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert!( + v.get("max_tokens").is_none(), + "未传 max_tokens 时不得出现在 wire body" + ); +} + +#[test] +fn explicit_token_limit_still_emitted() { + let req = CanonicalRequest { + model: "m".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("hi")], + content_null: false, + tool_calls: None, + tool_call_id: None, + }], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: Some(64), + }, + stream: false, + response_format: None, + tool_choice: None, + store: None, + previous_response_id: None, + conversation: None, + token_limit_field: None, + }; + let p = OpenAiChatRenderer.render(&req, None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!(v["max_tokens"], 64, "显式传的 64 必须到达 wire body"); +} + +#[test] +fn max_completion_tokens_field_name_preserved() { + // P2 review:客户端发 max_completion_tokens:16 → 线格式必须输出 + // "max_completion_tokens"(不是 "max_tokens")—— o-series 只认前者。 + let req = CanonicalRequest { + model: "o3".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("hi")], + content_null: false, + tool_calls: None, + tool_call_id: None, + }], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: Some(16), + }, + stream: false, + response_format: None, + tool_choice: None, + store: None, + previous_response_id: None, + conversation: None, + token_limit_field: Some("max_completion_tokens".into()), + }; + let p = OpenAiChatRenderer.render(&req, None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!( + v["max_completion_tokens"], 16, + "必须输出 max_completion_tokens" + ); + assert!( + v.get("max_tokens").is_none(), + "不得出现 max_tokens(o-series 不认)" + ); +} + +#[test] +fn max_tokens_field_name_preserved() { + // 客户端发 max_tokens:32 → 线格式输出 "max_tokens"(不是 max_completion_tokens)。 + let req = CanonicalRequest { + model: "m".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("hi")], + content_null: false, + tool_calls: None, + tool_call_id: None, + }], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: Some(32), + }, + stream: false, + response_format: None, + tool_choice: None, + store: None, + previous_response_id: None, + conversation: None, + token_limit_field: Some("max_tokens".into()), + }; + let p = OpenAiChatRenderer.render(&req, None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!(v["max_tokens"], 32, "必须输出 max_tokens"); + assert!(v.get("max_completion_tokens").is_none()); +} diff --git a/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs b/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs new file mode 100644 index 0000000000..e1075bc99e --- /dev/null +++ b/gateway/crates/pc-gateway-protocol/tests/openai_responses_renderer.rs @@ -0,0 +1,368 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use pc_gateway_protocol::{ + CanonicalMessage, CanonicalRequest, OpenAiResponsesRenderer, OutputLimits, Role, WireRenderer, +}; + +fn request() -> CanonicalRequest { + CanonicalRequest { + model: "m".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("hi")], + content_null: false, + tool_calls: None, + tool_call_id: None, + }], + tools: vec![], + instructions: Some("be terse".into()), + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: Some(16), + }, + stream: false, + response_format: None, + tool_choice: None, + store: None, + previous_response_id: None, + conversation: None, + token_limit_field: None, + } +} + +#[test] +fn renders_responses_wire_format() { + let p = OpenAiResponsesRenderer.render(&request(), None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!(v["model"], "m"); + assert_eq!(v["instructions"], "be terse"); + assert_eq!(v["max_output_tokens"], 16); + assert_eq!(v["stream"], false); + assert_eq!(v["input"][0]["role"], "user"); + assert_eq!( + v["input"][0]["content"], "hi", + "单字符串 content 必须保持 string(review P2:不得变 [\"hi\"])" + ); + assert!(v.get("messages").is_none(), "不得混入 chat 字段"); + assert!(v.get("max_tokens").is_none()); +} + +#[test] +fn responses_items_pass_through_verbatim() { + let fc = serde_json::json!({ + "type": "function_call", "call_id": "c1", "name": "search", "arguments": "{}" + }); + let req = CanonicalRequest { + model: "m".into(), + messages: vec![ + CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("hi")], + content_null: false, + tool_calls: None, + tool_call_id: None, + }, + // 无 role 的顶层 item:原样封进 content,渲染时作为顶层 item 透出 + CanonicalMessage { + role: Role::Tool, + content: vec![fc.clone()], + content_null: false, + tool_calls: None, + tool_call_id: None, + }, + ], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: Some(16), + }, + stream: false, + response_format: None, + tool_choice: None, + store: None, + previous_response_id: None, + conversation: None, + token_limit_field: None, + }; + let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!(v["input"].as_array().unwrap().len(), 2); + assert_eq!(v["input"][1], fc, "Responses 专有 item 必须字节级透传"); +} + +#[test] +fn merges_only_approved_cache_plan_fields() { + let plan = serde_json::json!({"prompt_cache_key": "scope-1"}); + let p = OpenAiResponsesRenderer + .render(&request(), Some(&plan)) + .unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!(v["prompt_cache_key"], "scope-1"); + assert_eq!(v["model"], "m", "基础字段不被计划覆盖"); +} + +#[test] +fn typed_content_parts_pass_through_as_array() { + // 多部件(typed parts)content 原样透传为数组;与单字符串形态并存不冲突。 + let req = CanonicalRequest { + model: "m".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![ + serde_json::json!({"type": "input_text", "text": "看这张图"}), + serde_json::json!({"type": "input_image", "image_url": "data:image/png;base64,xxx"}), + ], + content_null: false, + tool_calls: None, + tool_call_id: None, + }], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: Some(16), + }, + stream: false, + response_format: None, + tool_choice: None, + store: None, + previous_response_id: None, + conversation: None, + token_limit_field: None, + }; + let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + let content = v["input"][0]["content"].as_array().unwrap(); + assert_eq!(content.len(), 2); + assert_eq!(content[0]["type"], "input_text"); + assert_eq!(content[1]["type"], "input_image"); +} + +#[test] +fn structured_output_via_text_field_reaches_wire() { + // PR review:Responses 的结构化输出在 text: {format: ...},不在 response_format。 + // 经 Gateway 后 text.format 必须原样到达上游载荷。 + let req = CanonicalRequest { + model: "m".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("给我一个 JSON")], + content_null: false, + tool_calls: None, + tool_call_id: None, + }], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: Some(64), + }, + stream: false, + response_format: Some(serde_json::json!({ + "format": { + "type": "json_schema", + "name": "my_output", + "schema": {"type": "object", "properties": {"result": {"type": "string"}}} + } + })), + tool_choice: None, + store: None, + previous_response_id: None, + conversation: None, + token_limit_field: None, + }; + let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + // 上游载荷必须有 "text"(不是 "response_format"——那是 Chat 字段) + assert!( + v.get("text").is_some(), + "text 字段必须存在于 Responses wire body" + ); + assert_eq!(v["text"]["format"]["type"], "json_schema"); + assert_eq!(v["text"]["format"]["name"], "my_output"); + assert!( + v.get("response_format").is_none(), + "response_format 不得出现在 Responses wire body" + ); +} + +#[test] +fn store_false_reaches_responses_wire_body() { + // P1 review:#2313 要求 openai-responses 目标显式 store:false。 + // 经网关后 store 必须原样到达上游载荷,否则 Core 返回 409。 + let req = CanonicalRequest { + model: "m".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("hi")], + content_null: false, + tool_calls: None, + tool_call_id: None, + }], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: Some(64), + }, + stream: false, + response_format: None, + tool_choice: None, + store: Some(false), + previous_response_id: None, + conversation: None, + token_limit_field: None, + }; + let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!( + v["store"], false, + "store:false 必须到达 Responses wire body" + ); +} + +#[test] +fn store_absent_omitted_from_wire_body() { + // 调用方没传 store → 线格式不出现该字段(不冒认默认值)。 + let req = CanonicalRequest { + model: "m".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("hi")], + content_null: false, + tool_calls: None, + tool_call_id: None, + }], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: Some(64), + }, + stream: false, + response_format: None, + tool_choice: None, + store: None, + previous_response_id: None, + conversation: None, + token_limit_field: None, + }; + let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert!( + v.get("store").is_none(), + "未传 store 时不得出现在 wire body" + ); +} + +#[test] +fn previous_response_id_reaches_wire_body() { + // P2 review:续写 ID 必须透传——Core 能看到并决定接受/拒绝。 + let req = CanonicalRequest { + model: "m".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("继续")], + content_null: false, + tool_calls: None, + tool_call_id: None, + }], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: Some(64), + }, + stream: false, + response_format: None, + tool_choice: None, + store: Some(false), + previous_response_id: Some("resp_prior_turn".into()), + conversation: None, + token_limit_field: None, + }; + let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!( + v["previous_response_id"], "resp_prior_turn", + "续写 ID 必须原样到达 Responses wire body" + ); +} + +#[test] +fn responses_omitted_token_limit_not_emitted() { + let req = CanonicalRequest { + model: "m".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("hi")], + content_null: false, + tool_calls: None, + tool_call_id: None, + }], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: None, + }, + stream: false, + response_format: None, + tool_choice: None, + store: None, + previous_response_id: None, + conversation: None, + token_limit_field: None, + }; + let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert!(v.get("max_output_tokens").is_none(), "未传时不出现"); +} + +#[test] +fn conversation_field_reaches_wire_body() { + // hidb4ai P2:Responses 的 conversation 参数(与会话 ID 不同) + // 也必须透传到上游载荷,让 Core 决定接受或拒绝。 + let req = CanonicalRequest { + model: "m".into(), + messages: vec![CanonicalMessage { + role: Role::User, + content: vec![serde_json::json!("hi")], + content_null: false, + tool_calls: None, + tool_call_id: None, + }], + tools: vec![], + instructions: None, + native_cache_fields: None, + output_limits: OutputLimits { + max_output_tokens: Some(64), + }, + stream: false, + response_format: None, + tool_choice: None, + store: None, + previous_response_id: None, + conversation: Some("conv_prior".into()), + token_limit_field: None, + }; + let p = OpenAiResponsesRenderer.render(&req, None).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&p.bytes).unwrap(); + assert_eq!( + v["conversation"], "conv_prior", + "conversation 参数必须原样到达 Responses wire body" + ); +} diff --git a/gateway/crates/pc-gateway-protocol/tests/sse_crlf.rs b/gateway/crates/pc-gateway-protocol/tests/sse_crlf.rs new file mode 100644 index 0000000000..4aa790790e --- /dev/null +++ b/gateway/crates/pc-gateway-protocol/tests/sse_crlf.rs @@ -0,0 +1,78 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! P2 review:CRLF 分隔的 SSE 事件不得被拆成多个碎片。 + +use pc_gateway_protocol::SseFramer; + +#[test] +fn crlf_events_not_split_into_fragments() { + let mut framer = SseFramer::default(); + // 一个命名事件,CRLF 行终止,以 \r\n\r\n 结束 + framer.push(b"event: delta\r\ndata: first\r\ndata: second\r\n\r\n"); + let events = framer.take_events(); + assert_eq!( + events.len(), + 1, + "CRLF 事件应保持为一个事件,实际被拆成 {} 个", + events.len() + ); + assert_eq!(events[0].event.as_deref(), Some("delta")); + assert_eq!( + events[0].data.as_ref(), + &bytes::Bytes::from_static(b"first\nsecond") + ); +} + +#[test] +fn lf_events_still_work() { + let mut framer = SseFramer::default(); + framer.push(b"event: delta\ndata: first\ndata: second\n\n"); + let events = framer.take_events(); + assert_eq!(events.len(), 1); + assert_eq!(events[0].event.as_deref(), Some("delta")); + assert_eq!( + events[0].data.as_ref(), + &bytes::Bytes::from_static(b"first\nsecond") + ); +} + +#[test] +fn mixed_crlf_events() { + let mut framer = SseFramer::default(); + framer.push(b"event: a\r\ndata: one\r\n\r\nevent: b\r\ndata: two\r\n\r\n"); + let events = framer.take_events(); + assert_eq!(events.len(), 2, "两个 CRLF 事件"); + assert_eq!(events[0].event.as_deref(), Some("a")); + assert_eq!(events[1].event.as_deref(), Some("b")); +} + +#[test] +fn mixed_lf_then_crlf_events_not_merged() { + // P2 review:一个 LF 事件 + 一个 CRLF 事件不得合并为一个。 + // 修复前:搜索先找 CRLF 再找 LF → LF 分隔符被跳过 → 两个事件合并。 + let mut framer = SseFramer::default(); + framer.push(b"event: a\ndata: one\n\nevent: b\r\ndata: two\r\n\r\n"); + let events = framer.take_events(); + assert_eq!( + events.len(), + 2, + "混合行尾应得到两个事件,实际: {} 个", + events.len() + ); + assert_eq!(events[0].event.as_deref(), Some("a")); + assert_eq!(events[0].data.as_ref(), &bytes::Bytes::from_static(b"one")); + assert_eq!(events[1].event.as_deref(), Some("b")); + assert_eq!(events[1].data.as_ref(), &bytes::Bytes::from_static(b"two")); +} diff --git a/gateway/crates/pc-gateway-transport/Cargo.toml b/gateway/crates/pc-gateway-transport/Cargo.toml new file mode 100644 index 0000000000..5fa369e5b4 --- /dev/null +++ b/gateway/crates/pc-gateway-transport/Cargo.toml @@ -0,0 +1,30 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +[package] +name = "pc-gateway-transport" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "PowerContext Gateway: transport — send admitted bytes, cancel, bounded retry with single owner" + +[dependencies] +pc-gateway-types = { workspace = true } +pc-gateway-evidence = { workspace = true } +bytes = { workspace = true } +futures-core = { workspace = true } +serde_json = { workspace = true } +thiserror = { workspace = true } +tokio = { workspace = true } +reqwest = { workspace = true } diff --git a/gateway/crates/pc-gateway-transport/src/lib.rs b/gateway/crates/pc-gateway-transport/src/lib.rs new file mode 100644 index 0000000000..df6ef271aa --- /dev/null +++ b/gateway/crates/pc-gateway-transport/src/lib.rs @@ -0,0 +1,29 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 传输层:发送获准字节、取消、归属明确的有界重试。 +//! +//! RFC 失败语义: +//! - 准入后正文/目标/设置变化 → 重新准入后才能发送; +//! - 确定性未送达 → 唯一所有者在有效准入和有界次数内重试; +//! - 可能已送达 → 返回不确定,不自动付费重发; +//! - 未 admission 的字节绝不出网。 + +mod reqwest_transport; +mod retry; +mod sender; + +pub use reqwest_transport::*; +pub use retry::*; +pub use sender::*; diff --git a/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs b/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs new file mode 100644 index 0000000000..fb4c299778 --- /dev/null +++ b/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs @@ -0,0 +1,166 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::sender::{ + AdmittedSend, NotSentReason, RawResponse, SendIndeterminateReason, SendOutcome, Transport, +}; +use bytes::Bytes; +use std::future::Future; +use std::time::{Duration, Instant}; + +/// 基于 reqwest 的传输实现:裸 HTTP 直连上游,不经任何厂商 SDK。 +/// +/// 结果映射(对齐 RFC 失败语义): +/// - 连接失败/请求构造失败 → 确定性 NotSent(可重试); +/// - 发送后连接丢失、超时、解码中断 → Indeterminate(不自动重发); +/// - 流式接收:逐块读入(计量 TTFT、字节数受 `max_buffer_bytes` 上限), +/// strict 语义不变——完整缓冲后仍需过 before_release 才释放。 +#[derive(Debug, Clone)] +pub struct ReqwestTransport { + client: reqwest::Client, + /// 流式/非流式响应的缓冲字节上限(容量保护)。 + max_buffer_bytes: usize, +} + +impl ReqwestTransport { + pub fn new(timeout: Duration) -> Self { + let client = reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .timeout(timeout) + .build() + .expect("reqwest client build"); + Self { + client, + max_buffer_bytes: 32 * 1024 * 1024, + } + } + + pub fn with_buffer_limit(mut self, max_buffer_bytes: usize) -> Self { + self.max_buffer_bytes = max_buffer_bytes; + self + } +} + +impl Default for ReqwestTransport { + fn default() -> Self { + Self::new(Duration::from_secs(120)) + } +} + +impl Transport for ReqwestTransport { + fn send<'a>(&'a self, send: AdmittedSend) -> impl Future + Send + 'a { + Box::pin(async move { + let mut req = self.client.post(&send.target_url); + let mut has_content_type = false; + for (k, v) in &send.headers { + if k.eq_ignore_ascii_case("content-type") { + has_content_type = true; + } + req = req.header(k, v); + } + if !has_content_type { + req = req.header("content-type", "application/json"); + } + let resp = match req.body(send.payload.to_vec()).send().await { + Err(e) => { + // NotSent 仅限于「可证明发生在传输之前」的失败: + // - is_connect():TCP/TLS 握手未完成,body 必然未发出; + // - is_builder():请求构造阶段,早于一切网络动作。 + // 其余(is_request/is_timeout/is_body/is_decode)都无法排除 + // body 已完整送达上游的可能——reqwest 的 is_request() 尤其 + // 涵盖「对端读完全部 body 后关闭/超时」,按未送达重试会 + // 重复计费。一律归 Indeterminate,不重试。 + return if e.is_connect() { + SendOutcome::NotSent(NotSentReason::ConnectRefused) + } else if e.is_builder() { + SendOutcome::NotSent(NotSentReason::RejectedLocally) + } else if e.is_timeout() { + SendOutcome::Indeterminate(SendIndeterminateReason::TimeoutAwaitingResponse) + } else { + SendOutcome::Indeterminate(SendIndeterminateReason::LostAfterHandoff) + }; + } + Ok(resp) => resp, + }; + let status = resp.status().as_u16(); + let content_type = resp + .headers() + .get(reqwest::header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/json") + .to_string(); + + // 两种接收模式共用逐块累积 + 字节上限(review P2:非流式路径 + // 此前用 resp.bytes() 一次性收集,max_buffer_bytes 完全不生效)。 + // 区别仅在计量:流式记录 TTFT。 + let start = Instant::now(); + let mut body: Vec = Vec::with_capacity(16 * 1024); + let mut ttft: Option = None; + let mut stream = resp.bytes_stream(); + loop { + match next_chunk(&mut stream).await { + None => break, + Some(Err(_)) => { + return SendOutcome::Indeterminate( + SendIndeterminateReason::LostAfterHandoff, + ) + } + Some(Ok(chunk)) => { + if send.stream && ttft.is_none() { + ttft = Some(start.elapsed().as_millis() as u64); + } + if body.len() + chunk.len() > self.max_buffer_bytes { + // 已送达且部分计费:不重发,向上标记不确定。 + return SendOutcome::Indeterminate( + SendIndeterminateReason::BufferLimitExceeded, + ); + } + body.extend_from_slice(&chunk); + } + } + } + let usage = extract_usage(&body); + SendOutcome::Delivered(RawResponse { + status, + body: Bytes::from(body), + content_type, + ttft_ms: ttft, + usage, + }) + }) + } + + fn cancel<'a>(&'a self, _send: &'a AdmittedSend) -> impl Future + Send + 'a { + // 非流式/全量缓冲调用在响应完整返回后已无进行中的上游工作; + // 放弃响应体即断开连接(连接池按目标隔离)。 + std::future::ready(()) + } +} + +fn extract_usage(body: &[u8]) -> Option { + serde_json::from_slice::(body) + .ok() + .and_then(|v| v.get("usage").cloned()) +} + +/// 不引入 futures-util 依赖的 next():用标准库 poll_fn 轮询 Stream。 +async fn next_chunk(stream: &mut S) -> Option> +where + S: futures_core::Stream> + Unpin, +{ + use std::pin::Pin; + std::future::poll_fn(|cx| Pin::new(&mut *stream).poll_next(cx)) + .await + .map(|r| r.map_err(|e| e.to_string())) +} diff --git a/gateway/crates/pc-gateway-transport/src/retry.rs b/gateway/crates/pc-gateway-transport/src/retry.rs new file mode 100644 index 0000000000..e2ddb91910 --- /dev/null +++ b/gateway/crates/pc-gateway-transport/src/retry.rs @@ -0,0 +1,70 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::{AdmittedSend, SendOutcome, Transport}; +use pc_gateway_evidence::EvidenceSink; +use std::num::NonZeroU32; + +/// 有界重试:唯一所有者、有效准入、有界次数。 +/// 只重试确定性 `NotSent`;`Indeterminate` 一律上抛,绝不自动付费重发。 +pub struct BoundedRetry { + transport: T, + max_attempts: NonZeroU32, +} + +/// 重试的结果:`Done` 携带原始 `SendOutcome`; +/// `AllNotSent` 表示全部尝试都确定性未送达。 +#[derive(Debug)] +pub enum RetryOutcome { + Done(SendOutcome), + AllNotSent { attempts: u32 }, +} + +impl BoundedRetry { + pub fn new(transport: T, max_attempts: NonZeroU32) -> Self { + Self { + transport, + max_attempts, + } + } + + pub fn transport(&self) -> &T { + &self.transport + } + + pub async fn send_with_retry( + &self, + send: &AdmittedSend, + evidence: &dyn EvidenceSink, + ) -> RetryOutcome { + let mut attempt: u32 = 0; + loop { + attempt += 1; + evidence.record_attempt(attempt); + match self.transport.send(send.clone()).await { + // 可能已送达:立即上抛,不做任何自动重发。 + outcome @ SendOutcome::Indeterminate(_) | outcome @ SendOutcome::Delivered(_) => { + return RetryOutcome::Done(outcome) + } + SendOutcome::NotSent(reason) => { + if attempt >= self.max_attempts.get() { + evidence.record_not_sent(attempt, &reason.to_string()); + return RetryOutcome::AllNotSent { attempts: attempt }; + } + // 确定性未送达:唯一所有者继续重试。 + } + } + } + } +} diff --git a/gateway/crates/pc-gateway-transport/src/sender.rs b/gateway/crates/pc-gateway-transport/src/sender.rs new file mode 100644 index 0000000000..1b3d562092 --- /dev/null +++ b/gateway/crates/pc-gateway-transport/src/sender.rs @@ -0,0 +1,83 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use bytes::Bytes; +use std::future::Future; + +/// 一次已获准的发送。 +#[derive(Debug, Clone)] +pub struct AdmittedSend { + /// before_send allow 返回的不透明绑定字符串;必须原样用于 before_release。 + pub binding: String, + /// 最终获准字节(渲染产物,binding 绑定的就是这些字节)。 + pub payload: Bytes, + /// 获准目标 URL;不得静默重映射。 + pub target_url: String, + /// 目标协议要求的头部(凭据由受控配置解析,不经请求字段)。 + pub headers: Vec<(String, String)>, + /// 上游流式(SSE)接收:逐块读入并计量,strict 语义不变。 + pub stream: bool, +} + +/// 原始响应 + 传输结果,交给 output/check 后才允许释放。 +#[derive(Debug)] +pub struct RawResponse { + pub status: u16, + pub body: Bytes, + /// 响应的 Content-Type(SSE 为 text/event-stream),释放时原样使用。 + pub content_type: String, + /// 上游首字节延迟(毫秒);流式接收时计量,非流式为 None。 + pub ttft_ms: Option, + /// usage 证据(不可用时为 None,标记 unknown,不记零)。 + pub usage: Option, +} + +/// 发送结果:确定性状态优先;不确定即不确定。 +#[derive(Debug)] +pub enum SendOutcome { + /// 成功取得完整原始响应(尚未过 output/check,不得释放)。 + Delivered(RawResponse), + /// 确定尚未送达:可在有界次数内由唯一所有者重试。 + NotSent(NotSentReason), + /// 可能已到达上游:返回不确定,不自动付费重发,不假设退费。 + Indeterminate(SendIndeterminateReason), +} + +#[derive(Debug, thiserror::Error)] +pub enum NotSentReason { + #[error("connection refused before request sent")] + ConnectRefused, + #[error("request rejected before body accepted")] + RejectedLocally, +} + +#[derive(Debug, thiserror::Error)] +pub enum SendIndeterminateReason { + #[error("connection lost after request handed to transport")] + LostAfterHandoff, + #[error("timeout awaiting response")] + TimeoutAwaitingResponse, + /// 流式接收超过缓冲上限:请求已送达且部分计费,不重发。 + #[error("streaming buffer limit exceeded")] + BufferLimitExceeded, +} + +/// 传输器抽象;实现保证只发送 `AdmittedSend`(类型上无法构造未准入的发送)。 +pub trait Transport: Send + Sync { + fn send<'a>(&'a self, send: AdmittedSend) -> impl Future + Send + 'a; + + /// 尽力取消上游(strict 检查失败/缓冲超限时必需)。 + /// RPITIT 声明以固化 Send 约束(trait 是公开 API)。 + fn cancel<'a>(&'a self, send: &'a AdmittedSend) -> impl Future + Send + 'a; +} diff --git a/gateway/crates/pc-gateway-transport/tests/buffer_limit_nonstreaming.rs b/gateway/crates/pc-gateway-transport/tests/buffer_limit_nonstreaming.rs new file mode 100644 index 0000000000..2116a50d5d --- /dev/null +++ b/gateway/crates/pc-gateway-transport/tests/buffer_limit_nonstreaming.rs @@ -0,0 +1,102 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 回归测试(PR #2307 review P2): +//! 非流式路径的字节上限。with_buffer_limit(16) 下收到 1KB 响应必须 +//! 判为 Indeterminate(BufferLimitExceeded),不得 Delivered。 + +use pc_gateway_transport::{ + AdmittedSend, ReqwestTransport, SendIndeterminateReason, SendOutcome, Transport, +}; +use std::time::Duration; +use tokio::io::AsyncWriteExt; +use tokio::net::TcpListener; + +#[tokio::test] +async fn nonstreaming_response_over_buffer_limit_is_rejected() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(async move { + let (mut sock, _) = listener.accept().await.unwrap(); + // 读掉请求(忽略内容,client 会发完整 POST) + let mut buf = vec![0u8; 8192]; + let _ = tokio::time::timeout(Duration::from_secs(5), async { + use tokio::io::AsyncReadExt as _; + let _ = sock.read(&mut buf).await; + }) + .await; + // 回一个超过 16 字节上限的 JSON 响应 + let body = format!("{{\"padding\":\"{}\"}}", "x".repeat(1024)); + let resp = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), + body + ); + let _ = sock.write_all(resp.as_bytes()).await; + }); + + let transport = ReqwestTransport::new(Duration::from_secs(10)).with_buffer_limit(16); + let send = AdmittedSend { + binding: "b".into(), + payload: bytes::Bytes::from_static(b"{}"), + target_url: format!("http://127.0.0.1:{port}/v1/chat/completions"), + headers: vec![], + stream: false, // 关键:非流式路径 + }; + let outcome = transport.send(send).await; + match outcome { + SendOutcome::Indeterminate(SendIndeterminateReason::BufferLimitExceeded) => {} + other => panic!("expected Indeterminate(BufferLimitExceeded), got {other:?}"), + } +} + +#[tokio::test] +async fn nonstreaming_response_within_limit_still_delivers() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(async move { + let (mut sock, _) = listener.accept().await.unwrap(); + let mut buf = vec![0u8; 8192]; + let _ = tokio::time::timeout(Duration::from_secs(5), async { + use tokio::io::AsyncReadExt as _; + let _ = sock.read(&mut buf).await; + }) + .await; + let body = r#"{"ok":true}"#; + let resp = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), + body + ); + let _ = sock.write_all(resp.as_bytes()).await; + }); + + let transport = ReqwestTransport::new(Duration::from_secs(10)).with_buffer_limit(1024); + let send = AdmittedSend { + binding: "b".into(), + payload: bytes::Bytes::from_static(b"{}"), + target_url: format!("http://127.0.0.1:{port}/v1/chat/completions"), + headers: vec![], + stream: false, + }; + let outcome = transport.send(send).await; + match outcome { + SendOutcome::Delivered(raw) => { + assert_eq!(raw.status, 200); + let v: serde_json::Value = serde_json::from_slice(&raw.body).unwrap(); + assert_eq!(v["ok"], true); + } + other => panic!("expected Delivered, got {other:?}"), + } +} diff --git a/gateway/crates/pc-gateway-transport/tests/no_duplicate_send.rs b/gateway/crates/pc-gateway-transport/tests/no_duplicate_send.rs new file mode 100644 index 0000000000..d1a5037fda --- /dev/null +++ b/gateway/crates/pc-gateway-transport/tests/no_duplicate_send.rs @@ -0,0 +1,104 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 回归测试(PR #2307 review P1-1): +//! 对端读完整 POST body 后关闭连接 —— reqwest 报 is_request() 类错误。 +//! 断言:body 只被上游收到一次(绝不重复计费发送), +//! 且结果归为 Indeterminate 而非可重试的 NotSent。 + +use pc_gateway_transport::{AdmittedSend, ReqwestTransport, SendIndeterminateReason, SendOutcome}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; +use tokio::io::AsyncReadExt; +use tokio::net::TcpListener; + +#[tokio::test] +async fn upstream_closing_after_full_body_is_indeterminate_and_not_resent() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let bodies = Arc::new(AtomicUsize::new(0)); + let connections = Arc::new(AtomicUsize::new(0)); + + let b = bodies.clone(); + let c = connections.clone(); + tokio::spawn(async move { + // 接受至多 2 条连接:若网关错误地重试,第二条也会收到 body。 + for _ in 0..2 { + let (mut sock, _) = match listener.accept().await { + Ok(x) => x, + Err(_) => return, + }; + c.fetch_add(1, Ordering::SeqCst); + let mut buf = Vec::new(); + let mut chunk = [0u8; 4096]; + // 读到完整请求(头 + Content-Length 声明的 body) + loop { + let n = sock.read(&mut chunk).await.unwrap_or(0); + if n == 0 { + break; + } + buf.extend_from_slice(&chunk[..n]); + if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") { + let head = String::from_utf8_lossy(&buf[..pos]).to_ascii_lowercase(); + let len: usize = head + .lines() + .find_map(|l| l.strip_prefix("content-length: ")) + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(0); + if buf.len() >= pos + 4 + len { + break; + } + } + } + // 完整收到一条带 body 的 POST → 计数 + if buf.starts_with(b"POST") { + b.fetch_add(1, Ordering::SeqCst); + } + // 读完即关闭,不回任何响应(review 描述的复现场景) + drop(sock); + } + }); + + let transport = ReqwestTransport::default(); + let send = AdmittedSend { + binding: "b".into(), + payload: bytes::Bytes::from_static(br#"{"model":"m","messages":[]}"#), + target_url: format!("http://127.0.0.1:{port}/v1/chat/completions"), + headers: vec![], + stream: false, + }; + + // 复现 review 场景:BoundedRetry(max_attempts=2)。 + // 旧行为:is_request() 被归为 NotSent → 重试 → 上游收到两次完整 body + // 且最终谎报 AllNotSent{attempts:2}。 + // 新行为:归为 Indeterminate → 立即上抛,不进行第二次发送。 + let retry = + pc_gateway_transport::BoundedRetry::new(transport, std::num::NonZeroU32::new(2).unwrap()); + let outcome = retry + .send_with_retry(&send, &pc_gateway_evidence::NoopEvidenceSink) + .await; + match outcome { + pc_gateway_transport::RetryOutcome::Done(SendOutcome::Indeterminate( + SendIndeterminateReason::LostAfterHandoff, + )) => {} + other => panic!("expected Done(Indeterminate), got {other:?}"), + } + + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + assert_eq!( + bodies.load(Ordering::SeqCst), + 1, + "上游必须只收到一次 body(修复前是 2 次,重复计费)" + ); +} diff --git a/gateway/crates/pc-gateway-transport/tests/no_redirect_resend.rs b/gateway/crates/pc-gateway-transport/tests/no_redirect_resend.rs new file mode 100644 index 0000000000..5baf3229dd --- /dev/null +++ b/gateway/crates/pc-gateway-transport/tests/no_redirect_resend.rs @@ -0,0 +1,107 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! 回归测试(PR #2307 review P1-2): +//! 获准上游返回 307 时,reqwest 默认会把已准入的 POST body 原样重发到 +//! Location 指向的第二个地址(未经 Core 准入)。禁用自动跟随后: +//! 第二地址必须收到零字节;307 响应原样透传(Delivered status=307)。 + +use pc_gateway_transport::{AdmittedSend, ReqwestTransport, SendOutcome, Transport}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::Arc; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; + +/// 读一条完整 HTTP 请求(头 + content-length body),返回原始字节。 +async fn read_request(sock: &mut TcpStream) -> Vec { + let mut buf = Vec::new(); + let mut chunk = [0u8; 4096]; + loop { + let n = sock.read(&mut chunk).await.unwrap_or(0); + if n == 0 { + break; + } + buf.extend_from_slice(&chunk[..n]); + if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") { + let head = String::from_utf8_lossy(&buf[..pos]).to_ascii_lowercase(); + let len: usize = head + .lines() + .find_map(|l| l.strip_prefix("content-length: ")) + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(0); + if buf.len() >= pos + 4 + len { + break; + } + } + } + buf +} + +#[tokio::test] +async fn redirect_target_receives_nothing_and_307_surfaces() { + // 第二地址(重定向目标):任何到达的字节都记为违规 + let evil = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let evil_port = evil.local_addr().unwrap().port(); + let evil_received = Arc::new(AtomicUsize::new(0)); + let er = evil_received.clone(); + tokio::spawn(async move { + if let Ok((mut sock, _)) = evil.accept().await { + let data = read_request(&mut sock).await; + er.fetch_add(data.len(), Ordering::SeqCst); + let resp = b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok"; + let _ = sock.write_all(resp).await; + } + }); + + // 第一地址(获准上游):读完整请求后回 307 指向第二地址 + let approved = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let approved_port = approved.local_addr().unwrap().port(); + let served_307 = Arc::new(AtomicBool::new(false)); + let s307 = served_307.clone(); + let evil_addr = format!("127.0.0.1:{evil_port}"); + tokio::spawn(async move { + let (mut sock, _) = approved.accept().await.unwrap(); + let _ = read_request(&mut sock).await; + let resp = format!( + "HTTP/1.1 307 Temporary Redirect\r\nLocation: http://{evil_addr}/steer\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + ); + sock.write_all(resp.as_bytes()).await.unwrap(); + s307.store(true, Ordering::SeqCst); + }); + + let transport = ReqwestTransport::default(); + let send = AdmittedSend { + binding: "b".into(), + payload: bytes::Bytes::from_static(br#"{"model":"m","messages":[]}"#), + target_url: format!("http://127.0.0.1:{approved_port}/v1/chat/completions"), + headers: vec![], + stream: false, + }; + let outcome = transport.send(send).await; + + // 307 原样上抛(不跟随、不报错、不重发) + match outcome { + SendOutcome::Delivered(raw) => assert_eq!(raw.status, 307, "307 必须原样透传"), + other => panic!("expected Delivered(307), got {other:?}"), + } + assert!(served_307.load(Ordering::SeqCst), "获准地址已返回 307"); + + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + // 关键断言:重定向目标收到的字节数为零(修复前会收到完整 POST body) + assert_eq!( + evil_received.load(Ordering::SeqCst), + 0, + "重定向目标必须收到零字节(获准目的地=实际目的地)" + ); +} diff --git a/gateway/crates/pc-gateway-types/Cargo.toml b/gateway/crates/pc-gateway-types/Cargo.toml new file mode 100644 index 0000000000..172530425c --- /dev/null +++ b/gateway/crates/pc-gateway-types/Cargo.toml @@ -0,0 +1,26 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +[package] +name = "pc-gateway-types" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "PowerContext Gateway: check API DTOs, envelope bindings and shared value types" + +[dependencies] +serde = { workspace = true } +serde_json = { workspace = true } +bytes = { workspace = true } +thiserror = { workspace = true } diff --git a/gateway/crates/pc-gateway-types/src/check.rs b/gateway/crates/pc-gateway-types/src/check.rs new file mode 100644 index 0000000000..b517a3b032 --- /dev/null +++ b/gateway/crates/pc-gateway-types/src/check.rs @@ -0,0 +1,151 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! PR #2264 定义的 `POST /v1/context/check` 真实契约。 +//! +//! 关键语义(openapi/powercontext.yaml 原文): +//! - HTTP success alone is not approval——只有完整覆盖的 allow 才许可对应阶段; +//! - 执行器必须在 deadline(valid_until / limits.send_seconds)前 +//! 发送/释放**恰好获批的字节**; +//! - binding 是不透明字符串,绑定 phase、身份、目标、策略与精确载荷; +//! - correlate_until 只是关联窗口,绝不许可新的发送。 + +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +pub const MODEL_JSON_PAYLOAD_SCHEMA: &str = "powercontext.model-json-payload.v1"; +pub const CONTEXT_CHECK_SCHEMA: &str = "powercontext.context-check.v1"; +pub const CONTEXT_CHECK_COMPLETION: &str = "complete"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CheckPhase { + BeforeSend, + BeforeRelease, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CheckDecision { + Allow, + Block, + Withhold, +} + +/// 完整载荷信封:仅内容与协议头(凭据、传输覆盖头被禁止),body 为完整原始 JSON 文本。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ModelJsonPayload { + pub schema: String, + pub headers: BTreeMap, + pub body: String, +} + +impl ModelJsonPayload { + pub fn new(headers: BTreeMap, body: String) -> Self { + Self { + schema: MODEL_JSON_PAYLOAD_SCHEMA.into(), + headers, + body, + } + } +} + +/// prepare 复用信封的定位(binding + 文本位置;位置语义归 Core)。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PreparedContextLocation { + pub binding: String, + pub location: ModelJsonTextLocation, +} + +/// 线格式 JSON 指针 + 解码后 UTF-8 文本的半开字节区间。 +/// 指针形如 /messages/{i}/content 或 /messages/{i}/content/{j}/text, +/// 必须指向 user 消息(PC 的 _message_text 强制校验)。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ModelJsonTextLocation { + pub schema: String, + pub pointer: String, + pub start_byte: u64, + pub end_byte: u64, +} + +pub const MODEL_JSON_TEXT_LOCATION_SCHEMA: &str = "powercontext.model-json-text-location.v1"; + +/// `check_context` 请求:按 phase 二选一(内部标签即 phase 字段)。 +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "phase", rename_all = "snake_case")] +pub enum ContextCheckRequest { + BeforeSend { + scope_id: String, + target_profile: String, + payload: ModelJsonPayload, + /// 线格式必填:无复用块时也必须显式携带空数组。 + prepared_contexts: Vec, + }, + BeforeRelease { + scope_id: String, + target_profile: String, + /// 对应 before_send allow 返回的 binding。 + request_binding: String, + payload: ModelJsonPayload, + completion: String, + }, +} + +/// `check_context` 响应。两阶段共用 allow/block/withhold: +/// before_release 的 allow 即放行决定,block 即拒绝释放。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ContextCheckResult { + pub schema: String, + pub phase: CheckPhase, + pub decision: CheckDecision, + /// 无正文原因类别。 + pub reason_codes: Vec, + pub coverage: ContextCheckCoverage, + pub policy_version: String, + /// RFC3339 时间;发送/释放必须在此之前完成。 + pub valid_until: String, + /// 仅 before_send allow 有;绝不许可新发送。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub correlate_until: Option, + /// 仅 allow 有:不透明绑定字符串。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub binding: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ContextCheckCoverage { + pub profile: String, + pub complete: bool, +} + +/// ContextProtectionCapabilities(能力发现;enforcing 是动态降级的依据)。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ContextProtectionCapabilities { + pub check_versions: Vec, + pub payload_versions: Vec, + pub reuse_versions: Vec, + pub reuse_families: Vec, + pub enforcing: bool, + pub limits: ContextProtectionLimits, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ContextProtectionLimits { + pub payload_bytes: u64, + pub binding_bytes: u64, + pub prepared_contexts: u64, + pub dependencies: u64, + pub send_seconds: u64, + pub correlate_seconds: u64, +} diff --git a/gateway/crates/pc-gateway-types/src/lib.rs b/gateway/crates/pc-gateway-types/src/lib.rs new file mode 100644 index 0000000000..aa8812617c --- /dev/null +++ b/gateway/crates/pc-gateway-types/src/lib.rs @@ -0,0 +1,26 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! PR #2264 契约值类型。 +//! +//! 网关无策略:这里的类型只承载 Core 的输入/输出, +//! 与 openapi/powercontext.yaml 对齐。 + +mod check; +mod prepare; +mod time; + +pub use check::*; +pub use prepare::*; +pub use time::*; diff --git a/gateway/crates/pc-gateway-types/src/prepare.rs b/gateway/crates/pc-gateway-types/src/prepare.rs new file mode 100644 index 0000000000..dbb7cb52a4 --- /dev/null +++ b/gateway/crates/pc-gateway-types/src/prepare.rs @@ -0,0 +1,148 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! prepare 契约(PR #2264),字段形状对照真实响应校准。 + +use serde::{Deserialize, Serialize}; + +/// 注入块的标准包裹标记(与 PC 的 `_MARKERS` 对齐): +/// check 会扫描载荷中所有字符串,含标记的字节必须被 prepared_contexts 区间覆盖。 +pub const PREPARED_CONTEXT_MARKER_BEGIN: &str = "BEGIN_POWERCONTEXT_PREPARED_CONTEXT_V1"; +pub const PREPARED_CONTEXT_MARKER_END: &str = "END_POWERCONTEXT_PREPARED_CONTEXT_V1"; + +pub const PREPARED_CONTEXT_SCHEMA: &str = "powercontext.prepared-context.v1"; +pub const PREPARED_CONTEXT_WITH_REUSE_SCHEMA: &str = "powercontext.prepared-context-with-reuse.v1"; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PrepareContextRequest { + pub scope_id: String, + pub query: String, + #[serde(default = "default_max_bytes")] + pub max_bytes: u32, + #[serde(default)] + pub include_reuse: bool, + /// #2313 契约:限定召回家族。reuse 只支持 atomic-memory; + /// 不指定 assembly 时 Core 默认召回 Experience/Topic → check 阶段拒绝。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub assembly: Option, +} + +/// 召回组合:限定家族和条目数。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ContextAssembly { + pub sections: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct AssemblySection { + pub family: String, + pub limit: u32, +} + +impl ContextAssembly { + /// memory-only assembly(只召回 Atomic Memory):#2313 支持的唯一 reuse 家族。 + /// limit 可通过 PC_GATEWAY_ASSEMBLY_LIMIT 环境变量配置(默认 8, + /// 不超过 Server 的 context_assembly_max_entries)。 + pub fn memory_only() -> Self { + let limit = std::env::var("PC_GATEWAY_ASSEMBLY_LIMIT") + .ok() + .and_then(|v| v.parse().ok()) + .filter(|v| *v > 0 && *v <= 8) + .unwrap_or(8); + Self { + sections: vec![AssemblySection { + family: "memory".into(), + limit, + }], + } + } +} + +fn default_max_bytes() -> u32 { + 8192 +} + +/// prepare 响应:普通 PreparedContext 或带复用信封的 WithReuse(按 schema 判别)。 +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum PrepareContextResult { + WithReuse { + schema: String, + context: PreparedContext, + reuse: ContextReuse, + }, + Plain(PreparedContext), +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PreparedContext { + pub schema: String, + /// ready 时为内容文本;empty 时为 None。 + pub status: String, + pub content: Option, + pub content_bytes: u64, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ContextReuse { + pub schema: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub constraints: Option, + /// RFC3339。 + pub expires_at: String, + pub binding: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ReuseConstraints { + #[serde(default)] + pub preserve: Vec, + #[serde(default)] + pub refresh_on: Vec, +} + +impl PrepareContextResult { + pub fn content(&self) -> Option<&str> { + match self { + PrepareContextResult::WithReuse { context, .. } => context.content.as_deref(), + PrepareContextResult::Plain(c) => c.content.as_deref(), + } + } + + pub fn binding(&self) -> Option<&str> { + match self { + PrepareContextResult::WithReuse { reuse, .. } => Some(&reuse.binding), + PrepareContextResult::Plain(_) => None, + } + } +} + +/// 标准注入块:与 PC 的 `_MARKERS`/摘要校验对齐。 +/// check 会核验区间内字节与 binding 签发内容一致,不得增删一字节。 +pub fn wrap_prepared_block(content: &str) -> String { + format!("{PREPARED_CONTEXT_MARKER_BEGIN}\n{content}\n{PREPARED_CONTEXT_MARKER_END}") +} + +/// `POST /v1/sources/content`(capture_content_source): +/// 同步持久入库(Source journal),提取由 PC 后台异步完成。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CaptureContentSourceRequest { + pub scope_id: String, + /// 调用方指定的稳定 ID(幂等键):用 release binding 摘要生成。 + pub source_id: String, + /// 原始整合内容(≤200000 字符)。仅沉淀过检放行的内容。 + pub content: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, +} diff --git a/gateway/crates/pc-gateway-types/src/time.rs b/gateway/crates/pc-gateway-types/src/time.rs new file mode 100644 index 0000000000..57da94ea3c --- /dev/null +++ b/gateway/crates/pc-gateway-types/src/time.rs @@ -0,0 +1,191 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! RFC3339 时间解析(valid_until / correlate_until 消费)。 +//! 零依赖实现:覆盖 Core 实际输出的形态(含/不含分数秒、Z 后缀)。 + +/// 解析 RFC3339 时间戳为 Unix 毫秒。 +/// 支持: `2026-10-28T09:55:06Z` / `2026-10-28T09:55:06.464580Z` / 不含 Z 的 UTC 形态。 +/// 不支持的形态返回 None(调用方 fail-closed 处理)。 +pub fn parse_rfc3339_ms(s: &str) -> Option { + let bytes = s.as_bytes(); + if bytes.len() < 20 { + return None; + } + // 必须是数字的位置 + let digit = |i: usize| -> Option { (bytes[i] as char).to_digit(10).map(|d| d as u64) }; + let year: i64 = (digit(0)? * 1000 + digit(1)? * 100 + digit(2)? * 10 + digit(3)?) as i64; + if bytes[4] != b'-' + || bytes[7] != b'-' + || bytes[10] != b'T' + || bytes[13] != b':' + || bytes[16] != b':' + { + return None; + } + let month: i64 = (digit(5)? * 10 + digit(6)?) as i64; + let day: i64 = (digit(8)? * 10 + digit(9)?) as i64; + let hour: i64 = (digit(11)? * 10 + digit(12)?) as i64; + let min: i64 = (digit(14)? * 10 + digit(15)?) as i64; + let sec: i64 = (digit(17)? * 10 + digit(18)?) as i64; + if !(1..=12).contains(&month) || !(1..=31).contains(&day) || hour > 23 || min > 59 || sec > 60 { + return None; + } + // 分数秒(可选) + let mut millis: i64 = 0; + let mut idx = 19; + if idx < bytes.len() && bytes[idx] == b'.' { + idx += 1; + let start = idx; + while idx < bytes.len() && bytes[idx].is_ascii_digit() { + idx += 1; + } + if idx == start { + return None; + } + let frac = &s[start..idx]; + // 小数秒缩放(非截断):.5 = 500ms、.46 = 460ms、.464580 = 464ms。 + // 右补零到 3 位保证等效表示得到等效毫秒值。 + let millis_str = if frac.len() >= 3 { + &frac[..3] + } else { + // 右补零:.5 → "500"、.46 → "460" + &format!("{:0<3}", frac) + }; + millis = millis_str.parse().unwrap_or(0); + } + // 时区:Z 或 ±HH:MM + let tz_offset_sec: i64 = if idx < bytes.len() { + match bytes[idx] { + b'Z' | b'z' => 0i64, + b'+' | b'-' => { + let sign: i64 = if bytes[idx] == b'+' { 1 } else { -1 }; + let oh: i64 = if idx + 2 < bytes.len() { + (digit(idx + 1)? * 10 + digit(idx + 2)?) as i64 + } else { + return None; + }; + let om: i64 = if idx + 5 < bytes.len() && bytes[idx + 3] == b':' { + (digit(idx + 4)? * 10 + digit(idx + 5)?) as i64 + } else if idx + 4 < bytes.len() { + (digit(idx + 3)? * 10 + digit(idx + 4)?) as i64 + } else { + return None; + }; + sign * (oh * 3600 + om * 60) + } + _ => return None, + } + } else { + return None; + }; + + let days = days_from_civil(year, month, day); + let total_ms = ((days * 86_400 + hour * 3600 + min * 60 + sec - tz_offset_sec) * 1000) + millis; + if total_ms < 0 { + return None; + } + Some(total_ms as u64) +} + +/// Howard Hinnant 的 days_from_civil 算法(公历→Unix 天数)。 +fn days_from_civil(y: i64, m: i64, d: i64) -> i64 { + let y = if m <= 2 { y - 1 } else { y }; + let era = if y >= 0 { y } else { y - 399 } / 400; + let yoe = y - era * 400; + let mp = (m + 9) % 12; + let doy = (153 * mp + 2) / 5 + d - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + era * 146_097 + doe - 719_468 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn utc_no_fraction() { + assert_eq!( + parse_rfc3339_ms("2026-10-28T09:55:06Z"), + Some(1793181306000) + ); + } + + #[test] + fn utc_with_microseconds() { + // Core 实际输出形态:2026-10-28T09:55:06.464580Z + assert_eq!( + parse_rfc3339_ms("2026-10-28T09:55:06.464580Z"), + Some(1793181306464) + ); + } + + #[test] + fn utc_with_milliseconds() { + assert_eq!( + parse_rfc3339_ms("2026-10-28T09:55:06.464Z"), + Some(1793181306464) + ); + } + + #[test] + fn timezone_offset() { + assert_eq!( + parse_rfc3339_ms("2026-10-28T17:55:06+08:00"), + Some(1793181306000) + ); + } + + #[test] + fn invalid_returns_none() { + assert_eq!(parse_rfc3339_ms("not-a-date"), None); + assert_eq!(parse_rfc3339_ms("2026-10-28"), None); + assert_eq!(parse_rfc3339_ms("2026-13-28T09:55:06Z"), None); + assert_eq!(parse_rfc3339_ms(""), None); + } + + #[test] + fn epoch() { + assert_eq!(parse_rfc3339_ms("1970-01-01T00:00:00Z"), Some(0)); + } +} + +#[cfg(test)] +mod fraction_tests { + use super::*; + + #[test] + fn short_fractions_scale_correctly() { + // .5Z = 500ms(不是 5ms) + assert_eq!( + parse_rfc3339_ms("2026-10-28T09:55:06.5Z").unwrap() % 1000, + 500 + ); + // .46Z = 460ms(不是 46ms) + assert_eq!( + parse_rfc3339_ms("2026-10-28T09:55:06.46Z").unwrap() % 1000, + 460 + ); + } + + #[test] + fn equivalent_fractions_produce_equivalent_timestamps() { + // .5Z ≡ .500Z ≡ .500000Z —— 同一时刻 + let a = parse_rfc3339_ms("2026-10-28T09:55:06.5Z").unwrap(); + let b = parse_rfc3339_ms("2026-10-28T09:55:06.500Z").unwrap(); + let c = parse_rfc3339_ms("2026-10-28T09:55:06.500000Z").unwrap(); + assert_eq!(a, b, ".5Z 必须等于 .500Z"); + assert_eq!(b, c, ".500Z 必须等于 .500000Z"); + } +}