每個請求不再先排隊 40–50 毫秒(上一個 commit 怪錯了對象):部署 f697186 之後帳號伺服器的 /api/hello 還是每個 50 毫秒,本機跑也一樣——不是 Nagle。真正的原因是 httpd 接連線的迴圈:監聽設成非阻塞,沒有新連線就睡 50 毫秒再看;帳號伺服器每個回應後關掉連線(serve_upgrade),所以每個請求都先在那裡等。手機頁面區網 HTTPS 那層(lantls::front)也是同一種迴圈。

現在 httpd::accept_until_stopped:accept 用阻塞的、新連線一到就接;另一條執行緒每 200 毫秒看 alive,要停就連一下自己的埠讓 accept 醒來(閒置時每秒醒 5 次,原本 20 次;停下來最多約 0.25 秒,手機直接連線換埠時 lan_up 本來就每 60 毫秒重試綁定 2.4 秒)。serve_*、lantls 都改用它。上一個 commit 的 Nagle 關閉、小回應一次寫出留著(沒有壞處),FEATURES.md 那行改成真的原因。

已驗證: 本機帳號伺服器 4 個 /api/hello:40/51/59/60 ms → 0.47/0.31/0.25/0.26 ms;cargo test 全綠(822)、relay 全綠(26);測試改成 answers_come_back_at_once_and_a_stopped_server_stops(重用連線、每個請求一條新連線、中間有空檔,平均都要在 15 ms 內;alive 變 false 兩秒內停、埠可以再綁)——把舊的 50 ms 迴圈放回去它會失敗;clippy:app 錯誤數跟之前一樣(12)、relay 乾淨。
未驗證: Linux 上的前後對照,部署到 ai 之後量(之前 50 ms)。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha2uBHmbnuWBhNzjbJm
This commit is contained in:
王性驊 2026-11-21 11:10:20 +08:00
parent f6971861d2
commit 535f018515
4 changed files with 159 additions and 107 deletions

View File

