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
2 changes: 1 addition & 1 deletion bin/twcore/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -697,7 +697,7 @@ fn cmd_serve(path: &Path, port: Option<u16>, safe: bool, parent: Option<u32>) ->
let config_path = path.to_path_buf();
rt.block_on(async move {
let state = tw_gateway::AppState::new(cfg.clone())
.map_err(|e| anyhow::anyhow!("{}", e.message))?;
.map_err(|e| anyhow::anyhow!("{}", e.message()))?;
// 默认价目表:上次联网刷新存下的那份,或者内置的。自定义价目表已经
// 随配置进了价格簿
state.set_price_table(tw_control::pricing::load_table(&config_path));
Expand Down
4 changes: 2 additions & 2 deletions crates/tw-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ pub enum Event {
RequestFailed {
id: u64,
source: String,
message: String,
message: Msg,
/// 失败之前从上游收到了多少字节。**响应头都没到的没有**
#[serde(default, skip_serializing_if = "Option::is_none")]
bytes: Option<u64>,
Expand Down Expand Up @@ -2790,7 +2790,7 @@ mod tests {
Event::RequestFailed {
id: 7,
source: "upstream".into(),
message: "x".into(),
message: tw_types::msg!("t.x" => "x"),
bytes: None,
duration_ms: None,
usage: None,
Expand Down
4 changes: 2 additions & 2 deletions crates/tw-control/src/chatgpt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -723,7 +723,7 @@ fn client_for(s: &ControlState, name: &str, proxy: &str) -> Result<reqwest::Clie
proxy: proxy.to_string(),
..Default::default()
};
tw_gateway::client_for_provider(&s.config(), &route).map_err(|e| e.message)
tw_gateway::client_for_provider(&s.config(), &route).map_err(|e| e.message().to_string())
}

fn announce(
Expand Down Expand Up @@ -895,7 +895,7 @@ async fn send(
StatusCode::BAD_GATEWAY,
format!(
"无法连接 ChatGPT 后端:{}",
tw_gateway::forward::map_reqwest_error(e).message
tw_gateway::forward::map_reqwest_error(e).message()
),
)
})
Expand Down
2 changes: 1 addition & 1 deletion crates/tw-control/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ impl ConfigManager {
})?;
self.gateway
.reload(cfg)
.map_err(|e| ApplyError::Build(e.message))?;
.map_err(|e| ApplyError::Build(e.message().to_string()))?;
// 存刚刚生效的这一版。加上写入路径在写之前存的那一次,去重
// 之后的效果是「每个存在过的版本各一条」,最新那条就是现在跑
// 着的 —— 于是「回到上一版」在列表上就是第二条,不用数。
Expand Down
4 changes: 3 additions & 1 deletion crates/tw-control/src/replay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,9 @@ pub async fn run(
let resp = r.body(body).send().await.map_err(|e| {
fail(
StatusCode::BAD_GATEWAY,
tw_gateway::forward::map_reqwest_error(e).message,
tw_gateway::forward::map_reqwest_error(e)
.message()
.to_string(),
)
})?;

Expand Down
2 changes: 1 addition & 1 deletion crates/tw-control/src/resources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ async fn test_provider(
};
let http = match tw_gateway::client_for_provider(&cfg, &p) {
Ok(h) => h,
Err(e) => return Ok(Json(failed(e.message))),
Err(e) => return Ok(Json(failed(e.message().to_string()))),
};
// OAuth 的 token:新填的那份只能用现成的 access token;沿用原来那份时走网关,
// **按原来的名字换** —— 缓存和轮换写回都认名字,而表单里可能刚改了名
Expand Down
8 changes: 5 additions & 3 deletions crates/tw-gateway/src/access.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@ pub struct Cidr {

#[derive(Debug, thiserror::Error, PartialEq)]
pub enum CidrError {
#[error("「{0}」不是合法的 CIDR,应写成 192.168.0.0/16 的形式")]
#[error("`{0}` is not a valid CIDR; it is written as 192.168.0.0/16")]
Malformed(String),
#[error("「{cidr}」的前缀长度 {prefix} 超出范围(IPv4 最大为 32,IPv6 最大为 128)")]
#[error(
"the prefix length {prefix} in `{cidr}` is out of range (at most 32 for IPv4, 128 for IPv6)"
)]
BadPrefix { cidr: String, prefix: u8 },
}

Expand Down Expand Up @@ -122,7 +124,7 @@ impl AllowList {
.map(|s| s.to_string())
.collect::<Vec<_>>(),
)
.expect("内置私网段是合法的 CIDR")
.expect("the built-in private ranges are valid CIDRs")
}

pub fn allows(&self, ip: IpAddr) -> bool {
Expand Down
40 changes: 29 additions & 11 deletions crates/tw-gateway/src/chatgpt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ pub fn redirect_uri(port: u16) -> String {
pub fn authorize_url(issuer: &str, redirect_uri: &str, pkce: &Pkce, state: &str) -> String {
let mut url = reqwest::Url::parse(&format!("{}/oauth/authorize", issuer.trim_end_matches('/')))
.unwrap_or_else(|_| {
reqwest::Url::parse(&format!("{ISSUER}/oauth/authorize")).expect("常量拼出的地址")
reqwest::Url::parse(&format!("{ISSUER}/oauth/authorize")).expect("built from constants")
});
url.query_pairs_mut()
.append_pair("response_type", "code")
Expand Down Expand Up @@ -336,28 +336,38 @@ pub async fn exchange_code(
])
.send()
.await
.map_err(|e| format!("无法连接 {}:{e}", tw_secret::redact_url(token_endpoint)))?;
.map_err(|e| {
format!(
"{} could not be reached: {e}",
tw_secret::redact_url(token_endpoint)
)
})?;
let status = resp.status().as_u16();
let text = resp.text().await.unwrap_or_default();
if status >= 400 {
let body = tw_secret::mask_body(&text.replace(code, "<省略>").replace(verifier, "<省略>"));
let body = tw_secret::mask_body(
&text
.replace(code, "<omitted>")
.replace(verifier, "<omitted>"),
);
return Err(format!(
"token 端点返回 {status}:{}",
"the token endpoint answered {status}: {}",
body.chars().take(400).collect::<String>()
));
}
let v: Value =
serde_json::from_str(&text).map_err(|_| "token 端点的响应不是 JSON".to_string())?;
let v: Value = serde_json::from_str(&text)
.map_err(|_| "the token endpoint's response is not JSON".to_string())?;
let field = |k: &str| {
v.get(k)
.and_then(|x| x.as_str())
.filter(|s| !s.is_empty())
.map(str::to_string)
};
Ok(Tokens {
id_token: field("id_token").ok_or("token 端点的响应中没有 id_token")?,
access: field("access_token").ok_or("token 端点的响应中没有 access_token")?,
refresh: field("refresh_token").ok_or("token 端点的响应中没有 refresh_token")?,
id_token: field("id_token").ok_or("the token endpoint's response has no id_token")?,
access: field("access_token").ok_or("the token endpoint's response has no access_token")?,
refresh: field("refresh_token")
.ok_or("the token endpoint's response has no refresh_token")?,
expires_in: v.get("expires_in").and_then(|x| x.as_u64()),
})
}
Expand All @@ -378,11 +388,19 @@ pub async fn revoke(
.timeout(std::time::Duration::from_secs(10))
.send()
.await
.map_err(|e| format!("无法连接 {}:{e}", tw_secret::redact_url(revoke_endpoint)))?;
.map_err(|e| {
format!(
"{} could not be reached: {e}",
tw_secret::redact_url(revoke_endpoint)
)
})?;
if resp.status().is_success() {
Ok(())
} else {
Err(format!("吊销接口返回 {}", resp.status().as_u16()))
Err(format!(
"the revoke endpoint answered {}",
resp.status().as_u16()
))
}
}

Expand Down
16 changes: 11 additions & 5 deletions crates/tw-gateway/src/ending.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,14 @@ use std::time::Instant;

use crate::bodies::{BodyKind, BodyRecord, BodySender, ResponseTap};
use crate::usage::{Sniffer, Usage};
use tw_types::{Msg, msg};

/// 一个还欠着结局的请求。
///
/// **到目前为止对响应知道的一切都在它身上**:状态码、收到多少字节、嗅到
/// 多少用量、攒下的响应体。放在一处是因为结局要用的正是这些 —— 不管这个
/// 结局是显式报的,还是在 Drop 里报的。
#[must_use = "丢弃它等同于报告客户端已断开"]
#[must_use = "dropping it reports that the client disconnected"]
pub struct Ending {
bus: tw_observe::EventBus,
id: u64,
Expand Down Expand Up @@ -112,7 +113,7 @@ impl Ending {
/// `x-thinkwatch-error` 那个词表。
///
/// **断在流中间的失败也带着用量** —— 上游已经为它计了费。
pub fn failed(mut self, source: &str, message: String) {
pub fn failed(mut self, source: &str, message: Msg) {
let usage = self.settle();
self.bus.emit(tw_api::Event::RequestFailed {
id: self.id,
Expand Down Expand Up @@ -169,7 +170,9 @@ impl Drop for Ending {
self.bus.emit(tw_api::Event::RequestFailed {
id: self.id,
source: "internal".to_string(),
message: "请求中断:网关内部错误".to_string(),
message: msg!(
"gw.internal" => "The request was interrupted by an error inside the gateway."
),
bytes: self.received(),
duration_ms: Some(self.duration_ms()),
usage,
Expand Down Expand Up @@ -252,7 +255,10 @@ mod tests {
let mut rx = bus.subscribe();
let mut e = responding(&bus);
e.feed(MESSAGE_START);
e.failed("upstream", "流中断:上游断开了".into());
e.failed(
"upstream",
msg!("t.broke" => "the stream broke: the upstream disconnected"),
);

let got = drain(&mut rx);
assert_eq!(got.len(), 1, "{got:?}");
Expand Down Expand Up @@ -280,7 +286,7 @@ mod tests {
let bus = tw_observe::EventBus::new();
let mut rx = bus.subscribe();
Ending::new(bus.clone(), 7, Instant::now(), 1_000, None)
.failed("rate_limited", "`up` 限流了".into());
.failed("rate_limited", msg!("t.limited" => "`up` rate-limited us"));

let got = drain(&mut rx);
assert!(
Expand Down
71 changes: 50 additions & 21 deletions crates/tw-gateway/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@

use axum::http::{HeaderValue, StatusCode};
use axum::response::{IntoResponse, Response};
use tw_types::Msg;
#[cfg(test)]
use tw_types::msg;

/// 失败源。分类的意义在于**用户能看出该去哪儿修**。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
Expand Down Expand Up @@ -124,43 +127,65 @@ impl Dialect {
#[derive(Debug)]
pub struct GatewayError {
pub source: Source,
pub message: String,
/// 为什么失败。**发给 AI 客户端的是 `detail.text`**(它们只认字符串),
/// 界面拿 `detail.code` 去自己的词表里找句子。见 [`tw_types::Msg`]。
pub detail: Msg,
/// 用哪种方言的形状回。**认证失败时还不知道方言**(key 就是没认出
/// 来),所以它有默认值而不是必填。
pub dialect: Dialect,
}

impl GatewayError {
pub fn new(source: Source, message: impl Into<String>) -> Self {
pub fn new(source: Source, detail: Msg) -> Self {
Self {
source,
message: message.into(),
detail,
dialect: Dialect::default(),
}
}

/// 给人看的那句话。
pub fn message(&self) -> &str {
&self.detail.text
}

/// 在原因后面补上尝试过哪几家上游。
///
/// **码不变,补的是同一条消息的细节。**界面照 `code` 说它自己那句话,
/// 需要时从 `attempts` 参数里取这份链路;只读字符串的客户端拿到的是
/// 补过的 `text`。
pub fn with_attempts(mut self, attempts: &[String]) -> Self {
if attempts.is_empty() {
return self;
}
let chain = attempts.join(" → ");
self.detail.text = format!("{} (tried: {chain})", self.detail.text);
self.detail.args.insert("attempts".into(), chain);
self
}
/// 认出客户端之后补上方言。**忘了调只会退回 Anthropic 形状**,
/// 那是个安全的默认,不是一个静默的错误。
pub fn in_dialect(mut self, d: Dialect) -> Self {
self.dialect = d;
self
}
pub fn rate_limited(m: impl Into<String>) -> Self {
Self::new(Source::RateLimited, m)
pub fn rate_limited(detail: Msg) -> Self {
Self::new(Source::RateLimited, detail)
}
pub fn denied(m: impl Into<String>) -> Self {
Self::new(Source::Denied, m)
pub fn denied(detail: Msg) -> Self {
Self::new(Source::Denied, detail)
}
pub fn auth(m: impl Into<String>) -> Self {
Self::new(Source::Auth, m)
pub fn auth(detail: Msg) -> Self {
Self::new(Source::Auth, detail)
}
pub fn config(m: impl Into<String>) -> Self {
Self::new(Source::Config, m)
pub fn config(detail: Msg) -> Self {
Self::new(Source::Config, detail)
}
pub fn upstream(m: impl Into<String>) -> Self {
Self::new(Source::Upstream, m)
pub fn upstream(detail: Msg) -> Self {
Self::new(Source::Upstream, detail)
}
pub fn request(m: impl Into<String>) -> Self {
Self::new(Source::Request, m)
pub fn request(detail: Msg) -> Self {
Self::new(Source::Request, detail)
}
}

Expand All @@ -171,7 +196,7 @@ impl GatewayError {
/// 客户端看到的是一个**戛然而止的流**,而截断和「答完了」在 SSE
/// 里长得一模一样。
pub fn sse_frame(&self) -> String {
let msg = format!("[ThinkWatch] {}", self.message);
let msg = format!("[ThinkWatch] {}", self.detail.text);
let data = match self.dialect {
Dialect::Anthropic => serde_json::json!({
"type": "error",
Expand Down Expand Up @@ -200,7 +225,7 @@ impl IntoResponse for GatewayError {
fn into_response(self) -> Response {
// `[ThinkWatch]` 前缀不是装饰。没有它,用户看到一个 401 会先去
// 查上游的密钥 —— 而问题在中间这一层。
let msg = format!("[ThinkWatch] {}", self.message);
let msg = format!("[ThinkWatch] {}", self.detail.text);
let body = match self.dialect {
Dialect::Anthropic => serde_json::json!({
"type": "error",
Expand Down Expand Up @@ -253,7 +278,8 @@ mod tests {

#[tokio::test]
async fn an_auth_failure_is_401_and_says_who_rejected_it() {
let (status, slug, json) = body_of(GatewayError::auth("密钥不对")).await;
let (status, slug, json) =
body_of(GatewayError::auth(msg!("t.auth" => "the key is wrong"))).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(slug, "auth");
// 客户端解析的是 Anthropic 的形状
Expand All @@ -270,7 +296,10 @@ mod tests {
#[tokio::test]
async fn upstream_failures_are_502_not_500() {
// 500 会让人怀疑我们;502 说清楚是上游那边。
let (status, slug, _) = body_of(GatewayError::upstream("连不上")).await;
let (status, slug, _) = body_of(GatewayError::upstream(
msg!("t.upstream" => "cannot connect"),
))
.await;
assert_eq!(status, StatusCode::BAD_GATEWAY);
assert_eq!(slug, "upstream");
}
Expand All @@ -279,12 +308,12 @@ mod tests {
async fn each_source_maps_to_its_own_status_and_slug() {
for (e, want_status, want_slug) in [
(
GatewayError::config("x"),
GatewayError::config(msg!("t.x" => "x")),
StatusCode::INTERNAL_SERVER_ERROR,
"config",
),
(
GatewayError::request("x"),
GatewayError::request(msg!("t.x" => "x")),
StatusCode::BAD_REQUEST,
"request",
),
Expand Down
Loading
Loading