出站 HTTP 客户端

属于 kxed 全栈 Rust 后端框架生态:官网 | 在线文档 | 源码仓库 | 主包 crates.io

管理全进程共享的出站 HTTP 连接池,自动继承当前请求或后台 Task 的剩余截止时间并透传 x-request-id 与 W3C traceparent 链路追踪头,内置幂等安全重试、SSRF 内网地址拦截、有界并发回包内存预算以及零网络单测替身 HttpFake。实战示例见 分页、OpenAPI 与出站 HTTP 教程。

快速接入#

在 Cargo.toml 开启主包 kxed 的 http-client 特性(编写单元测试替身时在 [dev-dependencies] 加开 testing;独立组装可依赖 kxed-plugins = { version = "0.0.5-alpha", features = ["http-client"] }):

TOML
[dependencies]
kxed = { version = "0.0.5-alpha", features = ["http-client"] }

[dev-dependencies]
kxed = { version = "0.0.5-alpha", features = ["http-client", "testing"] }

在应用配置文件中设置默认超时(可选,开箱即有合理默认值):

TOML
[http_client]
timeout = "10s"
connect_timeout = "3s"

在应用中注册 HttpClientPlugin::new(),即可在业务 Procedure、Task 或事件订阅中通过 ctx.http()? 调用外部第三方接口:

Rust
use kxed::plugins::http_client::HttpClientPlugin;
use kxed::prelude::*;
use std::time::Duration;

#[derive(Serialize)]
struct ChargeReq<'a> {
    order_id: &'a str,
    amount: u64,
}

#[derive(Deserialize, Serialize, ToSchema)]
pub struct Receipt {
    pub id: String,
}

#[mutation(name = "payments.charge", post = "/api/payments/charge")]
pub async fn create_charge(ctx: &AppCtx, order_id: String, amount: u64) -> Result<Receipt, AppErr> {
    ctx.http()?
        .post("https://pay.example.com/v1/charges")
        .with_token("sk_live_example")
        .header("idempotency-key", &order_id)
        .idempotent()
        .json(&ChargeReq { order_id: &order_id, amount })
        .timeout(Duration::from_secs(5))
        .retry(3, Duration::from_millis(200))
        .receive_json()
        .await
        .map_err(Into::into)
}

#[kxed::main]
async fn main() -> kxed::Result<()> {
    App::new()
        .plugin(HttpClientPlugin::new())
        .run()
        .await
}

核心用法#

发起请求、重试与期限继承#

通过 ctx.http()? 链式调用 get/post/put/patch/delete/head,搭配 .with_token、.with_basic_auth、.header、.query、.json、.form 或 .body 组装请求:

Rust
use kxed_core::{AppCtx, AppErr};
use kxed_plugins::http_client::AppCtxHttp;
use serde::{Deserialize, Serialize};
use std::time::Duration;

#[derive(Serialize)]
struct Charge<'a> {
    order_id: &'a str,
    amount: u64,
}

#[derive(Deserialize)]
struct Receipt {
    id: String,
}

async fn charge(ctx: AppCtx, order_id: &str) -> Result<String, AppErr> {
    let receipt: Receipt = ctx
        .http()?
        .post("https://pay.example.com/v1/charges")
        .with_token("sk_live_example")
        .header("idempotency-key", order_id)
        .idempotent()
        .json(&Charge { order_id, amount: 4200 })
        .timeout(Duration::from_secs(5))
        .retry(3, Duration::from_millis(200))
        .receive_json()
        .await?;
    Ok(receipt.id)
}
  • 三种接收方式:.receive_json::<T>()(要求 2xx 并解码 JSON)、.receive_text()(要求 2xx 并返回字符串)、.send()(任意状态码均返回 HttpResponse,方便自行检查状态码或响应头;单次响应上限 MAX_RESPONSE_BYTES 16 MiB)。
  • 幂等安全重试:.retry(attempts, backoff) 默认只对确定未执行的 NotExecuted 错误与幂等方法(GET/HEAD/PUT/DELETE)的 Indeterminate 错误自动重发(遵守上游 Retry-After 头);携带了幂等键的 POST/PATCH 显式调用 .idempotent() 后才会对超时与 5xx 重发。
  • 自动继承上下文期限与链路头:单次尝试超时取 .timeout(..)(或 http_client.timeout)与当前 ctx.deadline() 剩余时间的较小值,外层请求或任务已超时则不再白发网络请求;自动透传 x-request-id 与 traceparent。

重定向与 SSRF#

当请求 URL 来自用户输入(如用户自定义 Webhook 回调地址、网页链接摘要抓取、远程图片拉取)时,链式调用 .only_public_targets() 阻断对内网、回环与云厂商元数据地址(如 169.254.169.254、100.100.100.200)的 SSRF 探测:

Rust
use kxed_core::{AppCtx, AppErr};
use kxed_plugins::http_client::AppCtxHttp;

