diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index b0dd4321..fbf419b6 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -37,10 +37,15 @@ pub use tw_types::Msg; /// **6 概览带上了配置版本号,协议里不再有为老版本留的默认值。**照 5 写的 /// 界面从别处读版本号;而缺了这些字段的 core 现在连概览都解析不了。 /// +/// **8 额度的重置时间换成了时刻**(`resets_at_ms`,不再是 `reset_in_secs`): +/// 秒数是收到响应那一刻的,存下来原样再给出去就是一个不会走的倒计时。另外 +/// 概览带上了上游凭据被拒、代理不通的现状,请求详情能取还在跑的请求,掉队的 +/// 事件流订阅者会收到一条 `EventsDropped`。照 7 写的界面拿不到倒计时。 +/// /// **7 把手动配置的说明拆成了步骤、字段和地址**(`ManualClient.how` 没了, /// 换成 `setup`;能接管的客户端也带上了 `manual`),客户端的最近一次请求改按 /// 为它生成的密钥算。照 6 写的界面会把手动配置那一栏画成空白。 -pub const CONTROL_API_VERSION: u32 = 7; +pub const CONTROL_API_VERSION: u32 = 8; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Status { @@ -443,9 +448,9 @@ pub enum Event { provider: String, /// 和 `QuotaWindow.window` 同一个词表 window: String, - /// 多久之后重置。上游没说就没有 + /// 什么时候重置(见 `QuotaWindow::resets_at_ms`)。上游没说就没有 #[serde(default, skip_serializing_if = "Option::is_none")] - reset_in_secs: Option, + resets_at_ms: Option, at_ms: u64, }, /// 数据面换了监听地址,或者没换成(旧的还在服务)。 @@ -522,6 +527,16 @@ pub enum Event { probe: String, at_ms: u64, }, + /// 这个订阅者跟不上,事件流丢了它 `count` 条事件。 + /// + /// **只发给掉队的那一个**,不进总线:别的订阅者什么都没丢。收到它就说明 + /// 只靠增量维护的东西(进行中的请求、列表里每一行的状态)从这一刻起不可信, + /// 要整体对一次账:重读 `/in-flight`、最近的历史和概览。 + /// + /// 以前丢了只记一行日志。那时事件只喂几行实时日志,少几行无所谓;现在 + /// 「进行中」的计数和每一行的状态都靠事件,丢一个结局,那一行就永远停在 + /// 「进行中」。 + EventsDropped { id: u64, count: u64, at_ms: u64 }, } /// 尝试链里的一跳。 @@ -566,8 +581,11 @@ pub struct QuotaWindow { /// `5h` / `7d`(Anthropic)/ `weekly`(Codex) pub window: String, pub used_percent: f64, + /// 什么时候重置,Unix 毫秒。**是时刻,不是「还有多少秒」**:上游报的秒数 + /// 只在收到响应那一刻成立,存下来原样给出去,界面上就是一个不会走的倒计时。 + /// 上游没说就没有 #[serde(default, skip_serializing_if = "Option::is_none")] - pub reset_in_secs: Option, + pub resets_at_ms: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option, } @@ -593,6 +611,7 @@ impl Event { | Event::RequestFailed { id, .. } | Event::RequestCancelled { id, .. } | Event::LocallyAnswered { id, .. } + | Event::EventsDropped { id, .. } | Event::ConfigReloaded { id, .. } | Event::ListenChanged { id, .. } | Event::ConfigRejected { id, .. } @@ -682,6 +701,24 @@ pub struct ProxyView { pub has_auth: bool, /// 哪些上游在用它。删之前要知道,改名时它们会跟着改 pub used_by: Vec, + /// 网关发现它不通了:经它转发的请求连不上之后检过一次,卡在哪一步、为什么。 + /// 之后经它的请求成功了、或者再检一次通了,就又是空的。 + /// + /// **不定时探测**(见 `ProxyChanged`),所以空的意思是「没发现问题」,不是 + /// 「刚测过是通的」。和 `ProxyChanged` 说的是同一件事:一个是现状,一个是变化 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub unreachable: Option, +} + +/// 网关发现一个代理不通时,检出来的样子。 +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct ProxyFault { + /// 卡在哪一步。说不出来的没有 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub failed: Option, + pub detail: Msg, + /// 什么时候检的 + pub at_ms: u64, } /// 一类客户端辅助请求的处置。 @@ -783,8 +820,15 @@ pub struct ProviderView { pub model_count: usize, /// 停用:不参与路由,模型不出现在 `/v1/models` 里 pub disabled: bool, - /// closed / open + /// `ok` / `open`(熔断中) pub health: String, + /// 上游拒绝了凭据:最近一次得到答复的请求回的是这个状态码(401 / 403)。 + /// 没被拒是空的,被拒之后有请求成功了也是空的。 + /// + /// **熔断看不见这件事**:4xx 不算失败,换一家也一样被拒,所以一家凭据坏掉的 + /// 上游永远不会熔断。和 `AuthChanged` 说的是同一件事:一个是现状,一个是变化 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub auth_rejected: Option, /// 配置里写明的计费方式:`per-token` / `subscription` / `free` / `unknown`。 /// 空 = 自动识别 pub billing: Option, @@ -2009,6 +2053,11 @@ pub struct RequestDetail { pub row: HistoryRow, pub request_body: Option, pub response_body: Option, + /// 这个请求还在跑。**记录在结局到了才落库**,这时的 `row` 是到目前为止 + /// 知道的那些:开始时的身份和上游,响应头到了就有状态码,路由走完就有 + /// 尝试链;耗时、用量、金额都还没有。请求体已经存下了,响应体要等结局。 + /// 结局到了再取一次,就是完整的那一份 + pub in_flight: bool, } /// 一份存下来的 body。 diff --git a/crates/tw-control/src/chatgpt.rs b/crates/tw-control/src/chatgpt.rs index 0fcdc669..4414013f 100644 --- a/crates/tw-control/src/chatgpt.rs +++ b/crates/tw-control/src/chatgpt.rs @@ -960,7 +960,7 @@ async fn usage( Path(name): Path, ) -> Result, Fail> { let v = account_call(&s, &name, reqwest::Method::GET, "usage", None).await?; - let usage = parse_usage(&v); + let usage = parse_usage(&v, now_ms()); // 问来的额度和响应头里读到的一样记下来:**额度只在内存里**,冷启动之后要等这个账号 // 第一次有请求才会有,而界面一打开就该看得见 s.gateway.record_quota( @@ -973,7 +973,7 @@ async fn usage( .map(|w| tw_gateway::quota::Window { window: w.window.clone(), used_percent: w.used_percent, - reset_in_secs: w.reset_in_secs, + resets_at_ms: w.resets_at_ms, status: w.status.clone(), }) .collect(), @@ -985,14 +985,19 @@ async fn usage( /// `wham/usage` 的回答。**只取界面要用的几项**:额度、套餐,以及邮箱 /// —— 账号不止一个时,邮箱是用户分得清哪个是哪个的唯一一项。同一份回答里 /// 的用户 ID 和账户 ID 不往外带:界面用不上,而它们一旦出去就会进日志 -fn parse_usage(v: &Value) -> tw_api::ChatgptUsage { +/// +/// `now_ms`:收到回答的时刻。「还有多少秒重置」要靠它换成时刻 +fn parse_usage(v: &Value, now_ms: u64) -> tw_api::ChatgptUsage { let window = |w: &Value| { let secs = w.get("limit_window_seconds")?.as_u64().filter(|s| *s > 0)?; let used = w.get("used_percent")?.as_f64()?.clamp(0.0, 100.0); Some(tw_api::QuotaWindow { window: tw_gateway::quota::codex_window(secs / 60), used_percent: used, - reset_in_secs: w.get("reset_after_seconds").and_then(|x| x.as_u64()), + resets_at_ms: w + .get("reset_after_seconds") + .and_then(|x| x.as_u64()) + .map(|secs| now_ms.saturating_add(secs.saturating_mul(1000))), status: (used >= 100.0).then(|| "rejected".to_string()), }) }; @@ -1122,13 +1127,17 @@ mod tests { }, "rate_limit_reset_credits": {"available_count": 2} }); - let u = parse_usage(&v); + let u = parse_usage(&v, 1_758_000_000_000); assert_eq!(u.email.as_deref(), Some("someone@example.com")); assert_eq!(u.plan.as_deref(), Some("plus")); assert_eq!(u.windows.len(), 1); assert_eq!(u.windows[0].window, "weekly"); assert_eq!(u.windows[0].used_percent, 21.0); - assert_eq!(u.windows[0].reset_in_secs, Some(410907)); + // 「还有 410907 秒」换成了时刻:收到回答那一刻往后数 + assert_eq!( + u.windows[0].resets_at_ms, + Some(1_758_000_000_000 + 410_907_000) + ); assert_eq!(u.reset_credits, Some(2)); // 用户 ID 不往外带:界面读不出是谁,而它一旦出去就会进日志 let json = serde_json::to_string(&u).unwrap(); diff --git a/crates/tw-control/src/config.rs b/crates/tw-control/src/config.rs index 4bd7cfc9..03ae87c8 100644 --- a/crates/tw-control/src/config.rs +++ b/crates/tw-control/src/config.rs @@ -216,7 +216,7 @@ impl ConfigManager { } } -fn now_ms() -> u64 { +pub(crate) fn now_ms() -> u64 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_millis() as u64) diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index 08d6104c..cdfb725a 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -190,7 +190,7 @@ async fn events( State(s): State, ) -> Sse>> { let rx = s.bus().subscribe(); - let stream = async_stream_from(rx); + let stream = async_stream_from(rx, s.bus().clone()); // 心跳。UI 那边要能区分「没有请求」和「连接断了」—— 没有心跳的话 // 一个安静的下午看起来就像挂了。 Sse::new(stream).keep_alive(KeepAlive::new().interval(std::time::Duration::from_secs(15))) @@ -204,28 +204,43 @@ async fn in_flight(State(s): State) -> Json> { Json(s.bus().in_flight()) } +/// 事件流编码成 SSE。 fn async_stream_from( - mut rx: broadcast::Receiver, + rx: broadcast::Receiver, + bus: EventBus, ) -> impl Stream> { - futures::stream::unfold(rx_state(&mut rx), |mut rx| async move { - loop { - match rx.recv().await { - Ok(ev) => { - let data = serde_json::to_string(&ev).unwrap_or_default(); - return Some((Ok(SseEvent::default().data(data)), rx)); - } - // 订阅者跟不上时 broadcast 会丢最老的。**继续收而不是断开** —— - // UI 少几行实时日志无所谓,断掉重连才是真的难受。 - Err(broadcast::error::RecvError::Lagged(n)) => { - tracing::warn!( - dropped = n, - "a control-plane subscriber fell behind; some events were dropped" - ); - continue; + use futures::StreamExt; + event_stream(rx, bus).map(|ev| { + let data = serde_json::to_string(&ev).unwrap_or_default(); + Ok(SseEvent::default().data(data)) + }) +} + +/// 一个订阅者收到的事件。`bus` 用来给掉队的那条标记取一个号。 +fn event_stream( + mut rx: broadcast::Receiver, + bus: EventBus, +) -> impl Stream { + futures::stream::unfold((rx_state(&mut rx), bus), |(mut rx, bus)| async move { + let ev = match rx.recv().await { + Ok(ev) => ev, + // 订阅者跟不上时 broadcast 会丢最老的。**继续收而不是断开**(断掉重连 + // 丢得更多),**但要告诉它丢了**:它手上只靠增量维护的状态从这一刻起 + // 不可信,得自己对一次账(见 `Event::EventsDropped`) + Err(broadcast::error::RecvError::Lagged(n)) => { + tracing::warn!( + dropped = n, + "a control-plane subscriber fell behind; some events were dropped" + ); + tw_api::Event::EventsDropped { + id: bus.next_id(), + count: n, + at_ms: config::now_ms(), } - Err(broadcast::error::RecvError::Closed) => return None, } - } + Err(broadcast::error::RecvError::Closed) => return None, + }; + Some((ev, (rx, bus))) }) } @@ -262,6 +277,7 @@ async fn overview(State(s): State) -> Json { // 而这个视图会进日志、进诊断包、进用户贴出来的截图。 has_auth: x.auth.is_some(), used_by: tw_config::refs::proxy_users(cfg, &x.name), + unreachable: s.gateway.proxy_fault(&x.name), }) .collect(), providers: cfg @@ -414,6 +430,7 @@ fn provider_view( tw_gateway::health::State::Closed => "ok".into(), tw_gateway::health::State::Open => "open".into(), }, + auth_rejected: s.gateway.auth_rejected(&p.name), billing: p.billing.map(|b| b.slug().to_string()), billing_effective: s.gateway.billing_of(p).slug().to_string(), references: tw_config::refs::provider_refs(cfg, &p.name) @@ -855,12 +872,23 @@ async fn request_detail( ) -> Result, Fail> { let store = need_store(&s)?; let g = store.lock().await; - let row = g.db().get(id).map_err(internal)?.ok_or_else(|| { - fail( - StatusCode::NOT_FOUND, - msg!("control.request_not_found", id = id => "There is no request {id}."), - ) - })?; + // **还在跑的也答。**记录要等结局才落库,而用户点开的往往正是那个跑了很久的 + // 请求:给到目前为止知道的,标着还在跑 + let (row, in_flight) = match g.db().get(id).map_err(internal)? { + Some(row) => (row, false), + None => { + let row = u64::try_from(id) + .ok() + .and_then(|id| g.in_flight_row(id)) + .ok_or_else(|| { + fail( + StatusCode::NOT_FOUND, + msg!("control.request_not_found", id = id => "There is no request {id}."), + ) + })?; + (row, true) + } + }; let at = row.at_ms; let body = |which| { let raw = g.blobs().get(at, id, which)?; @@ -885,6 +913,7 @@ async fn request_detail( request_body: body(tw_store::Which::Request), response_body: body(tw_store::Which::Response), row: history_row(row, security), + in_flight, }; Ok(Json(detail)) } @@ -906,7 +935,7 @@ async fn quota(State(s): State) -> Json .map(|w| tw_api::QuotaWindow { window: w.window, used_percent: w.used_percent, - reset_in_secs: w.reset_in_secs, + resets_at_ms: w.resets_at_ms, status: w.status, }) .collect(), @@ -1550,3 +1579,37 @@ mod describe_tests { assert_eq!(lines[0].values, ["relay"], "{lines:?}"); } } + +#[cfg(test)] +mod event_stream_tests { + use super::*; + use futures::StreamExt; + + /// 订阅者跟不上时,**丢了要说**。以前只记一行日志,而界面上「进行中」的 + /// 计数和每一行的状态都靠增量维护 —— 丢一个结局,那一行就永远在跑。 + #[tokio::test] + async fn a_subscriber_that_falls_behind_is_told_how_many_events_it_lost() { + let bus = EventBus::new(); + let stream = event_stream(bus.subscribe(), bus.clone()); + let mut stream = Box::pin(stream); + // 比缓冲多塞 10 条,一条都还没读 + let n = 1024 + 10; + for i in 0..n { + bus.emit(tw_api::Event::HealthChanged { + id: i, + provider: "p".into(), + state: "open".into(), + at_ms: 0, + }); + } + match stream.next().await { + Some(tw_api::Event::EventsDropped { count, .. }) => assert_eq!(count, 10), + other => panic!("该先说丢了几条,实际 {other:?}"), + } + // 然后接着收留下来的:最老的丢掉了,从第 10 条开始 + match stream.next().await { + Some(tw_api::Event::HealthChanged { id, .. }) => assert_eq!(id, 10), + other => panic!("该接着收留下来的,实际 {other:?}"), + } + } +} diff --git a/crates/tw-control/tests/chatgpt.rs b/crates/tw-control/tests/chatgpt.rs index 048038d8..71d0688d 100644 --- a/crates/tw-control/tests/chatgpt.rs +++ b/crates/tw-control/tests/chatgpt.rs @@ -817,10 +817,16 @@ async fn usage_shows_the_limits_without_personal_details() { assert_eq!(st, StatusCode::OK, "{v}"); assert_eq!(v["plan"], "plus"); assert_eq!(v["reset_credits"], 2); - assert_eq!( - v["windows"], - json!([{"window": "weekly", "used_percent": 21.0, "reset_in_secs": 410907}]), - "长度为 0 的窗口不算" + let windows = v["windows"].as_array().unwrap(); + assert_eq!(windows.len(), 1, "长度为 0 的窗口不算:{v}"); + assert_eq!(windows[0]["window"], "weekly"); + assert_eq!(windows[0]["used_percent"], 21.0); + // 「还有 410907 秒」换成了重置的时刻 + let now = now_ms(); + let at = windows[0]["resets_at_ms"].as_u64().expect("没有重置时刻"); + assert!( + (now + 410_907_000 - 60_000..=now + 410_907_000).contains(&at), + "{at} vs {now}" ); // 邮箱要给:账号不止一个时,它是用户分辨哪个是哪个的唯一一项 assert_eq!(v["email"], "someone@example.com"); @@ -1008,3 +1014,10 @@ async fn a_login_still_used_by_another_upstream_is_not_revoked() { tokio::time::sleep(Duration::from_millis(300)).await; assert!(b.openai.revoked.lock().unwrap().is_empty()); } + +fn now_ms() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis() as u64 +} diff --git a/crates/tw-control/tests/live_state.rs b/crates/tw-control/tests/live_state.rs new file mode 100644 index 00000000..b2fedb16 --- /dev/null +++ b/crates/tw-control/tests/live_state.rs @@ -0,0 +1,260 @@ +//! 界面不靠轮询也能对得上的那几样**现状**。 +//! +//! 变化走事件流,但界面总有晚到的时候:窗口才打开、页面才挂上、事件流掉了几条。 +//! 那时它问的是这里 —— 所以事件说过的每一种状态,这里都要答得出来:还在跑的 +//! 请求、被拒的凭据、不通的代理。 + +use std::net::SocketAddr; +use std::sync::Arc; +use std::time::Duration; + +use axum::body::Body; +use axum::http::{Request, StatusCode}; +use tower::ServiceExt; +use tw_control::{ConfigManager, ControlState}; + +fn control( + d: &tempfile::TempDir, + yaml: &str, + store: Option>>, +) -> (tw_gateway::AppState, axum::Router) { + let p = d.path().join("config.yaml"); + std::fs::write(&p, yaml).unwrap(); + let cfg: tw_config::Config = serde_yaml_ng::from_str(yaml).unwrap(); + let gw = tw_gateway::AppState::new(cfg).unwrap(); + let bus = gw.bus.clone(); + let state = ControlState { + cfg: Arc::new(ConfigManager::new(p, gw.clone(), bus)), + gateway: gw.clone(), + store, + started: std::time::Instant::now(), + price_updater: Default::default(), + chatgpt: Default::default(), + home: d.path().join("home"), + }; + (gw, tw_control::router(state)) +} + +async fn get(app: &axum::Router, path: &str) -> (StatusCode, serde_json::Value) { + let r = app + .clone() + .oneshot(Request::get(path).body(Body::empty()).unwrap()) + .await + .unwrap(); + let status = r.status(); + let body = axum::body::to_bytes(r.into_body(), usize::MAX) + .await + .unwrap(); + (status, serde_json::from_slice(&body).unwrap_or_default()) +} + +/// 把网关真的跑起来:凭据和代理的状态只有真实转发才会碰到。 +async fn serve(gw: tw_gateway::AppState) -> SocketAddr { + let addr = { + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + l.local_addr().unwrap() + }; + tokio::spawn(async move { tw_gateway::serve(gw, addr).await.unwrap() }); + tokio::time::sleep(Duration::from_millis(60)).await; + addr +} + +async fn ask(gw: SocketAddr) -> u16 { + reqwest::Client::builder() + .no_proxy() + .build() + .unwrap() + .post(format!("http://{gw}/v1/messages")) + .header("x-api-key", "tw-k") + .body(r#"{"model":"claude-sonnet-4-5","max_tokens":16,"messages":[]}"#) + .send() + .await + .unwrap() + .status() + .as_u16() +} + +/// 一个确定没人在听的地址。 +fn dead_addr() -> SocketAddr { + let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + l.local_addr().unwrap() +} + +// ---------------------------------------------------------------- 还在跑的请求 + +const BASE: &str = "version: 1\nclients:\n - name: 我\n key: tw-k\nproviders:\n - name: 官方\n base_url: https://api.anthropic.com\n key: sk-x\n"; + +fn recorder(d: &tempfile::TempDir) -> Arc> { + Arc::new(tokio::sync::Mutex::new(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()), + ))) +} + +fn started(id: u64) -> tw_api::Event { + tw_api::Event::RequestStarted { + id, + client: "我".into(), + client_hint: Some("claude-code".into()), + session_fp: None, + peer: None, + key_masked: None, + provider: "官方".into(), + billing: "per-token".into(), + model: "claude-sonnet-4-5".into(), + method: "POST".into(), + path: "/v1/messages".into(), + at_ms: 1_758_000_000_000, + } +} + +/// **记录要等结局才落库**,而详情里最常被点开的恰恰是那个跑了很久的请求。 +/// 以前点开它得到的是「没有这个请求」,结束了也不会自己补上。 +#[tokio::test] +async fn a_request_still_running_can_be_opened_and_becomes_whole_when_it_ends() { + let d = tempfile::tempdir().unwrap(); + let store = recorder(&d); + let (_, app) = control(&d, BASE, Some(store.clone())); + { + let mut rec = store.lock().await; + rec.on_event(&started(7)); + rec.record_body( + 1_758_000_000_000, + 7, + tw_store::Which::Request, + br#"{"model":"claude-sonnet-4-5"}"#, + 29, + ); + rec.on_event(&tw_api::Event::RequestHeaders { + id: 7, + status: 200, + ttfb_ms: 900, + }); + rec.on_event(&tw_api::Event::RequestRouted { + id: 7, + rule: "catch-all".into(), + group: Some("__all__".into()), + attempts: vec![tw_api::AttemptView { + provider: "官方".into(), + outcome: "served".into(), + status: Some(200), + error: None, + ms: 900, + }], + billing: "per-token".into(), + }); + } + + let (st, v) = get(&app, "/request/7").await; + assert_eq!(st, StatusCode::OK, "{v}"); + assert_eq!(v["in_flight"], true); + // 到目前为止知道的:身份、上游、响应头、尝试链 + assert_eq!(v["row"]["model"], "claude-sonnet-4-5"); + assert_eq!(v["row"]["status"], 200); + assert_eq!(v["row"]["ttfb_ms"], 900); + assert_eq!(v["row"]["routing"]["rule"], "catch-all"); + // 还没有的就是没有:耗时、用量、金额 + assert!(v["row"]["duration_ms"].is_null(), "{v}"); + assert!(v["row"]["input_tokens"].is_null(), "{v}"); + assert!(v["row"]["cost_micros"].is_null(), "{v}"); + // 请求体开始时就存下了,响应体要等结局 + assert!( + v["request_body"]["text"] + .as_str() + .is_some_and(|t| t.contains("claude-sonnet-4-5")), + "{v}" + ); + assert!(v["response_body"].is_null(), "{v}"); + + store + .lock() + .await + .on_event(&tw_api::Event::RequestFinished { + id: 7, + model: "claude-sonnet-4-5".into(), + status: 200, + bytes: 120, + duration_ms: 4_000, + usage: None, + }); + let (st, v) = get(&app, "/request/7").await; + assert_eq!(st, StatusCode::OK, "{v}"); + assert_eq!(v["in_flight"], false, "结束了还说在跑"); + assert_eq!(v["row"]["duration_ms"], 4_000); +} + +#[tokio::test] +async fn a_request_that_never_started_is_still_not_found() { + let d = tempfile::tempdir().unwrap(); + let (_, app) = control(&d, BASE, Some(recorder(&d))); + let (st, _) = get(&app, "/request/99").await; + assert_eq!(st, StatusCode::NOT_FOUND); +} + +// ---------------------------------------------------------------- 凭据与代理 + +/// **熔断看不见被拒的凭据**(4xx 不算失败),所以它要自己一项。以前只有那一条 +/// 事件:界面晚打开,上游页上就看不出是哪一家的凭据坏了。 +#[tokio::test] +async fn the_overview_says_which_upstream_rejects_its_credential() { + let up = { + let app = axum::Router::new().fallback(|| async { StatusCode::UNAUTHORIZED }); + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let a = l.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(l, app).await.unwrap() }); + a + }; + let d = tempfile::tempdir().unwrap(); + let yaml = format!( + "version: 1\nclients:\n - name: 我\n key: tw-k\nproviders:\n - name: 中转\n base_url: http://{up}\n protocol: anthropic\n key: sk-stale\n" + ); + let (gw, app) = control(&d, &yaml, None); + let (_, v) = get(&app, "/overview").await; + assert!(v["providers"][0]["auth_rejected"].is_null(), "{v}"); + + let addr = serve(gw).await; + assert_eq!(ask(addr).await, 401); + let (_, v) = get(&app, "/overview").await; + assert_eq!(v["providers"][0]["auth_rejected"], 401, "{v}"); +} + +/// 代理挂掉的现状。**不定时探测**:经它的转发失败之后才检一次,检出来的原因要 +/// 留着,页面什么时候打开都看得见。 +#[tokio::test] +async fn the_overview_says_which_proxy_is_down_and_why() { + let dead = dead_addr(); + let d = tempfile::tempdir().unwrap(); + let yaml = format!( + "version: 1\nclients:\n - name: 我\n key: tw-k\nproxies:\n - name: 代理一\n kind: http\n addr: {dead}\nproviders:\n - name: 中转\n base_url: http://127.0.0.1:9\n protocol: anthropic\n key: sk-x\n proxy: 代理一\n" + ); + let (gw, app) = control(&d, &yaml, None); + let mut rx = gw.bus.subscribe(); + let (_, v) = get(&app, "/overview").await; + assert!(v["proxies"][0]["unreachable"].is_null(), "{v}"); + + let addr = serve(gw).await; + assert_ne!(ask(addr).await, 200); + // 检查是在后台做的,等它报出来 + tokio::time::timeout(Duration::from_secs(10), async { + loop { + if let Ok(tw_api::Event::ProxyChanged { state, .. }) = rx.recv().await + && state == "unreachable" + { + return; + } + } + }) + .await + .expect("10 秒内没有检出代理不通"); + + let (_, v) = get(&app, "/overview").await; + let fault = &v["proxies"][0]["unreachable"]; + assert!( + fault["detail"]["code"] + .as_str() + .is_some_and(|c| c.starts_with("l1.")), + "要说清为什么不通:{v}" + ); + assert_eq!(fault["failed"]["peer"], "proxy", "{v}"); +} diff --git a/crates/tw-gateway/src/quota.rs b/crates/tw-gateway/src/quota.rs index 153ad308..597699f5 100644 --- a/crates/tw-gateway/src/quota.rs +++ b/crates/tw-gateway/src/quota.rs @@ -26,10 +26,13 @@ pub struct Window { pub window: String, /// 用了百分之多少。0–100 pub used_percent: f64, - /// 还有多少秒重置。**上游没给就是 None** —— 那时界面上只能说 - /// 「不知道什么时候重置」,不能编一个倒计时 + /// 什么时候重置,Unix 毫秒。**读响应头的那一刻就换成时刻**:上游说的 + /// 「还有多少秒」只在那一刻成立,存下来原样再给出去,就是一个不会走的倒计时。 + /// + /// **上游没给就是 None** —— 那时界面上只能说「不知道什么时候重置」,不能编 + /// 一个倒计时 #[serde(default, skip_serializing_if = "Option::is_none")] - pub reset_in_secs: Option, + pub resets_at_ms: Option, /// `allowed` / `allowed_warning` / `rejected` #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option, @@ -79,7 +82,9 @@ impl Quota { /// 从响应头里读额度。**读不到就是空的**,不是零 —— 按量付费的账号本来 /// 就没有这些头,把它当成「用了 0%」会在菜单栏上显示一个假的进度条。 -pub fn from_headers(h: &HeaderMap) -> Quota { +/// +/// `now_ms`:收到这些头的时刻。「还有多少秒重置」要靠它换成时刻 +pub fn from_headers(h: &HeaderMap, now_ms: u64) -> Quota { let mut windows = Vec::new(); let get = |k: &str| h.get(k).and_then(|v| v.to_str().ok()); @@ -96,8 +101,8 @@ pub fn from_headers(h: &HeaderMap) -> Quota { // 百分比**:一个真实的 0.62 和一个真实的 62 都要能读对,而 // 「用了 0.62%」这种值在订阅场景下没有意义。 used_percent: normalize_percent(u), - reset_in_secs: get(&format!("anthropic-ratelimit-unified-{key}-reset")) - .and_then(parse_reset), + resets_at_ms: get(&format!("anthropic-ratelimit-unified-{key}-reset")) + .and_then(|v| parse_reset(v, now_ms)), status: get(&format!("anthropic-ratelimit-unified-{key}-status")) .map(|s| s.to_string()), }); @@ -136,8 +141,9 @@ pub fn from_headers(h: &HeaderMap) -> Quota { windows.push(Window { window, used_percent, - reset_in_secs: get(&format!("x-codex-{prefix}-reset-after-seconds")) - .and_then(|v| v.parse().ok()), + resets_at_ms: get(&format!("x-codex-{prefix}-reset-after-seconds")) + .and_then(|v| v.parse::().ok()) + .map(|secs| after(now_ms, secs)), // Codex 不报状态。用满就是被拒 —— 这是上游数字的直接结论,不是推断 status: (used_percent >= 100.0).then(|| "rejected".to_string()), }); @@ -160,25 +166,42 @@ fn normalize_percent(v: f64) -> f64 { p.clamp(0.0, 100.0) } -/// `reset` 头可能是秒数,也可能是一个 RFC 3339 时间戳。 +/// `reset` 头换成重置的时刻。它可能是还有多少秒、一个 Unix 时间戳(秒), +/// 也可能是一个 RFC 3339 时间戳。 /// -/// **认不出来就是 None。**编一个倒计时出来,用户会照着它安排自己的活。 -fn parse_reset(v: &str) -> Option { - if let Ok(secs) = v.parse::() { - return Some(secs); - } - // `2026-09-09T12:00:00Z` - let t = chrono::DateTime::parse_from_rfc3339(v).ok()?; - let now = chrono::Utc::now(); - let d = t.with_timezone(&chrono::Utc) - now; - d.num_seconds().try_into().ok() +/// **秒数和时间戳按大小分**:额度窗口最长一周(60 万秒出头),而任何一个 +/// 近年的时间戳都在十亿以上,两者之间隔着三个数量级。以前纯数字一律当成秒数, +/// 一个时间戳会被读成「五十多年后重置」。 +/// +/// **认不出来就是 None。**编一个倒计时出来,用户会照着它安排自己的活。已经 +/// 过去的时刻同样是 None。 +fn parse_reset(v: &str, now_ms: u64) -> Option { + let at = match v.parse::() { + Ok(n) if n >= EPOCH_SECONDS => n.checked_mul(1000)?, + Ok(secs) => after(now_ms, secs), + // `2026-09-09T12:00:00Z` + Err(_) => chrono::DateTime::parse_from_rfc3339(v) + .ok()? + .timestamp_millis() + .try_into() + .ok()?, + }; + (at >= now_ms).then_some(at) +} + +/// 比它大的数字是 Unix 时间戳(秒),不是「还有多少秒」:2001 年之后的任何时刻 +const EPOCH_SECONDS: u64 = 1_000_000_000; + +/// `now_ms` 之后 `secs` 秒的时刻 +fn after(now_ms: u64, secs: u64) -> u64 { + now_ms.saturating_add(secs.saturating_mul(1000)) } /// 从 reqwest 的响应头读。 /// /// **两个 HeaderMap 类型,一段逻辑。**reqwest 和 axum 各有各的 /// `HeaderMap`,而把解析抄两遍必然会漂移出两套行为。 -pub fn from_headers_reqwest(h: &reqwest::header::HeaderMap) -> Quota { +pub fn from_headers_reqwest(h: &reqwest::header::HeaderMap, now_ms: u64) -> Quota { let mut axum_map = HeaderMap::new(); for (k, v) in h.iter() { if let (Ok(name), Ok(val)) = ( @@ -188,14 +211,17 @@ pub fn from_headers_reqwest(h: &reqwest::header::HeaderMap) -> Quota { axum_map.insert(name, val); } } - from_headers(&axum_map) + from_headers(&axum_map, now_ms) } #[cfg(test)] mod tests { use super::*; - fn headers(pairs: &[(&str, &str)]) -> HeaderMap { + /// 收到这些头的时刻。测试里固定下来,重置时刻才能算准 + const NOW: u64 = 1_758_000_000_000; + + fn headers_at(pairs: &[(&str, &str)]) -> HeaderMap { let mut h = HeaderMap::new(); for (k, v) in pairs { h.insert( @@ -208,17 +234,21 @@ mod tests { #[test] fn anthropic_windows_are_read_straight_from_the_headers() { - let q = from_headers(&headers(&[ - ("anthropic-ratelimit-unified-5h-utilization", "62"), - ("anthropic-ratelimit-unified-5h-reset", "7200"), - ("anthropic-ratelimit-unified-5h-status", "allowed"), - ("anthropic-ratelimit-unified-7d-utilization", "18"), - ])); + let q = from_headers( + &headers_at(&[ + ("anthropic-ratelimit-unified-5h-utilization", "62"), + ("anthropic-ratelimit-unified-5h-reset", "7200"), + ("anthropic-ratelimit-unified-5h-status", "allowed"), + ("anthropic-ratelimit-unified-7d-utilization", "18"), + ]), + NOW, + ); assert_eq!(q.windows.len(), 2); let five = &q.windows[0]; assert_eq!(five.window, "5h"); assert_eq!(five.used_percent, 62.0); - assert_eq!(five.reset_in_secs, Some(7200)); + // 两小时之后,**是时刻** —— 过一会儿再读,它还是同一个时刻 + assert_eq!(five.resets_at_ms, Some(NOW + 7_200_000)); assert_eq!(five.status.as_deref(), Some("allowed")); } @@ -226,10 +256,10 @@ mod tests { fn a_fractional_utilization_is_read_as_a_percentage_too() { // 各家给 0–1 还是 0–100 不一样,而「用了 0.62%」在订阅场景下 // 没有意义 —— 读错的话菜单栏上会显示一个几乎空着的进度条。 - let q = from_headers(&headers(&[( - "anthropic-ratelimit-unified-5h-utilization", - "0.62", - )])); + let q = from_headers( + &headers_at(&[("anthropic-ratelimit-unified-5h-utilization", "0.62")]), + NOW, + ); assert_eq!(q.windows[0].used_percent, 62.0); } @@ -237,131 +267,189 @@ mod tests { fn a_pay_as_you_go_response_yields_nothing_not_zero() { // **按量付费的账号本来就没有这些头。**当成「用了 0%」会在菜单栏 // 上显示一个假的进度条。 - let q = from_headers(&headers(&[("content-type", "application/json")])); + let q = from_headers(&headers_at(&[("content-type", "application/json")]), NOW); assert!(q.is_empty()); assert!(q.tightest().is_none()); } #[test] fn codex_headers_work_too() { - let q = from_headers(&headers(&[ - ("x-codex-primary-used-percent", "45"), - ("x-codex-primary-reset-after-seconds", "86400"), - ("x-codex-secondary-used-percent", "88"), - ])); + let q = from_headers( + &headers_at(&[ + ("x-codex-primary-used-percent", "45"), + ("x-codex-primary-reset-after-seconds", "86400"), + ("x-codex-secondary-used-percent", "88"), + ]), + NOW, + ); assert_eq!(q.windows.len(), 2); assert_eq!(q.tightest().unwrap().used_percent, 88.0); - assert_eq!(q.windows[0].reset_in_secs, Some(86400)); + assert_eq!(q.windows[0].resets_at_ms, Some(NOW + 86_400_000)); } #[test] fn a_codex_window_is_named_by_its_length_and_an_unused_one_is_left_out() { // Plus 账号实测的那组头:secondary 报 0 分钟,那个窗口没有启用 - let q = from_headers(&headers(&[ - ("x-codex-primary-used-percent", "21"), - ("x-codex-primary-window-minutes", "10080"), - ("x-codex-primary-reset-after-seconds", "410912"), - ("x-codex-secondary-used-percent", "0"), - ("x-codex-secondary-window-minutes", "0"), - ("x-codex-secondary-reset-after-seconds", "0"), - ])); + let q = from_headers( + &headers_at(&[ + ("x-codex-primary-used-percent", "21"), + ("x-codex-primary-window-minutes", "10080"), + ("x-codex-primary-reset-after-seconds", "410912"), + ("x-codex-secondary-used-percent", "0"), + ("x-codex-secondary-window-minutes", "0"), + ("x-codex-secondary-reset-after-seconds", "0"), + ]), + NOW, + ); assert_eq!(q.windows.len(), 1, "{q:?}"); assert_eq!(q.windows[0].window, "weekly"); assert_eq!(q.windows[0].used_percent, 21.0); assert!(!q.windows[0].rejected()); - let five = from_headers(&headers(&[ - ("x-codex-primary-used-percent", "1"), - ("x-codex-primary-window-minutes", "300"), - ])); + let five = from_headers( + &headers_at(&[ + ("x-codex-primary-used-percent", "1"), + ("x-codex-primary-window-minutes", "300"), + ]), + NOW, + ); assert_eq!(five.windows[0].window, "5h"); assert_eq!(five.windows[0].used_percent, 1.0, "1% 不是 100%"); } #[test] fn a_full_codex_window_is_rejected() { - let q = from_headers(&headers(&[ - ("x-codex-primary-used-percent", "100"), - ("x-codex-primary-window-minutes", "10080"), - ])); + let q = from_headers( + &headers_at(&[ + ("x-codex-primary-used-percent", "100"), + ("x-codex-primary-window-minutes", "10080"), + ]), + NOW, + ); assert!(q.windows[0].rejected()); } #[test] fn the_tightest_window_is_the_one_the_menubar_shows() { - let q = from_headers(&headers(&[ - ("anthropic-ratelimit-unified-5h-utilization", "20"), - ("anthropic-ratelimit-unified-7d-utilization", "91"), - ])); + let q = from_headers( + &headers_at(&[ + ("anthropic-ratelimit-unified-5h-utilization", "20"), + ("anthropic-ratelimit-unified-7d-utilization", "91"), + ]), + NOW, + ); assert_eq!(q.tightest().unwrap().window, "7d"); } #[test] fn an_upstream_warning_is_taken_at_face_value() { // **限流不再是突然发生的**。 - let q = from_headers(&headers(&[ - ("anthropic-ratelimit-unified-5h-utilization", "30"), - ("anthropic-ratelimit-unified-5h-status", "allowed_warning"), - ])); + let q = from_headers( + &headers_at(&[ + ("anthropic-ratelimit-unified-5h-utilization", "30"), + ("anthropic-ratelimit-unified-5h-status", "allowed_warning"), + ]), + NOW, + ); assert!(q.windows[0].warning(), "上游说快到了,我们却没当回事"); assert!(!q.windows[0].rejected()); } #[test] fn a_rejected_status_is_distinct_from_a_warning() { - let q = from_headers(&headers(&[ - ("anthropic-ratelimit-unified-5h-utilization", "100"), - ("anthropic-ratelimit-unified-5h-status", "rejected"), - ])); + let q = from_headers( + &headers_at(&[ + ("anthropic-ratelimit-unified-5h-utilization", "100"), + ("anthropic-ratelimit-unified-5h-status", "rejected"), + ]), + NOW, + ); assert!(q.windows[0].rejected()); } #[test] fn the_seven_day_threshold_header_turns_into_a_warning() { - let q = from_headers(&headers(&[ - ("anthropic-ratelimit-unified-7d-utilization", "83"), - ("anthropic-ratelimit-unified-7d-surpassed-threshold", "true"), - ])); + let q = from_headers( + &headers_at(&[ + ("anthropic-ratelimit-unified-7d-utilization", "83"), + ("anthropic-ratelimit-unified-7d-surpassed-threshold", "true"), + ]), + NOW, + ); assert!(q.windows[0].warning()); } #[test] fn a_reset_header_we_cannot_read_becomes_none_not_a_made_up_countdown() { // **编一个倒计时出来,用户会照着它安排自己的活。** - let q = from_headers(&headers(&[ - ("anthropic-ratelimit-unified-5h-utilization", "50"), - ("anthropic-ratelimit-unified-5h-reset", "不是时间"), - ])); - assert_eq!(q.windows[0].reset_in_secs, None); + let q = from_headers( + &headers_at(&[ + ("anthropic-ratelimit-unified-5h-utilization", "50"), + ("anthropic-ratelimit-unified-5h-reset", "不是时间"), + ]), + NOW, + ); + assert_eq!(q.windows[0].resets_at_ms, None); + } + + #[test] + fn an_rfc3339_reset_timestamp_is_taken_as_the_moment_it_names() { + let then = chrono::DateTime::from_timestamp_millis((NOW + 3_600_000) as i64).unwrap(); + let q = from_headers( + &headers_at(&[ + ("anthropic-ratelimit-unified-5h-utilization", "50"), + ("anthropic-ratelimit-unified-5h-reset", &then.to_rfc3339()), + ]), + NOW, + ); + assert_eq!(q.windows[0].resets_at_ms, Some(NOW + 3_600_000)); + } + + /// 纯数字也可能是 Unix 时间戳。**当成秒数的话**,一个时间戳会被读成 + /// 「五十多年后重置」—— 额度窗口最长一周,时间戳在十亿以上,两者分得开。 + #[test] + fn a_numeric_unix_timestamp_is_not_read_as_a_countdown() { + let at_secs = NOW / 1000 + 5 * 3600; + let q = from_headers( + &headers_at(&[ + ("anthropic-ratelimit-unified-5h-utilization", "50"), + ("anthropic-ratelimit-unified-5h-reset", &at_secs.to_string()), + ]), + NOW, + ); + assert_eq!(q.windows[0].resets_at_ms, Some(at_secs * 1000)); } + /// 已经过去的时刻不是一个倒计时:那个窗口已经重置过了,这一份额度是旧的。 #[test] - fn an_rfc3339_reset_timestamp_is_turned_into_seconds() { - let then = chrono::Utc::now() + chrono::Duration::seconds(3600); - let q = from_headers(&headers(&[ - ("anthropic-ratelimit-unified-5h-utilization", "50"), - ("anthropic-ratelimit-unified-5h-reset", &then.to_rfc3339()), - ])); - let s = q.windows[0].reset_in_secs.expect("时间戳没认出来"); - assert!((3590..=3600).contains(&s), "{s}"); + fn a_reset_moment_already_past_is_none() { + let past = chrono::DateTime::from_timestamp_millis((NOW - 60_000) as i64).unwrap(); + let q = from_headers( + &headers_at(&[ + ("anthropic-ratelimit-unified-5h-utilization", "50"), + ("anthropic-ratelimit-unified-5h-reset", &past.to_rfc3339()), + ]), + NOW, + ); + assert_eq!(q.windows[0].resets_at_ms, None); } #[test] fn a_percentage_out_of_range_is_clamped_rather_than_shown_as_is() { // 一个 150% 的进度条只会让人以为界面坏了。 - let q = from_headers(&headers(&[( - "anthropic-ratelimit-unified-5h-utilization", - "150", - )])); + let q = from_headers( + &headers_at(&[("anthropic-ratelimit-unified-5h-utilization", "150")]), + NOW, + ); assert_eq!(q.windows[0].used_percent, 100.0); } #[test] fn a_garbage_utilization_header_is_skipped_not_defaulted_to_zero() { - let q = from_headers(&headers(&[( - "anthropic-ratelimit-unified-5h-utilization", - "unknown", - )])); + let q = from_headers( + &headers_at(&[("anthropic-ratelimit-unified-5h-utilization", "unknown")]), + NOW, + ); assert!(q.is_empty(), "读不懂的头产生了一个假窗口"); } } diff --git a/crates/tw-gateway/src/server.rs b/crates/tw-gateway/src/server.rs index 8ca8cf1e..b2ceb459 100644 --- a/crates/tw-gateway/src/server.rs +++ b/crates/tw-gateway/src/server.rs @@ -284,8 +284,8 @@ pub struct AppState { expired_told: Arc>>, /// 已经报过「用完」的额度窗口:(上游, 窗口)。**窗口恢复之后清掉**,再用完会重新报 exhausted: Arc>>, - /// 凭据正被上游拒绝的那几家。**进入和恢复各报一次** - rejected: Arc>>, + /// 凭据正被上游拒绝的那几家,和它回的状态码。**进入和恢复各报一次** + rejected: Arc>>, /// 每个代理最近一次检查的结果。见 [`AppState::check_proxy`] proxies: Arc>>, /// 正在服务中的请求数。见 [`crate::live`]。 @@ -307,6 +307,9 @@ struct ProxyState { checked_at: std::time::Instant, /// 正在检查。并发的失败只触发一次 checking: bool, + /// 不通时检出来的样子。**概览要给现状**:只在变化时报的事件,界面晚打开 + /// 就错过了 + fault: Option, } /// 同一个代理两次检查之间至少隔多久 @@ -502,9 +505,9 @@ impl AppState { .lock() .map(|mut g| { if rejected { - g.insert(provider.to_string()) + g.insert(provider.to_string(), status).is_none() } else { - g.remove(provider) + g.remove(provider).is_some() } }) .unwrap_or(false); @@ -535,6 +538,7 @@ impl AppState { Some(st) if !st.reachable => { st.reachable = true; st.checked_at = std::time::Instant::now(); + st.fault = None; true } _ => false, @@ -569,6 +573,7 @@ impl AppState { // 第一次就该检:把时间放到足够早 checked_at: std::time::Instant::now() - PROXY_RECHECK, checking: false, + fault: None, }); let due = !st.checking && st.checked_at.elapsed() >= PROXY_RECHECK; if due { @@ -616,6 +621,14 @@ impl AppState { // 配置刚好在这中间改了,代理没了:不报 None => None, }; + let fault = result.as_ref().map(|(stage, why)| tw_api::ProxyFault { + failed: stage.as_ref().map(|s| tw_api::L1Stage { + step: s.step.slug().into(), + peer: s.peer.slug().into(), + }), + detail: why.clone(), + at_ms: now_ms(), + }); let changed = state .proxies .lock() @@ -623,9 +636,11 @@ impl AppState { Some(st) => { st.checking = false; st.checked_at = std::time::Instant::now(); - let reachable = result.is_none(); + let reachable = fault.is_none(); let changed = st.reachable != reachable; st.reachable = reachable; + // 一直不通、原因换了也记下最新的这一次 + st.fault = fault.clone(); changed } None => false, @@ -634,18 +649,12 @@ impl AppState { if !changed { return; } - match &result { - Some((_, why)) => tracing::warn!(proxy = %name, "proxy is unreachable: {why}"), + match &fault { + Some(f) => tracing::warn!(proxy = %name, "proxy is unreachable: {}", f.detail), None => tracing::info!(proxy = %name, "proxy is reachable again"), } - let (failed, detail) = match result { - Some((stage, why)) => ( - stage.map(|s| tw_api::L1Stage { - step: s.step.slug().into(), - peer: s.peer.slug().into(), - }), - Some(why), - ), + let (failed, detail) = match fault { + Some(f) => (f.failed, Some(f.detail)), None => (None, None), }; state.bus.emit(tw_api::Event::ProxyChanged { @@ -691,7 +700,11 @@ impl AppState { /// **429 的那一跳也要读**:额度用完时上游回的正是 429,只读成功那一跳的话, /// 「用完了」这件事永远看不到。 pub(crate) fn note_quota(&self, id: u64, provider: &str, headers: &reqwest::header::HeaderMap) { - self.record_quota(id, provider, crate::quota::from_headers_reqwest(headers)); + self.record_quota( + id, + provider, + crate::quota::from_headers_reqwest(headers, now_ms()), + ); } /// 记下一份额度。**账号接口问来的也走这里**:额度只在内存里,冷启动之后要等第一次 @@ -712,7 +725,7 @@ impl AppState { .map(|w| tw_api::QuotaWindow { window: w.window.clone(), used_percent: w.used_percent, - reset_in_secs: w.reset_in_secs, + resets_at_ms: w.resets_at_ms, status: w.status.clone(), }) .collect(), @@ -738,7 +751,7 @@ impl AppState { id: self.bus.next_id(), provider: provider.to_string(), window: w.window.clone(), - reset_in_secs: w.reset_in_secs, + resets_at_ms: w.resets_at_ms, at_ms: now_ms(), }); } @@ -909,6 +922,22 @@ impl AppState { self.quotas.lock().map(|g| g.clone()).unwrap_or_default() } + /// 这一家的凭据正被拒绝的话,它回的状态码(见 [`AppState::note_auth`])。 + pub fn auth_rejected(&self, provider: &str) -> Option { + self.rejected + .lock() + .ok() + .and_then(|g| g.get(provider).copied()) + } + + /// 这个代理被发现不通的话,检出来的样子(见 [`AppState::check_proxy`])。 + pub fn proxy_fault(&self, proxy: &str) -> Option { + self.proxies + .lock() + .ok() + .and_then(|g| g.get(proxy).and_then(|st| st.fault.clone())) + } + /// 换一份配置进去(第 ④⑤ 步)。 /// /// **建不起来就什么都不换。**校验已经在 `tw_config::reload` 里做过 diff --git a/crates/tw-gateway/tests/chatgpt.rs b/crates/tw-gateway/tests/chatgpt.rs index c217269c..be5655d7 100644 --- a/crates/tw-gateway/tests/chatgpt.rs +++ b/crates/tw-gateway/tests/chatgpt.rs @@ -602,13 +602,18 @@ async fn an_exhausted_window_is_reported_once_and_the_429_reaches_the_client() { .filter_map(|e| match e { tw_api::Event::QuotaExhausted { window, - reset_in_secs, + resets_at_ms, + at_ms, .. - } => Some((window, reset_in_secs)), + } => Some((window, resets_at_ms.map(|r| r.saturating_sub(at_ms)))), _ => None, }) .collect(); - assert_eq!(exhausted, vec![("weekly".to_string(), Some(3600))]); + // 重置的是一个时刻:收到 429 的那一刻往后一小时 + assert_eq!(exhausted.len(), 1, "{exhausted:?}"); + assert_eq!(exhausted[0].0, "weekly"); + let ahead = exhausted[0].1.expect("没有重置时刻"); + assert!((3_590_000..=3_600_000).contains(&ahead), "{ahead}"); } #[tokio::test] diff --git a/crates/tw-gateway/tests/notices.rs b/crates/tw-gateway/tests/notices.rs index b92c71ab..3d0081bb 100644 --- a/crates/tw-gateway/tests/notices.rs +++ b/crates/tw-gateway/tests/notices.rs @@ -127,16 +127,24 @@ fn config(p: Provider) -> Config { } } -async fn serve(cfg: Config) -> (SocketAddr, tokio::sync::broadcast::Receiver) { +/// 起一个网关。**状态也交出来**:变化靠事件,现状要从它上面读 +async fn serve( + cfg: Config, +) -> ( + SocketAddr, + tokio::sync::broadcast::Receiver, + tw_gateway::AppState, +) { let state = tw_gateway::AppState::new(cfg).unwrap(); let rx = state.bus.subscribe(); + let kept = state.clone(); let addr = { let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); l.local_addr().unwrap() }; tokio::spawn(async move { tw_gateway::serve(state, addr).await.unwrap() }); tokio::time::sleep(Duration::from_millis(60)).await; - (addr, rx) + (addr, rx, kept) } async fn ask(gw: SocketAddr) -> u16 { @@ -191,7 +199,7 @@ async fn next_change( #[tokio::test] async fn an_upstream_that_rejects_the_credential_is_reported_once_and_again_when_it_recovers() { let up = upstream(2).await; - let (gw, mut rx) = serve(config(Provider { + let (gw, mut rx, st) = serve(config(Provider { name: "relay".into(), base_url: format!("http://{up}"), key: Some(tw_config::Secret::new("sk-stale")), @@ -201,6 +209,8 @@ async fn an_upstream_that_rejects_the_credential_is_reported_once_and_again_when assert_eq!(ask(gw).await, 401); assert_eq!(next_change(&mut rx, "auth").await.0, "rejected"); + // **现状也要问得到**:界面晚打开就错过了那条事件,概览靠的是它 + assert_eq!(st.auth_rejected("relay"), Some(401)); // 第二次还是 401:**同一件事不再说第二遍** assert_eq!(ask(gw).await, 401); // 凭据又被接受了 @@ -210,6 +220,7 @@ async fn an_upstream_that_rejects_the_credential_is_reported_once_and_again_when (state.as_str(), provider.as_deref()), ("accepted", Some("relay")) ); + assert_eq!(st.auth_rejected("relay"), None); } #[tokio::test] @@ -230,18 +241,23 @@ async fn a_dead_proxy_is_named_as_the_cause_and_reported_again_when_it_comes_bac addr: px.to_string(), auth: None, }]; - let (gw, mut rx) = serve(cfg).await; + let (gw, mut rx, st) = serve(cfg).await; // 代理连上就断:请求失败,而失败的是代理不是上游 assert_ne!(ask(gw).await, 200); let (state, code) = next_change(&mut rx, "proxy").await; assert_eq!(state, "unreachable"); assert!( - code.is_some_and(|c| c.starts_with("l1.")), + code.as_ref().is_some_and(|c| c.starts_with("l1.")), "要说清卡在哪一步" ); + // **现状和事件说的是同一件事**:界面晚打开时读的是这一份 + let fault = st.proxy_fault("代理一").expect("不通的代理,现状里没有"); + assert_eq!(Some(fault.detail.code), code); + assert!(fault.failed.is_some(), "要说清卡在哪一步"); broken.store(false, Ordering::SeqCst); assert_eq!(ask(gw).await, 200); assert_eq!(next_change(&mut rx, "proxy").await.0, "reachable"); + assert!(st.proxy_fault("代理一").is_none(), "通了,现状还说不通"); } diff --git a/crates/tw-gateway/tests/passthrough.rs b/crates/tw-gateway/tests/passthrough.rs index 2b6dfcdf..85fe3951 100644 --- a/crates/tw-gateway/tests/passthrough.rs +++ b/crates/tw-gateway/tests/passthrough.rs @@ -2297,3 +2297,64 @@ async fn writing_billing_in_the_config_removes_the_first_request_ambiguity() { } panic!("没等到路由事件"); } + +/// 额度的重置是一个**时刻**。以前存的是「还有多少秒」,之后原样给出去 —— +/// 界面每次读到的都是收到响应那一刻的秒数,一个不会走的倒计时。 +#[tokio::test] +async fn a_quota_reset_is_kept_as_the_moment_it_happens() { + let up = { + let app = Router::new().fallback(axum::routing::any(|| async { + axum::response::Response::builder() + .header("content-type", "application/json") + .header("anthropic-ratelimit-unified-5h-utilization", "40") + .header("anthropic-ratelimit-unified-5h-reset", "7200") + .body(axum::body::Body::from(r#"{"id":"m"}"#)) + .unwrap() + })); + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let a = l.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(l, app).await.unwrap() }); + a + }; + let state = tw_gateway::AppState::new(cfg_with( + vec![Provider { + name: "订阅账号".into(), + base_url: format!("http://{up}"), + key: Some("k".into()), + ..Default::default() + }], + vec![], + )) + .unwrap(); + let kept = state.clone(); + let mut rx = state.bus.subscribe(); + let gw = { + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + l.local_addr().unwrap() + }; + tokio::spawn(async move { tw_gateway::serve(state, gw).await.unwrap() }); + tokio::time::sleep(Duration::from_millis(50)).await; + send_to(gw).await; + + let (resets_at, seen_at) = loop { + match tokio::time::timeout(Duration::from_secs(2), rx.recv()).await { + Ok(Ok(tw_api::Event::QuotaSeen { windows, at_ms, .. })) => { + break (windows[0].resets_at_ms, at_ms); + } + Ok(Ok(_)) => continue, + other => panic!("没等到额度事件:{other:?}"), + } + }; + let resets_at = resets_at.expect("上游说了多久重置,事件里却没有"); + // 收到响应的那一刻往后两小时。两个时刻各自取的钟,差几毫秒 + assert!( + (seen_at + 7_200_000 - 1_000..=seen_at + 7_200_000 + 1_000).contains(&resets_at), + "{resets_at} vs {seen_at}" + ); + // **存下来的是同一个时刻**:过一会儿再问,它不会变成「又是两小时」 + tokio::time::sleep(Duration::from_millis(20)).await; + assert_eq!( + kept.quotas()["订阅账号"].windows[0].resets_at_ms, + Some(resets_at) + ); +} diff --git a/crates/tw-store/src/recorder.rs b/crates/tw-store/src/recorder.rs index 861288d2..84ade57f 100644 --- a/crates/tw-store/src/recorder.rs +++ b/crates/tw-store/src/recorder.rs @@ -131,6 +131,46 @@ impl Recorder { &self.db } + /// 一个还在跑的请求到目前为止的样子。 + /// + /// **记录要等结局才落库**,而详情里最常被点开的,恰恰是那个跑了很久还没 + /// 结束的请求。这里给已经知道的那些:身份和上游、响应头到了就有状态码、 + /// 路由走完就有尝试链;耗时、用量、金额要等结局。不在跑(已经落库、或者 + /// 根本没有这个号)是 None。 + pub fn in_flight_row(&self, id: u64) -> Option { + let p = self.inflight.get(&id)?; + Some(RequestRow { + id: id as i64, + at_ms: p.at_ms, + client: p.client.clone(), + client_hint: p.client_hint.clone(), + peer: p.peer.clone(), + key_masked: p.key_masked.clone(), + session: p.session.clone(), + provider: p.provider.clone(), + model: p.model.clone(), + path: p.path.clone(), + status: p.status, + ttfb_ms: p.ttfb_ms, + duration_ms: None, + bytes: None, + input_tokens: None, + output_tokens: None, + cache_read_tokens: None, + cache_write_tokens: None, + cost_micros: None, + cost_estimated: false, + error: None, + local: false, + cancelled: false, + routing: p.routing.clone(), + billing: p.billing.clone(), + cache_saved_micros: None, + price_source: None, + translated: p.translated.clone(), + }) + } + pub fn blobs(&self) -> &Blobs { &self.blobs } @@ -468,7 +508,9 @@ impl Recorder { | Event::AuthChanged { .. } | Event::ListenChanged { .. } // 自己刚报出去的那条。**不能再处理一遍** —— 那是一个回路 - | Event::RequestPriced { .. } => {} + | Event::RequestPriced { .. } + // 只发给事件流上掉队的那一个订阅者,从不进总线 + | Event::EventsDropped { .. } => {} } }