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
9 changes: 9 additions & 0 deletions crates/tw-control/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ pub fn router(state: ControlState) -> Router {
.route("/interfaces", get(interfaces))
.merge(keys::router())
.route("/events", get(events))
.route("/in-flight", get(in_flight))
.route("/overview", get(overview))
.route("/l1", post(l1))
.route(
Expand Down Expand Up @@ -189,6 +190,14 @@ async fn events(
Sse::new(stream).keep_alive(KeepAlive::new().interval(std::time::Duration::from_secs(15)))
}

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

fn async_stream_from(
mut rx: broadcast::Receiver<tw_api::Event>,
) -> impl Stream<Item = Result<SseEvent, std::convert::Infallible>> {
Expand Down
91 changes: 91 additions & 0 deletions crates/tw-control/tests/in_flight.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
//! `/in-flight`:此刻还在跑的请求。
//!
//! 半路才来听事件流的一方拿它补上漏掉的开始事件。这里盯的是**界面拿到的
//! 那份 JSON**:和事件流里的开始事件同一个形状,有了结局的不在里面。

use std::sync::Arc;

use axum::body::Body;
use axum::http::{Request, StatusCode};
use tower::ServiceExt;
use tw_control::{ConfigManager, ControlState};

const BASE: &str = "version: 1\nclients:\n - name: 我\n key: tw-一把钥匙就够\nproviders:\n - name: 官方\n base_url: https://api.anthropic.com\n key: sk-x\n";

fn app() -> (tempfile::TempDir, tw_observe::EventBus, axum::Router) {
let d = tempfile::tempdir().unwrap();
let p = d.path().join("config.yaml");
std::fs::write(&p, BASE).unwrap();
let cfg: tw_config::Config = serde_yaml_ng::from_str(BASE).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.clone())),
gateway: gw,
gateway_addr: None,
store: None,
started: std::time::Instant::now(),
price_updater: Default::default(),
chatgpt: Default::default(),
home: d.path().join("home"),
};
(d, bus, tw_control::router(state))
}

fn started(id: u64, model: &str) -> tw_api::Event {
tw_api::Event::RequestStarted {
id,
client: "我".into(),
client_hint: Some("claude-code".into()),
session_fp: None,
provider: "官方".into(),
model: model.into(),
method: "POST".into(),
path: "/v1/messages".into(),
at_ms: 1_000 + id,
}
}

async fn get(router: axum::Router) -> Vec<serde_json::Value> {
let resp = router
.oneshot(Request::get("/in-flight").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();
serde_json::from_slice(&body).unwrap()
}

/// 开始了没结束的在里面,结束了的不在;每一条都是一个完整的开始事件。
#[tokio::test]
async fn it_lists_the_start_of_every_request_that_has_not_ended() {
let (_d, bus, router) = app();
bus.emit(started(1, "claude-sonnet-5"));
bus.emit(started(2, "gpt-5.5"));
bus.emit(tw_api::Event::RequestFinished {
id: 1,
model: "claude-sonnet-5".into(),
status: 200,
bytes: 10,
duration_ms: 5,
usage: None,
});

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);
}

/// 什么都没在跑:一个空数组,不是 404,也不是 null。
#[tokio::test]
async fn nothing_running_is_an_empty_list() {
let (_d, _bus, router) = app();
assert!(get(router).await.is_empty());
}
39 changes: 37 additions & 2 deletions crates/tw-gateway/tests/endings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,15 +200,22 @@ fn cfg(provider: Provider) -> Config {
/// 起一个网关,**先订阅事件再起服务** —— 之后才订的话,早到的事件就
/// 看不见了。
async fn serve(cfg: Config) -> (SocketAddr, Receiver<Event>) {
let (addr, events, _) = serve_with_bus(cfg).await;
(addr, events)
}

/// 同上,再把总线交出来 —— 要看「此刻还在跑的」那份快照时用。
async fn serve_with_bus(cfg: Config) -> (SocketAddr, Receiver<Event>, tw_observe::EventBus) {
let state = tw_gateway::AppState::new(cfg).unwrap();
let events = state.bus.subscribe();
let bus = state.bus.clone();
let events = bus.subscribe();
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(50)).await;
(addr, events)
(addr, events, bus)
}

