diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e0cab1e1..0bf43aa9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -56,7 +56,7 @@ jobs: run: ./scripts/smoke.sh # **第一层改了,企业版还编得过吗。**企业版钉 core 的 tag、只依赖第一层 - # (tw-dialect、tw-guard、tw-breaker)。以前要等 core 发版、企业版升级那天 + # (tw-dialect、tw-guard、tw-breaker、tw-bedrock)。以前要等 core 发版、企业版升级那天 # 才知道某个改名或删掉的函数把它弄坏了,这里提前到 PR 上。 # # 企业版取和这个 PR 同名的分支 —— 要改接口的一方在企业版开一个同名分支 @@ -78,6 +78,7 @@ jobs: - 'crates/tw-dialect/**' - 'crates/tw-guard/**' - 'crates/tw-breaker/**' + - 'crates/tw-bedrock/**' - 'Cargo.toml' - '.github/workflows/ci.yml' @@ -113,10 +114,20 @@ jobs: tw-dialect = { path = "../core/crates/tw-dialect" } tw-guard = { path = "../core/crates/tw-guard" } tw-breaker = { path = "../core/crates/tw-breaker" } + tw-bedrock = { path = "../core/crates/tw-bedrock" } TOML # 企业版的 Cargo.lock 锁着它钉的那个版本;版本号不同时补丁会被 - # 静默忽略(只报一条警告),编的还是旧的 core - cd enterprise && cargo update -p tw-dialect -p tw-guard -p tw-breaker + # 静默忽略(只报一条警告),编的还是旧的 core。 + # + # 只更新企业版确实依赖的:它还没用上的第一层 crate 不在 lock 里, + # `cargo update -p` 对它直接报错(补丁用不上只是一条警告) + cd enterprise + pkgs=() + for c in tw-dialect tw-guard tw-breaker tw-bedrock; do + if grep -qx "name = \"$c\"" Cargo.lock; then pkgs+=(-p "$c"); fi + done + echo "updating: ${pkgs[*]}" + cargo update "${pkgs[@]}" - uses: Swatinem/rust-cache@v2 if: steps.changed.outputs.layer1 == 'true' diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c339ce97..5f41ce55 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -32,10 +32,10 @@ Two products are built on these crates. the desktop app, bundles `twcore` as its gateway and can also connect to one running on a server. [ThinkWatch Enterprise](https://github.com/ThinkWatchProject/ThinkWatch) -depends on exactly three of the crates, `tw-dialect`, `tw-guard` and -`tw-breaker`, and CI checks that it still compiles against every change -to them. A change here reaches every installation of the app and every -server running `twcore`, and a change to those three crates reaches +depends on exactly four of the crates, `tw-dialect`, `tw-guard`, +`tw-breaker` and `tw-bedrock`, and CI checks that it still compiles against +every change to them. A change here reaches every installation of the app and +every server running `twcore`, and a change to those four crates reaches ThinkWatch Enterprise as well, so "it works for my case" is not the bar. What is *not* here: adopting AI clients, editing their MCP servers and diff --git a/Cargo.lock b/Cargo.lock index 96644b93..cfae742d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -147,6 +147,18 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "aws-credential-types" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e93964ffdaf57857f544be3666a5f57570bb699e934700f11b49708f61bb556e" +dependencies = [ + "aws-smithy-async", + "aws-smithy-runtime-api", + "aws-smithy-types", + "zeroize", +] + [[package]] name = "aws-lc-rs" version = "1.18.1" @@ -170,6 +182,119 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "aws-sigv4" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2312577f088c9fbf4206dfdb884cf1de9407b43e1a923cbed5237775116fc24b" +dependencies = [ + "aws-credential-types", + "aws-smithy-http", + "aws-smithy-runtime-api", + "aws-smithy-types", + "bytes", + "form_urlencoded", + "hex", + "hmac", + "http", + "percent-encoding", + "sha2", + "time", + "tracing", +] + +[[package]] +name = "aws-smithy-async" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f02e407fb3b54891734224b9ffac8a71fdd35f542500fa1af95754a6b2beb316" +dependencies = [ + "futures-util", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "aws-smithy-eventstream" +version = "0.60.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78d8391e65fcea47c586a22e1a41f173b38615b112b2c6b7a44e80cec3e6b706" +dependencies = [ + "aws-smithy-types", + "bytes", + "crc32fast", +] + +[[package]] +name = "aws-smithy-http" +version = "0.64.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "639b4d8f8555f24a9be649811c3eb0b4d4616f4d61daf0c32e28873bc1ea9af1" +dependencies = [ + "aws-smithy-runtime-api", + "aws-smithy-types", + "bytes", + "bytes-utils", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "percent-encoding", + "pin-project-lite", + "pin-utils", + "tracing", +] + +[[package]] +name = "aws-smithy-runtime-api" +version = "1.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb0deb40a69de59f7809251cfe1ab16de135f42c49d222d1202b4d0ce19720f" +dependencies = [ + "aws-smithy-async", + "aws-smithy-runtime-api-macros", + "aws-smithy-types", + "bytes", + "http", + "pin-project-lite", + "tokio", + "tracing", + "zeroize", +] + +[[package]] +name = "aws-smithy-runtime-api-macros" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "221eaa237ddf1ca79b60d1372aad77e47f9c0ea5b3ce5099da8c61d027dc77b3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "aws-smithy-types" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69bb407740a197147da48238ecc94498493c9e85445732360cec180296ca45f1" +dependencies = [ + "base64-simd", + "bytes", + "bytes-utils", + "http", + "http-body", + "http-body-util", + "itoa", + "num-integer", + "pin-project-lite", + "pin-utils", + "ryu", + "serde", + "time", +] + [[package]] name = "axum" version = "0.8.9" @@ -243,6 +368,16 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64-simd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "339abbe78e73178762e23bea9dfd08e697eb3f3301cd4be981c0f78ba5859195" +dependencies = [ + "outref", + "vsimd", +] + [[package]] name = "bitflags" version = "2.13.1" @@ -301,6 +436,16 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "bytes-utils" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dafe3a8757b027e2be6e4e5601ed563c55989fcf1546e933c66c8eb3a058d35" +dependencies = [ + "bytes", + "either", +] + [[package]] name = "cc" version = "1.4.5" @@ -434,6 +579,12 @@ dependencies = [ "cc", ] +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "colorchoice" version = "1.0.5" @@ -524,6 +675,15 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "ctutils" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e" +dependencies = [ + "cmov", +] + [[package]] name = "curve25519-dalek" version = "4.1.3" @@ -555,6 +715,12 @@ version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" + [[package]] name = "digest" version = "0.10.7" @@ -575,6 +741,7 @@ dependencies = [ "block-buffer 0.12.1", "const-oid", "crypto-common 0.2.2", + "ctutils", ] [[package]] @@ -594,6 +761,12 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" +[[package]] +name = "either" +version = "1.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" + [[package]] name = "equivalent" version = "1.0.2" @@ -876,6 +1049,21 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "http" version = "1.5.0" @@ -1397,6 +1585,21 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -1430,6 +1633,12 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" +[[package]] +name = "outref" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e" + [[package]] name = "percent-encoding" version = "2.3.2" @@ -1442,6 +1651,12 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + [[package]] name = "pkg-config" version = "0.3.34" @@ -1468,6 +1683,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -2209,6 +2430,36 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tinystr" version = "0.8.4" @@ -2500,6 +2751,27 @@ dependencies = [ "tw-types", ] +[[package]] +name = "tw-bedrock" +version = "0.54.0" +dependencies = [ + "aws-credential-types", + "aws-sigv4", + "aws-smithy-eventstream", + "aws-smithy-types", + "axum", + "bytes", + "futures", + "hex", + "hmac", + "percent-encoding", + "reqwest", + "serde_json", + "sha2", + "tokio", + "tw-dialect", +] + [[package]] name = "tw-breaker" version = "0.54.0" @@ -2868,6 +3140,12 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "vsimd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64" + [[package]] name = "walkdir" version = "2.5.0" diff --git a/Cargo.toml b/Cargo.toml index e395cc5e..52ad396b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,14 +1,16 @@ [workspace] resolver = "2" members = [ - # ── 第一层 · 共用(企业版依赖的只有这三个)────────── + # ── 第一层 · 共用(企业版依赖的只有这四个)────────── # 只准依赖彼此和第三方 crate,不准依赖第二层 —— tw-dialect 里的 # layer_one_depends_only_on_itself 测试守着这条。改这一层要 grep 企业版; # CI 的 enterprise 任务会拿企业版对着这次改动编译一遍。 - # **只有一方在用的「共用件」搬回那一方**,不留在这里。 + # **只有一方在用的「共用件」搬回那一方**,不留在这里;两边都用上了就搬回来 + # (tw-bedrock 就是这么回来的)。 "crates/tw-dialect", "crates/tw-guard", "crates/tw-breaker", + "crates/tw-bedrock", # ── 第二层 · 桌面网关(企业版不依赖)──────────────── "crates/tw-types", "crates/tw-secret", @@ -67,6 +69,7 @@ tw-watch = { path = "crates/tw-watch" } tw-guard = { path = "crates/tw-guard" } tw-breaker = { path = "crates/tw-breaker" } tw-dialect = { path = "crates/tw-dialect" } +tw-bedrock = { path = "crates/tw-bedrock" } tw-link = { path = "crates/tw-link" } # ── 版本与企业版 workspace 对齐,便于反向依赖时不打架 ──── @@ -120,6 +123,15 @@ futures = "0.3" tokio-stream = "0.1" async-stream = "0.3" +# ── Bedrock(tw-bedrock):SigV4 签名、eventstream 拆帧 ───────── +# aws-sigv4 1.5 起签名不再带 http 0.2,所以不再关在 feature 后面。 +# 最低要 rustc 1.94.1,比上面写的 rust-version 高 —— 两边的 CI 都用 stable +aws-sigv4 = "1" +aws-credential-types = "1" +aws-smithy-eventstream = "0.60" +aws-smithy-types = "1" +percent-encoding = "2" + thiserror = "2" anyhow = "1" tracing = "0.1" diff --git a/README.md b/README.md index 355722c3..a20033d8 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,8 @@ calls an upstream returns. desktop app for macOS, Windows and Linux, or as a standalone gateway on a Linux server, which ThinkWatch Lite connects to over an encrypted control channel. [ThinkWatch Enterprise](https://github.com/ThinkWatchProject/ThinkWatch) -depends on three of the crates: `tw-dialect`, `tw-guard` and `tw-breaker`. +depends on four of the crates: `tw-dialect`, `tw-guard`, `tw-breaker` and +`tw-bedrock`. Documentation: [configuration reference](docs/config.md) · [running core on a server](docs/server.md) · @@ -190,15 +191,15 @@ exposure and uninstalling. Every field of `config.yaml` is described in the ## Crate layers -The workspace holds sixteen crates and the `twcore` binary in `bin/twcore`. -It divides the crates in two: the three that ThinkWatch Enterprise depends +The workspace holds seventeen crates and the `twcore` binary in `bin/twcore`. +It divides the crates in two: the four that ThinkWatch Enterprise depends on, and the crates of the gateway that `twcore` runs, which ThinkWatch Enterprise does not use. Within the second part, the crates are grouped by role. No crate depends on a group below its own. | Group | Crates | |---|---| -| Shared with ThinkWatch Enterprise | `tw-dialect` · `tw-guard` · `tw-breaker` | +| Shared with ThinkWatch Enterprise | `tw-dialect` · `tw-guard` · `tw-breaker` · `tw-bedrock` | | Domain logic | `tw-types` · `tw-engine` · `tw-pricing` · `tw-yaml` · `tw-secret` · `tw-watch` | | Control-plane contract | `tw-api` · `tw-link` | | Assembly | `tw-config` · `tw-store` · `tw-observe` | @@ -206,9 +207,10 @@ role. No crate depends on a group below its own. ThinkWatch Enterprise depends on the first group and nothing else: format conversion and usage parsing (`tw-dialect`), redaction, tool-call inspection -and the other protections (`tw-guard`), and the circuit-breaker state machine -(`tw-breaker`). These three crates depend only on one another; a test enforces -this, and CI checks that ThinkWatch Enterprise compiles against every change to +and the other protections (`tw-guard`), the circuit-breaker state machine +(`tw-breaker`), and what only Amazon Bedrock needs on the wire: SigV4 signing, +eventstream unframing, its addresses and its model catalog (`tw-bedrock`). +These four crates depend only on one another; a test enforces this, and CI checks that ThinkWatch Enterprise compiles against every change to them. A component that only one product uses lives in that product's repository. diff --git a/README.zh-CN.md b/README.zh-CN.md index d0c4b2a0..066e9ef9 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -12,7 +12,7 @@ ThinkWatch Core 是一组 Rust crate,以及由它们构建的网关二进制 `twcore`。Claude Code、Codex 以及其他使用 Anthropic、OpenAI、Gemini 接口的客户端经由 `twcore` 发出请求;它按规则路由每个请求,在响应开始前故障转移到其他上游,记录每个请求的费用,在请求发出前脱敏其中的密钥,并审查上游返回的工具调用。 -`twcore` 既作为本机网关运行在桌面应用 [ThinkWatch Lite](https://github.com/ThinkWatchProject/ThinkWatch-Lite)(macOS、Windows、Linux)中,也可以作为独立网关部署在 Linux 服务器上,由 ThinkWatch Lite 通过加密的控制通道连接。[ThinkWatch 企业版](https://github.com/ThinkWatchProject/ThinkWatch)依赖其中三个 crate:`tw-dialect`、`tw-guard` 和 `tw-breaker`。 +`twcore` 既作为本机网关运行在桌面应用 [ThinkWatch Lite](https://github.com/ThinkWatchProject/ThinkWatch-Lite)(macOS、Windows、Linux)中,也可以作为独立网关部署在 Linux 服务器上,由 ThinkWatch Lite 通过加密的控制通道连接。[ThinkWatch 企业版](https://github.com/ThinkWatchProject/ThinkWatch)依赖其中四个 crate:`tw-dialect`、`tw-guard`、`tw-breaker` 和 `tw-bedrock`。 文档:[配置手册](docs/config.zh-CN.md) · [在服务器上运行 core](docs/server.zh-CN.md) · [thinkwat.ch/zh-CN/core](https://thinkwat.ch/zh-CN/core/) @@ -103,17 +103,17 @@ sudo twcore upgrade --restart # 安装最新 Release 并重 ## crate 分层 -工作区共有十六个 crate,`twcore` 二进制位于 `bin/twcore`。这些 crate 分为两部分:ThinkWatch 企业版依赖的三个 crate,以及 `twcore` 所运行网关的其余 crate(ThinkWatch 企业版不使用)。第二部分再按职责分组。任何 crate 都不依赖排在其所在组下方的组。 +工作区共有十七个 crate,`twcore` 二进制位于 `bin/twcore`。这些 crate 分为两部分:ThinkWatch 企业版依赖的四个 crate,以及 `twcore` 所运行网关的其余 crate(ThinkWatch 企业版不使用)。第二部分再按职责分组。任何 crate 都不依赖排在其所在组下方的组。 | 分组 | crate | |---|---| -| 与 ThinkWatch 企业版共用 | `tw-dialect` · `tw-guard` · `tw-breaker` | +| 与 ThinkWatch 企业版共用 | `tw-dialect` · `tw-guard` · `tw-breaker` · `tw-bedrock` | | 领域逻辑 | `tw-types` · `tw-engine` · `tw-pricing` · `tw-yaml` · `tw-secret` · `tw-watch` | | 控制面契约 | `tw-api` · `tw-link` | | 装配 | `tw-config` · `tw-store` · `tw-observe` | | 数据面与控制面 | `tw-gateway` · `tw-control` | -ThinkWatch 企业版只依赖第一组,不依赖其他 crate:格式转换与用量解析(`tw-dialect`),脱敏、工具调用审查及其他防护(`tw-guard`),以及熔断状态机(`tw-breaker`)。这三个 crate 只相互依赖,由测试保证;CI 会针对它们的每一次改动检查 ThinkWatch 企业版能否编译。只有一方使用的组件放在那一方的仓库中。 +ThinkWatch 企业版只依赖第一组,不依赖其他 crate:格式转换与用量解析(`tw-dialect`),脱敏、工具调用审查及其他防护(`tw-guard`),熔断状态机(`tw-breaker`),以及只有 Amazon Bedrock 需要的线上处理:SigV4 签名、eventstream 拆帧、地址与模型目录(`tw-bedrock`)。这四个 crate 只相互依赖,由测试保证;CI 会针对它们的每一次改动检查 ThinkWatch 企业版能否编译。只有一方使用的组件放在那一方的仓库中。 ThinkWatch Lite 把 `tw-api`、`tw-types`、`tw-yaml`、`tw-guard`、`tw-watch` 和 `tw-link` 固定在某个 Release 的 tag 上,并打包同一 Release 的 `twcore`。接管 AI 客户端(把其配置指向网关)、编辑其 MCP 服务器和扫描其配置文件都在 ThinkWatch Lite 中完成:这些操作修改的是应用所在机器上的文件,而这台机器不一定运行着 `twcore`。`twcore` 只负责为每个客户端签发专用的网关密钥。 diff --git a/crates/tw-bedrock/Cargo.toml b/crates/tw-bedrock/Cargo.toml new file mode 100644 index 00000000..90c06948 --- /dev/null +++ b/crates/tw-bedrock/Cargo.toml @@ -0,0 +1,38 @@ +[package] +name = "tw-bedrock" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +homepage.workspace = true +documentation.workspace = true +readme.workspace = true +description = "What only Amazon Bedrock needs on the wire, for both gateways: SigV4 signing, eventstream to SSE, runtime and control-plane addresses, and the model catalog" + +[dependencies] +# 签名。1.5 起签名不再带 http 0.2,所以不用再关在 feature 后面 +aws-sigv4 = { workspace = true } +aws-credential-types = { workspace = true } +# ConverseStream 的二进制帧:拆帧、校验 CRC +aws-smithy-eventstream = { workspace = true } +bytes = { workspace = true } +futures = { workspace = true } +percent-encoding = { workspace = true } +# 只有模型目录发请求。**不开任何 feature**:TLS、代理这些由调用方的 +# reqwest 决定,共享层不替它选 +reqwest = { version = "0.13", default-features = false } +serde_json = { workspace = true } + +[dev-dependencies] +tokio = { workspace = true } +# 假的控制面,和 core 别处的测试一样手写 +axum = { workspace = true } +# 造 eventstream 帧 +aws-smithy-types = { workspace = true } +# 从线上的二进制帧一路走到客户端格式,证明拆帧和方言的约定对得上 +tw-dialect = { workspace = true } +# 照着 SigV4 规范另算一遍签名:和签名库各写各的,才不会错在一处 +hmac = "0.13" +sha2 = { workspace = true } +hex = "0.4" diff --git a/crates/tw-bedrock/src/catalog.rs b/crates/tw-bedrock/src/catalog.rs new file mode 100644 index 00000000..09e68b42 --- /dev/null +++ b/crates/tw-bedrock/src/catalog.rs @@ -0,0 +1,298 @@ +//! 一家 Bedrock 上游能路由到哪些模型。 +//! +//! Bedrock 列出的基础模型不是这份清单本身。它列的是基础模型 id,而现在的大多数 +//! 模型 —— Claude 3.7 以后的都是 —— 根本不按基础 id 提供:要经推理配置(inference +//! profile)调用,比如 `us.anthropic.claude-sonnet-4-5-20250929-v1:0`,它把请求 +//! 分摊到几个区域。所以清单是区域控制面(`bedrock.{区域}.amazonaws.com`)上几份 +//! 列表的并集: +//! +//! - 能按需调用、输出文本的基础模型(`ListFoundationModels`); +//! - AWS 预设的推理配置(`ListInferenceProfiles`,`SYSTEM_DEFINED`); +//! - 要的话,还有账号自己建的应用推理配置(`APPLICATION`),按 ARN 调用。 +//! +//! 这些列表都不说**这个账号**能不能调某个模型、走哪个接口 —— 那要调的时候才知道。 +//! +//! 请求怎么认证和转发时一样:上游自己的请求头里有 Bedrock API Key 就原样带上, +//! 否则每个请求都签名(见 [`crate::carries_api_key`])。 + +use std::collections::BTreeSet; +use std::time::SystemTime; + +use serde_json::Value; + +use crate::Credentials; + +/// 一份推理配置列表最多读几页。一页最多 1000 个,一个区域也就几百个, +/// 只有永远翻不完的列表才会走到这里。 +pub const MAX_PROFILE_PAGES: usize = 10; + +/// 列哪几种推理配置。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Profiles { + /// 只列 AWS 预设的 + SystemDefined, + /// 预设的,加上账号自己建的应用推理配置(它们按 ARN 调用,列出来的就是 ARN) + WithApplication, +} + +/// 怎么认证列模型的请求。 +#[derive(Debug, Clone, Copy)] +pub struct Auth<'a> { + /// 上游自己的请求头,每个请求都带上。里面有 `Authorization`(Bedrock API Key) + /// 就不签名 + pub headers: &'a [(String, String)], + /// 签名用的凭证。请求头里没有 API Key 时必须有 + pub credentials: Option<&'a Credentials>, + /// 签名用的区域 + pub region: &'a str, +} + +/// 清单为什么没列出来。 +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Failure { + /// AWS 回答了,拒绝了。`kind` 是异常名,比如 `AccessDeniedException`、 + /// `UnrecognizedClientException` —— 凭证不对和凭证对但没有列模型的权限, + /// 靠它分开。`message` 是 AWS 的原话,**可能点名账号**,见 [`crate::error`] + Status { + status: u16, + kind: Option, + message: String, + }, + /// 没有可读的:请求签不了、发不出去,或者回来的不是一份列表 + Request(String), +} + +/// `auth` 能在 `control_base` 上路由到的每一个模型 id,排好序。 +/// +/// `control_base` 是区域的控制面([`crate::endpoint::control_base`]),或者一个 +/// 替它回答的代理。每份列表都得成功:只有基础 id 的清单,给出的恰恰是大多数现在的 +/// 模型**不能**用的那些 id,还不如没有。 +pub async fn list_models( + http: &reqwest::Client, + control_base: &str, + auth: &Auth<'_>, + profiles: Profiles, +) -> Result, Failure> { + let application = async { + match profiles { + Profiles::SystemDefined => Ok(Vec::new()), + Profiles::WithApplication => { + inference_profiles(http, control_base, auth, ProfileType::Application).await + } + } + }; + let (models, system, application) = futures::try_join!( + foundation_models(http, control_base, auth), + inference_profiles(http, control_base, auth, ProfileType::SystemDefined), + application, + )?; + let ids: BTreeSet = models + .into_iter() + .chain(system) + .chain(application) + .collect(); + Ok(ids.into_iter().collect()) +} + +/// 控制面认不认 `auth` 的凭证。只列一个推理配置:凭证被拒会在这里露出来,某一个 +/// 模型被拒不会。 +pub async fn accepts_credential( + http: &reqwest::Client, + control_base: &str, + auth: &Auth<'_>, +) -> bool { + let Ok(url) = listing_url( + control_base, + "inference-profiles", + &[("type", "SYSTEM_DEFINED"), ("maxResults", "1")], + ) else { + return false; + }; + get(http, url, auth).await.is_ok() +} + +async fn foundation_models( + http: &reqwest::Client, + control_base: &str, + auth: &Auth<'_>, +) -> Result, Failure> { + let url = listing_url( + control_base, + "foundation-models", + &[ + ("byInferenceType", "ON_DEMAND"), + ("byOutputModality", "TEXT"), + ], + )?; + let listing = get(http, url, auth).await?; + ids(&listing, "modelSummaries", "modelId") +} + +#[derive(Debug, Clone, Copy)] +enum ProfileType { + SystemDefined, + Application, +} + +impl ProfileType { + /// 查询参数 `type`(接口文档里叫 `typeEquals`)的值 + fn query(self) -> &'static str { + match self { + ProfileType::SystemDefined => "SYSTEM_DEFINED", + ProfileType::Application => "APPLICATION", + } + } + + /// 调用它时写进模型 id 的那个字段:预设的按 id(`us.anthropic.…`), + /// 应用推理配置按 ARN + fn id_field(self) -> &'static str { + match self { + ProfileType::SystemDefined => "inferenceProfileId", + ProfileType::Application => "inferenceProfileArn", + } + } +} + +async fn inference_profiles( + http: &reqwest::Client, + control_base: &str, + auth: &Auth<'_>, + kind: ProfileType, +) -> Result, Failure> { + let mut profiles = Vec::new(); + let mut next_token: Option = None; + for _ in 0..MAX_PROFILE_PAGES { + let mut query = vec![("type", kind.query()), ("maxResults", "1000")]; + if let Some(token) = &next_token { + query.push(("nextToken", token)); + } + let url = listing_url(control_base, "inference-profiles", &query)?; + let page = get(http, url, auth).await?; + profiles.extend(ids(&page, "inferenceProfileSummaries", kind.id_field())?); + next_token = page + .get("nextToken") + .and_then(Value::as_str) + .filter(|t| !t.is_empty()) + .map(str::to_string); + if next_token.is_none() { + return Ok(profiles); + } + } + Err(Failure::Request(format!( + "the inference profile listing did not end after {MAX_PROFILE_PAGES} pages" + ))) +} + +/// `{control_base}/{path}?{query}`,查询串做百分号编码:`nextToken` 里可能有 `+`、 +/// `/`、`=`,而签名覆盖的是 AWS 解码之后的查询串。 +fn listing_url( + control_base: &str, + path: &str, + query: &[(&str, &str)], +) -> Result { + let base = control_base.trim_end_matches('/'); + reqwest::Url::parse_with_params(&format!("{base}/{path}"), query) + .map_err(|e| Failure::Request(format!("{base}/{path}: {e}"))) +} + +/// GET 一份列表,按 JSON 读。 +async fn get(http: &reqwest::Client, url: reqwest::Url, auth: &Auth<'_>) -> Result { + let mut req = http.get(url.clone()); + for (k, v) in auth.headers { + req = req.header(k.as_str(), v.as_str()); + } + if !crate::carries_api_key(auth.headers.iter().map(|(k, _)| k.as_str())) { + let credentials = auth.credentials.ok_or_else(|| { + Failure::Request("no credential: neither a Bedrock API key nor AWS keys".into()) + })?; + let signed = crate::sign::sign( + credentials, + auth.region, + "GET", + url.as_str(), + None, + SystemTime::now(), + ) + .map_err(|e| Failure::Request(e.to_string()))?; + for (k, v) in signed { + req = req.header(k, v); + } + } + + let resp = req + .send() + .await + .map_err(|e| Failure::Request(e.to_string()))?; + let status = resp.status(); + let kind_header = resp + .headers() + .get(crate::error::ERROR_TYPE) + .and_then(|v| v.to_str().ok()) + .map(str::to_string); + let body = resp + .bytes() + .await + .map_err(|e| Failure::Request(e.to_string()))?; + if status.is_success() { + return Ok(serde_json::from_slice(&body).unwrap_or(Value::Null)); + } + Err(Failure::Status { + status: status.as_u16(), + kind: crate::error::kind_of(kind_header.as_deref(), &body), + message: crate::error::message_in(&body) + .unwrap_or_else(|| status.canonical_reason().unwrap_or("error").to_string()), + }) +} + +/// 一份列表里 `list` 数组每一项的 `id`。 +/// +/// 没有那个数组的「列表」不可信,报错,而不是当成空的读。 +fn ids(listing: &Value, list: &str, id: &str) -> Result, Failure> { + let entries = listing + .get(list) + .and_then(Value::as_array) + .ok_or_else(|| Failure::Request(format!("the listing has no {list}")))?; + Ok(entries + .iter() + .filter_map(|entry| entry.get(id).and_then(Value::as_str)) + .map(str::to_string) + .collect()) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + + const TOKEN: &str = "page+2/of=2=="; + + #[test] + fn a_page_token_is_percent_encoded_into_the_query() { + let url = listing_url( + "https://bedrock.us-east-1.amazonaws.com/", + "inference-profiles", + &[("type", "SYSTEM_DEFINED"), ("nextToken", TOKEN)], + ) + .unwrap(); + assert_eq!( + url.as_str(), + "https://bedrock.us-east-1.amazonaws.com/inference-profiles\ + ?type=SYSTEM_DEFINED&nextToken=page%2B2%2Fof%3D2%3D%3D" + ); + } + + #[test] + fn a_listing_without_its_array_fails_rather_than_reading_as_empty() { + assert_eq!( + ids( + &json!({"modelSummaries": [{"modelId": "a"}, {}]}), + "modelSummaries", + "modelId" + ), + Ok(vec!["a".to_string()]) + ); + assert!(ids(&json!({"message": "?"}), "modelSummaries", "modelId").is_err()); + assert!(ids(&Value::Null, "modelSummaries", "modelId").is_err()); + } +} diff --git a/crates/tw-bedrock/src/endpoint.rs b/crates/tw-bedrock/src/endpoint.rs new file mode 100644 index 00000000..ae952abf --- /dev/null +++ b/crates/tw-bedrock/src/endpoint.rs @@ -0,0 +1,251 @@ +//! 区域、地址,以及模型 id 怎么写进路径。 +//! +//! Bedrock 的主机名是从区域拼出来的:推理走 `bedrock-runtime.{区域}.amazonaws.com`, +//! 列模型走控制面 `bedrock.{区域}.amazonaws.com`。所以**区域就是主机名的一部分**, +//! 校验区域就是在校验请求 —— 连同它带着的凭证 —— 会去哪一台主机:区域之外多一个 +//! 字符,都可能把请求带到别处。 + +use std::fmt; + +use percent_encoding::{AsciiSet, CONTROLS, utf8_percent_encode}; + +/// 不是 AWS 的区域代码。 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct InvalidRegion; + +impl fmt::Display for InvalidRegion { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("not an AWS region code such as us-east-1") + } +} + +impl std::error::Error for InvalidRegion {} + +/// 一个 AWS 区域代码,比如 `us-east-1`、`us-gov-west-1`。 +/// +/// 只认「至少两个用 `-` 连起来的小写单词,再接 `-` 和数字」。更宽的写法都可能改掉 +/// 拼出来的主机名:`us-east-1.evil.example`、`evil.example#` 拼进去就是另一台主机。 +pub fn validate_region(region: &str) -> Result<(), InvalidRegion> { + let valid = region.rsplit_once('-').is_some_and(|(name, number)| { + !number.is_empty() + && number.bytes().all(|b| b.is_ascii_digit()) + && name.split('-').count() >= 2 + && name + .split('-') + .all(|word| !word.is_empty() && word.bytes().all(|b| b.is_ascii_lowercase())) + }); + if valid { Ok(()) } else { Err(InvalidRegion) } +} + +/// 这个区域的推理地址。调用方先校验过区域。 +pub fn runtime_base(region: &str) -> String { + format!("https://bedrock-runtime.{region}.amazonaws.com") +} + +/// 这个区域的控制面,Bedrock 在这里列模型。调用方先校验过区域。 +pub fn control_base(region: &str) -> String { + format!("https://bedrock.{region}.amazonaws.com") +} + +/// 标准推理地址里的区域。 +/// +/// 认 `https://bedrock-runtime.{区域}.amazonaws.com` 和它的 FIPS 版 +/// `https://bedrock-runtime-fips.{区域}.amazonaws.com`,末尾的 `/` 可有可无,主机名 +/// 不分大小写。带路径、查询、端口、用户信息的都不算:那是代理或者 VPC 端点,它的 +/// 区域得另外说。 +pub fn region_of(base_url: &str) -> Option<&str> { + let scheme = "https://"; + let rest = base_url + .get(..scheme.len()) + .filter(|s| s.eq_ignore_ascii_case(scheme)) + .map(|_| &base_url[scheme.len()..])?; + let host = rest.strip_suffix('/').unwrap_or(rest); + let lower = host.to_ascii_lowercase(); + let start = ["bedrock-runtime.", "bedrock-runtime-fips."] + .iter() + .find(|p| lower.starts_with(**p))? + .len(); + let suffix = ".amazonaws.com"; + if !lower.ends_with(suffix) || lower.len() < start + suffix.len() { + return None; + } + // 小写化不改变字节长度,所以按小写的那份量出来的边界在原串上一样合法 + let region = &host[start..host.len() - suffix.len()]; + validate_region(region).ok().map(|_| region) +} + +/// 写进路径的模型 id 里要转义的字符。 +/// +/// ARN 形式的模型 id(`arn:aws:bedrock:…:application-inference-profile/abc`)里有 +/// `/`,不转义的话 `/model/{id}/converse` 就多出一段路径,AWS 按路径找不到操作。 +/// 会改变 URL 结构的另外几个字符(`?`、`#`、`%`、空格和控制字符)一并转义。 +/// +/// `:` 不转:每个模型 id 都带它(`…-v1:0`),AWS 的文档和示例也都原样写。签名覆盖的 +/// 是实际发出去的那个写法,写法本身不影响签名对不对得上。 +const MODEL_ID: &AsciiSet = &CONTROLS + .add(b' ') + .add(b'"') + .add(b'#') + .add(b'%') + .add(b'/') + .add(b'<') + .add(b'>') + .add(b'?') + .add(b'`') + .add(b'{') + .add(b'}'); + +/// 发往推理地址的完整 URL。 +/// +/// `base` 是推理地址([`runtime_base`],或者配置里写的代理地址),末尾的 `/` 会去掉。 +/// `path` 是 `tw_dialect` 写好的 `/model/{id}/{操作}`,模型 id 在这里转义,见 +/// [`MODEL_ID`]。认不出这个形状的路径原样接上。 +pub fn runtime_url(base: &str, path: &str) -> String { + let base = base.trim_end_matches('/'); + let shaped = path + .strip_prefix("/model/") + .and_then(|rest| rest.rsplit_once('/')); + match shaped { + Some((id, action)) if !id.is_empty() => { + format!( + "{base}/model/{}/{action}", + utf8_percent_encode(id, MODEL_ID) + ) + } + _ => format!("{base}{path}"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn region_codes_are_accepted() { + for region in [ + "us-east-1", + "eu-central-2", + "ap-southeast-7", + "us-gov-west-1", + ] { + assert!(validate_region(region).is_ok(), "{region}"); + } + } + + #[test] + fn anything_that_could_change_the_host_is_refused() { + for bad in [ + "", + "us-east", + "useast1", + "US-EAST-1", + "us--east-1", + "-us-east-1", + "us-east-1.evil.example", + "evil.example#", + "evil.example/x?-1", + "https://bedrock-runtime.us-east-1.amazonaws.com", + ] { + assert!(validate_region(bad).is_err(), "{bad:?}"); + } + } + + #[test] + fn both_hosts_are_built_from_the_region() { + assert_eq!( + runtime_base("eu-west-1"), + "https://bedrock-runtime.eu-west-1.amazonaws.com" + ); + assert_eq!( + control_base("eu-west-1"), + "https://bedrock.eu-west-1.amazonaws.com" + ); + } + + #[test] + fn the_region_is_read_back_from_a_standard_runtime_address() { + for (url, region) in [ + ( + "https://bedrock-runtime.us-east-1.amazonaws.com", + "us-east-1", + ), + ( + "https://bedrock-runtime.us-east-1.amazonaws.com/", + "us-east-1", + ), + ( + "https://bedrock-runtime-fips.us-gov-west-1.amazonaws.com", + "us-gov-west-1", + ), + ( + "HTTPS://Bedrock-Runtime.eu-west-3.AmazonAWS.com", + "eu-west-3", + ), + ] { + assert_eq!(region_of(url), Some(region), "{url}"); + } + } + + #[test] + fn anything_else_has_no_region_of_its_own() { + for url in [ + // 不是 https + "http://bedrock-runtime.us-east-1.amazonaws.com", + // 控制面不是推理地址 + "https://bedrock.us-east-1.amazonaws.com", + // 路径、端口、用户信息:是代理或者别的什么 + "https://bedrock-runtime.us-east-1.amazonaws.com/v1", + "https://bedrock-runtime.us-east-1.amazonaws.com:443", + "https://user@bedrock-runtime.us-east-1.amazonaws.com", + // 主机名里借壳 + "https://bedrock-runtime.us-east-1.amazonaws.com.evil.example", + "https://bedrock-runtime.evil.example.amazonaws.com", + // VPC 端点 + "https://vpce-0a1b.bedrock-runtime.us-east-1.vpce.amazonaws.com", + "https://bedrock-runtime..amazonaws.com", + "", + ] { + assert_eq!(region_of(url), None, "{url}"); + } + } + + #[test] + fn a_plain_model_id_goes_into_the_path_as_it_is() { + assert_eq!( + runtime_url( + "https://bedrock-runtime.us-east-1.amazonaws.com/", + "/model/us.anthropic.claude-sonnet-4-5-20250929-v1:0/converse-stream" + ), + "https://bedrock-runtime.us-east-1.amazonaws.com/model/\ + us.anthropic.claude-sonnet-4-5-20250929-v1:0/converse-stream" + ); + } + + #[test] + fn the_slash_of_an_arn_is_encoded_so_the_path_keeps_its_shape() { + assert_eq!( + runtime_url( + "https://bedrock-runtime.us-east-2.amazonaws.com", + "/model/arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/a1b2c3/converse" + ), + "https://bedrock-runtime.us-east-2.amazonaws.com/model/\ + arn:aws:bedrock:us-east-2:123456789012:application-inference-profile%2Fa1b2c3/converse" + ); + } + + #[test] + fn characters_that_would_change_the_url_are_encoded_too() { + assert_eq!( + runtime_url("https://h", "/model/a?b#c%d e/converse"), + "https://h/model/a%3Fb%23c%25d%20e/converse" + ); + } + + #[test] + fn a_path_of_another_shape_is_appended_as_it_is() { + assert_eq!( + runtime_url("https://h/", "/foundation-models"), + "https://h/foundation-models" + ); + } +} diff --git a/crates/tw-bedrock/src/error.rs b/crates/tw-bedrock/src/error.rs new file mode 100644 index 00000000..bb892379 --- /dev/null +++ b/crates/tw-bedrock/src/error.rs @@ -0,0 +1,118 @@ +//! AWS 的错误里能拿出来什么,哪些能给谁看。 +//! +//! 出错时 AWS 在 `x-amzn-ErrorType` 头里给异常名,比如 +//! `AccessDeniedException:http://internal.amazon.com/coral/com.amazon.bedrock/`; +//! 正文是 `{"message": "…"}`,有的错误写成 `Message`。 +//! +//! **异常名能给人看,正文不一定。**401/403 的正文会点名账号 ID 和 IAM 身份 +//! (`User: arn:aws:iam::123456789012:user/x is not authorized to perform …`), +//! 那不该出现在返回给客户端的文字里,也不该进日志里的错误类型。 + +use serde_json::Value; + +/// AWS 放异常名的响应头。 +pub const ERROR_TYPE: &str = "x-amzn-errortype"; + +/// 异常名:先看 `x-amzn-ErrorType` 头(冒号后面是命名空间,不要),没有再看正文的 +/// `__type`(`com.amazon.coral.service#UnrecognizedClientException` 取 `#` 后面)。 +/// +/// 只认像名字的东西 —— 字母和数字。它会原样进错误信息,不能夹带别的。 +pub fn kind_of(header: Option<&str>, body: &[u8]) -> Option { + let from_header = header.and_then(|h| h.split(':').next()).map(str::trim); + let parsed = serde_json::from_slice::(body).ok(); + let from_body = parsed + .as_ref() + .and_then(|v| v.get("__type")) + .and_then(Value::as_str) + .map(|t| t.rsplit('#').next().unwrap_or(t).trim()); + from_header + .filter(|k| !k.is_empty()) + .or(from_body) + .filter(|k| !k.is_empty() && k.len() <= 128 && k.bytes().all(|b| b.is_ascii_alphanumeric())) + .map(str::to_string) +} + +/// 正文里 AWS 说的原因:`message`,或者 `Message`。 +pub fn message_in(body: &[u8]) -> Option { + let v: Value = serde_json::from_slice(body).ok()?; + v.get("message") + .or_else(|| v.get("Message")) + .and_then(Value::as_str) + .map(str::to_string) +} + +/// 一个异常名对应的 HTTP 状态。 +/// +/// 流里的异常事件来的时候 200 早已发出去了,异常名是剩下的唯一线索;状态照 AWS +/// 给同名异常定的那个,客户端和日志靠它分清「限流了,等等再试」和「请求本身不对」。 +/// 大小写、有没有 `Exception` 结尾都认:流里是 `throttlingException`,HTTP 错误里是 +/// `ThrottlingException`。认不出的算 502:上游出了错,说不清是哪种。 +pub fn status_of(kind: &str) -> u16 { + let k = kind.to_ascii_lowercase(); + let k = k.strip_suffix("exception").unwrap_or(&k); + match k { + "validation" | "servicequotaexceeded" => 400, + "accessdenied" => 403, + "resourcenotfound" => 404, + "modeltimeout" => 408, + "modelerror" | "modelstreamerror" => 424, + "throttling" | "modelnotready" => 429, + "internalserver" => 500, + "serviceunavailable" => 503, + _ => 502, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_kind_comes_from_the_header_without_its_namespace() { + assert_eq!( + kind_of( + Some("AccessDeniedException:http://internal.amazon.com/coral/com.amazon.bedrock/"), + br#"{"message":"User: arn:aws:iam::123456789012:user/x is not authorized"}"#, + ) + .as_deref(), + Some("AccessDeniedException") + ); + } + + #[test] + fn without_the_header_the_kind_comes_from_the_body() { + assert_eq!( + kind_of( + None, + br#"{"__type":"com.amazon.coral.service#UnrecognizedClientException","message":"The security token included in the request is invalid."}"#, + ) + .as_deref(), + Some("UnrecognizedClientException") + ); + assert_eq!(kind_of(None, b"not json"), None); + } + + #[test] + fn a_kind_that_is_not_a_name_is_not_repeated() { + assert_eq!(kind_of(Some("Access Denied