@ -536,7 +536,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。
- **更新要驗簽章**:`make sign-setup`(作者做一次)讓之後每個 commit 用 SSH 金鑰簽章,公鑰記在 `deploy/allowed_signers`。安裝時把它記到原始碼資料夾外面(`~/.config/anybot/allowed_signers`);之後 `make update`/重跑安裝腳本,新版不是那把金鑰簽的就不裝(Mac、Linux、Windows 都一樣)。換金鑰:用舊金鑰簽一個把新公鑰加進名單的 commit。確定要跳過一次:`ANYBOT_UNSIGNED=1`。還沒有 `deploy/allowed_signers` 時跟以前一樣不檢查。
- **聊天各存各的檔**:state.json 只剩設定;每個 Bot 的聊天存在 `chats/bot-<編號>.json`,有變才寫;過去的對話(討論串)另外存在 `chats/threads/bot-<編號>.json`,只有收起、切換或刪掉對話時才寫。Bot 工作時每 5 秒的存檔只寫目前這段對話:一個留了 3.5 萬則舊訊息(60 MB)的 Bot,存一次從 90–290 毫秒、寫 77 MB 降到 7–10 毫秒、寫 0.75 MB(以前每 5 秒整份重寫,在 2 核、沒有顯示卡的電腦上視窗每次停住快一秒)。刪掉 Bot 時兩個檔一起刪。舊版存的(聊天在 state.json 裡、或過去的對話在聊天檔裡)照樣讀得進來,下次存檔就分開;中間跑過舊版 AnyBot(它看不到另存的對話、放下的新對話寫在聊天檔裡)也不會少:兩邊合在一起,舊版放下的排前面。壞掉的檔案改名留著,不會被蓋掉。
- **沒有顯示卡的電腦**(虛擬機、透過遠端桌面看的電腦:畫面由 CPU 畫,例如 llvmpipe):開視窗時認出來、紀錄寫一行。Bot 工作時的轉圈、流光字、側欄頭像、串流的重畫從每秒 20–30 次放慢成每秒 4 次——每一張都是整個視窗用 CPU 重畫,原本吃掉大半個核心、旁邊 Bot 自己開的瀏覽器跟著卡,從遠端桌面看視窗一直閃。有顯示卡的電腦照舊。
- **回應不再每個多等 40 毫秒**:帳號伺服器和手機頁面(含區網 HTTPS 那一層)每條連線都關掉 Nagle,小的回應標頭和內容一次寫出。以前標頭、內容分兩次寫,內容要等對方確認標頭,對方又把確認壓著最多 40 毫秒:同一條連線上每個回應 40–50 毫秒(家裡實測帳號伺服器的 /api/hello),手機經帳號伺服器問大腦一次要付兩次。
- **回應不再每個多等 40–50 毫秒**:接連線的迴圈以前是「沒有新連線就睡 50 毫秒再看」,帳號伺服器每個回應後又關掉連線,所以每個請求都先在那裡等(家裡實測帳號伺服器的 /api/hello 每個 40–50 毫秒,本機一樣)。現在新連線一到就接(本機 0.3 毫秒),另一條執行緒每 200 毫秒看要不要停、要停就敲一下讓它醒來(閒置時每秒醒 5 次,原本 20 次)。帳號伺服器、手機頁面和它的區網 HTTPS 那層都是。連線也都關掉 Nagle,小的回應標頭和內容一次寫出。
- **帳號伺服器的資源**:閒置的連線從每秒醒 25 次降到 5 次;每條連線的讀取緩衝從 128 KB 降到 32 KB;請求的開頭 15 秒內沒送完就斷(原本最長 90 秒)。本機壓測(100 台電腦連著、3000 個請求、120 次錯誤登入、128 個送一半的請求、3 輪重連):記憶體 32 MB 持平,執行緒和檔案描述元都回到起點,閒置 CPU 約 1.5%(一個核心)。
- **團隊成員在 Bot 忙的時候傳的訊息**不再被丟掉:排在後面,Bot 做完手上的事就輪到它(每個 Bot 最多排 8 則)。成員的話不會插進擁有者正在跑的那一輪。
- **群組沒有 @ 時看擅長分派**:訊息的內容對得上某些成員「擅長」寫的事(而且不在它「不找它做的事」裡),就只由那幾位回答,聊天裡會有一行「這題看擅長交給「…」。要其他人也回答,用 @ 點名。」;對不上任何人、或每個人都對得上,就跟以前一樣全員輪流。

View File