fn post(gw: SocketAddr) -> reqwest::RequestBuilder {
Expand Down Expand Up @@ -325,6 +332,34 @@ async fn a_client_that_walks_away_mid_stream_is_reported_once_as_cancelled() {
assert_eq!(model_of(&got[0]), MODEL);
}

/// 流还开着的时候,这个请求在「此刻还在跑的」快照里;结局一报,它就不在了。
///
/// **半路才来听事件流的一方靠这份快照数「进行中」**(桌面版的实时档每次
/// 打开都是这样),而它只有在每一种结局都划掉那一笔时才是对的 —— 漏掉一
/// 种,那个请求就永远「进行中」。
#[tokio::test]
async fn a_request_is_in_flight_until_its_ending_and_not_after() {
let (gw, mut events, bus) = serve_with_bus(cfg(provider(slow_stream_upstream().await))).await;

let resp = post(gw).send().await.unwrap();
let mut body = resp.bytes_stream();
body.next().await.unwrap().unwrap();
let open = bus.in_flight();
assert!(
matches!(open.as_slice(), [Event::RequestStarted { model, .. }] if model == MODEL),
"第一帧到了、流还开着,它该在快照里:{open:?}"
);

drop(body);
let got = endings(&mut events).await;
assert_eq!(got.len(), 1, "该恰好有一个结局:{got:?}");
assert!(
bus.in_flight().is_empty(),
"结局报了,快照里还挂着:{:?}",
bus.in_flight()
);
}

/// 上游中途断了:**报失败,不报取消**。网关随后往客户端补的那个错误帧,
/// 在它发出去之前结局就已经报过了。
#[tokio::test]
Expand Down
134 changes: 133 additions & 1 deletion crates/tw-observe/src/bus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@
//! 注意这条豁免**不适用于成本记账**:那类数据丢了账单永久对不
//! 上,必须走别的路径。这里只走「丢了只是图上少个点」的东西。

use std::sync::Arc;
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};

use tokio::sync::broadcast;

Expand All @@ -19,6 +20,8 @@ const CAPACITY: usize = 1024;
pub struct EventBus {
tx: broadcast::Sender<tw_api::Event>,
next_id: Arc<AtomicU64>,
/// 开始了、还没有结局的请求:它们的开始事件,按 id。见 [`EventBus::in_flight`]
open: Arc<Mutex<BTreeMap<u64, tw_api::Event>>>,
}

