From f6971861d2e094e4676523329e241ff1b13ce977 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Sat, 21 Nov 2026 11:03:38 +0800 Subject: [PATCH] =?UTF-8?q?=E6=AF=8F=E5=80=8B=E5=9B=9E=E6=87=89=E4=B8=8D?= =?UTF-8?q?=E5=86=8D=E5=A4=9A=E7=AD=89=2040=20=E6=AF=AB=E7=A7=92=EF=BC=9A?= =?UTF-8?q?=E5=B8=B3=E8=99=9F=E4=BC=BA=E6=9C=8D=E5=99=A8=EF=BC=88ai?= =?UTF-8?q?=EF=BC=8C=E5=AE=B6=E8=A3=A1=EF=BC=89=E4=B8=8A=E4=B8=80=E5=80=8B?= =?UTF-8?q?=E6=9C=80=E7=B0=A1=E5=96=AE=E7=9A=84=20/api/hello=EF=BC=8C?= =?UTF-8?q?=E5=9C=A8=E5=90=8C=E4=B8=80=E6=A2=9D=E9=80=A3=E7=B7=9A=E4=B8=8A?= =?UTF-8?q?=E6=AF=8F=E5=80=8B=E8=A6=81=2040=E2=80=9350=20=E6=AF=AB?= =?UTF-8?q?=E7=A7=92=E2=80=94=E2=80=94=E7=9B=B4=E6=8E=A5=E6=89=93=20relay?= =?UTF-8?q?=20=E5=AE=B9=E5=99=A8=E4=B9=9F=E4=B8=80=E6=A8=A3=EF=BC=8C?= =?UTF-8?q?=E4=B8=8D=E6=98=AF=20Caddy=20=E4=B9=9F=E4=B8=8D=E6=98=AF?= =?UTF-8?q?=E7=B6=B2=E8=B7=AF=E3=80=82httpd=20=E6=8A=8A=E5=9B=9E=E6=87=89?= =?UTF-8?q?=E7=9A=84=E6=A8=99=E9=A0=AD=E5=92=8C=E5=85=A7=E5=AE=B9=E5=88=86?= =?UTF-8?q?=E5=85=A9=E6=AC=A1=E5=AF=AB=EF=BC=8C=E4=B8=80=E8=88=AC=E7=9A=84?= =?UTF-8?q?=20HTTP=20=E9=80=A3=E7=B7=9A=E5=8F=88=E6=B2=92=E6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=9B=E6=89=8B=E6=A9=9F?= =?UTF-8?q?=E9=A0=81=E9=9D=A2=E7=9A=84=E5=8D=80=E7=B6=B2=20HTTPS=20?= =?UTF-8?q?=E9=82=A3=E5=B1=A4=EF=BC=88lantls=EF=BC=89=E5=85=A9=E9=82=8A?= =?UTF-8?q?=E7=9A=84=E9=80=A3=E7=B7=9A=E4=B9=9F=E9=97=9C=E6=8E=89=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 已驗證: cargo test 全綠(822)、relay cargo test 全綠(26);新測試 answers_on_a_kept_connection_come_back_at_once(同一條連線 10 個請求平均要在 15 毫秒內;macOS 的本機迴路不壓確認,這台關掉修正也會過——擋的是 Linux,帳號伺服器和大腦都跑在 Linux);clippy 錯誤數跟之前一樣(12)。 未驗證: Linux 上修正前後的對照,部署到 ai 之後量(修正前 /api/hello 每個 50 毫秒)。 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Uirha2uBHmbnuWBhNzjbJm --- FEATURES.md | 1 + src/httpd.rs | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++- src/lantls.rs | 3 +++ 3 files changed, 55 insertions(+), 1 deletion(-) diff --git a/FEATURES.md b/FEATURES.md index 91173a3..7a32f63 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -536,6 +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),手機經帳號伺服器問大腦一次要付兩次。 - **帳號伺服器的資源**:閒置的連線從每秒醒 25 次降到 5 次;每條連線的讀取緩衝從 128 KB 降到 32 KB;請求的開頭 15 秒內沒送完就斷(原本最長 90 秒)。本機壓測(100 台電腦連著、3000 個請求、120 次錯誤登入、128 個送一半的請求、3 輪重連):記憶體 32 MB 持平,執行緒和檔案描述元都回到起點,閒置 CPU 約 1.5%(一個核心)。 - **團隊成員在 Bot 忙的時候傳的訊息**不再被丟掉:排在後面,Bot 做完手上的事就輪到它(每個 Bot 最多排 8 則)。成員的話不會插進擁有者正在跑的那一輪。 - **群組沒有 @ 時看擅長分派**:訊息的內容對得上某些成員「擅長」寫的事(而且不在它「不找它做的事」裡),就只由那幾位回答,聊天裡會有一行「這題看擅長交給「…」。要其他人也回答,用 @ 點名。」;對不上任何人、或每個人都對得上,就跟以前一樣全員輪流。 diff --git a/src/httpd.rs b/src/httpd.rs index 5027335..9d5728e 100644 --- a/src/httpd.rs +++ b/src/httpd.rs @@ -478,7 +478,15 @@ fn write_kept(c: &mut TcpStream, r: &Resp, keep: bool) -> bool { } true }; - if send(head.as_bytes()) && send(&r.body) { + // (A small answer goes in one piece with its head: one packet, not two.) + let sent = if r.body.len() <= 16 * 1024 { + let mut whole = head.into_bytes(); + whole.extend_from_slice(&r.body); + send(&whole) + } else { + send(head.as_bytes()) && send(&r.body) + }; + if sent { c.flush().is_ok() } else { let _ = c.shutdown(std::net::Shutdown::Both); @@ -581,6 +589,11 @@ fn serve_with(listener: TcpListener, handler: Handler, upgrade: Option, 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; @@ -954,6 +967,43 @@ pub fn open(key: &[u8; 32], sealed: &[u8]) -> Option> { 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. + #[test] + fn answers_on_a_kept_connection_come_back_at_once() { + 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(); + let port = l.local_addr().unwrap().port(); + std::thread::spawn(move || serve_kept(l, h, None, Arc::new(|| true))); + let mut c = TcpStream::connect(("127.0.0.1", port)).unwrap(); + let mut rd = BufReader::new(c.try_clone().unwrap()); + let mut ask = || { + c.write_all(b"GET /api/hello HTTP/1.1\r\nHost: x\r\n\r\n").unwrap(); + let mut n = 0usize; + loop { + let mut l = String::new(); + rd.read_line(&mut l).unwrap(); + if let Some(v) = l.strip_prefix("Content-Length: ") { + n = v.trim().parse().unwrap(); + } + if l == "\r\n" { + break; + } + } + let mut body = vec![0u8; n]; + rd.read_exact(&mut body).unwrap(); + }; + ask(); + let t = std::time::Instant::now(); + for _ in 0..10 { + ask(); + } + let each = t.elapsed() / 10; + assert!(each < Duration::from_millis(15), "{each:?} an answer"); + } + #[test] fn totp_matches_the_rfc_6238_vectors() { // RFC 6238's SHA-1 test secret, 8-digit codes; the last six of each. diff --git a/src/lantls.rs b/src/lantls.rs index af242dd..45c3ab1 100644 --- a/src/lantls.rs +++ b/src/lantls.rs @@ -332,6 +332,8 @@ impl Drop for Carried { fn reach(inner: SocketAddr, peer: IpAddr) -> Option<(TcpStream, Carried)> { let up = TcpStream::connect_timeout(&inner, Duration::from_secs(5)).ok()?; + // (Both legs send what they have at once: see httpd's accept.) + let _ = up.set_nodelay(true); let port = up.local_addr().ok()?.port(); // (Before a byte goes through: the server reads who asked once it has the request.) crate::httpd::carried().lock().unwrap().insert(port, peer); @@ -347,6 +349,7 @@ pub fn front(listener: TcpListener, inner: SocketAddr, cfg: Arc { 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;