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
38 changes: 29 additions & 9 deletions bin/twcore/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -782,7 +782,7 @@ fn cmd_serve(path: &Path, port: Option<u16>, safe: bool, parent: Option<u32>) ->
//
// body 的通道在这里建:**它是唯一同时看得见网关和存储的地方**,
// 而两边各有各的同形结构,是为了不让「观测」挂到「转发」下面。
let (body_tx, body_rx) = tokio::sync::mpsc::channel(tw_gateway::bodies::CHANNEL_CAP);
let (body_tx, body_rx) = tw_gateway::bodies::channel();
let store = build_store(&dir, state.bus.clone(), state.pricing.clone(), body_rx);
if store.is_some() {
state.set_body_sink(body_tx);
Expand Down Expand Up @@ -975,25 +975,45 @@ fn build_store(
"could not read the last request id, so this run may overwrite the oldest records: {e}"
),
}
// 两边的 body 结构在这里对接。**一次移动,不复制** —— `Bytes` 的
// 克隆是引用计数。
let (tx, rx) = tokio::sync::mpsc::channel(tw_gateway::bodies::CHANNEL_CAP);
/*
两边的 body 结构在这里对接,**落盘的不是原文**:脱敏规则认得出的值在这里换掉、
打码(`BodyRecord::for_disk`,见 `tw_gateway::bodies`)。放在阻塞线程上 ——
一份 4 MB 的正文要扫好几遍,占着异步线程的话,同一个线程上的转发都得等它。

交给存储层的这一头**只留一个空位**。等着落盘的正文由网关那一头按字节记账
(`bodies::QUEUED_MAX`),一份正文的额度要等存储层收下它才还回去;这里再开一个
大口子的话,攒在这里的那些就没人管了。
*/
let (tx, rx) = tokio::sync::mpsc::channel(1);
let mut bodies = bodies;
tokio::spawn(async move {
while let Some(b) = bodies.recv().await {
let Ok(disk) = tokio::task::spawn_blocking(move || b.for_disk()).await else {
continue;
};
let tw_gateway::bodies::ForDisk {
id,
at_ms,
kind,
body,
original_len,
held,
} = disk;
let mapped = tw_store::StoredBody {
id: b.id,
at_ms: b.at_ms,
which: match b.kind {
id,
at_ms,
which: match kind {
tw_gateway::bodies::BodyKind::Request => tw_store::Which::Request,
tw_gateway::bodies::BodyKind::Response => tw_store::Which::Response,
},
body: b.body,
original_len: b.original_len,
body,
original_len,
};
if tx.send(mapped).await.is_err() {
return;
}
// 存储层收下了:额度还回去
drop(held);
}
});
Some(tw_store::task::spawn(
Expand Down
15 changes: 12 additions & 3 deletions crates/tw-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1706,7 +1706,7 @@ pub struct RetentionView {
/// 正文总共最多占多少字节
pub body_max_bytes: u64,
/// 正文现在实际占了多少。**不是配置,是现状** —— 没有它,
/// 「2 GB 上限」是个用户无从判断松紧的数字
/// 「5 GB 上限」是个用户无从判断松紧的数字
pub body_bytes_now: u64,
}

Expand Down Expand Up @@ -3676,14 +3676,23 @@ pub struct RequestDetail {
pub in_flight: bool,
}

/// 一份正文最多存多少字节:请求和回答一样,4 MiB。更长的只存开头,[`BodyView::truncated`]
/// 说出来。
///
/// **存储层按它截,网关攒回答也按它攒**(`tw_store::blobs::MAX_ONE`、
/// `tw_gateway::bodies::RESPONSE_TAP_MAX`)。两个数放在一处:各写各的话,改了一个,
/// 另一个还停在原地 —— 以前回答只攒 256 KB,比存储层肯收的少十几倍。
pub const BODY_MAX: usize = 4 * 1024 * 1024;

/// 一份存下来的 body。
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct BodyView {
/// **已脱敏**。这段文字会被复制到 issue 里
/// **已脱敏**。这段文字会被复制到 issue 里。落盘的那一份就是换过、打过码的(脱敏规则
/// 认得出的值不会原样写进磁盘),读出来再打一遍
pub text: String,
/// 原本多长。**截断了要能说出来** —— 不说的话用户会以为请求本身
/// 就长这样
/// 就长这样。没截断的就是存下来的这一份的长度:换掉、打码的那几处和原文差几个字节
pub original_len: usize,
pub truncated: bool,
}
Expand Down
2 changes: 1 addition & 1 deletion crates/tw-config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1183,7 +1183,7 @@ mod tests {
assert_eq!(back.retention.body_days, 3);
// 没写的那两个仍然是默认值,不是 0 —— 0 会让 gc 把一切都删掉
assert_eq!(back.retention.row_days, 90);
assert_eq!(back.retention.body_max_bytes, 2 * 1024 * 1024 * 1024);
assert_eq!(back.retention.body_max_bytes, 5 * 1024 * 1024 * 1024);
assert!(
serde_yaml_ng::to_string(&back)
.unwrap()
Expand Down
4 changes: 2 additions & 2 deletions crates/tw-config/src/retention.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub struct Retention {
/// 一行记录留几天。它撑着「上个月花了多少」那类问题
#[serde(default = "d_row_days")]
pub row_days: u64,
/// 正文总共最多占多少字节。超了从最旧的整天开始删
/// 正文总共最多占多少字节。超了从最旧的整天开始删。出厂 5 GiB
#[serde(default = "d_body_max_bytes")]
pub body_max_bytes: u64,
}
Expand All @@ -33,7 +33,7 @@ fn d_row_days() -> u64 {
90
}
fn d_body_max_bytes() -> u64 {
2 * 1024 * 1024 * 1024
5 * 1024 * 1024 * 1024
}

impl Default for Retention {
Expand Down
6 changes: 3 additions & 3 deletions crates/tw-config/tests/manual/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1165,10 +1165,10 @@ pub fn sections() -> Vec<Section> {
row(
"body_max_bytes",
Kind::Int,
Def::Is("2147483648"),
Def::Is("5368709120"),
t(
"Upper bound on the bytes bodies may take; beyond it the oldest days go first. The default is 2 GiB.",
"正文最多占用的字节数,超出时从最早的日期开始删除。默认 2 GiB。",
"Upper bound on the bytes bodies may take; beyond it the oldest days go first. The default is 5 GiB.",
"正文最多占用的字节数,超出时从最早的日期开始删除。默认 5 GiB。",
),
),
],
Expand Down
2 changes: 1 addition & 1 deletion crates/tw-control/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -390,7 +390,7 @@ async fn overview(State(s): State<ControlState>) -> Json<tw_api::Overview> {
body_days: cfg.retention.body_days,
row_days: cfg.retention.row_days,
body_max_bytes: cfg.retention.body_max_bytes,
// **现状和配置一起给。**「上限 2 GB」这个数字,用户没法
// **现状和配置一起给。**「上限 5 GB」这个数字,用户没法
// 判断松还是紧,除非同时看得见现在占了多少
body_bytes_now,
},
Expand Down
23 changes: 19 additions & 4 deletions crates/tw-control/src/replay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,17 @@
//! **三、脱敏照做。**重放走的是控制面,不经过数据面的管线,所以
//! 脱敏那一层要在这里显式调一次。少了它,一条本来会被脱敏的请求,
//! 会因为「重放」这个动作把密钥原样发给中转站。
//!
//! # 重放的是存下来的那一份
//!
//! 存下来的请求不是原文:脱敏规则认得出的值落盘之前就换掉了(见
//! `tw_gateway::bodies`)—— 拦截档下是发给上游的占位符(`<<TW_SECRET_1>>`),别的档位
//! 打了码(`sk-an…7f9c`)。所以重放发出去的就是这样一份:拦截档下它带着的正是原来那一次
//! 发给上游的占位符,别的档位少了原值。**换不回来,也不该换回来**:真值从没进过磁盘。
//!
//! 那些占位符这一次没有对应的原值,回答里提到它们也原样留着。这一次重新找到的值从
//! 存下来的那些号后面接着编([`tw_gateway::guard::ledger_for`]),不会和它们撞号 ——
//! 撞了的话,回答里的 1 号会被还原成这一次新找到的那个值,而它原本指的是另一样。

use std::time::Instant;

Expand All @@ -34,10 +45,11 @@ fn fail(code: StatusCode, detail: tw_types::Msg) -> Fail {
(code, axum::Json(detail))
}

/// 找到那条请求,把**原样的**请求体取出来。
/// 找到那条请求,把存下来的请求体取出来。
///
/// 注意不是 `request_detail` 里那份 —— 那一份是脱敏之后给人看的
/// (它会被复制进 issue)。重放要的是原样。
/// 注意不是 `request_detail` 里那份 —— 那一份读出来又打了一遍码,是给人看的
/// (它会被复制进 issue)。重放要的是存下来的那一份:它落盘之前已经换过、打过码,
/// 结构和原来的一样。
fn stored_body(
g: &tw_store::Recorder,
id: i64,
Expand Down Expand Up @@ -206,12 +218,15 @@ pub async fn run(
})?;

// **脱敏照做。**重放不经过数据面的管线,少了这一行,一条本来会被
// 脱敏的请求会因为「重放」这个动作把密钥原样发出去
// 脱敏的请求会因为「重放」这个动作把密钥原样发出去。新找到的值让开存下来的那份
// 里已经写着的占位符(见模块说明)
let rt = s.gateway.runtime();
let ledger = tw_gateway::guard::ledger_for(&raw);
let (body, ledger) = tw_gateway::guard::replace(
rt.config.security.redact.mode,
&rt.redact,
bytes::Bytes::from(raw),
&ledger,
);

let url = tw_gateway::forward::upstream_url(&provider.base_url, &row.path, None);
Expand Down
62 changes: 61 additions & 1 deletion crates/tw-control/tests/replay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,14 +126,21 @@ fn row(id: i64, provider: &str) -> tw_store::db::RequestRow {

/// 一个记着一条请求(连同请求体)的控制面。
fn app(config: &str) -> (tempfile::TempDir, axum::Router) {
app_with(
config,
br#"{"model":"claude-sonnet-4-5","max_tokens":8,"messages":[{"role":"user","content":"hi"}]}"#,
)
}

/// 同上,存着的请求体是 `body`。
fn app_with(config: &str, body: &[u8]) -> (tempfile::TempDir, axum::Router) {
let d = tempfile::tempdir().unwrap();
let p = d.path().join("config.yaml");
std::fs::write(&p, config).unwrap();
let db = tw_store::Db::open(&d.path().join("data.db")).unwrap();
let r = row(1, "本机");
db.insert(&r).unwrap();
let blobs = tw_store::Blobs::new(d.path().join("blobs"));
let body = br#"{"model":"claude-sonnet-4-5","max_tokens":8,"messages":[{"role":"user","content":"hi"}]}"#;
assert!(blobs.put(r.at_ms, r.id, tw_store::Which::Request, body));
let rec = tw_store::Recorder::new(
db,
Expand Down Expand Up @@ -240,3 +247,56 @@ async fn a_bedrock_upstream_is_not_offered_a_replay_it_cannot_take() {
assert_eq!(v["code"], "control.replay_bedrock", "{path}: {v}");
}
}

/// 一个把收到的请求体原样回给你的上游,顺手记下收到了什么。
async fn echoing() -> (SocketAddr, Arc<std::sync::Mutex<String>>) {
let seen: Arc<std::sync::Mutex<String>> = Arc::default();
let s = seen.clone();
let app = axum::Router::new().route(
"/v1/messages",
axum::routing::post(move |body: String| {
let s = s.clone();
async move {
*s.lock().unwrap() = body.clone();
body
}
}),
);
let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = l.local_addr().unwrap();
tokio::spawn(async move { axum::serve(l, app).await.unwrap() });
(addr, seen)
}

/// 存下来的请求(拦截档下存的是换过的那一份)里写着 1 号;这一次又找到一把密钥(比如
/// 那之后加了一条规则,或者观察档下存的)。**新找到的拿 2 号**:拿 1 号的话,回答里的
/// 1 号会被还原成这把新的,而它原本指的是另一样。
#[tokio::test]
async fn a_replay_numbers_new_finds_after_the_placeholders_already_stored() {
const KEY: &str = "sk-ant-api03-REPLAYKEYAAAAAAAAAAAAAAAA";
let (upstream, seen) = echoing().await;
let stored = format!(
r#"{{"model":"claude-sonnet-4-5","max_tokens":8,"messages":[{{"role":"user","content":"旧的 <<TW_SECRET_1>>,新的 {KEY}"}}]}}"#
);
let (_d, app) = app_with(
&format!(
"version: 1\nlisten:\n control:\n key: c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00\nclients:\n - name: 我\n key: tw-一把钥匙就够\nproviders:\n \
- name: 本机\n base_url: http://{upstream}\n key: sk-x\n billing: free\n\
security:\n redact:\n mode: enforce\n"
),
stored.as_bytes(),
);

let v = replay(&app, "本机").await;
let sent = seen.lock().unwrap().clone();
assert!(
sent.contains("旧的 <<TW_SECRET_1>>,新的 <<TW_SECRET_2>>"),
"{sent}"
);
// 1 号没有原值,原样留着;2 号还原成新找到的那把(给人看的打了码)
let body = v["body"].as_str().unwrap();
assert!(
body.contains("旧的 <<TW_SECRET_1>>,新的 sk-an…AAAA"),
"{v}"
);
}
Loading
Loading