impl Default for EventBus {
Expand All @@ -33,6 +36,7 @@ impl EventBus {
Self {
tx,
next_id: Arc::new(AtomicU64::new(1)),
open: Arc::default(),
}
}

Expand Down Expand Up @@ -64,10 +68,57 @@ impl EventBus {
}

/// 发一条。**没有订阅者不是错误** —— 没开 UI 的时候数据面照常跑。
///
/// **先记账再发**(见 [`EventBus::in_flight`]):订阅者收到一个结局的
/// 时候,快照里已经没有它了。
pub fn emit(&self, ev: tw_api::Event) {
self.track(&ev);
let _ = self.tx.send(ev);
}

/// 开始的记下,有了结局的划掉。
///
/// **这里什么都不能 panic。**`Ending` 在 Drop 里也会走到这儿,那时可能
/// 正处在一次 unwind 里 —— 再 panic 一次,整个进程就没了。锁中毒了也照样
/// 拿里面的表:少记一笔的快照,好过一个没了的网关。
fn track(&self, ev: &tw_api::Event) {
use tw_api::Event as E;
let mut open = self.open.lock().unwrap_or_else(|p| p.into_inner());
match ev {
E::RequestStarted { id, .. } => {
open.insert(*id, ev.clone());
}
E::RequestFinished { id, .. }
| E::RequestFailed { id, .. }
| E::RequestCancelled { id, .. } => {
open.remove(id);
}
_ => {}
}
}

/// 此刻还在跑的请求:它们的开始事件,**原样**,按 id 从小到大。
///
/// 给**半路才来听的一方**用。事件流只送订阅之后发生的事,一个在那之前
/// 就开始、此刻还没结束的请求,它的开始事件早就发过了 —— 听的人数
/// 「进行中」时就漏掉它,直到它结束。桌面版概览的实时档每次打开都是
/// 这样。把这份快照当成补发的开始事件处理,就和从头听起一样。
///
/// **和 `Status::in_flight` 不是一个数。**那个从连接进到数据面就算,比
/// 开始事件早,排队等名额的、鉴权没过的都在里面 —— 它回答的是「现在
/// 重启会掐断几个连接」。这里只有发过开始事件的请求,和事件流里说的是
/// 同一批。
///
/// 表不会只进不出:每个开始事件都欠着恰好一个结局,由 `Ending` 保证。
pub fn in_flight(&self) -> Vec<tw_api::Event> {
self.open
.lock()
.unwrap_or_else(|p| p.into_inner())
.values()
.cloned()
.collect()
}

pub fn subscribe(&self) -> broadcast::Receiver<tw_api::Event> {
self.tx.subscribe()
}
Expand All @@ -81,6 +132,87 @@ impl EventBus {
mod tests {
use super::*;

fn started(id: u64) -> tw_api::Event {
tw_api::Event::RequestStarted {
id,
client: "c".into(),
client_hint: None,
session_fp: None,
provider: "p".into(),
model: "m".into(),
method: "POST".into(),
path: "/v1/messages".into(),
at_ms: 1_000 + id,
}
}

/// 快照里是**开始了、还没有结局**的那些。三种结局都算结局,响应头不算。
#[test]
fn in_flight_is_what_started_and_has_not_ended() {
let b = EventBus::new();
for id in 1..=4 {
b.emit(started(id));
}
b.emit(tw_api::Event::RequestFinished {
id: 1,
model: "m".into(),
status: 200,
bytes: 0,
duration_ms: 0,
usage: None,
});
b.emit(tw_api::Event::RequestFailed {
id: 2,
model: "m".into(),
source: "upstream".into(),
message: tw_api::Msg {
code: "t.x".into(),
args: Default::default(),
text: "x".into(),
},
bytes: None,
duration_ms: None,
usage: None,
});
b.emit(tw_api::Event::RequestCancelled {
id: 3,
model: "m".into(),
status: None,
bytes: 0,
duration_ms: 0,
usage: None,
});
b.emit(tw_api::Event::RequestHeaders {
id: 4,
status: 200,
ttfb_ms: 5,
});

let open = b.in_flight();
assert_eq!(open.iter().map(|e| e.id()).collect::<Vec<_>>(), [4]);
// **原样**:听的人拿它当补发的开始事件,字段一个都不能少
assert!(
matches!(&open[0], tw_api::Event::RequestStarted { model, at_ms: 1004, .. } if model == "m"),
"{open:?}"
);
}

/// 没有订阅者的时候照样记 —— 这份快照就是给还没来的订阅者准备的。
/// 按 id 排,也就是按开始的先后。
#[test]
fn in_flight_is_kept_with_no_subscriber_and_in_start_order() {
let b = EventBus::new();
assert!(b.in_flight().is_empty());
for id in [7, 3, 5] {
b.emit(started(id));
}
assert_eq!(b.subscriber_count(), 0);
assert_eq!(
b.in_flight().iter().map(|e| e.id()).collect::<Vec<_>>(),
[3, 5, 7]
);
}

#[test]
fn ids_resume_after_the_number_the_store_already_has() {
let b = EventBus::new();
Expand Down
Loading