async fn preview(ctx: AppCtx, url: &str) -> Result<String, AppErr> {
    Ok(ctx.http()?.only_public_targets().get(url).receive_text().await?)
}
  • DNS Rebinding 免疫:地址合法性直接在底层建连 DNS 解析器内核验并复用该解析地址建连(覆盖全部 IANA 保留/私网 IPv4、IPv6、IPv4-mapped IPv6 与 NAT64 段,且绕过环境变量代理直连),解析出任一非公网 IP 立即拦截并返回 422 http_client_private_target_denied。
  • 同源重定向限制:客户端仅跟随同 Origin(或同主机 http 升 https 默认端口)至多 10 跳重定向,拒绝跨域名 302 跳转到内网。若整个服务只访问公网第三方 API,也可全局开启 http_client.only_public_targets = true(未显式调 only_public_targets() 却命中私网时返 500 http_client_private_upstream_denied)。

单元测试替身(HttpFake)#

启用 testing 特性后,使用 HttpFake 在内存中拦截出站请求并断言调用次数、请求头与 JSON 体,无需启动外部 Mock 服务器(未匹配的意外请求直接报 500 http_client_fake_route_not_found,防止测试误打真实外网):

Rust
use kxed_plugins::http_client::{FakeResponse, HttpClient, HttpFake, Method};
use serde_json::{json, Value};

async fn reads_the_rate_from_the_fake() {
    let fake = HttpFake::new()
        .route(Method::GET, "https://api.example.com/*", |_| FakeResponse::json(&json!({ "usd": 7.1 })));
    let rate: Value = HttpClient::fake(&fake).get("https://api.example.com/rate").receive_json().await.unwrap();
    assert_eq!(rate["usd"], 7.1);
    fake.assert_sent(|sent| sent.is(Method::GET, "https://api.example.com/rate"));
}

在完整应用或插件测试中,通过 App::provide(fake.clone())(或 PluginHarness::state(fake.clone()))注入后,业务代码里的 ctx.http()? 会自动路由至 HttpFake(还可用 FakeResponse::timeout() 与 connect_failure() 测试重试与降级逻辑):

Rust
use kxed_core::testing::PluginHarness;
use kxed_core::AppCtx;
use kxed_plugins::http_client::{AppCtxHttp, FakeResponse, HttpClientPlugin, HttpFake, Method};

async fn the_handler_path_uses_the_fake() {
    let fake = HttpFake::new()
        .route(Method::POST, "https://sms.example.com/send", |_| FakeResponse::text("queued").with_status(202));
    let mut running = PluginHarness::new()
        .state(fake.clone())
        .plugin(HttpClientPlugin::new())
        .boot()
        .await
        .unwrap();
    let ctx = AppCtx::new(running.app_state());
    let status = ctx.http().unwrap().post("https://sms.example.com/send").send().await.unwrap().status();
    assert_eq!(status.as_u16(), 202);
    fake.assert_sent_count(1);
    running.shutdown().await.unwrap();
}

配置#

键缺省范围与含义
http_client.timeout10s单次尝试从建连到读完响应体的默认上限,范围 10ms..=300s(可按请求 .timeout(..) 覆盖)
http_client.connect_timeout3sDNS 解析、TCP 与 TLS 握手上限,范围 10ms..=timeout
http_client.user_agentkxed/ 加 crate 版本默认 User-Agent 请求头
http_client.max_in_flight128单实例同时在途的出站请求并发上限,范围 1..=65536
http_client.max_in_flight_response_bytes268435456(256MiB)单实例正在读取的在途响应体总内存预算,范围 16MiB..=64GiB
http_client.only_public_targetsfalse设为 true 时全局强制拦截一切非公网目标地址,见 重定向与 SSRF

失败分类与状态码#

HttpClientError 实现了 CallFailure,在 handler 中用 ? 自动映射为脱敏响应(上游 4xx 统一映射为 502 以免前端将第三方 401 误认为本系统掉线;告警日志自动剥离 query 参数并将路径中的长密钥段脱敏为 {N bytes}):

故障情形错误变体重试分类HTTP 状态码错误码 code
DNS、TCP 建连或 TLS 握手失败 / 上游返 503 或 408Connect / StatusNotExecuted503http_client_unavailable
发出前外层 ctx.deadline() 已耗尽DeadlineExceededNotExecuted503http_client_deadline_exceeded
并发在途请求满 max_in_flight 等不到槽位BusyNotExecuted503http_client_busy
上游返 429 限流StatusNotExecuted503(透传 Retry-After)http_client_rate_limited
请求发出后等待响应或回包内存预算超时TimeoutIndeterminate504http_client_timeout
传输中途断连 / 上游返其余 5xxTransfer / StatusIndeterminate502http_client_transfer_failed / http_client_server_error
上游返其余 4xx 或未跟随的跨源 3xxStatusSettled502http_client_rejected
2xx 响应超 16 MiB / JSON 解码失败TooLarge / DecodeSettled502http_client_response_too_large / http_client_invalid_response
only_public_targets() 拦下私网用户输入 URLPrivateTargetSettled422http_client_private_target_denied
全局 only_public_targets 拦下私网配置上游 / 非法请求参数PrivateUpstream / InvalidRequestSettled500http_client_private_upstream_denied / http_client_invalid_request
单测 HttpFake 未匹配路由StraySettled500http_client_fake_route_not_found