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
6 changes: 4 additions & 2 deletions crates/tw-api/src/ep.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ endpoints! {
Interfaces: GET "/interfaces", () => Vec<api::NicView>;
/// 实时事件流
Events: GET "/events", () => api::Event, events;
/// 此刻还没结束的请求,按开始事件的样子给
InFlight: GET "/in-flight", () => Vec<api::Event>;
/// 此刻还没结束的请求,每个到目前为止的事件,和 core 的时钟
InFlight: GET "/in-flight", () => api::InFlight;
/// 此刻的实时读数:在跑的请求、最近一分钟的生成速率
Live: GET "/live", () => api::LiveView;
Overview: GET "/overview", () => api::Overview;
Expand All @@ -42,6 +42,8 @@ endpoints! {
CostBuckets: GET "/summary/buckets", api::BucketQuery => Vec<api::CostBucket>;
CostBucketsBy: GET "/summary/buckets/by", api::BucketGroupQuery => Vec<api::CostBucketGroup>;
CostBy: GET "/summary/by", api::GroupQuery => Vec<api::CostGroup>;
/// 各条路由走了多少请求、各条规则命中了多少
RouteStats: GET "/summary/routes", api::Window => Vec<api::RouteHits>;
History: GET "/history", api::ListQuery => Vec<api::HistoryRow>;
Latency: GET "/latency", api::Window => Vec<api::LatencyView>;
LatencyByProvider: GET "/latency/provider", api::Window => Vec<api::LatencyView>;
Expand Down
223 changes: 214 additions & 9 deletions crates/tw-api/src/lib.rs

Large diffs are not rendered by default.

23 changes: 20 additions & 3 deletions crates/tw-control/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ pub fn router(state: ControlState) -> Router {
.at(ep::CostBuckets, cost_buckets)
.at(ep::CostBucketsBy, cost_buckets_by)
.at(ep::CostBy, cost_by)
.at(ep::RouteStats, route_stats)
.at(ep::History, history)
.at(ep::Latency, latency)
.at(ep::LatencyByProvider, latency_by_provider)
Expand Down Expand Up @@ -227,11 +228,13 @@ async fn events(
Sse::new(stream).keep_alive(KeepAlive::new().interval(std::time::Duration::from_secs(15)))
}

/// 此刻还在跑的请求:它们的开始事件,原样(见 `EventBus::in_flight`)。
/// 此刻还在跑的请求:每个到目前为止的事件,原样,和 core 的时钟(见
/// `EventBus::in_flight`)。
///
/// **半路才开始听 `/events` 的一方先问这个。**不问的话,订阅之前就开始了
/// 的请求它一个都不知道,直到它们结束 —— 数「进行中」就会少数。
async fn in_flight(State(s): State<ControlState>) -> Json<Vec<tw_api::Event>> {
/// 的请求它一个都不知道,直到它们结束 —— 数「进行中」就会少数,画路径只能
/// 画到一半。
async fn in_flight(State(s): State<ControlState>) -> Json<tw_api::InFlight> {
Json(s.bus().in_flight())
}

Expand Down Expand Up @@ -686,6 +689,20 @@ async fn cost_by(
Ok(Json(x))
}

/// 各条路由走了多少请求、各条规则命中了多少。不给参数就是「今天」。
///
/// **路由图按它给线加粗、标出从没命中过的规则**:按请求落库时记下的路由和规则
/// 数,不按现在的配置推(见 [`tw_api::RouteHits`])。
async fn route_stats(
State(s): State<ControlState>,
axum::extract::Query(q): axum::extract::Query<tw_api::Window>,
) -> Result<Json<Vec<tw_api::RouteHits>>, Fail> {
let (from, to) = range(q.from_ms, q.to_ms);
let store = need_store(&s)?;
let g = store.lock().await;
Ok(Json(g.db().route_hits(from, to).map_err(records)?))
}

/// 一段时间的汇总。不给参数就是「今天」。
async fn summary(
State(s): State<ControlState>,
Expand Down
83 changes: 68 additions & 15 deletions crates/tw-control/tests/in_flight.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
//! `/in-flight`:此刻还在跑的请求。
//!
//! 半路才来听事件流的一方拿它补上漏掉的开始事件。这里盯的是**界面拿到的
//! 那份 JSON**:和事件流里的开始事件同一个形状,有了结局的不在里面。
//! 半路才来听事件流的一方拿它补上漏掉的事件。这里盯的是**界面拿到的那份
//! JSON**:core 的时钟,加上每个在跑的请求到目前为止的事件 —— 和事件流里同一个
//! 形状;有了结局的不在里面。

use std::sync::Arc;

Expand Down Expand Up @@ -40,7 +41,11 @@ fn started(id: u64, model: &str) -> tw_api::Event {
id,
client: "我".into(),
client_hint: Some("claude-code".into()),
session_fp: None,
session: None,
route: "default".into(),
rule: "catch-all".into(),
group: None,
rewritten_by: vec![],
provider: "官方".into(),
billing: tw_api::Billing::PerToken,
model: model.into(),
Expand All @@ -50,7 +55,7 @@ fn started(id: u64, model: &str) -> tw_api::Event {
}
}

async fn get(router: axum::Router) -> Vec<serde_json::Value> {
async fn get(router: axum::Router) -> serde_json::Value {
let resp = router
.oneshot(Request::get("/in-flight").body(Body::empty()).unwrap())
.await
Expand All @@ -62,12 +67,35 @@ async fn get(router: axum::Router) -> Vec<serde_json::Value> {
serde_json::from_slice(&body).unwrap()
}

/// 开始了没结束的在里面,结束了的不在;每一条都是一个完整的开始事件。
/// 开始了没结束的在里面,结束了的不在;每一个都带着到目前为止的事件,第一条是
/// 完整的开始事件,之后是响应头、路由 —— 界面按顺序过一遍自己处理事件的代码,
/// 就和从头听起一样。
#[tokio::test]
async fn it_lists_the_start_of_every_request_that_has_not_ended() {
async fn it_gives_every_running_request_with_what_has_happened_to_it_so_far() {
let (_d, bus, router) = app();
bus.emit(started(1, "claude-sonnet-5"));
bus.emit(started(2, "gpt-5.5"));
bus.emit(tw_api::Event::RequestHeaders {
id: 2,
status: 200,
ttfb_ms: 700,
});
bus.emit(tw_api::Event::RequestRouted {
id: 2,
route: "default".into(),
rule: "catch-all".into(),
group: None,
rewritten_by: vec![],
denied_by: None,
attempts: vec![tw_api::AttemptView {
provider: "官方".into(),
outcome: tw_api::AttemptOutcome::Served,
status: Some(200),
error: None,
ms: 700,
}],
billing: tw_api::Billing::PerToken,
});
bus.emit(tw_api::Event::RequestFinished {
id: 1,
model: "claude-sonnet-5".into(),
Expand All @@ -78,20 +106,39 @@ async fn it_lists_the_start_of_every_request_that_has_not_ended() {
});

let got = get(router).await;
assert_eq!(got.len(), 1, "{got:?}");
// **和事件流里的开始事件同一个形状** —— 界面拿它原样补一条开始
assert_eq!(got[0]["kind"], "request_started");
assert_eq!(got[0]["id"], 2);
assert_eq!(got[0]["model"], "gpt-5.5");
assert_eq!(got[0]["client"], "我");
assert_eq!(got[0]["at_ms"], 1_002);
// **core 的时钟**:界面拿它减 `at_ms` 算跑了多久,不用自己的时钟
assert!(
got["now_ms"]
.as_u64()
.is_some_and(|t| t > 1_700_000_000_000),
"{got}"
);
let requests = got["requests"].as_array().unwrap();
assert_eq!(requests.len(), 1, "{got}");
assert_eq!(requests[0]["id"], 2);
let events = requests[0]["events"].as_array().unwrap();
// **和事件流里同一个形状** —— 界面拿它们原样补上
assert_eq!(
events
.iter()
.map(|e| e["kind"].as_str().unwrap())
.collect::<Vec<_>>(),
["request_started", "request_headers", "request_routed"]
);
assert_eq!(events[0]["model"], "gpt-5.5");
assert_eq!(events[0]["client"], "我");
assert_eq!(events[0]["route"], "default");
assert_eq!(events[0]["at_ms"], 1_002);
assert_eq!(events[1]["status"], 200);
assert_eq!(events[2]["attempts"][0]["provider"], "官方");
}

/// 什么都没在跑:一个空数组,不是 404,也不是 null。
/// 什么都没在跑:一个空的列表,不是 404,也不是 null。
#[tokio::test]
async fn nothing_running_is_an_empty_list() {
let (_d, _bus, router) = app();
assert!(get(router).await.is_empty());
let got = get(router).await;
assert_eq!(got["requests"], serde_json::json!([]), "{got}");
}

async fn live(router: axum::Router) -> serde_json::Value {
Expand Down Expand Up @@ -143,4 +190,10 @@ async fn live_gives_the_running_requests_and_the_generation_rate() {
assert_eq!(r["client_hint"], "claude-code");
assert_eq!(r["model"], "gpt-5.5");
assert_eq!(r["at_ms"], 1_002);
// 路由的第一阶段开始时就有;跑了多久是 core 数的
assert_eq!(r["route"], "default");
assert_eq!(r["rule"], "catch-all");
assert!(r["elapsed_ms"].is_u64(), "{v}");
// 路由还没报出结论:不知道是哪家接下的
assert!(r["upstream"].is_null(), "{v}");
}
9 changes: 8 additions & 1 deletion crates/tw-control/tests/live_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,11 @@ fn started(id: u64) -> tw_api::Event {
id,
client: "我".into(),
client_hint: Some("claude-code".into()),
session_fp: None,
session: None,
route: "default".into(),
rule: "catch-all".into(),
group: None,
rewritten_by: vec![],
peer: None,
key_masked: None,
provider: "官方".into(),
Expand Down Expand Up @@ -135,8 +139,11 @@ async fn a_request_still_running_can_be_opened_and_becomes_whole_when_it_ends()
});
rec.on_event(&tw_api::Event::RequestRouted {
id: 7,
route: "default".into(),
rule: "catch-all".into(),
group: Some("__all__".into()),
rewritten_by: vec![],
denied_by: None,
attempts: vec![tw_api::AttemptView {
provider: "官方".into(),
outcome: tw_api::AttemptOutcome::Served,
Expand Down
Loading
Loading