From 51cb2df45dd3e62f7254841beca226456399da16 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Fri, 25 Sep 2026 15:10:08 +0800 Subject: [PATCH] feat(api): route stats say where their history starts; the ChatGPT login result names the account GET /summary/routes now returns RouteStats { covered_since_ms, routes } instead of a bare RouteHits array. The counts only see requests that are still in the store: on a fresh install, after the store is rebuilt on an upgrade, or when rows are kept for fewer days than the window, the oldest stored request is later than the window's start, and "no hits" before it means "not known", not "never matched". covered_since_ms is the later of the window's start and the oldest stored request (any request, routed or answered locally); it is null when no moment of the window is covered (no stored request at all, or the oldest one is at or after the window's end). When set it lies inside the window: from <= covered_since_ms < to. The field is always present, so a client has to handle null. ChatgptLoginStatus drops `plan` and carries `account` (AccountView: email and plan), the same block as OAuthView.account and read from the same token: the access token the sign-in just saved to the config. The login result and the upstream row cannot name different accounts, and the login completion page no longer needs an Overview read. The id_token is still read for the account id only. LoginFinished is unchanged. CONTROL_API_VERSION is 22. No message codes changed; the request store SCHEMA stays 20. Tests: store-level coverage for an empty store, history shorter than the window (including after pruning), history longer than the window, and a window before the history began; an end-to-end /summary/routes with a fresh store and with no history yet; the login result's account for browser, device and repeated sign-ins, equal to the upstream view's, and taken from the access token when the id_token carries only the account id. The TypeScript export and the smoke script follow the new shapes. Co-Authored-By: Claude Opus 5.5 --- crates/tw-api/src/ep.rs | 4 +- crates/tw-api/src/lib.rs | 44 +++++++++-- crates/tw-api/src/ts.rs | 14 +++- crates/tw-control/src/chatgpt.rs | 26 ++++--- crates/tw-control/src/lib.rs | 7 +- crates/tw-control/tests/chatgpt.rs | 90 +++++++++++++++++----- crates/tw-control/tests/route_stats.rs | 66 +++++++++++++++- crates/tw-store/src/db.rs | 100 ++++++++++++++++++++++--- scripts/smoke.sh | 7 +- 9 files changed, 305 insertions(+), 53 deletions(-) diff --git a/crates/tw-api/src/ep.rs b/crates/tw-api/src/ep.rs index bee9bdc4..50295e17 100644 --- a/crates/tw-api/src/ep.rs +++ b/crates/tw-api/src/ep.rs @@ -42,8 +42,8 @@ endpoints! { CostBuckets: GET "/summary/buckets", api::BucketQuery => Vec; CostBucketsBy: GET "/summary/buckets/by", api::BucketGroupQuery => Vec; CostBy: GET "/summary/by", api::GroupQuery => Vec; - /// 各条路由走了多少请求、各条规则命中了多少 - RouteStats: GET "/summary/routes", api::Window => Vec; + /// 各条路由走了多少请求、各条规则命中了多少,记录从哪一刻起是全的 + RouteStats: GET "/summary/routes", api::Window => api::RouteStats; History: GET "/history", api::ListQuery => Vec; Latency: GET "/latency", api::Window => Vec; LatencyByProvider: GET "/latency/provider", api::Window => Vec; diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index fa6062a3..1c337f42 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -582,7 +582,14 @@ pub const MSG_CODES: &str = include_str!("../msg-codes.txt"); /// [`InFlight`]:core 的时钟加上每个在跑的请求到目前为止的事件。`RunningView` /// 多了 `elapsed_ms`、`session`、`route`、`rule`、`group`、`upstream`。新增 /// `GET /summary/routes`。照 20 写的界面会把 `/in-flight` 当成数组去读。 -pub const CONTROL_API_VERSION: u32 = 21; +/// +/// **22 起命中数说清楚记录从哪一刻起是全的**:`GET /summary/routes` 不再是 +/// [`RouteHits`] 的数组,是 [`RouteStats`] —— `routes` 加上 `covered_since_ms`。库刚建好 +/// (新装、升级时重建)、记录留的天数比窗口短时,它比问的起点晚;库里没有记录时是空。 +/// ChatGPT 登录的结果([`ChatgptLoginStatus`])不再带 `plan`,换成 `account`:和 +/// [`OAuthView::account`] 同一块(邮箱、套餐),从同一个 access token 里读。照 21 写的 +/// 界面会把 `/summary/routes` 当成数组去读,在登录结果里找不到套餐。 +pub const CONTROL_API_VERSION: u32 = 22; #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] @@ -2884,12 +2891,35 @@ pub struct CostGroup { pub no_usage_requests: i64, } -/// 一条路由在一段时间里走了多少请求,各条规则命中了多少(`GET /summary/routes`)。 +/// 一段时间里各条路由走了多少请求、各条规则命中了多少,以及这些数从哪一刻起是全的 +/// (`GET /summary/routes`)。 +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct RouteStats { + /// 这段时间里记录从哪一刻起是全的,Unix 毫秒:问的起点和库里最老那条请求开始的 + /// 时刻,取晚的那个。 + /// + /// **数只数得到库里还在的请求。**刚装好、升级时库重建了、记录留的天数比窗口短, + /// 库里最老的那条都比窗口的起点晚:更早的那一截不是「没有命中」,是「不知道」。 + /// 「这段时间一次都没命中」只对这一刻之后成立。 + /// + /// - 等于问的起点:整段都有记录 + /// - 比起点晚:记录从这一刻才开始,[`RouteStats::routes`] 数的是从这一刻到窗口结束 + /// - 空:这段时间里没有一刻有记录 —— 库里一条请求都没有,或者最老的那条也在窗口 + /// 结束之后。这时的「没有命中」什么都说明不了 + /// + /// 有值时总在窗口里面:不早于问的起点,早于窗口的终点。 + pub covered_since_ms: Option, + /// 各条路由,走得多的在前 + pub routes: Vec, +} + +/// 一条路由在一段时间里走了多少请求,各条规则命中了多少。 /// /// **按请求落库时记下的路由算**,不按现在的配置推:一个请求走的是它那一刻的 /// 路由和规则,之后改名、删掉、换了绑定都不改它。所以这里可能有配置里已经没有的 /// 路由和规则,而配置里有、这段时间一次都没命中的不在这里 —— 「从来没命中过」 -/// 就是在配置里有、在这里找不到。 +/// 就是在配置里有、在这里找不到(只对 [`RouteStats::covered_since_ms`] 之后成立)。 /// /// 数的是经过路由的请求:本地应答的不算(它们没到规则那一层);规则还没做出决定 /// 就失败了的也不算 —— 鉴权没过、模型不让用、没有一条规则命中。 @@ -3161,9 +3191,13 @@ pub struct ChatgptLoginStatus { /// 写进配置的上游名。`done` 时有 #[serde(default, skip_serializing_if = "Option::is_none")] pub provider: Option, - /// 套餐。`done` 时有,令牌里没写就没有 + /// 登的是哪个账号:邮箱和套餐。`done` 时有,令牌里一项都读不出来时没有。 + /// + /// **和上游视图的 [`OAuthView::account`] 是同一块、同一个来源**:从这次登录存进 + /// 配置的 access token 里读。登录完成时说的账号和上游那一行说的是同一个,不用 + /// 再去读一次概览 #[serde(default, skip_serializing_if = "Option::is_none")] - pub plan: Option, + pub account: Option, /// `failed` 时的原因 #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option, diff --git a/crates/tw-api/src/ts.rs b/crates/tw-api/src/ts.rs index 8202a15c..86990752 100644 --- a/crates/tw-api/src/ts.rs +++ b/crates/tw-api/src/ts.rs @@ -206,8 +206,20 @@ mod tests { assert!(known.contains("\"prolite\""), "{known}"); let oauth = decl_of(&ts, "OAuthView"); assert!(oauth.contains("account?: AccountView"), "{oauth}"); + // 登录结果说的账号和上游视图是同一块 let login = decl_of(&ts, "ChatgptLoginStatus"); - assert!(login.contains("plan?: ChatgptPlan"), "{login}"); + assert!(login.contains("account?: AccountView"), "{login}"); + assert!(!login.contains("plan"), "{login}"); + } + + /// 命中数带着记录从哪一刻起是全的:必有的字段,没有记录时是 null,不是省掉。 + #[test] + fn route_stats_say_where_their_history_starts() { + let ts = typescript(); + let stats = decl_of(&ts, "RouteStats"); + assert!(stats.contains("covered_since_ms: number | null"), "{stats}"); + assert!(stats.contains("routes: Array"), "{stats}"); + assert!(ts.contains(" RouteStats: { req: Window; res: RouteStats };")); } #[test] diff --git a/crates/tw-control/src/chatgpt.rs b/crates/tw-control/src/chatgpt.rs index 8b19b291..d0027abb 100644 --- a/crates/tw-control/src/chatgpt.rs +++ b/crates/tw-control/src/chatgpt.rs @@ -385,7 +385,7 @@ fn pending(id: &str) -> tw_api::ChatgptLoginStatus { id: id.to_string(), status: LoginStatus::Pending, provider: None, - plan: None, + account: None, error: None, } } @@ -471,7 +471,7 @@ async fn await_device( id: id.clone(), status: LoginStatus::Expired, provider: None, - plan: None, + account: None, error: Some(not_in_time()), }); announce(&s, &id, LoginStatus::Expired, None, None); @@ -486,13 +486,13 @@ fn not_in_time() -> Msg { } /// 记下登录的结果,并告诉界面一声 -fn settle(s: &ControlState, id: &str, done: Result<(String, Option), Msg>) { +fn settle(s: &ControlState, id: &str, done: Result<(String, Option), Msg>) { let status = match done { - Ok((provider, plan)) => tw_api::ChatgptLoginStatus { + Ok((provider, account)) => tw_api::ChatgptLoginStatus { id: id.to_string(), status: LoginStatus::Done, provider: Some(provider), - plan, + account, error: None, }, Err(why) => { @@ -501,7 +501,7 @@ fn settle(s: &ControlState, id: &str, done: Result<(String, Option, listener: tokio::net::TcpListener) { id: flow.id.clone(), status: LoginStatus::Expired, provider: None, - plan: None, + account: None, error: Some(not_in_time()), }); announce(&flow.s, &flow.id, LoginStatus::Expired, None, None); @@ -673,7 +673,10 @@ async fn callback( Html(html) } -/// 用授权码换 token,写进配置。返回上游名和套餐。 +/// 用授权码换 token,写进配置。返回上游名和登的是哪个账号。 +/// +/// **账号从存进配置的 access token 里读**,和上游视图([`account_view`])同一个来源: +/// 登录完成时说的和上游那一行说的不会是两个账号。id_token 只用来取账户 ID async fn exchange_and_save( s: &ControlState, name: &str, @@ -681,12 +684,12 @@ async fn exchange_and_save( code: &str, verifier: &str, redirect_uri: &str, -) -> Result<(String, Option), Msg> { +) -> Result<(String, Option), Msg> { let endpoints = &s.chatgpt.endpoints; let http = client_for(s, name, proxy)?; let tokens = chatgpt::exchange_code(&http, &endpoints.token, code, verifier, redirect_uri).await?; - let account = chatgpt::account(&tokens.id_token); + let account_id = chatgpt::account(&tokens.id_token).account_id; let oauth = tw_config::OAuth { access: Some(tokens.access.clone()), expires_at: tokens.expires_in.map(|secs| { @@ -702,7 +705,6 @@ async fn exchange_and_save( let name = name.to_string(); let proxy = proxy.to_string(); let backend = endpoints.backend.clone(); - let account_id = account.account_id.clone(); s.cfg .transform(None, Origin::Ui, |text, cfg| { let existing = cfg.providers.iter().find(|p| p.name == name); @@ -756,7 +758,7 @@ async fn exchange_and_save( tokio::spawn(async move { tw_gateway::models::refresh_one(&gateway, &provider).await; }); - Ok((name, account.plan)) + Ok((name, chatgpt::account(&tokens.access).view())) } /// 这个上游登的是哪个账号:从它在用的 access token 里读(见 [`tw_api::AccountView`])。 diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index 3b0d3a6a..846986d1 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -692,15 +692,16 @@ async fn cost_by( /// 各条路由走了多少请求、各条规则命中了多少。不给参数就是「今天」。 /// /// **路由图按它给线加粗、标出从没命中过的规则**:按请求落库时记下的路由和规则 -/// 数,不按现在的配置推(见 [`tw_api::RouteHits`])。 +/// 数,不按现在的配置推(见 [`tw_api::RouteHits`])。「从没命中过」只对记录说得上 +/// 话的那一段成立,所以一起给出记录从哪一刻起是全的(见 [`tw_api::RouteStats`])。 async fn route_stats( State(s): State, axum::extract::Query(q): axum::extract::Query, -) -> Result>, Fail> { +) -> Result, 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)?)) + Ok(Json(g.db().route_stats(from, to).map_err(records)?)) } /// 一段时间的汇总。不给参数就是「今天」。 diff --git a/crates/tw-control/tests/chatgpt.rs b/crates/tw-control/tests/chatgpt.rs index a2e4e604..2706789c 100644 --- a/crates/tw-control/tests/chatgpt.rs +++ b/crates/tw-control/tests/chatgpt.rs @@ -43,6 +43,8 @@ struct OpenAi { device_approve_after: Mutex, /// 设备码的两个接口收到的请求体 device_asks: Mutex>, + /// 登录换 token 时发的 id_token。不设就是 [`id_token`] + id_token: Mutex>, } fn jwt(claims: Value) -> String { @@ -69,6 +71,14 @@ fn access_token(plan: &str) -> String { })) } +/// 登录换来的 id_token:邮箱在顶层,账户和套餐在 auth 那一块 +fn id_token() -> String { + jwt(json!({ + "email": "someone@example.com", + "https://api.openai.com/auth": {"chatgpt_account_id": "acct-1", "chatgpt_plan_type": "plus"} + })) +} + /// 登录换来的 access token fn at_login() -> String { access_token("plus") @@ -129,11 +139,9 @@ async fn token( })) .into_response(); } + let id = o.id_token.lock().unwrap().clone().unwrap_or_else(id_token); axum::Json(json!({ - "id_token": jwt(json!({ - "email": "someone@example.com", - "https://api.openai.com/auth": {"chatgpt_account_id": "acct-1", "chatgpt_plan_type": "plus"} - })), + "id_token": id, "access_token": at_login(), "refresh_token": "rt-login", "expires_in": 864000 @@ -506,6 +514,7 @@ async fn a_browser_login_writes_the_account_into_the_config_and_hands_back_to_th (st, v["status"].as_str()), (StatusCode::OK, Some("pending")) ); + assert!(v.get("account").is_none(), "还没登上,说不上是谁:{v}"); let (code, page) = browser(&format!("{}?code=code-1&state={}", s.redirect_uri, s.state)).await; assert_eq!(code, 200); @@ -526,13 +535,18 @@ async fn a_browser_login_writes_the_account_into_the_config_and_hands_back_to_th s.challenge ); - let (st, v) = b + let (st, done) = b .call("GET", &format!("/chatgpt/login/{}", s.id), Value::Null) .await; assert_eq!(st, StatusCode::OK); - assert_eq!(v["status"], "done"); - assert_eq!(v["provider"], "chatgpt"); - assert_eq!(v["plan"], "plus"); + assert_eq!(done["status"], "done"); + assert_eq!(done["provider"], "chatgpt"); + // 登的是哪个账号:邮箱和套餐,没有单独的套餐一项 + assert_eq!( + done["account"], + json!({"email": "someone@example.com", "plan": "plus"}) + ); + assert!(done.get("plan").is_none(), "{done}"); assert_eq!( b.login_finished().await, (s.id.clone(), "done".into(), Some("chatgpt".into())) @@ -562,11 +576,8 @@ async fn a_browser_login_writes_the_account_into_the_config_and_hands_back_to_th ); assert!(b.provider("relay").is_some(), "别的上游不动"); - // 上游页马上就知道登的是谁:从刚写进配置的 access token 里读 - assert_eq!( - b.oauth_view("chatgpt").await["account"], - json!({"email": "someone@example.com", "plan": "plus"}) - ); + // 上游页马上就知道登的是谁:从刚写进配置的 access token 里读,和登录结果是同一块 + assert_eq!(b.oauth_view("chatgpt").await["account"], done["account"]); // 模型清单马上就去问,不等下一轮 eventually("登录后获取模型清单", || { @@ -647,6 +658,7 @@ async fn a_callback_with_the_wrong_state_does_not_end_the_login() { .call("GET", &format!("/chatgpt/login/{}", s.id), Value::Null) .await; assert_eq!(v["status"], "failed"); + assert!(v.get("account").is_none(), "{v}"); assert_eq!( v["error"]["code"], "control.chatgpt_login.page_error", "{v}" @@ -706,6 +718,14 @@ async fn logging_in_again_replaces_the_credentials_and_keeps_the_settings() { let s = start_login(&b, json!({"name": "chatgpt"})).await; let (_, page) = browser(&format!("{}?code=code-1&state={}", s.redirect_uri, s.state)).await; assert!(page.contains("Signed in to ChatGPT"), "{page}"); + let (_, done) = b + .call("GET", &format!("/chatgpt/login/{}", s.id), Value::Null) + .await; + assert_eq!( + done["account"], + json!({"email": "someone@example.com", "plan": "plus"}), + "登录结果说的是新登上的账号,不是原来那个" + ); let p = b.provider("chatgpt").unwrap(); let o = p.oauth.as_ref().unwrap(); assert_eq!( @@ -723,10 +743,42 @@ async fn logging_in_again_replaces_the_credentials_and_keeps_the_settings() { p.headers.get("chatgpt-account-id").unwrap().value.raw(), "acct-1" ); - // 换了账号,上游页上跟着换 + // 换了账号,上游页上跟着换,和登录结果说的是同一个 + assert_eq!(b.oauth_view("chatgpt").await["account"], done["account"]); +} + +/// 登录结果里的账号从存进配置的 access token 里读,和上游视图同一个来源:id_token 说得 +/// 少(只有账户 ID)时,登录结果照样是全的,和上游那一行一样。 +#[tokio::test] +async fn the_login_result_names_the_account_from_the_token_the_upstream_view_reads() { + let mut b = bed(|_| String::new()).await; + *b.openai.id_token.lock().unwrap() = Some(jwt(json!({ + "https://api.openai.com/auth": {"chatgpt_account_id": "acct-1"} + }))); + let s = start_login(&b, json!({})).await; + let (_, page) = browser(&format!("{}?code=code-1&state={}", s.redirect_uri, s.state)).await; + assert!(page.contains("Signed in to ChatGPT"), "{page}"); + assert_eq!(b.login_finished().await.1, "done"); + + let (_, done) = b + .call("GET", &format!("/chatgpt/login/{}", s.id), Value::Null) + .await; assert_eq!( - b.oauth_view("chatgpt").await["account"], - json!({"email": "someone@example.com", "plan": "plus"}) + done["account"], + json!({"email": "someone@example.com", "plan": "plus"}), + "{done}" + ); + assert_eq!(b.oauth_view("chatgpt").await["account"], done["account"]); + // 账户 ID 仍然取自 id_token + assert_eq!( + b.provider("chatgpt") + .unwrap() + .headers + .get("ChatGPT-Account-Id") + .unwrap() + .value + .raw(), + "acct-1" ); } @@ -863,7 +915,11 @@ async fn a_device_login_waits_for_the_other_device_and_saves_the_account() { let (_, v) = b .call("GET", &format!("/chatgpt/login/{id}"), Value::Null) .await; - assert_eq!(v["plan"], "plus"); + assert_eq!( + v["account"], + json!({"email": "someone@example.com", "plan": "plus"}) + ); + assert_eq!(b.oauth_view("chatgpt").await["account"], v["account"]); eventually("登录后获取模型清单", || { b.openai .backend diff --git a/crates/tw-control/tests/route_stats.rs b/crates/tw-control/tests/route_stats.rs index d5c0a42d..1f84e97f 100644 --- a/crates/tw-control/tests/route_stats.rs +++ b/crates/tw-control/tests/route_stats.rs @@ -114,6 +114,7 @@ async fn every_route_and_rule_counts_what_went_through_it_including_denials() { .await .unwrap(); + let before = now_ms(); assert_eq!(ask(addr, "claude-sonnet-4-5").await, 200); assert_eq!(ask(addr, "claude-haiku-4-5").await, 200); assert_eq!(ask(addr, "claude-opus-4-1").await, 403, "该被规则拒绝"); @@ -138,7 +139,14 @@ async fn every_route_and_rule_counts_what_went_through_it_including_denials() { let body = axum::body::to_bytes(resp.into_body(), usize::MAX) .await .unwrap(); - let got: Vec = serde_json::from_slice(&body).unwrap(); + let stats: tw_api::RouteStats = serde_json::from_slice(&body).unwrap(); + // 库是这个测试里新建的:记录从第一个请求开始,不是问的起点(0) + let covered = stats.covered_since_ms.expect("库里有请求,记录有起点"); + assert!( + (before..=now_ms()).contains(&covered), + "记录应当从第一个请求开始:{covered},测试开始于 {before}" + ); + let got = &stats.routes; assert_eq!(got.len(), 1, "{got:?}"); let work = &got[0]; assert_eq!(work.route, "工作", "按密钥指定的路由记,不是默认路由"); @@ -163,6 +171,62 @@ async fn every_route_and_rule_counts_what_went_through_it_including_denials() { assert_eq!(rule("从没命中过"), None, "没命中过的规则不在里面"); } +/// 还没有一条记录的库:线上的起点是 null,界面不会把空表读成「一周都没命中」。 +#[tokio::test] +async fn a_store_with_no_history_yet_says_nothing_is_covered() { + let d = tempfile::tempdir().unwrap(); + let text = yaml(SocketAddr::from(([127, 0, 0, 1], 9))); + let p = d.path().join("config.yaml"); + std::fs::write(&p, &text).unwrap(); + let cfg: tw_config::Config = serde_yaml_ng::from_str(&text).unwrap(); + let gw = tw_gateway::AppState::new(cfg).unwrap(); + let (_bodies, rx) = tokio::sync::mpsc::channel(8); + let store = tw_store::task::spawn( + tw_store::Recorder::new( + tw_store::Db::open(&d.path().join("data.db")).unwrap(), + tw_store::Blobs::new(d.path().join("blobs")), + tw_pricing::shared(tw_pricing::PriceBook::builtin().unwrap()), + ), + gw.bus.subscribe(), + rx, + ); + let state = ControlState { + shutdown: Default::default(), + remote: Default::default(), + cfg: Arc::new(ConfigManager::new(p, gw.clone(), gw.bus.clone())), + gateway: gw, + store: Some(store), + started: std::time::Instant::now(), + price_updater: Default::default(), + chatgpt: Default::default(), + zai: Default::default(), + }; + let resp = tw_control::router(state) + .oneshot( + Request::get("/summary/routes?from_ms=0") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::OK); + let body = axum::body::to_bytes(resp.into_body(), usize::MAX) + .await + .unwrap(); + let v: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert_eq!( + v, + serde_json::json!({"covered_since_ms": null, "routes": []}) + ); +} + +fn now_ms() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis() as i64 +} + /// 没有存储层(记录没起来)时说清楚,不是一张空表 —— 空表读起来是「没有请求」。 #[tokio::test] async fn without_a_store_it_says_so() { diff --git a/crates/tw-store/src/db.rs b/crates/tw-store/src/db.rs index a5a30f97..55861f3d 100644 --- a/crates/tw-store/src/db.rs +++ b/crates/tw-store/src/db.rs @@ -1021,16 +1021,28 @@ impl Db { rows.collect::, _>>().map_err(Into::into) } + /// 各条路由走了多少请求、各条规则命中了多少,以及记录从哪一刻起是全的(见 + /// [`tw_api::RouteStats`])。 + pub fn route_stats(&self, since_ms: i64, until_ms: i64) -> Result { + // 库里最老的那条,**不论是不是经过了路由**:本地应答的那一行也说明那时候 + // 已经在记了,那段时间里经过路由的请求都会在库里 + let oldest: Option = + self.conn + .query_row("SELECT MIN(at_ms) FROM requests", [], |r| r.get(0))?; + Ok(tw_api::RouteStats { + covered_since_ms: oldest + .map(|o| o.max(since_ms)) + .filter(|&from| from < until_ms), + routes: self.route_hits(since_ms, until_ms)?, + }) + } + /// 各条路由走了多少请求、各条规则命中了多少(见 [`tw_api::RouteHits`])。 /// /// **按每一行记下的路由算**,不按现在的配置推:请求走的是它那一刻的路由和 /// 规则。一个请求算在这几条规则上,每条只算一次:决定去向的那一条、附加了 /// 改写的每一条、选定上游之后拒绝了它的那一条。本地应答的没有路由,不算。 - pub fn route_hits( - &self, - since_ms: i64, - until_ms: i64, - ) -> Result, DbError> { + fn route_hits(&self, since_ms: i64, until_ms: i64) -> Result, DbError> { /// 数命中要的那几项。尝试链不用解 #[derive(serde::Deserialize)] struct Routed { @@ -2377,7 +2389,7 @@ mod security_log_tests { } #[cfg(test)] -mod route_hits_tests { +mod route_stats_tests { use super::tests::{row, upstream_failed}; use super::*; @@ -2438,7 +2450,7 @@ mod route_hits_tests { late.error = Some(upstream_failed("denied")); db.insert(&late).unwrap(); - let got = db.route_hits(0, 1_000).unwrap(); + let got = db.route_stats(0, 1_000).unwrap().routes; assert_eq!( got.iter().map(|r| r.route.as_str()).collect::>(), ["工作", "默认"], @@ -2498,9 +2510,79 @@ mod route_hits_tests { broken.routing = Some("{\"rule\":".into()); db.insert(&broken).unwrap(); - let got = db.route_hits(100, 200).unwrap(); + let got = db.route_stats(100, 200).unwrap().routes; assert_eq!(got.len(), 1, "{got:?}"); assert_eq!((got[0].requests, got[0].last_ms), (1, 150)); - assert!(db.route_hits(1_000, 2_000).unwrap().is_empty()); + assert!(db.route_stats(1_000, 2_000).unwrap().routes.is_empty()); + } + + /// 库里一条请求都没有(刚装好、升级时刚重建):什么都说不上,不是「整段都没命中」。 + #[test] + fn an_empty_store_covers_nothing() { + let db = Db::in_memory().unwrap(); + let got = db.route_stats(0, 1_000).unwrap(); + assert_eq!(got.covered_since_ms, None); + assert!(got.routes.is_empty()); + // 线上是 null,不是省掉:界面必须想到这一种 + let v = serde_json::to_value(&got).unwrap(); + assert!(v["covered_since_ms"].is_null(), "{v}"); + assert!(v.get("covered_since_ms").is_some(), "{v}"); + } + + /// 记录比窗口短(库在窗口中间才建好,或者留的天数比窗口短):记录从最老那条开始的 + /// 时刻起才是全的。**不论它是不是经过了路由** —— 本地应答的那一行也说明那时候 + /// 已经在记了。 + #[test] + fn history_shorter_than_the_window_starts_at_the_oldest_request() { + let db = Db::in_memory().unwrap(); + let mut local = row(1, 400); + local.local = true; + db.insert(&local).unwrap(); + db.insert(&routed(2, 600, "默认", "兜底", &[], None)) + .unwrap(); + + let got = db.route_stats(0, 1_000).unwrap(); + assert_eq!(got.covered_since_ms, Some(400)); + assert_eq!(got.routes.len(), 1, "{got:?}"); + assert_eq!(got.routes[0].requests, 1); + + // 过期的记录删掉之后,最老的那条往后挪,记录的起点跟着挪 + assert_eq!(db.prune_before(500).unwrap(), 1); + assert_eq!( + db.route_stats(0, 1_000).unwrap().covered_since_ms, + Some(600) + ); + } + + /// 记录比窗口长:整段都有记录,起点就是问的起点。窗口里没有请求也一样 —— + /// 那段时间在记,只是没有请求来。 + #[test] + fn history_longer_than_the_window_covers_all_of_it() { + let db = Db::in_memory().unwrap(); + db.insert(&routed(1, 50, "默认", "兜底", &[], None)) + .unwrap(); + db.insert(&routed(2, 500, "默认", "兜底", &[], None)) + .unwrap(); + + let got = db.route_stats(100, 1_000).unwrap(); + assert_eq!(got.covered_since_ms, Some(100)); + assert_eq!(got.routes[0].requests, 1, "窗口外的那条不算:{got:?}"); + + let quiet = db.route_stats(100, 400).unwrap(); + assert_eq!(quiet.covered_since_ms, Some(100)); + assert!(quiet.routes.is_empty(), "{quiet:?}"); + } + + /// 窗口整个在记录开始之前(或者窗口本身是空的):这段时间没有一刻有记录。 + #[test] + fn a_window_before_the_history_began_covers_nothing() { + let db = Db::in_memory().unwrap(); + db.insert(&routed(1, 500, "默认", "兜底", &[], None)) + .unwrap(); + assert_eq!(db.route_stats(0, 400).unwrap().covered_since_ms, None); + // 窗口的终点不含在内:恰好在终点开始的请求不在这段里 + assert_eq!(db.route_stats(0, 500).unwrap().covered_since_ms, None); + assert_eq!(db.route_stats(0, 501).unwrap().covered_since_ms, Some(500)); + assert_eq!(db.route_stats(700, 700).unwrap().covered_since_ms, None); } } diff --git a/scripts/smoke.sh b/scripts/smoke.sh index f5cbcff2..e86bfaf5 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -368,9 +368,10 @@ C=$(post /models/refresh '{}'); [ "$C" = "200" ] && ok "POST /models/refresh" || C=$(ctl /overview | python3 -c 'import json,sys;p=json.load(sys.stdin)["providers"][0];print(p["model_status"] in ("pending","listed","no_list","failed") and isinstance(p["model_fetching"],bool))') [ "$C" = "True" ] && ok "/overview 带模型获取状态" || bad "/overview 的模型状态字段不对:$C" -# 经过路由的请求按路由和规则数得到:决定去向的那条规则至少命中过一次 -C=$(ctl "/summary/routes?from_ms=$DAY" | python3 -c 'import json,sys;d=json.load(sys.stdin);print(bool(d) and d[0]["requests"]>0 and any(r["decided"]>0 for r in d[0]["rules"]))') -[ "$C" = "True" ] && ok "/summary/routes 数到了经过路由的请求" || bad "/summary/routes 没数到请求:$C" +# 经过路由的请求按路由和规则数得到:决定去向的那条规则至少命中过一次。库是这次新建 +# 的,记录从第一个请求开始:比问的起点晚,不是空 +C=$(ctl "/summary/routes?from_ms=$DAY" | python3 -c 'import json,sys;d=json.load(sys.stdin);r=d["routes"];c=d["covered_since_ms"];print(bool(r) and r[0]["requests"]>0 and any(x["decided"]>0 for x in r[0]["rules"]) and c is not None and c>int(sys.argv[1]))' "$DAY") +[ "$C" = "True" ] && ok "/summary/routes 数到了经过路由的请求,也说了记录从哪一刻开始" || bad "/summary/routes 没数到请求:$C" ID=$(ctl "/history?limit=1" \ | python3 -c 'import json,sys;d=json.load(sys.stdin);print(d[0]["id"] if d else 0)')