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
32 changes: 31 additions & 1 deletion crates/tw-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2647,12 +2647,20 @@ pub struct CostBucket {
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct CostBucketGroup {
pub at_ms: i64,
/// 模型名或上游名,看查的是哪一维
/// 模型名、上游名或密钥名,看查的是哪一维
pub name: String,
pub requests: i64,
pub failed: i64,
pub cost_micros_exact: i64,
pub cost_micros_estimated: i64,
/// 这一格里这一项有几条请求的模型不在价目表里(用量是有的),见
/// `Summary::unpriced_requests`。
///
/// **每一项自己带着。**这一项的金额是 0 时,要分得清「没有价格」和「确实
/// 没花钱」—— 只有整格的数的话,说不出缺着钱的是哪一项。
pub unpriced_requests: i64,
/// 这一格里这一项有几条请求没有拿到用量,见 `Summary::no_usage_requests`
pub no_usage_requests: i64,
/// 这一格里这一项用掉的 token。
///
/// **四类分开给。**它们的单价差十倍以上,加成一个数之后既算不回
Expand Down Expand Up @@ -3596,6 +3604,28 @@ pub struct SecurityEventView {
pub struct SecurityEventsPage {
pub events: Vec<SecurityEventView>,
pub more: bool,
/// 这一段时间里、按这一项筛出来的一共几条 —— **整段的,不只是这一页**。
///
/// `before` 是翻页的位置,不是筛选:翻到第几页,这个数都一样。页头的
/// 「N 次命中」是它;拿读到的条数去数,读满一页就只能写「100+」
pub total: i64,
/// `total` 里各做了什么。四项加起来就是 `total`
pub by_outcome: SecurityOutcomeCounts,
}

/// 一段安全日志里,每一种做法各几条(见 [`SecurityOutcome`])。没有的是 0,
/// 四项都在。
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct SecurityOutcomeCounts {
/// 只记录
pub recorded: i64,
/// 已替换成占位符
pub replaced: i64,
/// 已切断
pub cut: i64,
/// 请求被拒,没有发出去
pub blocked: i64,
}

/// 一条内置规则按什么认。**给界面说明用**,界面按类型写成自己的话。
Expand Down
4 changes: 2 additions & 2 deletions crates/tw-control/src/security.rs
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,7 @@ async fn events(
let g = store.lock().await;
// **缺省是「全部」,不是「今天」。**这是一张列表,「最近 N 条」本身就是
// 一个完整的回答
let (events, more) = g
let page = g
.db()
.security_events(
guard,
Expand All @@ -356,7 +356,7 @@ async fn events(
q.limit.unwrap_or(100).clamp(1, PAGE_MAX),
)
.map_err(crate::records)?;
Ok(Json(tw_api::SecurityEventsPage { events, more }))
Ok(Json(page))
}

// ---------------------------------------------------------------- 写
Expand Down
59 changes: 58 additions & 1 deletion crates/tw-control/tests/security.rs
Original file line number Diff line number Diff line change
Expand Up @@ -649,6 +649,12 @@ async fn the_log_pages_backwards_and_names_the_upstream_that_served_the_request(
let events = v["events"].as_array().unwrap();
assert_eq!(events.len(), 2);
assert_eq!(v["more"], true);
// 页头的数是整段的,不是这一页的
assert_eq!(v["total"], 3, "{v}");
assert_eq!(
v["by_outcome"],
json!({ "recorded": 1, "replaced": 1, "cut": 1, "blocked": 0 })
);
assert_eq!(events[0]["rule"], "jwt", "倒序:新的在前");
assert_eq!(events[0]["provider"], "首选");
assert_eq!(
Expand All @@ -675,8 +681,9 @@ async fn the_log_pages_backwards_and_names_the_upstream_that_served_the_request(
.await;
assert_eq!(v["events"].as_array().unwrap().len(), 1);
assert_eq!(v["more"], false);
assert_eq!(v["total"], 3, "翻页不是筛选,总数不该变:{v}");

// 按类型、按时间段筛
// 按类型、按时间段筛:总数跟着一起筛
let (_, v) = call(
&b.app,
"GET",
Expand All @@ -687,6 +694,11 @@ async fn the_log_pages_backwards_and_names_the_upstream_that_served_the_request(
let only = v["events"].as_array().unwrap();
assert_eq!(only.len(), 1, "{v}");
assert_eq!(only[0]["rule"], "jwt");
assert_eq!(v["total"], 1);
assert_eq!(
v["by_outcome"],
json!({ "recorded": 0, "replaced": 1, "cut": 0, "blocked": 0 })
);

// 概览上的计数和日志数的是同一批
let (_, v) = call(
Expand All @@ -708,6 +720,51 @@ async fn the_log_pages_backwards_and_names_the_upstream_that_served_the_request(
assert_eq!(v[0]["security"].as_array().unwrap().len(), 2, "{v}");
}

/// 比一页多的时候,页头照样说得出一共几条(以前只能写「100+」);一条都
/// 没有的一段,四项都在、都是 0。
#[tokio::test]
async fn the_log_counts_past_one_page_and_an_empty_window_counts_zero() {
let b = bed_with(BASE, |db| {
for i in 0..150 {
let (guard, action) = match i % 3 {
0 => ("redact", "recorded"),
1 => ("redact", "replaced"),
_ => ("inspect_tools", "cut"),
};
db.insert_security_event(&event(i, 1_000 + i, guard, "r", action))
.unwrap();
}
});
// 不给条数是一页 100 条
let (st, v) = call(&b.app, "GET", "/security/events", serde_json::Value::Null).await;
assert_eq!(st, StatusCode::OK, "{v}");
assert_eq!(v["events"].as_array().unwrap().len(), 100);
assert_eq!(v["more"], true);
assert_eq!(v["total"], 150);
assert_eq!(
v["by_outcome"],
json!({ "recorded": 50, "replaced": 50, "cut": 50, "blocked": 0 })
);

let (st, v) = call(
&b.app,
"GET",
"/security/events?from_ms=5000&to_ms=6000",
serde_json::Value::Null,
)
.await;
assert_eq!(st, StatusCode::OK, "{v}");
assert_eq!(
v,
json!({
"events": [],
"more": false,
"total": 0,
"by_outcome": { "recorded": 0, "replaced": 0, "cut": 0, "blocked": 0 },
})
);
}

// ─────────────────────────────────────────────────────────── 藏匿字符、内容过滤、输出长度

#[tokio::test]
Expand Down
147 changes: 147 additions & 0 deletions crates/tw-control/tests/summary.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
//! 汇总端点的形状。
//!
//! 各种请求怎么数在 tw-store 里测;这里盯的是**界面拿到的那份 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\nlisten:\n control:\n key: c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00\nclients:\n - name: 我\n key: tw-一把钥匙就够\nproviders:\n - name: 官方\n base_url: https://api.anthropic.com\n key: sk-x\n";

/// 一条有用量、有价格的请求。
fn req(id: i64, model: &str) -> tw_store::db::RequestRow {
tw_store::db::RequestRow {
key_masked: None,
peer: None,
id,
at_ms: 1000 + id,
client: "我".into(),
client_hint: None,
session: None,
provider: "官方".into(),
model: model.into(),
path: "/v1/messages".into(),
status: Some(200),
ttfb_ms: Some(100),
duration_ms: Some(200),
bytes: Some(10),
input_tokens: Some(50),
output_tokens: Some(20),
cache_read_tokens: None,
cache_write_tokens: None,
cost_micros: Some(1_000),
cost_estimated: false,
error: None,
local: false,
cancelled: false,
routing: None,
billing: tw_api::Billing::PerToken,
cache_saved_micros: None,
price_source: None,
translated: None,
}
}

fn app(rows: &[tw_store::db::RequestRow]) -> (tempfile::TempDir, axum::Router) {
let d = tempfile::tempdir().unwrap();
let p = d.path().join("config.yaml");
std::fs::write(&p, BASE).unwrap();
let db = tw_store::Db::open(&d.path().join("data.db")).unwrap();
for r in rows {
db.insert(r).unwrap();
}
let rec = tw_store::Recorder::new(
db,
tw_store::Blobs::new(d.path().join("blobs")),
tw_pricing::shared(tw_pricing::PriceBook::builtin().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 {
shutdown: Default::default(),
remote: Default::default(),
cfg: Arc::new(ConfigManager::new(p, gw.clone(), bus)),
gateway: gw,
store: Some(Arc::new(tokio::sync::Mutex::new(rec))),
started: std::time::Instant::now(),
price_updater: Default::default(),
chatgpt: Default::default(),
zai: Default::default(),
};
(d, tw_control::router(state))
}

async fn get(app: &axum::Router, path: &str) -> serde_json::Value {
let r = app
.clone()
.oneshot(Request::builder().uri(path).body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(r.status(), StatusCode::OK, "{path}");
let b = axum::body::to_bytes(r.into_body(), 1 << 20).await.unwrap();
serde_json::from_slice(&b).unwrap()
}

/// 趋势图的每一格、每一项都带着「没有价格」和「没有用量」的条数。
///
/// 金额是 0 的那一项,界面要分得清是价目表里没有它、上游没报用量,还是确实
/// 没花钱 —— 以前只有整格的数,只能笼统地说「这一格少算了」。
#[tokio::test]
async fn every_group_in_the_trend_says_how_much_of_its_money_is_missing() {
let mut unknown = req(2, "中转站自己起的名字");
unknown.cost_micros = None;
let mut silent = req(3, "claude-sonnet-4-5");
silent.input_tokens = None;
silent.output_tokens = None;
silent.cost_micros = None;
let (_d, app) = app(&[req(1, "claude-sonnet-4-5"), unknown, silent]);

let v = get(
&app,
"/summary/buckets/by?from_ms=0&to_ms=10000&bucket_ms=10000&dim=model",
)
.await;
let groups = v.as_array().unwrap();
assert_eq!(groups.len(), 2, "{v}");
let group = |name: &str| {
groups
.iter()
.find(|g| g["name"] == name)
.unwrap_or_else(|| panic!("没有「{name}」这一项:{v}"))
};
let sonnet = group("claude-sonnet-4-5");
assert_eq!(sonnet["requests"], 2);
assert_eq!(sonnet["cost_micros_exact"], 1_000);
assert_eq!(sonnet["unpriced_requests"], 0, "{sonnet}");
assert_eq!(sonnet["no_usage_requests"], 1, "{sonnet}");
// 金额是 0,但不是免费的:价目表里没有它
let unknown = group("中转站自己起的名字");
assert_eq!(unknown["cost_micros_exact"], 0);
assert_eq!(unknown["unpriced_requests"], 1, "{unknown}");
assert_eq!(unknown["no_usage_requests"], 0, "{unknown}");

// 按上游、按密钥分也一样带着;这三条同一家、同一把,合成一项
for dim in ["provider", "client"] {
let v = get(
&app,
&format!("/summary/buckets/by?from_ms=0&to_ms=10000&bucket_ms=10000&dim={dim}"),
)
.await;
assert_eq!(v.as_array().unwrap().len(), 1, "{dim}: {v}");
assert_eq!(v[0]["unpriced_requests"], 1, "{dim}: {v}");
assert_eq!(v[0]["no_usage_requests"], 1, "{dim}: {v}");
}

// 一条都没有的一段:没有组
let v = get(
&app,
"/summary/buckets/by?from_ms=20000&to_ms=30000&bucket_ms=10000&dim=model",
)
.await;
assert_eq!(v, serde_json::json!([]));
}
Loading
Loading