@ -558,6 +558,42 @@ pub fn serve_kept(listener: TcpListener, handler: Handler, upgrade: Option<Upgra
serve_with(listener, handler, upgrade, alive, true)
}
/// Take connections as they come, until `alive` says stop. The accept waits (it wakes the moment
/// one comes); a watcher looks at `alive` every 200 ms and, once it says stop, knocks on the
/// listener so the accept returns. (The loop before polled a non-blocking listener and slept
/// 50 ms between looks: every new connection waited up to 50 ms first. The account server closes
/// each connection after its answer, so every request did — 40–50 ms for /api/hello at home.)
pub fn accept_until_stopped(listener: TcpListener, alive: Arc<dyn Fn() -> bool + Send + Sync>, mut each: impl FnMut(TcpStream, std::net::SocketAddr)) {
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
listener.set_nonblocking(false).ok();
if let Ok(at) = listener.local_addr() {
let alive = alive.clone();
let _ = std::thread::Builder::new().name("accept-watch".into()).spawn(move || {
while alive() {
std::thread::sleep(Duration::from_millis(200));
}
let ip = match at.ip() {
IpAddr::V4(v) if v.is_unspecified() => IpAddr::V4(Ipv4Addr::LOCALHOST),
IpAddr::V6(v) if v.is_unspecified() => IpAddr::V6(Ipv6Addr::LOCALHOST),
ip => ip,
};
let _ = TcpStream::connect_timeout(&SocketAddr::new(ip, at.port()), Duration::from_secs(1));
});
}
while alive() {
match listener.accept() {
Ok((c, peer)) => {
if !alive() {
return;
}
each(c, peer);
}
// (Out of file descriptors and the like: a breath, then on.)
Err(_) => std::thread::sleep(Duration::from_millis(20)),
}
}
}
fn serve_with(listener: TcpListener, handler: Handler, upgrade: Option<Upgrade>, alive: Arc<dyn Fn() -> bool + Send + Sync>, keep: bool) {
use std::sync::atomic::{AtomicUsize, Ordering};
struct Slot(Arc<AtomicUsize>);
@ -566,7 +602,6 @@ fn serve_with(listener: TcpListener, handler: Handler, upgrade: Option<Upgrade>,
self.0.fetch_sub(1, Ordering::SeqCst);
}
}
listener.set_nonblocking(true).ok();
let active = Arc::new(AtomicUsize::new(0));
let sockets = Arc::new(AtomicUsize::new(0));
let per_addr: Arc<Mutex<HashMap<std::net::IpAddr, usize>>> = Arc::new(Mutex::new(HashMap::new()));
@ -582,96 +617,87 @@ fn serve_with(listener: TcpListener, handler: Handler, upgrade: Option<Upgrade>,
}
}
}
loop {
if !alive() {
let alive2 = alive.clone();
accept_until_stopped(listener, alive2, move |mut c, peer| {
c.set_nonblocking(false).ok();
// Every answer goes out as soon as it is written (not held for the client's
// acknowledgement of what went before).
c.set_nodelay(true).ok();
if active.load(Ordering::SeqCst) >= MAX_CONNS {
write_response(&mut c, &Resp::error(503, "伺服器忙碌中,請稍後再試"));
return;
}
match listener.accept() {
Ok((mut c, peer)) => {
c.set_nonblocking(false).ok();
// Every answer goes out as soon as it is written: with Nagle on, the part after
// the head waited for the client to acknowledge the head, which it holds back up
// to 40 ms — every answer on a kept connection took 40–50 ms (the account server's
// /api/hello, measured at home), and a phone's request to a brain pays it twice.
c.set_nodelay(true).ok();
if active.load(Ordering::SeqCst) >= MAX_CONNS {
write_response(&mut c, &Resp::error(503, "伺服器忙碌中,請稍後再試"));
continue;
}
// One internet address can't hold all the room (a proxy's or a private
// network's address stands for many people: not counted).
let ip = peer.ip();
let direct = !(ip.is_loopback() || is_private_addr(&ip));
let addr_slot = if direct {
let mut m = per_addr.lock().unwrap();
let n = m.entry(ip).or_insert(0);
if *n >= MAX_CONNS_PER_ADDR {
drop(m);
write_response(&mut c, &Resp::error(429, "同一個位址的連線太多了,請稍後再試"));
continue;
// One internet address can't hold all the room (a proxy's or a private
// network's address stands for many people: not counted).
let ip = peer.ip();
let direct = !(ip.is_loopback() || is_private_addr(&ip));
let addr_slot = if direct {
let mut m = per_addr.lock().unwrap();
let n = m.entry(ip).or_insert(0);
if *n >= MAX_CONNS_PER_ADDR {
drop(m);
write_response(&mut c, &Resp::error(429, "同一個位址的連線太多了,請稍後再試"));
return;
}
*n += 1;
Some(AddrSlot(per_addr.clone(), ip))
} else {
None
};
active.fetch_add(1, Ordering::SeqCst);
let slot = Slot(active.clone());
let h = handler.clone();
let up = upgrade.clone();
let socks = sockets.clone();
let alive = alive.clone();
if std::thread::Builder::new()
.spawn(move || {
let _addr = addr_slot;
let slot = slot;
let mut first = true;
loop {
if !first && !next_request_comes(&c, &*alive) {
return;
}
*n += 1;
Some(AddrSlot(per_addr.clone(), ip))
} else {
None
};
active.fetch_add(1, Ordering::SeqCst);
let slot = Slot(active.clone());
let h = handler.clone();
let up = upgrade.clone();
let socks = sockets.clone();
let alive = alive.clone();
if std::thread::Builder::new()
.spawn(move || {
let _addr = addr_slot;
let slot = slot;
let mut first = true;
loop {
if !first && !next_request_comes(&c, &*alive) {
first = false;
match read_request(&mut c) {
Ok(req) if req.header("upgrade").eq_ignore_ascii_case("websocket") && up.is_some() => {
// A lasting connection leaves the requests' room for its own.
if socks.load(Ordering::SeqCst) >= MAX_SOCKETS {
write_response(&mut c, &Resp::error(503, "伺服器忙碌中,請稍後再試"));
return;
}
first = false;
match read_request(&mut c) {
Ok(req) if req.header("upgrade").eq_ignore_ascii_case("websocket") && up.is_some() => {
// A lasting connection leaves the requests' room for its own.
if socks.load(Ordering::SeqCst) >= MAX_SOCKETS {
write_response(&mut c, &Resp::error(503, "伺服器忙碌中,請稍後再試"));
return;
}
socks.fetch_add(1, Ordering::SeqCst);
let _sock = Slot(socks.clone());
drop(slot);
if let Some(u) = up {
u(req, c)
}
return;
}
Ok(req) if !matches!(req.method.as_str(), "GET" | "HEAD") && !same_origin(&req) => {
write_response(&mut c, &Resp::error(403, "forbidden origin"));
return;
}
Ok(req) => {
let again = keep && !req.header("connection").eq_ignore_ascii_case("close");
let resp = h(req);
if !write_kept(&mut c, &resp, again) || !again {
return;
}
}
Err(code) => {
write_response(&mut c, &Resp::error(code, "bad request"));
return;
}
socks.fetch_add(1, Ordering::SeqCst);
let _sock = Slot(socks.clone());
drop(slot);
if let Some(u) = up {
u(req, c)
}
return;
}
Ok(req) if !matches!(req.method.as_str(), "GET" | "HEAD") && !same_origin(&req) => {
write_response(&mut c, &Resp::error(403, "forbidden origin"));
return;
}
Ok(req) => {
let again = keep && !req.header("connection").eq_ignore_ascii_case("close");
let resp = h(req);
if !write_kept(&mut c, &resp, again) || !again {
return;
}
}
})
.is_err()
{
// Slot drops immediately above on Err, decrementing `active`.
Err(code) => {
write_response(&mut c, &Resp::error(code, "bad request"));
return;
}
}
}
}
Err(_) => std::thread::sleep(Duration::from_millis(50)),
})
.is_err()
{
// Slot drops immediately above on Err, decrementing `active`.
}
}
});
}
/// 10.x, 172.16–31.x, 192.168.x, 100.64/10 (Tailscale), link-local, and IPv6's private ranges.
@ -967,11 +993,12 @@ pub fn open(key: &[u8; 32], sealed: &[u8]) -> Option<Vec<u8>> {
mod tests {
use super::*;
/// Answers on a kept connection come back at once: the account server's /api/hello took 40–50
/// ms each on Linux (the head and the body in two writes with Nagle on, against the client's
/// delayed acknowledgement), and a phone's request through it to a brain paid that twice.
/// Answers come back at once, on a new connection as on a kept one: the account server
/// (which closes each connection after its answer) took 40–50 ms for /api/hello — its accept
/// loop slept 50 ms between looks, and every request waited in it. A server told to stop
/// still stops.
#[test]
fn answers_on_a_kept_connection_come_back_at_once() {
fn answers_come_back_at_once_and_a_stopped_server_stops() {
use std::io::{BufRead, BufReader, Read, Write};
let h: Handler = Arc::new(|r: Req| Resp::json(&serde_json::json!({"path": r.path})));
let l = TcpListener::bind("127.0.0.1:0").unwrap();
@ -1001,7 +1028,37 @@ mod tests {
ask();
}
let each = t.elapsed() / 10;
assert!(each < Duration::from_millis(15), "{each:?} an answer");
assert!(each < Duration::from_millis(15), "{each:?} an answer on a kept connection");
// A new connection for each request, as the account server answers.
let on = Arc::new(std::sync::atomic::AtomicBool::new(true));
let l = TcpListener::bind("127.0.0.1:0").unwrap();
let port = l.local_addr().unwrap().port();
let h: Handler = Arc::new(|_r: Req| Resp::json(&serde_json::json!({"app": "anybot-relay"})));
let on2 = on.clone();
let done = std::thread::spawn(move || serve(l, h, Arc::new(move || on2.load(std::sync::atomic::Ordering::SeqCst))));
let once = || {
let mut c = TcpStream::connect(("127.0.0.1", port)).unwrap();
c.write_all(b"GET /api/hello HTTP/1.1\r\nHost: x\r\n\r\n").unwrap();
let mut all = vec![];
c.read_to_end(&mut all).unwrap();
assert!(String::from_utf8_lossy(&all).contains("anybot-relay"));
};
once();
std::thread::sleep(Duration::from_millis(120));
let t = std::time::Instant::now();
for _ in 0..10 {
once();
// (Idle in between, as requests come: the old loop was asleep when each came.)
std::thread::sleep(Duration::from_millis(30));
}
let each = t.elapsed() / 10 - Duration::from_millis(30);
assert!(each < Duration::from_millis(15), "{each:?} an answer on a new connection");
// Told to stop: it stops, and the port is free again.
on.store(false, std::sync::atomic::Ordering::SeqCst);
let t = std::time::Instant::now();
done.join().unwrap();
assert!(t.elapsed() < Duration::from_secs(2), "stopped in {:?}", t.elapsed());
assert!(TcpListener::bind(("127.0.0.1", port)).is_ok());
}
#[test]

View File

@ -343,26 +343,21 @@ fn reach(inner: SocketAddr, peer: IpAddr) -> Option<(TcpStream, Carried)> {
/// Take connections on `listener` until `alive` says stop: TLS is opened here and carried to
/// `inner`; plain HTTP goes through as it is where that is safe, and is sent to https elsewhere.
pub fn front(listener: TcpListener, inner: SocketAddr, cfg: Arc<rustls::ServerConfig>, alive: Arc<dyn Fn() -> bool + Send + Sync>) {
listener.set_nonblocking(true).ok();
let active = Arc::new(AtomicUsize::new(0));
while alive() {
match listener.accept() {
Ok((c, peer)) => {
c.set_nonblocking(false).ok();
c.set_nodelay(true).ok();
if active.fetch_add(1, Ordering::SeqCst) >= MAX_CARRIED {
active.fetch_sub(1, Ordering::SeqCst);
continue;
}
let (slot, cfg) = (Slot(active.clone()), cfg.clone());
let _ = std::thread::Builder::new().spawn(move || {
let _slot = slot;
carry(c, peer.ip(), inner, cfg);
});
}
Err(_) => std::thread::sleep(Duration::from_millis(50)),
// (Each connection taken the moment it comes: see httpd::accept_until_stopped.)
crate::httpd::accept_until_stopped(listener, alive, move |c, peer| {
c.set_nonblocking(false).ok();
c.set_nodelay(true).ok();
if active.fetch_add(1, Ordering::SeqCst) >= MAX_CARRIED {
active.fetch_sub(1, Ordering::SeqCst);
return;
}
}
let (slot, cfg) = (Slot(active.clone()), cfg.clone());
let _ = std::thread::Builder::new().spawn(move || {
let _slot = slot;
carry(c, peer.ip(), inner, cfg);
});
});
}
fn carry(c: TcpStream, peer: IpAddr, inner: SocketAddr, cfg: Arc<rustls::ServerConfig>) {

View File

@ -2025,7 +2025,7 @@ pub fn set_lan(on: bool) -> Result<(), String> {
Ok(())
}
/// A new generation: what listened before stops (within 50 ms). Its number.
/// A new generation: what listened before stops (within about a quarter second: httpd::accept_until_stopped). Its number.
fn lan_stop() -> u64 {
let gen = LAN_GEN.fetch_add(1, Ordering::SeqCst) + 1;
*LAN_BOUND.lock().unwrap() = None;