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
40 changes: 20 additions & 20 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ repository = "https://github.com/ThinkWatchProject/ThinkWatch-Core"

# 二进制走 CalVer,crate 走 SemVer —— 两者是两回事,卖给不同的人。
# 这里是 crate 的版本。
version = "0.1.0"
version = "0.1.1"

[workspace.dependencies]
# ── 内部 crate ───────────────────────────────────────────
Expand Down
10 changes: 9 additions & 1 deletion crates/tw-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ pub struct Status {
pub clients: usize,
pub providers: usize,
pub uptime_secs: u64,
/// 正在服务中的请求数:从进入网关到响应体最后一个字节发完为止,排队
/// 的和还在流式输出的都算。
///
/// 重启网关之前要看它 —— 重启会掐断所有还没结束的流。
pub in_flight: usize,
}

/// 一次请求的观测事件。UI 的实时列表吃这个。
Expand Down Expand Up @@ -1657,17 +1662,20 @@ mod tests {
clients: 1,
providers: 1,
uptime_secs: 0,
in_flight: 3,
};
let back: Status = serde_json::from_str(&serde_json::to_string(&s).unwrap()).unwrap();
assert_eq!(back.gateway_addr.as_deref(), Some("127.0.0.1:8788"));
assert_eq!(back.in_flight, 3);
}

#[test]
fn safe_mode_is_representable() {
// 安全模式 = 控制面在、数据面不在。它必须是一个能被表达的状态,
// 而不是「gateway_addr 是空字符串」这种约定。
let json = r#"{"api_version":1,"version":"x","pid":1,"gateway_addr":null,
"config_path":"/x","clients":0,"providers":0,"uptime_secs":0}"#;
"config_path":"/x","clients":0,"providers":0,"uptime_secs":0,
"in_flight":0}"#;
let s: Status = serde_json::from_str(json).unwrap();
assert!(s.gateway_addr.is_none());
}
Expand Down
1 change: 1 addition & 0 deletions crates/tw-control/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@ async fn status(State(s): State<ControlState>) -> Json<tw_api::Status> {
clients: cfg.clients.len(),
providers: cfg.providers.len(),
uptime_secs: s.started.elapsed().as_secs(),
in_flight: s.gateway.live.count(),
})
}

Expand Down
1 change: 1 addition & 0 deletions crates/tw-gateway/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ pub mod l3;
pub mod latency;
pub mod leak;
pub mod limits;
pub mod live;
pub mod oauth;
pub mod probe;
pub mod quota;
Expand Down
72 changes: 72 additions & 0 deletions crates/tw-gateway/src/live.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
//! 正在服务中的请求有几个。
//!
//! 数的是**客户端那一端还在等**的请求:从进入数据面起,到响应体的最后一
//! 个字节发完、或者客户端先走了为止。
//!
//! **不能数到 handler 返回为止。**流式响应在 handler 返回之后才真正开始
//! —— 那样数的话,一个正在吐字的六分钟任务在第一个字节发出去时就已经
//! 「结束」了。所以通行证跟着响应体走:体被丢掉的那一刻才还回来,而
//! 客户端中途断开时 hyper 丢掉的正是这个体。
//!
//! 它存在的理由是桌面版的更新:换版本要重启网关,重启会掐断所有还在流式
//! 输出的请求。等这个数归零再重启,用户手上跑着的任务就不会断在半截。

use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

/// 计数器本身。克隆出来的都指向同一个数。
///
/// **跨重载存活**(它挂在 `AppState` 上,不在 `Runtime` 里):改一条规则
/// 不会让正在跑的请求从这个数里消失。
#[derive(Clone, Default)]
pub struct Live(Arc<AtomicUsize>);

/// 一个请求的通行证。**Drop 时自动减一** —— 手工减的话,迟早有一条错误
/// 路径会漏掉,而漏掉的表现是这个数只增不减,等它归零的人永远等不到。
#[must_use = "丢掉通行证就等于这个请求已经结束"]
pub struct Pass(Arc<AtomicUsize>);

impl Live {
pub fn enter(&self) -> Pass {
self.0.fetch_add(1, Ordering::SeqCst);
Pass(self.0.clone())
}

pub fn count(&self) -> usize {
self.0.load(Ordering::SeqCst)
}
}

impl Drop for Pass {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::SeqCst);
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn a_pass_counts_while_it_is_held() {
let live = Live::default();
assert_eq!(live.count(), 0);
let a = live.enter();
let b = live.clone().enter();
assert_eq!(live.count(), 2, "克隆出来的计数器数的是同一个数");
drop(a);
assert_eq!(live.count(), 1);
drop(b);
assert_eq!(live.count(), 0);
}

