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
5 changes: 5 additions & 0 deletions bin/twcore/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1084,6 +1084,11 @@ fn build_store(
tw_gateway::bodies::BodyKind::Request => tw_store::Which::Request,
tw_gateway::bodies::BodyKind::Response => tw_store::Which::Response,
tw_gateway::bodies::BodyKind::AfterPlugins => tw_store::Which::AfterPlugins,
tw_gateway::bodies::BodyKind::UpstreamRequest => {
tw_store::Which::UpstreamRequest
}
tw_gateway::bodies::BodyKind::ClientResponse => tw_store::Which::ClientResponse,
tw_gateway::bodies::BodyKind::Heads => tw_store::Which::Heads,
},
body,
original_len,
Expand Down
3 changes: 2 additions & 1 deletion crates/tw-api/src/endpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ pub enum Format {
Json,
/// 一段纯文本,`Res` 是 `String`(诊断包、回放用例)
Text,
/// Server-Sent Events,每条 `data:` 是一个 `Res` 的 JSON。连着不断
/// Server-Sent Events,每条 `data:` 是一个 `Res` 的 JSON。连着不断。`Res` 是几种之一的
/// ([`LiveContent`](crate::LiveContent))每条另带 `event:`,说是哪一种
Events,
}

Expand Down
6 changes: 6 additions & 0 deletions crates/tw-api/src/ep.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ endpoints! {
HistorySearch: POST "/history/search", api::HistorySearchQuery => api::HistorySearchPage;
Latency: GET "/latency", api::Window => Vec<api::LatencyView>;
LatencyByProvider: GET "/latency/provider", api::Window => Vec<api::LatencyView>;
/// 首 token 的分位数,按密钥(谁在用、谁等得久)
LatencyByClient: GET "/latency/client", api::Window => Vec<api::LatencyView>;
/// 生成速度的中位数,按模型、按上游
TokenRate: GET "/token-rate", api::Window => Vec<api::TokenRateView>;
TokenRateByProvider: GET "/token-rate/provider", api::Window => Vec<api::TokenRateView>;
Expand All @@ -63,6 +65,10 @@ endpoints! {
/// 中止一个在跑的请求:和上游的连接断开,客户端收到错误,请求记成手动中止。已经
/// 结束了的是 404
AbortRequest: POST "/request/{id}/abort" [id], () => api::Aborted;
/// 一个在跑的请求的实时内容:报文头和正文,客户端那一边和每一跳上游那一边,先补发到
/// 目前为止有的,再接着发新来的,`end` 之后关闭(见 [`api::LiveContent`])。已经结束了的、
/// 从来没有过的、跑在 WebSocket 连接上的都是 404(`control.request_not_running`)
RequestLive: GET "/request/{id}/live" [id], () => api::LiveContent, events;
/// 把一条记录变成回放用例(YAML)
Fixture: GET "/request/{id}/fixture" [id], () => String, text;
Sessions: GET "/sessions", api::ListQuery => Vec<api::SessionView>;
Expand Down
525 changes: 505 additions & 20 deletions crates/tw-api/src/lib.rs

Large diffs are not rendered by default.

32 changes: 31 additions & 1 deletion crates/tw-api/src/ts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -508,9 +508,39 @@ mod tests {
assert!(res.contains(field), "{field}: {res}");
}
let log = decl_of(&ts, "SecurityEventView");
for field in ["match?: ContentMatch", "revealed?: string"] {
for field in [
"match?: ContentMatch",
"revealed?: string",
"session?: string",
"sent_model?: string",
"direction: SecurityDirection",
"locations: Array<HitLocation>",
"more_locations: number",
"rule_snapshot: RuleSnapshot",
"outcome_detail: OutcomeDetail",
] {
assert!(log.contains(field), "{field}: {log}");
}
assert_eq!(
decl_of(&ts, "HitPart"),
"export type HitPart = \"system\" | \"message\" | \"tool_result\" | \"tool_call\" | \"response_text\""
);
assert_eq!(
decl_of(&ts, "SecurityDirection"),
"export type SecurityDirection = \"request\" | \"response\""
);
let outcome = decl_of(&ts, "OutcomeDetail");
for shape in [
"{ \"action\": \"recorded\", }",
"{ \"action\": \"replaced\", placeholders: Array<string>, }",
"{ \"action\": \"stripped\", segments: number, }",
] {
assert!(outcome.contains(shape), "{shape}: {outcome}");
}
let at = decl_of(&ts, "HitLocation");
for field in ["part: HitPart", "message_index?: number", "path: string"] {
assert!(at.contains(field), "{field}: {at}");
}
let event = decl_of(&ts, "Event");
assert!(event.contains("outcome: ContentOutcome"), "{event}");
assert!(!event.contains("hidden_text_found") && !event.contains("output_limited"));
Expand Down
1 change: 1 addition & 0 deletions crates/tw-control/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ impl<E: Endpoint> Answer<E> for (StatusCode, Json<E::Res>) {}
impl<E: Endpoint<Res = String>> Answer<E> for String {}
impl<E: Endpoint<Res = String>> Answer<E> for Result<String, Fail> {}
impl<E: Endpoint<Res = tw_api::Event>, S> Answer<E> for Sse<S> {}
impl<E: Endpoint<Res = tw_api::LiveContent>, S> Answer<E> for Result<Sse<S>, Fail> {}

macro_rules! serves {
($($a:ident),*) => {
Expand Down
97 changes: 89 additions & 8 deletions crates/tw-control/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ pub fn router(state: ControlState) -> Router {
.at(ep::HistorySearch, history_search)
.at(ep::Latency, latency)
.at(ep::LatencyByProvider, latency_by_provider)
.at(ep::LatencyByClient, latency_by_client)
.at(ep::TokenRate, token_rate)
.at(ep::TokenRateByProvider, token_rate_by_provider)
.at(ep::UpstreamHealth, upstream_health)
Expand All @@ -127,6 +128,7 @@ pub fn router(state: ControlState) -> Router {
.at(ep::SpeedRun, speed_run)
.at(ep::RequestDetail, request_detail)
.at(ep::AbortRequest, abort_request)
.at(ep::RequestLive, request_live)
// 诊断包(脱敏纪律)。**只读,不写任何文件**
.at(ep::Diagnostics, diagnostics::bundle)
// 把一条真实请求变成回放用例。**录制不是新功能** ——
Expand Down Expand Up @@ -751,6 +753,8 @@ async fn summary(
output_tokens: x.output_tokens,
cache_read_tokens: x.cache_read_tokens,
cache_write_tokens: x.cache_write_tokens,
sent_bytes: x.sent_bytes,
received_bytes: x.received_bytes,
cost_micros_exact: x.cost_micros_exact,
cost_micros_estimated: x.cost_micros_estimated,
unpriced_requests: x.unpriced_requests,
Expand Down Expand Up @@ -1112,17 +1116,76 @@ async fn request_detail(
let by_plugins = plugins
.iter()
.any(|p| p.outcome == tw_api::PluginOutcome::Changed);
// 回答:交给客户端的和上游的原话不一样时各存了一份(`.client-res` 和 `.res`),一样的只有
// 上游那一份 —— 那就是客户端收到的
let (response_body, upstream_response_body) = match body(tw_store::Which::ClientResponse) {
Some(client) => (Some(client), body(tw_store::Which::Response)),
None => (body(tw_store::Which::Response), None),
};
let detail = tw_api::RequestDetail {
request_body: body(tw_store::Which::Request),
request_after_plugins: body(tw_store::Which::AfterPlugins),
response_body: body(tw_store::Which::Response),
response_body,
upstream_request_body: body(tw_store::Which::UpstreamRequest),
upstream_response_body,
heads: heads(g.blobs().get(at, id, tw_store::Which::Heads)),
plugins,
row: history_row(row, security, by_plugins),
in_flight,
};
Ok(Json(detail))
}

/// 存下来的报文头。落盘的那一份已经打过码,读出来再打一遍(和正文一样)。没有、读不懂的
/// 是空的
fn heads(raw: Option<Vec<u8>>) -> Vec<tw_api::HeadView> {
let Some(heads) = raw.and_then(|r| serde_json::from_slice::<Vec<tw_api::HeadView>>(&r).ok())
else {
return Vec::new();
};
heads
.into_iter()
.map(|h| tw_api::HeadView {
line: tw_secret::mask_body(&h.line),
headers: h
.headers
.into_iter()
.map(|(k, v)| (k, tw_secret::mask_body(&v)))
.collect(),
..h
})
.collect()
}

/// 一个在跑的请求的实时内容(见 `tw_gateway::content`):报文头和正文,先补发到目前为止
/// 有的,再接着发,`end` 之后关闭。**和别的端点同一道门**:本机的 socket、远程的控制端口都
/// 握过手才到这里。不在跑的(结束了、从没有过、跑在 WebSocket 上的)是 404
async fn request_live(
State(s): State<ControlState>,
axum::extract::Path(id): axum::extract::Path<u64>,
) -> Result<Sse<impl Stream<Item = Result<SseEvent, std::convert::Infallible>>>, Fail> {
let watch = s
.gateway
.contents
.watch(id)
.ok_or_else(|| not_running(id))?;
let stream = futures::stream::unfold(watch, |mut w| async move {
let ev = w.next().await?;
let data = serde_json::to_string(&ev).unwrap_or_default();
Some((Ok(SseEvent::default().event(ev.event()).data(data)), w))
});
// 心跳和事件流一样:一个等着上游的长请求,几分钟里可能一个字都没有
Ok(Sse::new(stream).keep_alive(KeepAlive::new().interval(std::time::Duration::from_secs(15))))
}

/// 请求 `id` 不在跑:结束了、从没有过,或者跑在 WebSocket 连接上
fn not_running(id: u64) -> Fail {
fail(
StatusCode::NOT_FOUND,
msg!("control.request_not_running", id = id => "Request {id} is not in progress."),
)
}

/// 订阅额度。**每个上游最近一次报的**。
///
/// 按量付费的账号没有这些头,那时这个列表是空的 —— 界面据此决定显示
Expand Down Expand Up @@ -1171,6 +1234,27 @@ async fn latency_by_provider(
))
}

/// 按密钥分的延迟:**谁在用、谁等得久**(概览上每把密钥一行)。样本的规矩和按模型分的一样
async fn latency_by_client(
State(s): State<ControlState>,
axum::extract::Query(q): axum::extract::Query<tw_api::Window>,
) -> Result<Json<Vec<tw_api::LatencyView>>, Fail> {
let (from, to) = range(q.from_ms, q.to_ms);
let store = need_store(&s)?;
let xs = on_store(store, move |g| g.db().latency_by_client(from, to)).await?;
Ok(Json(
xs.map_err(records)?
.into_iter()
.map(|l| tw_api::LatencyView {
model: l.model,
p50: l.p50,
p95: l.p95,
samples: l.samples,
})
.collect(),
))
}

/// 生成速度的中位数,按模型。**「哪个模型吐得快」**
async fn token_rate(
State(s): State<ControlState>,
Expand Down Expand Up @@ -1296,7 +1380,9 @@ fn history_row(
ttft_ms: r.ttft_ms,
duration_ms: r.duration_ms,
tokens_per_sec: r.tokens_per_sec,
bytes: r.bytes,
sent_bytes: r.sent_bytes,
received_bytes: r.received_bytes,
egress: r.egress,
input_tokens: r.input_tokens,
output_tokens: r.output_tokens,
cache_read_tokens: r.cache_read_tokens,
Expand Down Expand Up @@ -1721,12 +1807,7 @@ async fn abort_request(
State(s): State<ControlState>,
axum::extract::Path(id): axum::extract::Path<u64>,
) -> Result<Json<tw_api::Aborted>, Fail> {
s.gateway.aborts.request(id).map_err(|_| {
fail(
StatusCode::NOT_FOUND,
msg!("control.request_not_running", id = id => "Request {id} is not in progress."),
)
})?;
s.gateway.aborts.request(id).map_err(|_| not_running(id))?;
tracing::info!(id, "aborted a request over the control plane");
Ok(Json(tw_api::Aborted { requests: vec![id] }))
}
Expand Down
9 changes: 6 additions & 3 deletions crates/tw-control/src/replay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,10 @@ pub async fn run(

let status = resp.status().as_u16();
let ttfb_ms = started.elapsed().as_millis() as i64;
let text = resp.text().await.unwrap_or_default();
// 字节数照线上的数(HTTP 客户端不解压,见 `tw_gateway::traffic`),和原来那一次的
// `received_bytes` 同一个口径
let raw = resp.bytes().await.unwrap_or_default();
let text = String::from_utf8_lossy(&raw).into_owned();
let duration_ms = started.elapsed().as_millis() as i64;

// 回显还原之后再脱敏给人看。**两步都要**:还原是为了让内容和原来
Expand All @@ -338,15 +341,15 @@ pub async fn run(
status,
ttfb_ms,
duration_ms,
bytes: text.len() as i64,
bytes: raw.len() as i64,
body: tw_secret::mask_body(&restored.chars().take(20_000).collect::<String>()),
// 和原来那次并排比 —— 这是重放存在的理由
original: tw_api::ReplayOriginal {
provider: row.provider.clone(),
status: row.status,
ttfb_ms: row.ttfb_ms,
duration_ms: row.duration_ms,
bytes: row.bytes,
received_bytes: row.received_bytes,
},
}))
}
Expand Down
4 changes: 3 additions & 1 deletion crates/tw-control/tests/aliases.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,9 @@ fn row(id: i64, model: &str, ago_ms: i64, cost: Option<i64>) -> tw_store::db::Re
ttft_ms: None,
duration_ms: Some(200),
tokens_per_sec: None,
bytes: Some(10),
sent_bytes: Some(10),
received_bytes: Some(10),
egress: None,
input_tokens: Some(50),
output_tokens: Some(20),
cache_read_tokens: None,
Expand Down
4 changes: 3 additions & 1 deletion crates/tw-control/tests/bundle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,9 @@ async fn replaying_a_truncated_body_is_refused_rather_than_misleading() {
ttft_ms: None,
duration_ms: Some(200),
tokens_per_sec: None,
bytes: Some(10),
sent_bytes: Some(10),
received_bytes: Some(10),
egress: None,
input_tokens: Some(50),
output_tokens: Some(20),
cache_read_tokens: None,
Expand Down
3 changes: 3 additions & 0 deletions crates/tw-control/tests/error_answers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,9 @@ async fn world() -> World {
tw_gateway::bodies::BodyKind::Request => tw_store::Which::Request,
tw_gateway::bodies::BodyKind::Response => tw_store::Which::Response,
tw_gateway::bodies::BodyKind::AfterPlugins => tw_store::Which::AfterPlugins,
tw_gateway::bodies::BodyKind::UpstreamRequest => tw_store::Which::UpstreamRequest,
tw_gateway::bodies::BodyKind::ClientResponse => tw_store::Which::ClientResponse,
tw_gateway::bodies::BodyKind::Heads => tw_store::Which::Heads,
};
let stored = tw_store::StoredBody {
id: disk.id,
Expand Down
7 changes: 6 additions & 1 deletion crates/tw-control/tests/history_search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@ fn req(id: i64, client: &str) -> tw_store::db::RequestRow {
ttft_ms: Some(300),
duration_ms: Some(2000),
tokens_per_sec: Some(80),
bytes: Some(10),
sent_bytes: Some(10),
received_bytes: Some(10),
egress: None,
input_tokens: Some(50),
output_tokens: Some(20),
cache_read_tokens: None,
Expand Down Expand Up @@ -87,6 +89,9 @@ fn app(
count: 1,
matching: None,
revealed: None,
session: None,
sent_model: None,
detail: Default::default(),
})
.unwrap();
let rec = tw_store::Recorder::new(
Expand Down
8 changes: 6 additions & 2 deletions crates/tw-control/tests/in_flight.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,14 +100,17 @@ async fn it_gives_every_running_request_with_what_has_happened_to_it_so_far() {
usage: None,
queued_ms: None,
skipped: None,
proxy: None,
}],
billing: tw_api::Billing::PerToken,
egress: None,
});
bus.emit(tw_api::Event::RequestFinished {
id: 1,
model: "claude-sonnet-5".into(),
status: 200,
bytes: 10,
sent_bytes: 0,
received_bytes: 10,
duration_ms: 5,
usage: None,
tokens_per_sec: None,
Expand Down Expand Up @@ -185,7 +188,8 @@ async fn live_gives_the_running_requests_and_the_generation_rate() {
id: 1,
model: "claude-sonnet-5".into(),
status: 200,
bytes: 10,
sent_bytes: 0,
received_bytes: 10,
duration_ms: 3_000,
usage: Some(tw_api::UsageView {
output: 100,
Expand Down
9 changes: 7 additions & 2 deletions crates/tw-control/tests/key_limits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,14 +143,17 @@ fn request(id: u64, key: &str, at: i64, input: u64) -> Vec<Event> {
usage: None,
queued_ms: None,
skipped: None,
proxy: None,
}],
billing: tw_api::Billing::PerToken,
egress: None,
},
Event::RequestFinished {
id,
model: String::new(),
status: 200,
bytes: 1,
sent_bytes: 0,
received_bytes: 1,
duration_ms: 1,
usage: Some(tw_api::UsageView {
input,
Expand Down Expand Up @@ -420,7 +423,8 @@ fn refused(
args: Default::default(),
text: "refused".into(),
},
bytes: None,
sent_bytes: None,
received_bytes: None,
duration_ms: Some(1),
usage: None,
answered_model: None,
Expand All @@ -443,6 +447,7 @@ fn hop(outcome: tw_api::AttemptOutcome, code: &str, busy: bool) -> tw_api::Attem
usage: None,
queued_ms: None,
skipped: busy.then_some(tw_api::ServeSkip::Busy),
proxy: None,
}
}

Expand Down
Loading
Loading