diff --git a/crates/tw-gateway/src/limits.rs b/crates/tw-gateway/src/limits.rs index 94b522dd..4d3bb522 100644 --- a/crates/tw-gateway/src/limits.rs +++ b/crates/tw-gateway/src/limits.rs @@ -8,7 +8,9 @@ //! //! 超出上限的请求**等前面的结束**,不拒绝:客户端收到 429 通常不会优雅 //! 重试 —— Claude Code 把它当成硬失败,一个本来只需要多等两秒的请求会变成 -//! 一次任务中断。等多久由客户端决定:它断开连接,这个请求就不再等。 +//! 一次任务中断。等多久由客户端决定:它断开连接,这个请求就不再等。等的时候它不是 +//! 一个字节都收不到:流式的回答压过 [`crate::OPENING_HOLD`] 先拿到响应头和保活(见 +//! `server::pipeline::commit`),它等响应头的计时不会先到。 use std::collections::HashMap; use std::sync::{Arc, Mutex}; diff --git a/crates/tw-gateway/src/server/pipeline.rs b/crates/tw-gateway/src/server/pipeline.rs index 350f0a75..d751c680 100644 --- a/crates/tw-gateway/src/server/pipeline.rs +++ b/crates/tw-gateway/src/server/pipeline.rs @@ -5,8 +5,10 @@ //! 本地应答在准入之前(离线也要能答),准入在路由之前(列表即承诺), //! 并发闸门在路由之后(被规则挡下的不用先排队)。 //! -//! 发出开始事件之后的两段各自一个子模块:[`hop`] 依次试候选上游(每一跳先过插件的 -//! 请求钩子,见 [`plug`]),[`relay`] 把选中那一家的响应交给客户端。 +//! 路由之后的几步归 [`answer`] 所有:流式的回答压着不给响应头的时限(见 [`commit`])从进 +//! 准入起算,排在这把密钥的并发闸门、用量窗口后面的请求和等上游空位的一样,过了时限先拿到 +//! `200` 和保活。发出开始事件之后的两段各自一个子模块:[`hop`] 依次试候选上游(每一跳先过 +//! 插件的请求钩子,见 [`plug`]),[`relay`] 把选中那一家的响应交给客户端。 use std::sync::Arc; @@ -85,7 +87,7 @@ struct Started { pub(super) async fn pipeline( state: AppState, rt: Arc, - mut req: Inbound, + req: Inbound, live: crate::live::Pass, ending: &mut Option, ) -> Result { @@ -114,7 +116,7 @@ pub(super) async fn pipeline( // 管线第 2 步:读出路由事实,路由。**看的是客户端的原话**:插件的请求钩子排在路由 // 之后(每发往一个上游跑一次,见 `plug`),左右不了请求去哪一家 - let (mut reading, fp) = heavy(&req.body, || read(&req, intent, parsed.as_ref())); + let (reading, fp) = heavy(&req.body, || read(&req, intent, parsed.as_ref())); let conv = conversation(&rt, &req, &reading, fp.as_deref()); let (choice, decision) = match route(&state, &rt, &req, &reading, conv.as_ref())? { Routed::Go(choice, decision) => (choice, decision), @@ -140,6 +142,98 @@ pub(super) async fn pipeline( } }; + // 管线第 3 步起**归回答那一段**(见 [`answer`]):流式的回答压着不给响应头的时限从进 + // 准入起算 —— 等这把密钥的并发空位、等用量窗口的空位和等上游的空位一样,等过了时限客户端 + // 拿到 `200` 和保活(见 `commit`),不至于一个字节都收不到而自己断开 + let early = commit::early(&state, &req, &reading); + let abort = req.abort.clone(); + let dialect = req.dialect; + let run = answer( + state, + rt, + req, + Chosen { + parsed, + reading, + fp, + conv, + choice, + decision, + }, + live, + ending.take(), + ); + match early { + None => run.await, + Some(e) => commit::hold(run, dialect, e, abort).await, + } +} + +/// 路由之后定下的,准入起归回答那一段所有(见 [`answer`])。 +struct Chosen { + /// 解析过的请求体:内容过滤还要用一次,之后就用完了 + parsed: Option, + reading: crate::client_api::Reading, + /// 这段对话的指纹(见 [`crate::affinity::identity`]) + fp: Option, + conv: Option, + choice: Choice, + decision: tw_engine::Decision, +} + +/// 发出开始事件之后,回答那一段要的:路由事实、决定、开始时定下的、这段对话这一轮,和两张 +/// 通行证(在服务中、这把密钥的并发)。 +struct Tail { + reading: crate::client_api::Reading, + decision: tw_engine::Decision, + started: Started, + conv: Option, + passes: (crate::live::Pass, crate::limits::Pass), +} + +/// 管线第 3 步起:准入(见 [`admission`])、内容过滤、开始事件,然后依次试候选上游(见 +/// [`hop`]),把接下的那一家的回答交给客户端(见 [`relay`])。 +/// +/// **拥有它要的一切**(不借管线的东西):流式的回答等过一阵还没有内容时,响应头先交出去, +/// 它挪进响应体里接着跑(见 [`commit`])—— 等准入的那一段也在里面,排着队的请求一样等得到 +/// 响应头。结局也在它手上:返回错误之前自己报失败(准入拒绝的也是,和路由拒绝的留一样的 +/// 一行),被丢掉由结局的 Drop 报(客户端走了是取消,叫停了是手动中止)。 +async fn answer( + state: AppState, + rt: Arc, + mut req: Inbound, + chosen: Chosen, + live: crate::live::Pass, + mut ending: Option, +) -> Result { + let r = async { + let tail = enter(&state, &rt, &mut req, chosen, live, &mut ending).await?; + answer_with(&state, &rt, &req, tail, &mut ending).await + } + .await; + if let (Err(e), Some(end)) = (&r, ending.take()) { + end.failed(e.source.into(), e.detail.clone()); + } + r +} + +/// 管线第 3、4 步:准入,内容过滤,发出开始事件。 +async fn enter( + state: &AppState, + rt: &Arc, + req: &mut Inbound, + chosen: Chosen, + live: crate::live::Pass, + ending: &mut Option, +) -> Result { + let Chosen { + parsed, + mut reading, + fp, + conv, + choice, + decision, + } = chosen; // 管线第 3 步:这把密钥的用量上限和并发上限(见 `admission`)。放在路由之后:被规则 // 挡下的请求不用先等一轮。被用量上限拒绝的照样留一行 // @@ -150,9 +244,9 @@ pub(super) async fn pipeline( hold, wait_until, } = admission::admit( - &state, - &rt, - &req, + state, + rt, + req, &reading, &choice, &decision, @@ -166,13 +260,13 @@ pub(super) async fn pipeline( let size = req.body.len(); let screened = req.body.clone(); let (screening, started) = heavy_for(size, || { - let screening = screen(&rt, &mut req, &mut reading, parsed.as_ref()); + let screening = screen(rt, req, &mut reading, parsed.as_ref()); // 解析出来的那一份到这里就用完了:删过字的话它也不再是请求体的样子 drop(parsed); let started = start( - &state, - &rt, - &req, + state, + rt, + req, &reading, choice, wait_until, @@ -190,7 +284,7 @@ pub(super) async fn pipeline( let refused = (!screening.hits.is_empty()) .then(|| { // 前后文和存下来的正文一样换、打码:同一套规则、同一本账 - let redaction = redaction(&rt, started.ledger.clone()); + let redaction = redaction(rt, started.ledger.clone()); let src = crate::guard::detail::Screened { body: &screened, dialect: req.api.map(|a| a.dialect()), @@ -206,59 +300,16 @@ pub(super) async fn pipeline( if let Some(why) = refused { return Err(GatewayError::denied(why)); } - // 管线第 5 步:试上游、交回答(见 `answer`)。它拿走这个请求要的一切:流式的回答等不到 - // 内容时,响应头先交给客户端,它在响应体里接着跑(见 `commit`) - let early = commit::early(&state, &req, &reading); - let abort = req.abort.clone(); - let dialect = req.dialect; - let run = answer( - state, - rt, - req, - Tail { - reading, - decision, - started, - conv, - passes: (live, pass), - }, - ending.take(), - ); - match early { - None => run.await, - Some(e) => commit::hold(run, dialect, e, abort).await, - } -} - -/// 发出开始事件之后,回答那一段要的:路由事实、决定、开始时定下的、这段对话这一轮,和两张 -/// 通行证(在服务中、这把密钥的并发)。 -struct Tail { - reading: crate::client_api::Reading, - decision: tw_engine::Decision, - started: Started, - conv: Option, - passes: (crate::live::Pass, crate::limits::Pass), + Ok(Tail { + reading, + decision, + started, + conv, + passes: (live, pass), + }) } /// 管线第 5 步:依次试候选上游(见 [`hop`]),把接下的那一家的回答交给客户端(见 [`relay`])。 -/// -/// **拥有它要的一切**(不借管线的东西):流式的回答等过一阵还没有内容时,响应头先交出去, -/// 它挪进响应体里接着跑(见 [`commit`])。结局也在它手上:返回错误之前自己报失败,被丢掉 -/// 由结局的 Drop 报(客户端走了是取消,叫停了是手动中止)。 -async fn answer( - state: AppState, - rt: Arc, - req: Inbound, - tail: Tail, - mut ending: Option, -) -> Result { - let r = answer_with(&state, &rt, &req, tail, &mut ending).await; - if let (Err(e), Some(end)) = (&r, ending.take()) { - end.failed(e.source.into(), e.detail.clone()); - } - r -} - async fn answer_with( state: &AppState, rt: &Arc, diff --git a/crates/tw-gateway/src/server/pipeline/admission.rs b/crates/tw-gateway/src/server/pipeline/admission.rs index e6cc42a1..b6daa367 100644 --- a/crates/tw-gateway/src/server/pipeline/admission.rs +++ b/crates/tw-gateway/src/server/pipeline/admission.rs @@ -11,8 +11,11 @@ //! //! **等待期限一个请求只有一个**:过了并发上限那一刻起算 `failover.slot_wait_secs`,这里等 //! 滚动窗口的空位、之后等上游的空位(见 `hop`)都算在里面 —— 两段各给一份的话,一个请求能 -//! 等两倍那么久,而等的时候客户端一个字节都收不到。并发上限那一段不算:它等前面的请求结束, -//! 不拒绝,等多久由客户端决定(见 [`crate::limits`])。 +//! 等两倍那么久。并发上限那一段不算:它等前面的请求结束,不拒绝,等多久由客户端决定(见 +//! [`crate::limits`])。 +//! +//! 等的时候客户端收得到东西:流式的回答压着不给响应头的时限从进这一步起算(见 `commit`), +//! 等过了先交 `200` 和保活。之后才被拒的,429 那句话写进流里。 //! //! 被上限拒绝的请求**照样开始、照样留一行**(和路由拒绝的一样,见 //! [`crate::server::routed_nowhere`]):流量里看得见它被哪一条上限拒了。数 token 的请求 diff --git a/crates/tw-gateway/src/server/pipeline/commit.rs b/crates/tw-gateway/src/server/pipeline/commit.rs index cc40c267..a17aa0fa 100644 --- a/crates/tw-gateway/src/server/pipeline/commit.rs +++ b/crates/tw-gateway/src/server/pipeline/commit.rs @@ -10,9 +10,15 @@ //! 第一段真内容:在那之前这个请求照样能因为无响应超时、开头报错、流断了换下一家,被放弃的 //! 那一家一个字节都没交出去,下一家的流在同一个 `200` 底下从头开始。 //! +//! **从进准入起算**(见 [`super::admission`]):排在这把密钥的并发闸门、用量窗口后面的请求 +//! 和等上游空位的一样,一个字节都没发出去也要等;等过了时限就先交响应头、发保活,不然客户端 +//! 等响应头的计时到了,它排了多久都白排。无响应超时那条计时不受影响:它从请求发给上游那一刻 +//! 起算(见 [`super::idle`])。 +//! //! - **保活不算内容**:它是网关自己发的,不经过上游那条计时(见 [`super::idle`])。 //! - **候选都失败了**:状态码已经交出去了,按客户端的格式在流里报那个错 —— 和回答到一半 -//! 断了是同一种错误帧。 +//! 断了是同一种错误帧。响应头交出去之后准入才拒绝的(用量窗口等不到空位)也一样:同一条 +//! 429 的句子写进流里,流量里留的那一行和整包请求被拒的一样。 //! - **Gemini 的客户端不发保活**:它官方的 Python SDK 把注释行当成一段 JSON 去解析,直接 //! 报错。响应头照样先交,流里等到回答为止。 //! - 只管客户端要 SSE 流的生成请求。整包的请求、Gemini 不带 `alt=sse` 的那种(一个 JSON diff --git a/crates/tw-gateway/src/state.rs b/crates/tw-gateway/src/state.rs index aa1654ca..2d258561 100644 --- a/crates/tw-gateway/src/state.rs +++ b/crates/tw-gateway/src/state.rs @@ -135,7 +135,7 @@ pub struct AppState { /// **不在 Runtime 里,因为它握着正在跑的请求的通行证。**跟着配置一起 /// 换的话,每改一次配置,排着的请求就会失去位置,而已经在跑的那些的 /// 通行证会变成孤儿。上限改了由它自己在原地加减(见 `limits`)。 - pub(crate) gate: Arc, + pub gate: Arc, /// 每家上游自己的并发上限(见 [`crate::slots`])。**不在 Runtime 里**,理由和 `gate` /// 一样:它握着在跑的请求占着的位置。配置换了由 [`Self::reload`] 在原地改上限 pub slots: Arc, diff --git a/crates/tw-gateway/tests/idle_timeout.rs b/crates/tw-gateway/tests/idle_timeout.rs index 29ebdac8..243e8426 100644 --- a/crates/tw-gateway/tests/idle_timeout.rs +++ b/crates/tw-gateway/tests/idle_timeout.rs @@ -187,14 +187,29 @@ async fn gateway_held( SocketAddr, tokio::sync::broadcast::Receiver, tw_gateway::AppState, +) { + let client = Client { + name: "c".into(), + key: "tw-k".into(), + ..Default::default() + }; + gateway_as(client, providers, slot_wait_secs, hold).await +} + +/// 起网关,密钥是 `client`,流式回答最多压 `hold` 不给响应头 +async fn gateway_as( + client: Client, + providers: Vec, + slot_wait_secs: u64, + hold: Duration, +) -> ( + SocketAddr, + tokio::sync::broadcast::Receiver, + tw_gateway::AppState, ) { let cfg = Config { version: 1, - clients: vec![Client { - name: "c".into(), - key: "tw-k".into(), - ..Default::default() - }], + clients: vec![client], providers, failover: Failover { idle_timeout_secs: 30, @@ -1313,3 +1328,140 @@ async fn a_whole_answer_is_never_answered_early() { assert_eq!(status, 504, "{text}"); assert!(headers_at >= WINDOW, "{headers_at:?}"); } + +// ───────────────────────────────────────────── 排在准入后面的也等得到响应头 + +/// 密钥 `c`:同时只跑一个请求(`max_concurrent`),带着这几条用量上限 +fn key(limits: &str) -> Client { + Client { + name: "c".into(), + key: "tw-k".into(), + max_concurrent: Some(1), + limits: serde_yaml_ng::from_str(limits).unwrap(), + ..Default::default() + } +} + +/// 密钥的并发闸门占多久才空出来:比压着的时限长、比无响应超时短 +const QUEUED: Duration = Duration::from_millis(900); + +#[tokio::test] +async fn a_request_queued_on_the_keys_gate_gets_the_headers_and_keepalives_before_a_slot_frees() { + // 这把密钥的并发闸门满着,900 毫秒才空出来;之后上游 600 毫秒才出内容。压满之后先交响应 + // 头、发保活,空位空出来之前一个字节都不发给上游;排队的那段不算无响应超时(1 秒),照常答上 + let late = upstream(Script { + steps: vec![(0, MESSAGE_START), (600, answer("patience"))], + ..Default::default() + }) + .await; + let (gw, mut rx, state) = gateway_as( + key("[]"), + vec![provider("late", &late, Protocol::Anthropic)], + 30, + HOLD, + ) + .await; + let held = state.gate.acquire("c", Some(1)).await; + let asking = tokio::spawn(async move { timed(gw, "/v1/messages", &messages(true)).await }); + tokio::time::sleep(QUEUED).await; + assert_eq!(late.hits.load(Ordering::SeqCst), 0, "空位还没空出来"); + drop(held); + let (status, headers_at, text) = asking.await.unwrap(); + assert_eq!(status, 200, "{text}"); + assert!( + headers_at >= HOLD && headers_at < QUEUED, + "响应头在压满之后、空位空出来之前交出:{headers_at:?}" + ); + let answer = text.find("event: message_start").expect("回答"); + assert!( + text[..answer].trim_start().starts_with(": keep-alive"), + "{text}" + ); + assert!(text[..answer].matches(KA).count() >= 3, "{text}"); + assert!(text[answer..].contains("patience"), "{text}"); + assert!(!text.contains("event: error"), "{text}"); + assert!( + !text[answer..].contains("keep-alive"), + "回答开始之后不再插保活:{text}" + ); + let (_, attempts) = estimate_and_attempts(&mut rx).await; + assert_eq!(outcomes(&attempts), [("late", Served)]); + assert_eq!(outcome(&mut rx).await, Ok(200)); +} + +#[tokio::test] +async fn a_refusal_after_the_headers_went_out_is_told_in_the_stream() { + // 一分钟一个请求、不等空位:第一个答完了,第二个排在并发闸门后面,压满之后先拿到响应头; + // 空位空出来之后用量窗口把它拒了 —— 429 交不出去了,同一句话写进流里,流量里照样是被拒 + // 的那一行(开始了、尝试链是空的、按用量上限记失败) + let good = upstream(prompt("hello")).await; + let (gw, mut rx, state) = gateway_as( + key("[{per: minute, requests: 1}]"), + vec![provider("good", &good, Protocol::Anthropic)], + 0, + HOLD, + ) + .await; + let (status, text) = post(gw, "/v1/messages", &messages(true)).await; + assert_eq!(status, 200, "{text}"); + let (_, attempts) = estimate_and_attempts(&mut rx).await; + assert_eq!(outcomes(&attempts), [("good", Served)]); + assert_eq!(outcome(&mut rx).await, Ok(200)); + + let held = state.gate.acquire("c", Some(1)).await; + let asking = tokio::spawn(async move { timed(gw, "/v1/messages", &messages(true)).await }); + tokio::time::sleep(QUEUED).await; + drop(held); + let (status, headers_at, text) = asking.await.unwrap(); + assert_eq!(status, 200, "{text}"); + assert!(headers_at >= HOLD && headers_at < QUEUED, "{headers_at:?}"); + assert!(text.trim_start().starts_with(": keep-alive"), "{text}"); + let error = text.find("event: error").expect("流里的错误"); + assert!(text[error..].contains("rate_limit_error"), "{text}"); + assert!(text[error..].contains("1 requests per minute"), "{text}"); + assert_eq!( + good.hits.load(Ordering::SeqCst), + 1, + "被拒的一个字节都不发给上游" + ); + let (_, attempts) = estimate_and_attempts(&mut rx).await; + assert!(attempts.is_empty(), "{attempts:?}"); + assert_eq!( + outcome(&mut rx).await, + Err(( + tw_api::FailureSource::RateLimited, + "gw.key_limit.requests_rolling".into() + )) + ); +} + +#[tokio::test] +async fn a_whole_answer_queued_on_the_keys_gate_still_waits_for_the_answer() { + // 整包的请求排在并发闸门后面:照旧压到回答为止,不先交响应头、不插保活 + let only = upstream(Script { + steps: vec![(0, whole("patience"))], + content_type: "application/json", + ..Default::default() + }) + .await; + let (gw, mut rx, state) = gateway_as( + key("[]"), + vec![provider("only", &only, Protocol::Anthropic)], + 30, + HOLD, + ) + .await; + let held = state.gate.acquire("c", Some(1)).await; + let asking = tokio::spawn(async move { timed(gw, "/v1/messages", &messages(false)).await }); + tokio::time::sleep(QUEUED).await; + drop(held); + let (status, headers_at, text) = asking.await.unwrap(); + assert_eq!(status, 200, "{text}"); + assert!(headers_at >= QUEUED, "{headers_at:?}"); + assert!(!text.contains("keep-alive"), "{text}"); + assert!(text.trim_start().starts_with('{'), "{text}"); + assert!(text.contains("patience"), "{text}"); + let (_, attempts) = estimate_and_attempts(&mut rx).await; + assert_eq!(outcomes(&attempts), [("only", Served)]); + assert_eq!(outcome(&mut rx).await, Ok(200)); +}