/// 通行证可能在任何线程上被丢掉 —— 响应体在哪个线程上结束,由运行时
/// 决定,不由我们决定。
#[test]
fn a_pass_dropped_on_another_thread_still_counts_down() {
let live = Live::default();
let pass = live.enter();
std::thread::spawn(move || drop(pass)).join().unwrap();
assert_eq!(live.count(), 0);
}
}
18 changes: 17 additions & 1 deletion crates/tw-gateway/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,8 @@ pub struct AppState {
/// 忽略通知,包括那些真该看的。失败不一样:它要一直挂着,
/// 而且从成功变成失败是**状态变了**,必须重新说。
rotation_told: Arc<std::sync::Mutex<std::collections::HashSet<String>>>,
/// 正在服务中的请求数。见 [`crate::live`]。
pub live: crate::live::Live,
}

impl AppState {
Expand Down Expand Up @@ -314,6 +316,7 @@ impl AppState {
)),
rotation_sink: Arc::new(std::sync::Mutex::new(None)),
rotation_told: Arc::new(std::sync::Mutex::new(Default::default())),
live: crate::live::Live::default(),
})
}

Expand Down Expand Up @@ -551,6 +554,7 @@ pub fn router(state: AppState) -> Router {
/// 路由照走一遍 —— **一次升级也是一次请求**,`deny` 规则、`guard`、
/// 熔断对它一样有效。之后把连接交给 [`crate::ws::proxy`],那里会在
/// 每一帧上重新点一遍管线的保护。
#[allow(clippy::too_many_arguments)]
async fn ws_upgrade(
state: AppState,
rt: Arc<Runtime>,
Expand All @@ -559,6 +563,7 @@ async fn ws_upgrade(
uri: axum::http::Uri,
query: Option<String>,
headers: HeaderMap,
live: crate::live::Pass,
) -> Result<Response, GatewayError> {
// 升级请求没有体,所以性质里只有客户端名字 —— 按模型路由的规则
// 对它不适用,而那是对的:这条连接上会跑什么模型,现在还不知道
Expand Down Expand Up @@ -615,6 +620,8 @@ async fn ws_upgrade(
let rules = rt.rules.clone();
let protocol = provider.effective_protocol();
Ok(ws.on_upgrade(move |sock| async move {
// 一条 WS 连接活多久,这个请求就算在服务中多久
let _live = live;
crate::ws::proxy(state, sock, url, key, protocol, provider, guard, rules, id).await;
}))
}
Expand Down Expand Up @@ -723,6 +730,9 @@ async fn passthrough(
body: Bytes,
) -> Result<Response, GatewayError> {
let started = std::time::Instant::now();
// 从这一刻起它就算「在服务中」。**排队等并发名额的也算** —— 那时客户
// 端的连接已经开着在等了,这时候重启网关一样会让它失败。
let live = state.live.enter();
// **整个请求只取一次运行时。**中途重新取会让一个请求跨在两份配置
// 上:按新规则选了 provider,却拿旧的 Client 去发 —— 而那种不一致
// 完全静默。
Expand All @@ -743,7 +753,7 @@ async fn passthrough(
// 在前是因为一个不该连过来的地址不该有机会升级;解体之前是因为
// 升级要的是那条连接,而 `Bytes` 会把它读干净。
if let Some(ws) = upgrade.filter(|_| crate::ws::is_upgrade(&headers)) {
return ws_upgrade(state, rt, ws, client_name, uri, query, headers).await;
return ws_upgrade(state, rt, ws, client_name, uri, query, headers, live).await;
}
// 从这里往下,所有错误都要用客户端自己那套结构回。
// **认证失败在这一行之前,那时方言还猜不出来** —— key 就是没认出来
Expand All @@ -762,6 +772,7 @@ async fn passthrough(
client_name,
position,
started,
live,
)
.await
.map_err(|e| e.in_dialect(dialect))
Expand Down Expand Up @@ -829,6 +840,7 @@ async fn pipeline(
client_name: String,
position: crate::auth::KeyPosition,
started: std::time::Instant,
live: crate::live::Pass,
) -> Result<Response, GatewayError> {
forward::check_body_size(&body, MAX_BODY)?;

Expand Down Expand Up @@ -1416,6 +1428,10 @@ async fn pipeline(
.then(|| crate::toolwall::Wall::new(rt.rules.clone(), trust.blocks()));
let wall_provider = provider.name.clone();
let stream = async_stream::stream! {
// **通行证跟着响应体走。**这个流被丢掉的时候它才还回去:正常
// 发完是一种,客户端中途断开、hyper 丢掉响应体是另一种 —— 两种
// 都算这个请求结束了。
let _live = live;
let mut counted = std::pin::pin!(counted);
let mut broke: Option<GatewayError> = None;
// **旁路嗅探,不缓冲**:字节照常流向客户端,同时喂它
Expand Down
Loading
Loading