diff --git a/src/attach.rs b/src/attach.rs index f2f820b..6b980b0 100644 --- a/src/attach.rs +++ b/src/attach.rs @@ -100,7 +100,9 @@ pub fn failure_text(code: &str) -> &'static str { impl Attachment { /// A device's word on this file: kept when it is the first of its kind from that device and - /// there is room. True when it was kept. + /// there is room. True when it was kept. (The brain's road takes `guest` — this is the + /// test's shorthand for an owner's device.) + #[cfg(test)] pub fn note_seen(&mut self, device: &str, kind: SeenKind, why: &str, at: i64) -> bool { self.note_seen_by(device, kind, why, at, false) } diff --git a/src/remote.rs b/src/remote.rs index 57e69eb..9e8bb43 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -715,24 +715,33 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { // include that chat's messages whenever their signature changed (`&chat_sig=…`), only // from where they differ for a page that takes that (`&chat_delta=1`), from the window // it holds (`&w0=` the index of its first message). A streaming reply is told at most - // once a second — the smallest chat delta is a whole message, and its whole body - // would ride on every wake otherwise; the page asks again when the second is up. + // once a CHAT_EVERY_MS — the smallest chat delta is a whole message, and its whole + // body would ride on every wake otherwise. Inside the closing window the answer waits + // for the slot and then carries the freshest tail: a page steps its next `since` by + // the version it sees, so a 「throttled, look later」 answer whose version already + // passed would strand the tail until the long poll times out (seconds on a slow line). if let Some(open_id) = req.query.get("bot").and_then(|b| b.parse::().ok()).filter(|&id| id > 0) { - if let Some(raw) = v.messages.get(&open_id) { - let held = req.query.get("chat_sig").map(String::as_str).unwrap_or(""); - let part = req.query.get("chat_delta").is_some_and(|d| d == "1"); + let held = req.query.get("chat_sig").map(String::as_str).unwrap_or("").to_string(); + let part = req.query.get("chat_delta").is_some_and(|d| d == "1"); + let w0q = req.query.get("w0").and_then(|x| x.parse::().ok()); + let mut vv = v.clone(); + loop { + let Some(raw) = vv.messages.get(&open_id) else { break }; let msgs = messages_for_role(raw, &role); // A page that says where its copy starts gets the window from there; a page // opening the chat (first=1, or no word) gets the newest PHONE_FIRST. let n = msgs.as_array().map(Vec::len).unwrap_or(0); - let w0 = req.query.get("w0").and_then(|x| x.parse::().ok()).unwrap_or(n.saturating_sub(PHONE_FIRST)); - let del = json!(v.deliveries.get(&open_id).cloned().unwrap_or_default()); - let chat = chat_for(open_id, msgs, &del, held, part, Some(w0)); - if chat.get("messages").is_some() && since != 0 && !slot_open(&LAST_CHAT, CHAT_EVERY_MS) { - out["chat"] = json!({"bot": open_id, "sig": held, "throttled": true}); - } else { - out["chat"] = chat; + let w0 = w0q.unwrap_or(n.saturating_sub(PHONE_FIRST)); + let del = json!(vv.deliveries.get(&open_id).cloned().unwrap_or_default()); + let chat = chat_for(open_id, msgs, &del, &held, part, Some(w0)); + let now_ok = since == 0 || chat.get("messages").is_none() || slot_open(&LAST_CHAT, CHAT_EVERY_MS); + out["chat"] = chat; + if now_ok { + break; } + let last = LAST_CHAT.load(Ordering::Relaxed); + std::thread::sleep(Duration::from_millis(CHAT_EVERY_MS.saturating_sub(up_ms().saturating_sub(last)))); + vv = hub().view.lock().unwrap_or_else(|e| e.into_inner()).clone(); } } Resp::json(&out) @@ -2502,7 +2511,7 @@ fn rewrite_self(url: &str, tunnel: &[std::net::IpAddr], resolve: impl Fn(&str, u fn loopback_open(port: u16) -> bool { static CACHE: std::sync::OnceLock>> = std::sync::OnceLock::new(); let cache = CACHE.get_or_init(Default::default); - if let Some((ok, t)) = cache.lock().unwrap_or_else(|e| e.into_inner()).get(&port).filter(|(_, t)| t.elapsed().as_secs() < 60).copied() { + if let Some((ok, _)) = cache.lock().unwrap_or_else(|e| e.into_inner()).get(&port).filter(|(_, t)| t.elapsed().as_secs() < 60).copied() { return ok; } let ok = std::net::TcpStream::connect_timeout(&std::net::SocketAddr::from(([127, 0, 0, 1], port)), Duration::from_millis(200)).is_ok(); @@ -3895,6 +3904,40 @@ mod tests { assert_eq!(device_run(&signed_run(&Settings { link_keys: vec![new_link_key()], ..Default::default() }, "h1", "x", "{}", "大腦"), &hands, true, "brain1").status, 403, "another brain's key"); } + #[test] + fn a_chat_tail_arrives_on_the_next_poll_not_the_long_poll_timeout() { + // api/state?bot=… 串流降頻: at most one new chat tail per CHAT_EVERY_MS. Inside the + // closing window the answer must wait out the slot and carry the fresh tail with its + // version — a 「throttled」 answer that let the version pass would strand the tail + // until the long poll times out (tens of seconds on the phone). + let mut s = Settings { password: httpd::hash_password("pw-tail"), ..Default::default() }; + s.host_name = "測試 Mac".into(); + hub().set_settings(&s); + let ok = handle(Req { method: "POST".into(), path: "/api/login".into(), body: br#"{"password":"pw-tail","device":"iPhone"}"#.to_vec(), ..Default::default() }, false); + let token = serde_json::from_slice::(&ok.body).unwrap()["token"].as_str().unwrap().to_string(); + let say = |n: u64| (0..n).map(|i| json!({ "index": i, "role": "bot", "text": format!("第 {i} 則") })).collect::>(); + let view = |n: u64| View { host: "測試 Mac".into(), bots: vec![json!({ "id": 1, "name": "小助理" })], messages: HashMap::from([(1, say(n))]), ..Default::default() }; + hub().publish(view(3)); + let state = |since: u64, sig: &str| { + let mut r = Req { method: "GET".into(), path: "/api/state".into(), ..Default::default() }; + r.headers.insert("authorization".into(), format!("Bearer {token}")); + r.query = [("since", since.to_string()), ("bot", "1".into()), ("chat_delta", "1".into()), ("chat_sig", sig.to_string())].into_iter().map(|(k, v)| (k.to_string(), v)).collect(); + let a = handle(r, false); + assert_eq!(a.status, 200, "{}", String::from_utf8_lossy(&a.body)); + serde_json::from_slice::(&a.body).unwrap() + }; + let first = state(0, ""); + let (v1, sig1) = (first["version"].as_u64().unwrap(), first["chat"]["sig"].as_str().unwrap().to_string()); + assert_eq!(first["chat"]["messages"].as_array().map(Vec::len), Some(3)); + // The stream's last word lands while the slot is closing (the page's copy is the + // first answer's): the next poll answers with the tail and its version — spent. + hub().publish(view(4)); + let got = state(v1, &sig1); + assert!(got["chat"].get("throttled").is_none(), "tail was swallowed: {}", got["chat"]); + assert_eq!((got["chat"]["from"].as_u64(), got["chat"]["messages"].as_array().map(Vec::len)), (Some(3), Some(1)), "{}", got["chat"]); + assert!(got["version"].as_u64().unwrap() > v1, "the page must be allowed to step past this version"); + } + #[test] fn phone_login_and_api() { let mut s = Settings { password: httpd::hash_password("pw-123"), ..Default::default() }; diff --git a/src/smart.rs b/src/smart.rs index 103bfc4..276655f 100644 --- a/src/smart.rs +++ b/src/smart.rs @@ -126,6 +126,7 @@ pub struct Smart { impl Smart { /// Off, and never turns on (tests, untrusted turns). /// 開著,用預設逾時。 + #[cfg(test)] pub fn on(timeout: Duration) -> Smart { Self { on: Arc::new(AtomicBool::new(true)), timeout, scopes: std::cell::RefCell::new(vec![]), reviews: std::cell::RefCell::new(std::collections::HashMap::new()) } }