Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions crates/tw-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,16 @@ pub enum Event {
/// 结束了
RequestFinished {
id: u64,
/// 客户端要的模型名,和 `RequestStarted` 里的是同一个。
///
/// **三种结局都自己带着它。**听事件的一方不一定从请求开始时就在听
/// —— 界面的窗口开着才订阅,概览打开时才挂上实时曲线 —— 而用量是
/// 在结局里才到的。模型名只在开始事件里的话,一个开始时没人在听、
/// 结束时有人在听的请求,它的用量就不知道该记在哪个模型上。
///
/// WebSocket 那条路是空串:升级请求里没有模型名(和开始事件一样)。
#[serde(default)]
model: String,
status: u16,
bytes: u64,
duration_ms: u64,
Expand All @@ -101,6 +111,9 @@ pub enum Event {
/// 崩掉了。它只出现在这里 —— 那时往往已经没有一个 HTTP 响应能带上它。
RequestFailed {
id: u64,
/// 模型名。理由见 `RequestFinished::model`
#[serde(default)]
model: String,
source: String,
message: Msg,
/// 失败之前从上游收到了多少字节。**响应头都没到的没有**
Expand Down Expand Up @@ -133,6 +146,9 @@ pub enum Event {
/// 没有状态码、没有字节、也没有用量。
RequestCancelled {
id: u64,
/// 模型名。理由见 `RequestFinished::model`
#[serde(default)]
model: String,
/// 上游的响应头还没到就走了的,**没有状态码** —— 不是 0
#[serde(default, skip_serializing_if = "Option::is_none")]
status: Option<u16>,
Expand Down Expand Up @@ -2782,6 +2798,7 @@ mod tests {
// 前端按 `kind` 分派。少了它,TypeScript 那边只能靠字段有无来猜。
let e = Event::RequestFinished {
id: 1,
model: "claude-sonnet-5".into(),
status: 200,
bytes: 10,
duration_ms: 5,
Expand All @@ -2790,6 +2807,8 @@ mod tests {
let v: serde_json::Value = serde_json::to_value(&e).unwrap();
assert_eq!(v["kind"], "request_finished");
assert_eq!(v["id"], 1);
// 结局自己带着模型名:开始之后才来听的一方只有它
assert_eq!(v["model"], "claude-sonnet-5");
}

#[test]
Expand All @@ -2814,13 +2833,15 @@ mod tests {
},
Event::RequestFinished {
id: 7,
model: String::new(),
status: 200,
bytes: 1,
duration_ms: 1,
usage: None,
},
Event::RequestFailed {
id: 7,
model: String::new(),
source: "upstream".into(),
message: tw_types::msg!("t.x" => "x"),
bytes: None,
Expand All @@ -2829,6 +2850,7 @@ mod tests {
},
Event::RequestCancelled {
id: 7,
model: String::new(),
status: Some(200),
bytes: 1,
duration_ms: 1,
Expand All @@ -2845,6 +2867,7 @@ mod tests {
fn a_cancellation_carries_the_usage_seen_so_far() {
let e = Event::RequestCancelled {
id: 3,
model: String::new(),
status: Some(200),
bytes: 512,
duration_ms: 2400,
Expand All @@ -2866,6 +2889,7 @@ mod tests {
// 响应头之前就走了的:状态码和用量都不出现,不是 0
let none = Event::RequestCancelled {
id: 4,
model: String::new(),
status: None,
bytes: 0,
duration_ms: 10,
Expand Down
63 changes: 57 additions & 6 deletions crates/tw-gateway/src/ending.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ use tw_types::{Msg, msg};
pub struct Ending {
bus: tw_observe::EventBus,
id: u64,
/// 客户端要的模型名。**结局带着它走**(理由见 `tw_api::Event::RequestFinished`)
model: String,
started: Instant,
/// 请求开始的时刻。响应体按它归档,和请求体那一份对得上
at_ms: i64,
Expand All @@ -55,13 +57,15 @@ impl Ending {
pub fn new(
bus: tw_observe::EventBus,
id: u64,
model: String,
started: Instant,
at_ms: i64,
sink: Option<BodySender>,
) -> Self {
Self {
bus,
id,
model,
started,
at_ms,
sink,
Expand Down Expand Up @@ -102,6 +106,7 @@ impl Ending {
let usage = self.settle();
self.bus.emit(tw_api::Event::RequestFinished {
id: self.id,
model: std::mem::take(&mut self.model),
status,
bytes: self.bytes,
duration_ms: self.duration_ms(),
Expand All @@ -117,6 +122,7 @@ impl Ending {
let usage = self.settle();
self.bus.emit(tw_api::Event::RequestFailed {
id: self.id,
model: std::mem::take(&mut self.model),
source: source.to_string(),
message,
bytes: self.received(),
Expand Down Expand Up @@ -169,6 +175,7 @@ impl Drop for Ending {
if std::thread::panicking() {
self.bus.emit(tw_api::Event::RequestFailed {
id: self.id,
model: std::mem::take(&mut self.model),
source: "internal".to_string(),
message: msg!(
"gw.internal" => "The request was interrupted by an error inside the gateway."
Expand All @@ -181,6 +188,7 @@ impl Drop for Ending {
}
self.bus.emit(tw_api::Event::RequestCancelled {
id: self.id,
model: std::mem::take(&mut self.model),
status: self.status,
bytes: self.bytes,
duration_ms: self.duration_ms(),
Expand Down Expand Up @@ -208,10 +216,11 @@ mod tests {
/// Anthropic 流的第一帧:输入和缓存读是齐的,输出是个占位的 1。
const MESSAGE_START: &[u8] = b"event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"usage\":{\"input_tokens\":5000,\"cache_read_input_tokens\":4000,\"output_tokens\":1}}}\n\n";
const MESSAGE_DELTA: &[u8] = b"event: message_delta\ndata: {\"type\":\"message_delta\",\"usage\":{\"output_tokens\":777}}\n\n";
const MODEL: &str = "claude-sonnet-5";

/// 一个响应头已经到了的请求。
fn responding(bus: &tw_observe::EventBus) -> Ending {
let mut e = Ending::new(bus.clone(), 7, Instant::now(), 1_000, None);
let mut e = Ending::new(bus.clone(), 7, MODEL.into(), Instant::now(), 1_000, None);
e.responded(200);
e
}
Expand Down Expand Up @@ -279,13 +288,37 @@ mod tests {
}
}

/// **三种结局都带着模型名。**听事件的一方可能是请求开始之后才来的(界面
/// 的实时曲线就是这样),它手上只有结局 —— 这笔用量记在哪个模型上,只能
/// 看结局里写的。
#[test]
fn every_ending_carries_the_model() {
let bus = tw_observe::EventBus::new();
let mut rx = bus.subscribe();
responding(&bus).finished(200);
responding(&bus).failed("upstream", msg!("t.x" => "x"));
drop(responding(&bus));

let got = drain(&mut rx);
assert_eq!(got.len(), 3, "{got:?}");
for e in &got {
let model = match e {
Event::RequestFinished { model, .. }
| Event::RequestFailed { model, .. }
| Event::RequestCancelled { model, .. } => model,
other => panic!("该是一个结局,实际 {other:?}"),
};
assert_eq!(model, MODEL, "{e:?}");
}
}

/// 响应头之前就失败了(每家上游都拒绝、策略不让)。**没有字节、没有
/// 用量,但有耗时** —— 「试了二十秒才放弃」本身就是排查的线索。
#[test]
fn a_failure_before_the_response_headers_has_a_duration_but_no_bytes_or_usage() {
let bus = tw_observe::EventBus::new();
let mut rx = bus.subscribe();
Ending::new(bus.clone(), 7, Instant::now(), 1_000, None)
Ending::new(bus.clone(), 7, MODEL.into(), Instant::now(), 1_000, None)
.failed("rate_limited", msg!("t.limited" => "`up` rate-limited us"));

let got = drain(&mut rx);
Expand All @@ -310,7 +343,14 @@ mod tests {
let bus = tw_observe::EventBus::new();
let mut rx = bus.subscribe();
let (tx, mut bodies) = tokio::sync::mpsc::channel(4);
let mut e = Ending::new(bus.clone(), 7, Instant::now(), 1_000, Some(tx));
let mut e = Ending::new(
bus.clone(),
7,
MODEL.into(),
Instant::now(),
1_000,
Some(tx),
);
e.responded(200);
e.feed(MESSAGE_START);
drop(e);
Expand Down Expand Up @@ -344,7 +384,14 @@ mod tests {
fn dropped_before_the_response_headers_it_reports_neither_a_status_nor_usage() {
let bus = tw_observe::EventBus::new();
let mut rx = bus.subscribe();
drop(Ending::new(bus.clone(), 7, Instant::now(), 1_000, None));
drop(Ending::new(
bus.clone(),
7,
MODEL.into(),
Instant::now(),
1_000,
None,
));

let got = drain(&mut rx);
assert!(
Expand All @@ -367,7 +414,8 @@ mod tests {
fn counting_bytes_does_not_turn_frames_into_usage() {
let bus = tw_observe::EventBus::new();
let mut rx = bus.subscribe();
let mut e = Ending::new(bus.clone(), 7, Instant::now(), 1_000, None);
// WebSocket 那条路不知道模型名
let mut e = Ending::new(bus.clone(), 7, String::new(), Instant::now(), 1_000, None);
e.responded(101);
e.count(MESSAGE_START.len());
e.finished(101);
Expand Down Expand Up @@ -408,7 +456,10 @@ mod tests {

let got = drain(&mut rx);
assert!(
matches!(got.as_slice(), [Event::RequestFailed { source, .. }] if source == "internal"),
matches!(
got.as_slice(),
[Event::RequestFailed { source, model, .. }] if source == "internal" && model == MODEL
),
"{got:?}"
);
}
Expand Down
10 changes: 9 additions & 1 deletion crates/tw-gateway/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1071,7 +1071,14 @@ async fn ws_upgrade(
// 这条连接怎么断的,就是这个请求的结局。**跟着连接走**:升级没完成
// 就被丢掉的 —— 客户端没等到 101 就走了 —— 由 Drop 报成取消。WS 帧
// 不留档,所以没有 body 的去处
let ending = crate::ending::Ending::new(state.bus.clone(), id, started, now_ms() as i64, None);
let ending = crate::ending::Ending::new(
state.bus.clone(),
id,
String::new(),
started,
now_ms() as i64,
None,
);
let provider = provider.clone();
let guard = decision.guard.clone();
let rules = rt.rules.clone();
Expand Down Expand Up @@ -1635,6 +1642,7 @@ async fn pipeline(
*ending = Some(crate::ending::Ending::new(
state.bus.clone(),
id,
facts.model.clone(),
started,
at_ms,
sink.clone(),
Expand Down
28 changes: 27 additions & 1 deletion crates/tw-gateway/tests/endings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ use tw_config::{Client, Config, Provider, Security, SecurityMode};

/// Anthropic 流的第一帧。**输入和缓存读在这里就是齐的**,输出是个占位的
/// 1 —— 累计输出要等流的末尾才报。
/// 客户端要的模型名。**每一种结局都要带着它**(见 `model_of`)
const MODEL: &str = "claude-sonnet-4-5";

const MESSAGE_START: &[u8] = b"event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"usage\":{\"input_tokens\":5000,\"cache_read_input_tokens\":4000,\"output_tokens\":1}}}\n\n";

async fn listen(app: Router) -> SocketAddr {
Expand Down Expand Up @@ -212,7 +215,9 @@ fn post(gw: SocketAddr) -> reqwest::RequestBuilder {
reqwest::Client::new()
.post(format!("http://{gw}/v1/messages"))
.header("x-api-key", "tw-k")
.body(r#"{"model":"claude-sonnet-4-5","stream":true,"messages":[]}"#)
.body(format!(
r#"{{"model":"{MODEL}","stream":true,"messages":[]}}"#
))
}

async fn ws_connect(
Expand Down Expand Up @@ -250,6 +255,20 @@ async fn endings(rx: &mut Receiver<Event>) -> Vec<Event> {
got
}

/// 结局上写的模型名。
///
/// **每一种结局都要带着它**:听事件的一方可能是请求开始之后才来的(界面的
/// 实时曲线就是这样),它手上只有结局 —— 这笔用量记在哪个模型上,只能看
/// 结局里写的。
fn model_of(e: &Event) -> &str {
match e {
Event::RequestFinished { model, .. }
| Event::RequestFailed { model, .. }
| Event::RequestCancelled { model, .. } => model,
other => panic!("该是一个结局,实际 {other:?}"),
}
}

// ---------------------------------------------------------------- 流式响应开始之后

/// 跑完的流**只报结束**。Drop 那一侧不知道「已经报过了」的话,每一个正常
Expand All @@ -266,6 +285,7 @@ async fn a_stream_that_runs_to_its_end_is_finished_and_nothing_else() {
matches!(&got[0], Event::RequestFinished { usage: Some(u), .. } if u.output == 777),
"该是带着累计输出的结束:{got:?}"
);
assert_eq!(model_of(&got[0]), MODEL);
}

/// 客户端中途走了(Claude Code 里按一下 Esc)。
Expand Down Expand Up @@ -302,6 +322,7 @@ async fn a_client_that_walks_away_mid_stream_is_reported_once_as_cancelled() {
}
other => panic!("该是一次取消,实际 {other:?}"),
}
assert_eq!(model_of(&got[0]), MODEL);
}

/// 上游中途断了:**报失败,不报取消**。网关随后往客户端补的那个错误帧,
Expand Down Expand Up @@ -335,6 +356,7 @@ async fn a_stream_the_upstream_breaks_is_failed_and_not_also_cancelled() {
}
other => panic!("该是一次上游失败,实际 {other:?}"),
}
assert_eq!(model_of(&got[0]), MODEL);
}

/// 防火墙切断了一个高危工具调用。**这是策略拦下来的,不是上游坏了**,而
Expand Down Expand Up @@ -400,6 +422,7 @@ async fn a_client_that_leaves_before_the_response_headers_is_reported_once_as_ca
),
"该是一次没有状态码、没有用量的取消:{got:?}"
);
assert_eq!(model_of(&got[0]), MODEL);
}

/// 选中上游之后才生效的规则拒绝了这次请求(阶段二)。
Expand Down Expand Up @@ -442,6 +465,7 @@ async fn a_phase_two_deny_after_the_request_started_is_reported_as_denied() {
),
"该是一次带着理由的拒绝:{got:?}"
);
assert_eq!(model_of(&got[0]), MODEL);
}

/// 每一家上游都没接住。**只报一次失败,`source` 是它真正的原因** —— 被限流
Expand Down Expand Up @@ -474,6 +498,7 @@ async fn a_request_every_upstream_refused_is_failed_once_for_the_reason_it_was_r
}
other => panic!("该是一次失败,实际 {other:?}"),
}
assert_eq!(model_of(&got[0]), MODEL);
}

// ---------------------------------------------------------------- WebSocket
Expand Down Expand Up @@ -511,6 +536,7 @@ async fn a_websocket_session_the_client_closes_is_finished() {
),
"该是一次带着回帧字节数、没有用量的结束:{got:?}"
);
assert_eq!(model_of(&got[0]), "", "升级请求里没有模型名,不该编一个");
}

#[tokio::test]
Expand Down
Loading
Loading