From fb46ee4e3b9dba1bd14347616885d8e75423bc46 Mon Sep 17 00:00:00 2001 From: unRekable Date: Fri, 4 Dec 2026 15:46:45 +0100 Subject: [PATCH] Google Messages bounds its link-preview fetches, keeps what it unfurled over a restart, and asks for no page again that an unchanged chat already read --- crates/chatd/src/adapters/messages.rs | 87 +++- crates/chatd/src/adapters/messages/fake.rs | 31 +- crates/chatd/src/unfurl.rs | 237 ++++++++-- crates/chatd/tests/messages.rs | 297 +++++++++--- .../drive.linux.sh | 9 + .../drive.macos.sh | 9 + .../drive.py | 442 ++++++++++++++++++ .../drive.windows.ps1 | 17 + .../scenario.json | 12 + 9 files changed, 1017 insertions(+), 124 deletions(-) create mode 100644 e2e/scenarios/messages-restart-asks-nothing-again/drive.linux.sh create mode 100644 e2e/scenarios/messages-restart-asks-nothing-again/drive.macos.sh create mode 100644 e2e/scenarios/messages-restart-asks-nothing-again/drive.py create mode 100644 e2e/scenarios/messages-restart-asks-nothing-again/drive.windows.ps1 create mode 100644 e2e/scenarios/messages-restart-asks-nothing-again/scenario.json diff --git a/crates/chatd/src/adapters/messages.rs b/crates/chatd/src/adapters/messages.rs index 067abacf..aabcd2f9 100644 --- a/crates/chatd/src/adapters/messages.rs +++ b/crates/chatd/src/adapters/messages.rs @@ -684,6 +684,11 @@ struct Account { send_tx: std::sync::mpsc::Sender, /// Dedicated low-priority background crawl / media fetch worker channel. bg_tx: std::sync::mpsc::Sender, + /// The links looked up for this account, each with its preview or with none. What had no + /// preview is kept in the store, so a restart does not ask for it again. + unfurls: Arc>, + /// Where links wait for the one thread that looks them up. + unfurl_queue: crate::unfurl::Queue, } impl Account { @@ -987,6 +992,8 @@ fn connect( sims: Mutex::default(), send_tx: send_tx.clone(), bg_tx: bg_tx.clone(), + unfurls: Arc::new(Mutex::new(load_unfurls(ctx))), + unfurl_queue: crate::unfurl::Queue::start(), }); ctx.capabilities(capability_ceiling()); let _ = ctx.describe( @@ -1672,6 +1679,17 @@ fn is_known_contact(account: &Account, chat: Option<&Chat>, outgoing: bool) -> b true } +/// Where the links are kept that an earlier run looked up and found no preview for. +const UNFURL_NOTE: &str = "messages-unfurls"; + +/// The cache as an earlier run left it. Only links without a preview are in it: one with a +/// preview keeps that on its message. +fn load_unfurls(ctx: &Context) -> crate::unfurl::Cache { + ctx.note(UNFURL_NOTE) + .map(|kept| crate::unfurl::Cache::read(&kept)) + .unwrap_or_default() +} + fn maybe_unfurl(account: &Account, conversation: &str, message_id: &str, text: &str, outgoing: bool) { let Some(url) = crate::unfurl::extract_url(text) else { return; @@ -1689,22 +1707,43 @@ fn maybe_unfurl(account: &Account, conversation: &str, message_id: &str, text: & if !should_unfurl(chat.as_ref(), known, link_previews, allow_unknown) { return; } + // Looked up before, on this or an earlier run, and there is no preview to show. + if account + .unfurls + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .get(&url) + .is_some_and(|kept| kept.is_none()) + { + return; + } let ctx = account.ctx.clone(); + let unfurls = account.unfurls.clone(); let conversation = conversation.to_owned(); let message_id = message_id.to_owned(); - let _ = std::thread::Builder::new() - .name("messages-unfurl".into()) - .spawn(move || { - let Some(preview) = crate::unfurl::fetch(&url) else { - return; - }; - if let Ok(Some(mut stored)) = ctx.stored_message(&conversation, &message_id) { - if stored.previews.is_empty() { - stored.previews.push(preview); - let _ = ctx.message(&conversation, &stored); - } + account.unfurl_queue.add(Box::new(move || { + // A signed-out account has no message left to show a preview on, so its page is not asked for. + if ctx.stopped() { + return; + } + let (preview, changed) = crate::unfurl::fetch_with_cache(&url, &unfurls); + if changed { + let kept = unfurls + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .kept(); + ctx.set_note(UNFURL_NOTE, &kept); + } + let Some(preview) = preview else { + return; + }; + if let Ok(Some(mut stored)) = ctx.stored_message(&conversation, &message_id) { + if stored.previews.is_empty() { + stored.previews.push(preview); + let _ = ctx.message(&conversation, &stored); } - }); + } + })); } fn message(account: &Account, note: &bugle::Note, page: &[bugle::Note]) -> Message { @@ -4582,6 +4621,28 @@ mod tests { assert_eq!(filled_note("42"), "messages-filled:42"); } + #[test] + fn the_links_without_a_preview_from_an_earlier_run_are_found_again() { + let hub = Arc::new(crate::hub::Hub::new( + crate::store::Store::open(std::path::Path::new(":memory:")).expect("memory store"), + )); + let key = protocol::AccountKey { network: protocol::Network::Messages, account: "phone-unfurls".into() }; + let (_adapter, ctx, _inbox) = crate::adapters::local(key, hub); + assert_eq!(load_unfurls(&ctx).get("https://example.com/gone"), None, "nothing was kept yet"); + + let mut lookups = crate::unfurl::Cache::default(); + lookups.insert("https://example.com/gone", None); + lookups.insert( + "https://example.com/page", + crate::unfurl::parse_html("https://example.com/page", "Page"), + ); + ctx.set_note(UNFURL_NOTE, &lookups.kept()); + + let again = load_unfurls(&ctx); + assert_eq!(again.get("https://example.com/gone"), Some(None), "a link without a preview is not asked for again"); + assert_eq!(again.get("https://example.com/page"), None, "a link with a preview keeps it on its message"); + } + #[test] fn a_scheduled_text_survives_a_restart_and_one_missed_while_off_fails() { let hub = Arc::new(crate::hub::Hub::new( @@ -4736,6 +4797,8 @@ mod tests { sims: Mutex::default(), send_tx: std::sync::mpsc::channel().0, bg_tx: std::sync::mpsc::channel().0, + unfurls: Arc::default(), + unfurl_queue: crate::unfurl::Queue::start(), } } diff --git a/crates/chatd/src/adapters/messages/fake.rs b/crates/chatd/src/adapters/messages/fake.rs index 0f3c83c0..5c16f58e 100644 --- a/crates/chatd/src/adapters/messages/fake.rs +++ b/crates/chatd/src/adapters/messages/fake.rs @@ -103,7 +103,7 @@ impl Fake { mine: ME.into(), peer: GRACE_PARTICIPANT.into(), carrier: 0, - updated: 0, + updated: scripted_updated(GRACE), phones: false, status: 1, read_only: false, @@ -135,7 +135,7 @@ impl Fake { mine: ME.into(), peer: String::new(), carrier: 0, - updated: 0, + updated: scripted_updated(CLUB), phones: false, status: 1, read_only: false, @@ -297,14 +297,35 @@ impl Fake { } } +/// True while `TINYCLIENT_MESSAGES_MANY=100` scripts one conversation of 100 messages. +fn many() -> bool { + std::env::var("TINYCLIENT_MESSAGES_MANY").ok().as_deref() == Some("100") +} + +/// When the phone's chat list says the newest message of `conversation` was sent. chatd compares +/// it with the newest message it stored, and asks nothing of a chat nothing arrived in. 0: this +/// phone holds nothing for it. +fn scripted_updated(conversation: &str) -> i64 { + if conversation == GRACE && many() { + SCRIPTED_AT + SCRIPTED_LINES + } else { + 0 + } +} + +/// When the scripted lines were sent: line `n` at `SCRIPTED_AT + n` seconds, so the newest +/// line is the newest message the phone holds for Grace's chat. +const SCRIPTED_AT: i64 = 1_700_000_000; +const SCRIPTED_LINES: i64 = 100; + /// `TINYCLIENT_MESSAGES_MANY=100` is one conversation of 100 messages, newest page first. /// A cursor id `m-NNNN` is exclusive: the next page ends at the message before it. fn scripted_page(conversation: &str, before: Option<&str>) -> Vec { - if conversation != GRACE || std::env::var("TINYCLIENT_MESSAGES_MANY").ok().as_deref() != Some("100") { + if conversation != GRACE || !many() { return Vec::new(); } let end = match before { - None => 100, + None => SCRIPTED_LINES, Some(id) => { let Some(n) = id.strip_prefix("m-").and_then(|n| n.parse::().ok()) else { return Vec::new(); @@ -319,7 +340,7 @@ fn scripted_page(conversation: &str, before: Option<&str>) -> Vec { (start..=end) .map(|n| { let mut line = note(GRACE, "Grace Ombra", GRACE, &format!("m-{n:04}"), &format!("line {n}"), false, Vec::new(), Vec::new()); - line.sent = 1_700_000_000 + n; + line.sent = SCRIPTED_AT + n; // The 90th-newest line. A photo here is older than the first page, so a shared // search that only saw that page would miss it. if n == 11 { diff --git a/crates/chatd/src/unfurl.rs b/crates/chatd/src/unfurl.rs index d7f7b0f3..c218a961 100644 --- a/crates/chatd/src/unfurl.rs +++ b/crates/chatd/src/unfurl.rs @@ -2,25 +2,83 @@ //! (Google Messages, Tiny servers, etc.). //! //! Fetches HTML metadata (`og:title`, `og:site_name`, `og:description`, ``, -//! `<meta name="description">`) with a strict timeout and byte cap, and caches results in memory. +//! `<meta name="description">`) with a strict timeout and byte cap, and remembers every link it +//! looked up. Links wait in one queue that one thread reads in turn, so a page of links is +//! never a thread each. use protocol::Preview; -use std::collections::HashMap; use std::io::Read; -use std::sync::{Mutex, OnceLock}; +use std::sync::{mpsc, Mutex}; use std::time::Duration; /// Maximum HTML bytes read from a page while looking for title/description metadata. const MAX_HTML_BYTES: u64 = 256 * 1024; /// Network timeout for a single unfurl fetch. const FETCH_TIMEOUT: Duration = Duration::from_secs(5); -/// Maximum cached URLs kept in memory. +/// Most links the cache keeps. Past it the oldest leaves. const CACHE_CAP: usize = 256; +/// Longest link the cache keeps, in bytes. A longer one is looked up each time and not kept. +const LINK_CAP: usize = 2048; +/// Most links waiting for their preview. Past it a link is left without one until its message +/// is read again. +const QUEUE_CAP: usize = 64; -static GLOBAL_CACHE: OnceLock<Mutex<HashMap<String, Option<Preview>>>> = OnceLock::new(); +/// The links looked up so far, oldest first. `None` is a link that was looked up and has no +/// preview: it is kept too, so its page is not asked for again. +#[derive(Default)] +pub struct Cache { + links: Vec<(String, Option<Preview>)>, +} + +impl Cache { + /// What is kept for `url`: `Some(None)` is a link known to have no preview. + pub fn get(&self, url: &str) -> Option<Option<Preview>> { + self.links + .iter() + .find(|(kept, _)| kept.as_str() == url) + .map(|(_, preview)| preview.clone()) + } -fn global_cache() -> &'static Mutex<HashMap<String, Option<Preview>>> { - GLOBAL_CACHE.get_or_init(|| Mutex::new(HashMap::new())) + /// Keeps `result` for `url`. True when that added a link without a preview to the cache or + /// took one out, which is the part chatd keeps between runs. + pub fn insert(&mut self, url: &str, result: Option<Preview>) -> bool { + if url.len() > LINK_CAP { + return false; + } + if let Some(kept) = self.links.iter_mut().find(|(kept, _)| kept.as_str() == url) { + let changed = kept.1.is_none() != result.is_none(); + kept.1 = result; + return changed; + } + let mut changed = result.is_none(); + // A full cache loses its oldest link first. + if self.links.len() >= CACHE_CAP { + changed |= self.links.remove(0).1.is_none(); + } + self.links.push((url.to_owned(), result)); + changed + } + + /// The links that have no preview, as chatd keeps them between runs. A link with a preview + /// keeps it on its message. + pub fn kept(&self) -> String { + let bare: Vec<&str> = self + .links + .iter() + .filter(|(_, preview)| preview.is_none()) + .map(|(url, _)| url.as_str()) + .collect(); + serde_json::to_string(&bare).unwrap_or_default() + } + + /// The cache as an earlier run kept it. One that cannot be read is empty: its links are + /// looked up again, which costs a request and is never wrong. + pub fn read(kept: &str) -> Cache { + let bare: Vec<String> = serde_json::from_str(kept).unwrap_or_default(); + Cache { + links: bare.into_iter().map(|url| (url, None)).collect(), + } + } } /// Extracts the first `http://` or `https://` URL from message text, trimming trailing @@ -44,33 +102,65 @@ pub fn extract_url(text: &str) -> Option<String> { None } -/// Fetches a link preview card for `url`, using the process-wide in-memory cache. -pub fn fetch(url: &str) -> Option<Preview> { - fetch_with_cache(url, global_cache()) -} - -/// Fetches a link preview card for `url` using a caller-provided cache (handy for isolated tests). -pub fn fetch_with_cache( - url: &str, - cache: &Mutex<HashMap<String, Option<Preview>>>, -) -> Option<Preview> { +/// Looks `url` up. A link looked up before is answered from `cache`. The second value is true +/// when a link without a preview was added to the cache or left it, so chatd keeps the cache. +pub fn fetch_with_cache(url: &str, cache: &Mutex<Cache>) -> (Option<Preview>, bool) { { - let guard = cache.lock().unwrap_or_else(|p| p.into_inner()); - if let Some(hit) = guard.get(url) { - return hit.clone(); + let cache = cache.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if let Some(kept) = cache.get(url) { + return (kept, false); } } + // Not held while the page is asked for: a slow page would hold every other link up. let result = fetch_uncached(url); - { - let mut guard = cache.lock().unwrap_or_else(|p| p.into_inner()); - if guard.len() >= CACHE_CAP && !guard.contains_key(url) { - if let Some(oldest) = guard.keys().next().cloned() { - guard.remove(&oldest); + let kept = cache + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .insert(url, result.clone()); + (result, kept) +} + +type Job = Box<dyn FnOnce() + Send>; + +/// Where links wait for their preview. One thread reads them in turn, first asked first +/// answered, so a page of links never starts a thread each. Dropping the queue ends the thread +/// once what is in it is done. +pub struct Queue { + send: mpsc::SyncSender<Job>, +} + +impl Queue { + /// Starts that thread. It uses nothing while no link waits. + pub fn start() -> Queue { + let (send, jobs) = mpsc::sync_channel::<Job>(QUEUE_CAP); + if let Err(err) = std::thread::Builder::new() + .name("messages-unfurl".into()) + .spawn(move || { + for job in jobs { + // One link that panics must not leave the rest without their preview. + if std::panic::catch_unwind(std::panic::AssertUnwindSafe(job)).is_err() { + tracing::warn!("chatd: looking up a link for a preview failed"); + } + } + }) + { + tracing::warn!("chatd: no thread to look links up, so no link previews: {err}"); + } + Queue { send } + } + + /// Adds `job`. False when the queue is full or its thread is gone: the job is dropped, and + /// a link that is dropped is looked up the next time its message is read. + pub fn add(&self, job: Job) -> bool { + match self.send.try_send(job) { + Ok(()) => true, + Err(mpsc::TrySendError::Full(_)) => { + tracing::debug!("chatd: too many links wait for a preview; one is left for the next time its message is read"); + false } + Err(mpsc::TrySendError::Disconnected(_)) => false, } - guard.insert(url.to_owned(), result.clone()); } - result } /// Redirects followed for one page. Each one is checked the same way as the first address. @@ -373,17 +463,100 @@ Connection: close } }); - let cache = Mutex::new(HashMap::new()); + let cache = Mutex::new(Cache::default()); let url = format!("http://{addr}/article"); - let first = fetch_with_cache(&url, &cache).expect("preview"); + let (first, kept) = fetch_with_cache(&url, &cache); + let first = first.expect("preview"); assert_eq!(first.title, "Tiny & Fast"); assert_eq!(first.site, "Example News"); assert_eq!(first.description, "A short summary."); + assert!(!kept, "a link with a preview keeps it on its message, so the note does not change"); assert_eq!(hits.load(Ordering::SeqCst), 1); - // Second call hits the in-memory cache without contacting the server again. - let second = fetch_with_cache(&url, &cache).expect("cached preview"); - assert_eq!(second, first); + // Second call hits the cache without contacting the server again. + let (second, kept) = fetch_with_cache(&url, &cache); + assert_eq!(second, Some(first)); + assert!(!kept); assert_eq!(hits.load(Ordering::SeqCst), 1); } + + #[test] + fn a_link_with_no_preview_is_remembered_between_runs() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let hits = Arc::new(AtomicUsize::new(0)); + let hits_bg = hits.clone(); + std::thread::spawn(move || { + for mut stream in listener.incoming().flatten() { + hits_bg.fetch_add(1, Ordering::SeqCst); + let mut buf = [0u8; 1024]; + let _ = stream.read(&mut buf); + let _ = stream.write_all(b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"); + } + }); + + let first = Mutex::new(Cache::default()); + let url = format!("http://{addr}/gone"); + let (none, kept) = fetch_with_cache(&url, &first); + assert!(none.is_none() && kept, "a link without a preview is what the note keeps"); + + // The next run starts from that note and asks for the page again not once. + let next = Mutex::new(Cache::read(&first.lock().unwrap().kept())); + let (again, kept) = fetch_with_cache(&url, &next); + assert!(again.is_none() && !kept); + assert_eq!(hits.load(Ordering::SeqCst), 1, "the page was asked for again after a restart"); + assert_eq!(next.lock().unwrap().get("/elsewhere"), None, "only a link that was looked up is kept"); + } + + #[test] + fn the_cache_keeps_the_newest_links_and_no_long_one() { + let mut cache = Cache::default(); + for n in 0..CACHE_CAP { + assert!(cache.insert(&format!("https://example.com/{n}"), None)); + } + assert!(cache.insert("https://example.com/last", None)); + assert_eq!(cache.get("https://example.com/0"), None, "the oldest link left the full cache"); + assert_eq!(cache.get("https://example.com/1"), Some(None), "the rest is still kept"); + + // A link this long is looked up each time and never kept. + let long = format!("https://example.com/{}", "a".repeat(LINK_CAP)); + assert!(!cache.insert(&long, None)); + assert_eq!(cache.get(&long), None); + + // A link that gains a preview leaves the note, and one that loses it comes back. + let page = parse_html("https://example.com/1", "<html><head><title>Page"); + assert!(cache.insert("https://example.com/1", page.clone())); + assert_eq!(cache.get("https://example.com/1"), Some(page)); + assert!(cache.insert("https://example.com/1", None)); + assert_eq!(cache.get("https://example.com/1"), Some(None)); + } + + #[test] + fn the_queue_runs_its_jobs_in_turn_and_takes_no_more_than_it_holds() { + use std::sync::mpsc; + let queue = Queue::start(); + let (started, began) = mpsc::channel(); + let (gate, gated) = mpsc::channel(); + let (done, finished) = mpsc::channel(); + assert!(queue.add(Box::new(move || { + let _ = started.send(()); + let _ = gated.recv(); + }))); + began.recv().unwrap(); + + // The first job waits, so every other one waits in the queue behind it. + for n in 0..QUEUE_CAP { + let done = done.clone(); + assert!(queue.add(Box::new(move || { + let _ = done.send(n); + }))); + } + assert!(!queue.add(Box::new(|| {})), "a full queue takes no more"); + drop(done); + gate.send(()).unwrap(); + + // The channel ends once every queued job has run. + let order: Vec = finished.iter().collect(); + assert_eq!(order, (0..QUEUE_CAP).collect::>()); + } } diff --git a/crates/chatd/tests/messages.rs b/crates/chatd/tests/messages.rs index a09e5993..76b6561b 100644 --- a/crates/chatd/tests/messages.rs +++ b/crates/chatd/tests/messages.rs @@ -11,7 +11,8 @@ use protocol::{ use std::io::Write; use std::path::PathBuf; use std::process::{Child, Command, Stdio}; -use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering}; +use std::sync::Arc; use std::thread::sleep; use std::time::{Duration, Instant}; @@ -39,6 +40,8 @@ fn account() -> AccountKey { struct World { child: Child, dir: PathBuf, + /// Whether the phone scripts a conversation of 100 messages. + many: bool, } impl World { @@ -83,49 +86,16 @@ impl World { .unwrap(); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); - let log = std::fs::File::create(dir.join("stderr.log")).unwrap(); - // `CHATD_TEST_BIN` names a copy of the binary, for a target directory other builds also write to. - let mut command = Command::new( - std::env::var("CHATD_TEST_BIN") - .unwrap_or_else(|_| env!("CARGO_BIN_EXE_chatd").to_owned()), - ); - command - .env("TINYCLIENT_DIR", &dir) - .env_remove("TINYCLIENT_MESSAGES_FAKE") - .env_remove("TINYCLIENT_MESSAGES_RELAY") - .env_remove("TINYCLIENT_MESSAGES_QR_TTL_MS") - .env_remove("TINYCLIENT_SESSION_DISCORD") - .env_remove("TINYCLIENT_SESSION_SLACK") - .env_remove("TINYCLIENT_SESSION_TELEGRAM") - .env_remove("TINYCLIENT_SESSION_TEAMS") - .env_remove("TINYCLIENT_SESSION_SIGNAL") - .env_remove("TINYCLIENT_SESSION_MESSAGES") - .env_remove("TINYCLIENT_MESSAGES_OFFLINE") - .stderr(Stdio::from(log)); - if let Some((url, qr_ttl_ms)) = relay { - command.env("TINYCLIENT_MESSAGES_RELAY", url); - if let Some(ms) = qr_ttl_ms { - command.env("TINYCLIENT_MESSAGES_QR_TTL_MS", ms.to_string()); - } - } else { - command.env("TINYCLIENT_MESSAGES_FAKE", "1"); - } - if offline { - command.env("TINYCLIENT_MESSAGES_OFFLINE", "1"); - } - if let Some(session) = session { - command.env("TINYCLIENT_SESSION_MESSAGES", session); - } - if many { - command.env("TINYCLIENT_MESSAGES_MANY", "100"); - } - let child = command.spawn().unwrap(); - let deadline = Instant::now() + Duration::from_secs(10); - while ChatStream::connect(&dir.join("chat.sock")).is_err() { - assert!(Instant::now() < deadline, "chatd did not open its socket"); - sleep(Duration::from_millis(10)); - } - World { child, dir } + let child = launch(&dir, session, many, offline, relay); + World { child, dir, many } + } + + /// chatd started again on the same directory: a later connection to the same phone, which + /// finds everything the last connection stored. + fn restart(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + self.child = launch(&self.dir, Some(SESSION), self.many, false, None); } fn ask(&self, request: Request) -> Response { @@ -159,6 +129,14 @@ impl World { .collect() } + /// How many pages of `chat` the phone was asked for. + fn asked(&self, chat: &str) -> usize { + self.calls() + .iter() + .filter(|call| call.starts_with(&format!("history {chat}"))) + .count() + } + fn heard(&self, line: &str) { self.until(&format!("Messages to hear {line:?}"), || { self.calls().iter().any(|call| call == line).then_some(()) @@ -359,6 +337,59 @@ impl Drop for World { } } +/// Starts chatd on `dir` with the scripted phone and waits for its socket. +fn launch( + dir: &std::path::Path, + session: Option<&str>, + many: bool, + offline: bool, + relay: Option<(&str, Option)>, +) -> Child { + let log = std::fs::File::create(dir.join("stderr.log")).unwrap(); + // `CHATD_TEST_BIN` names a copy of the binary, for a target directory other builds also write to. + let mut command = Command::new( + std::env::var("CHATD_TEST_BIN") + .unwrap_or_else(|_| env!("CARGO_BIN_EXE_chatd").to_owned()), + ); + command + .env("TINYCLIENT_DIR", dir) + .env_remove("TINYCLIENT_MESSAGES_FAKE") + .env_remove("TINYCLIENT_MESSAGES_RELAY") + .env_remove("TINYCLIENT_MESSAGES_QR_TTL_MS") + .env_remove("TINYCLIENT_SESSION_DISCORD") + .env_remove("TINYCLIENT_SESSION_SLACK") + .env_remove("TINYCLIENT_SESSION_TELEGRAM") + .env_remove("TINYCLIENT_SESSION_TEAMS") + .env_remove("TINYCLIENT_SESSION_SIGNAL") + .env_remove("TINYCLIENT_SESSION_MESSAGES") + .env_remove("TINYCLIENT_MESSAGES_OFFLINE") + .stderr(Stdio::from(log)); + if let Some((url, qr_ttl_ms)) = relay { + command.env("TINYCLIENT_MESSAGES_RELAY", url); + if let Some(ms) = qr_ttl_ms { + command.env("TINYCLIENT_MESSAGES_QR_TTL_MS", ms.to_string()); + } + } else { + command.env("TINYCLIENT_MESSAGES_FAKE", "1"); + } + if offline { + command.env("TINYCLIENT_MESSAGES_OFFLINE", "1"); + } + if let Some(session) = session { + command.env("TINYCLIENT_SESSION_MESSAGES", session); + } + if many { + command.env("TINYCLIENT_MESSAGES_MANY", "100"); + } + let child = command.spawn().unwrap(); + let deadline = Instant::now() + Duration::from_secs(10); + while ChatStream::connect(&dir.join("chat.sock")).is_err() { + assert!(Instant::now() < deadline, "chatd did not open its socket"); + sleep(Duration::from_millis(10)); + } + child +} + #[test] fn a_paired_phone_lists_its_chats_and_a_text_arrives() { let world = World::linked(); @@ -1210,22 +1241,14 @@ fn scrolling_back_reads_every_message_and_then_stops_asking() { calls.iter().any(|call| call == "history phone-grace m-0021"), "the last page did not start after the second: {calls:?}" ); - let asked = world - .calls() - .iter() - .filter(|call| call.starts_with("history phone-grace")) - .count(); + let asked = world.asked(GRACE); let _ = world.before(&oldest(&all)); world.ask(Request::Typing { conversation: key(GRACE), activity: protocol::Compose::Typing, }); world.heard(&format!("typing {GRACE}")); - let after = world - .calls() - .iter() - .filter(|call| call.starts_with("history phone-grace")) - .count(); + let after = world.asked(GRACE); assert_eq!( after, asked, "a third scroll asked the phone again: {:?}", @@ -1971,36 +1994,72 @@ fn create_group_starts_a_named_group_conversation_with_multiple_numbers() { } } -#[test] -fn link_previews_unfurl_for_known_contacts_and_skip_unknown_numbers_and_spam() { +/// The page the loopback page server shows for a link. +const PAGE: &str = r#" + + + + ok"#; + +/// A page server on loopback that chatd may look links up at, as a scratch directory lets it. +struct Pages { + addr: std::net::SocketAddr, + hits: Arc, + /// The most requests that were open at one time. + peak: Arc, +} + +/// Starts one. It counts its hits, holds every answer for `hold`, answers 404 to a link with +/// `dead` in its path and [`PAGE`] to anything else. +fn pages(hold: Duration) -> Pages { use std::io::Read; use std::net::TcpListener; - use std::sync::atomic::{AtomicUsize, Ordering}; - use std::sync::Arc; - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = listener.local_addr().unwrap(); let hits = Arc::new(AtomicUsize::new(0)); - let hits_bg = hits.clone(); + let peak = Arc::new(AtomicUsize::new(0)); + let open = Arc::new(AtomicUsize::new(0)); + let (counted, highest, busy) = (hits.clone(), peak.clone(), open.clone()); std::thread::spawn(move || { for stream in listener.incoming().flatten() { - hits_bg.fetch_add(1, Ordering::SeqCst); - let mut stream = stream; - let mut buf = [0u8; 1024]; - let _ = stream.read(&mut buf); - let body = r#" - - - - ok"#; - let resp = format!( - "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", - body.len(), - body - ); - let _ = stream.write_all(resp.as_bytes()); + let (counted, highest, busy) = (counted.clone(), highest.clone(), busy.clone()); + std::thread::spawn(move || { + counted.fetch_add(1, Ordering::SeqCst); + highest.fetch_max(busy.fetch_add(1, Ordering::SeqCst) + 1, Ordering::SeqCst); + let mut stream = stream; + let mut asked = Vec::new(); + let mut buf = [0u8; 1024]; + // The request line says which page is asked for. + while !asked.contains(&b'\n') { + match stream.read(&mut buf) { + Ok(0) | Err(_) => break, + Ok(n) => asked.extend_from_slice(&buf[..n]), + } + } + std::thread::sleep(hold); + // Counted out before the answer: a client that comes back at once is never two. + busy.fetch_sub(1, Ordering::SeqCst); + let (status, body) = if asked.starts_with(b"GET /dead") { + ("404 Not Found", "") + } else { + ("200 OK", PAGE) + }; + let resp = format!( + "HTTP/1.1 {status}\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let _ = stream.write_all(resp.as_bytes()); + }); } }); + Pages { addr, hits, peak } +} + +#[test] +fn link_previews_unfurl_for_known_contacts_and_skip_unknown_numbers_and_spam() { + let server = pages(Duration::ZERO); + let addr = server.addr; + let hits = &server.hits; let world = World::linked(); world.connected(); @@ -2042,6 +2101,94 @@ fn link_previews_unfurl_for_known_contacts_and_skip_unknown_numbers_and_spam() { assert_eq!(hits.load(Ordering::SeqCst), hits_after_known, "spam conversation must never unfurl links"); } +#[test] +fn a_link_with_no_preview_is_not_fetched_again_after_a_restart() { + let server = pages(Duration::ZERO); + let hits = &server.hits; + let mut world = World::linked(); + world.connected(); + let dead = format!("See http://{}/dead", server.addr); + let good = format!("Look at http://{}/good", server.addr); + + // Links are looked up first asked first answered, so the one with no page is done + // once the other shows its preview. + world.steer(&format!("incoming grace {dead}")); + world.steer(&format!("incoming grace {good}")); + let kept = world.until("link preview card", || { + world + .messages(GRACE) + .into_iter() + .find(|m| m.text == good && !m.previews.is_empty()) + }); + assert_eq!(kept.previews[0].title, "Bridge Schedule"); + assert!(world.arrived(GRACE, &dead).previews.is_empty()); + assert_eq!(hits.load(Ordering::SeqCst), 2, "each link was looked up once"); + + // chatd is started again: what it looked up is still known, so neither page is asked for. + world.restart(); + world.connected(); + world.steer(&format!("incoming grace {dead}")); + sleep(Duration::from_millis(500)); + assert_eq!(hits.load(Ordering::SeqCst), 2, "a link that had no preview was fetched again after a restart"); + world.steer(&format!("incoming grace {good}")); + sleep(Duration::from_millis(500)); + assert_eq!(hits.load(Ordering::SeqCst), 2, "a kept preview was fetched again after a restart"); + assert_eq!(world.arrived(GRACE, &good).previews.len(), 1, "the preview did not survive the restart"); +} + +#[test] +fn links_are_looked_up_one_at_a_time_not_a_thread_each() { + // Every answer waits, so links fetched together are open at the page server together. + let server = pages(Duration::from_secs(1)); + let hits = &server.hits; + let world = World::linked(); + world.connected(); + + // The scripted phone names a message after the length of its text, so each text differs. + let links: Vec = (0..6) + .map(|n| format!("{}{n} http://{}/slow/{n}", "#".repeat(n), server.addr)) + .collect(); + for link in &links { + world.steer(&format!("incoming grace {link}")); + } + world.until("six previews", || { + let shown = world + .messages(GRACE) + .into_iter() + .filter(|m| !m.previews.is_empty()) + .count(); + (shown == 6).then_some(()) + }); + for link in &links { + assert_eq!(world.arrived(GRACE, link).previews[0].title, "Bridge Schedule"); + } + assert_eq!(hits.load(Ordering::SeqCst), 6, "each link was looked up once"); + assert_eq!(server.peak.load(Ordering::SeqCst), 1, "a page of links was fetched by a thread each"); +} + +#[test] +fn a_chat_read_to_its_start_is_not_asked_for_again_on_a_later_connection() { + let mut world = World::many(); + world.connected(); + world.until("all one hundred", || { + let lines = world.lines(); + (lines.len() == 100).then_some(lines) + }); + world.heard("history phone-club"); + let (grace, club) = (world.asked(GRACE), world.asked(CLUB)); + assert!(grace >= 3, "a hundred lines of forty take three pages to read: {grace}"); + + // chatd connects again. The phone's list says the newest line is still the newest message + // of the chat, so Grace's chat is left alone. The chat with nothing stored is asked for + // its newest page, which says the background read has had its turn over the chats. + world.restart(); + world.connected(); + world.until("the chat with nothing stored is asked for its newest page", || (world.asked(CLUB) > club).then_some(())); + sleep(Duration::from_millis(600)); + assert_eq!(world.asked(GRACE), grace, "a chat nothing arrived in was asked for its newest page again: {:?}", world.calls()); + assert_eq!(world.lines().len(), 100, "the lines did not survive the restart"); +} + #[test] fn messages_can_be_starred_unstarred_and_listed_under_starred() { let world = World::linked(); diff --git a/e2e/scenarios/messages-restart-asks-nothing-again/drive.linux.sh b/e2e/scenarios/messages-restart-asks-nothing-again/drive.linux.sh new file mode 100644 index 00000000..8682123f --- /dev/null +++ b/e2e/scenarios/messages-restart-asks-nothing-again/drive.linux.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# messages-restart-asks-nothing-again on Linux. The lab runs this with bash while ffmpeg films the display. +set -u +HERE=$(cd "$(dirname "$0")" && pwd) +if command -v python3 >/dev/null 2>&1; then + exec python3 "$HERE/drive.py" +fi +echo "python3 is not on PATH" >&2 +exit 1 diff --git a/e2e/scenarios/messages-restart-asks-nothing-again/drive.macos.sh b/e2e/scenarios/messages-restart-asks-nothing-again/drive.macos.sh new file mode 100644 index 00000000..114b8e3b --- /dev/null +++ b/e2e/scenarios/messages-restart-asks-nothing-again/drive.macos.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# messages-restart-asks-nothing-again on macOS. The lab runs this with bash while the display is filmed. +set -u +HERE=$(cd "$(dirname "$0")" && pwd) +if command -v python3 >/dev/null 2>&1; then + exec python3 "$HERE/drive.py" +fi +echo "python3 is not on PATH" >&2 +exit 1 diff --git a/e2e/scenarios/messages-restart-asks-nothing-again/drive.py b/e2e/scenarios/messages-restart-asks-nothing-again/drive.py new file mode 100644 index 00000000..18a69f5e --- /dev/null +++ b/e2e/scenarios/messages-restart-asks-nothing-again/drive.py @@ -0,0 +1,442 @@ +#!/usr/bin/env python3 +"""After a restart chatd asks neither the phone nor the pages again for what a Messages chat already has. + +Starts this build's chatd with the scripted phone (TINYCLIENT_MESSAGES_FAKE) on an isolated +TINYCLIENT_DIR, steers it over its control file the way tests/messages.rs does, and speaks +chatd's real socket. The phone scripts Grace's chat with a hundred lines, and a page server on +loopback counts what chatd asks it for. + +The first run reads the chat back to its first line and shows two links from Grace: a page with +no preview to show and a page with one. chatd is then stopped and started again on the same +directory. The fixed build asks the phone for no page of the unchanged chat, fetches neither +link again, and looks six links up one at a time. A build from before the fix asks for the +newest page again, fetches the link without a preview again, and fetches the six at once, so +this driver fails there. + +Env from the lab: E2E_OUT, E2E_T0, E2E_APP_DIR. +""" + +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import json +import os +import shutil +import socket +import struct +import subprocess +import sys +import tempfile +import threading +import time + +OUT = os.environ.get("E2E_OUT", "") +T0 = float(os.environ.get("E2E_T0") or time.time()) +APP = os.environ.get("E2E_APP_DIR", "") + +ME = "phone-ada" +GRACE = "phone-grace" +CLUB = "phone-club" +SESSION = json.dumps({"account": ME, "name": "Ada Quill"}) +SLOW = 6 +HOLD = 1.0 + +FAILED = False +STEPS = "" + + +def now(): + return time.time() - T0 + + +def step(words, ok): + global FAILED + if not ok: + FAILED = True + line = '{"t": %s, "step": "%s", "ok": %s}' % (round(now(), 1), words.replace('"', "'"), "true" if ok else "false") + print(("[ok] " if ok else "[FAILED] ") + words, flush=True) + if STEPS: + with open(STEPS, "a", encoding="utf-8") as handle: + handle.write(line + "\n") + + +def app_bin(app_dir): + name = "chatd.exe" if sys.platform == "win32" else "chatd" + if sys.platform == "darwin" and app_dir.endswith(".app"): + return os.path.join(app_dir, "Contents", "MacOS", "chatd") + return os.path.join(app_dir, name) + + +def sip13(data): + """Rust's `DefaultHasher`: SipHash-1-3 with both keys zero.""" + mask = (1 << 64) - 1 + v0, v1, v2, v3 = 0x736F6D6570736575, 0x646F72616E646F6D, 0x6C7967656E657261, 0x7465646279746573 + + def turn(): + nonlocal v0, v1, v2, v3 + v0 = (v0 + v1) & mask + v1 = ((v1 << 13) | (v1 >> 51)) & mask + v1 ^= v0 + v0 = ((v0 << 32) | (v0 >> 32)) & mask + v2 = (v2 + v3) & mask + v3 = ((v3 << 16) | (v3 >> 48)) & mask + v3 ^= v2 + v0 = (v0 + v3) & mask + v3 = ((v3 << 21) | (v3 >> 43)) & mask + v3 ^= v0 + v2 = (v2 + v1) & mask + v1 = ((v1 << 17) | (v1 >> 47)) & mask + v1 ^= v2 + v2 = ((v2 << 32) | (v2 >> 32)) & mask + + whole = len(data) - len(data) % 8 + for at in range(0, whole, 8): + word = int.from_bytes(data[at:at + 8], "little") + v3 ^= word + turn() + v0 ^= word + last = ((len(data) & 0xFF) << 56) | int.from_bytes(data[whole:], "little") + v3 ^= last + turn() + v0 ^= last + v2 ^= 0xFF + for _ in range(3): + turn() + return (v0 ^ v1 ^ v2 ^ v3) & mask + + +def connect(sock_path): + """chatd's socket: a file on Unix, a named pipe on Windows. The pipe is named with the + hasher's hash of that path (crates/protocol/src/ipc.rs).""" + if sys.platform == "win32": + path = os.fsencode(sock_path) + return open("\\\\.\\pipe\\tinyclient-%016x" % sip13(len(path).to_bytes(8, "little") + path), "r+b", buffering=0) + stream = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + stream.settimeout(5) + stream.connect(sock_path) + return stream + + +def write_all(stream, data): + view = memoryview(data) + while view: + written = stream.write(view) + if not written: + raise RuntimeError("chatd's socket took nothing") + view = view[written:] + + +class Chat: + def __init__(self, sock_path): + self.stream = connect(sock_path) + + def ask(self, request): + body = json.dumps(request, separators=(",", ":")).encode() + write_all(self.stream, struct.pack("!I", len(body)) + body) + head = b"" + while len(head) < 4: + got = self.stream.read(4 - len(head)) + if not got: + raise RuntimeError("chatd closed its socket") + head += got + length = struct.unpack("!I", head)[0] + if length > 1024 * 1024: + raise RuntimeError("answer exceeds the protocol size limit") + chunks = b"" + while len(chunks) < length: + got = self.stream.read(length - len(chunks)) + if not got: + raise RuntimeError("chatd closed its socket mid-frame") + chunks += got + return json.loads(chunks) + + def close(self): + try: + self.stream.close() + except OSError: + pass + + +def keep(profile): + """What the run leaves behind for a reader: the phone's record of what chatd asked for, + and chatd's own log.""" + for name, kept in (("messages.calls", "messages.calls"), (os.path.join("logs", "chatd.log"), "chatd.log")): + source = os.path.join(profile, name) + if os.path.isfile(source): + shutil.copy(source, os.path.join(OUT, kept)) + + +def main(): + global STEPS + if not OUT or not APP: + print("E2E_OUT and E2E_APP_DIR are required", file=sys.stderr) + return 1 + os.makedirs(OUT, exist_ok=True) + STEPS = os.path.join(OUT, "steps.jsonl") + open(STEPS, "w", encoding="utf-8").close() + binary = app_bin(APP) + if not os.path.isfile(binary): + step("chatd is in E2E_APP_DIR", False) + return 1 + + server, base = pages() + try: + # A profile of this run alone, empty at the start. chatd's socket lives in it, and a + # socket's path may not be long: so under /tmp on a Mac or a Linux machine. + with tempfile.TemporaryDirectory(prefix="tiny-msg-", dir=None if sys.platform == "win32" else "/tmp") as temp: + profile = os.path.join(temp, "data") + os.makedirs(profile) + drive(binary, profile, base) + keep(profile) + finally: + server.shutdown() + server.server_close() + return 1 if FAILED else 0 + + +def key(id): + return {"network": "messages", "account": ME, "id": id} + + +def wait(what, chat, look, seconds=15): + deadline = time.time() + seconds + while time.time() < deadline: + found = look() + if found is not None: + step(what, True) + return found + time.sleep(0.2) + step(what, False) + return None + + +def ask(chat, request): + try: + return chat.ask(request) + except Exception: + return None + + +def connected(chat): + answer = ask(chat, {"op": "status"}) or {} + return any(account.get("link") == "connected" for account in answer.get("accounts", [])) or None + + +def messages(chat, id): + answer = ask(chat, {"op": "messages", "conversation": key(id), "page": {"at": "newest"}, "limit": 100}) + return (answer or {}).get("messages", []) + + +def lines(chat): + return [message for message in messages(chat, GRACE) if message.get("text", "").startswith("line ")] + + +def preview(chat, needle): + """The first preview on a message of Grace's that links to `needle`, once it has one.""" + for message in messages(chat, GRACE): + if needle in message.get("text", "") and message.get("previews"): + return message["previews"][0] + return None + + +def asked(calls, what): + """How many times the phone wrote a line that starts with `what` to its record.""" + try: + with open(calls, encoding="utf-8") as handle: + return sum(1 for line in handle if line.startswith(what)) + except OSError: + return 0 + + +def start(binary, data, run): + """chatd on `data`, started the way a person starts it.""" + env = os.environ.copy() + env.update(TINYCLIENT_DIR=data, TINYCLIENT_MESSAGES_FAKE="1", TINYCLIENT_MESSAGES_MANY="100", + TINYCLIENT_SESSION_MESSAGES=SESSION) + for name in ("TINYCLIENT_MESSAGES_OFFLINE", "TINYCLIENT_MESSAGES_RELAY", "TINYCLIENT_SESSION_DISCORD", + "TINYCLIENT_SESSION_SLACK", "TINYCLIENT_SESSION_TELEGRAM", "TINYCLIENT_SESSION_TEAMS", + "TINYCLIENT_SESSION_SIGNAL"): + env.pop(name, None) + kwargs = {"cwd": data, "env": env, "stdin": subprocess.DEVNULL} + if sys.platform == "win32": + kwargs["creationflags"] = 0x08000000 + logs = [open(os.path.join(OUT, "chatd-%d.%s.log" % (run, kind)), "w", encoding="utf-8") for kind in ("out", "err")] + kwargs["stdout"], kwargs["stderr"] = logs + return subprocess.Popen([binary], **kwargs), logs + + +def stop(process): + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + + +def running(process, sock_path, what): + """A connection to chatd's socket, once chatd is up and listening.""" + deadline = time.time() + 15 + while time.time() < deadline: + if process.poll() is not None: + step(what, False) + return None + try: + chat = Chat(sock_path) + step(what, True) + return chat + except OSError: + time.sleep(0.1) + step(what, False) + return None + + +def steer(control, line): + """Appends a line to the phone's control file and waits until the phone has taken it.""" + deadline = time.time() + 10 + while not os.path.exists(control) and time.time() < deadline: + time.sleep(0.05) + if not os.path.exists(control): + return False + with open(control, "a", encoding="utf-8", newline="\n") as handle: + handle.write(line + "\n") + end = os.path.getsize(control) + while time.time() < deadline: + try: + with open(control + ".taken", encoding="utf-8") as handle: + at = int(handle.read().strip() or 0) + except (OSError, ValueError): + # The phone rewrites how far it has read; an empty or half-written count waits. + at = 0 + if at >= end: + return True + time.sleep(0.05) + return False + + +HITS = {} +COUNT = [0, 0] +LOCK = threading.Lock() + +PAGE = (b'' + b'' + b'ok') + + +class Pages(BaseHTTPRequestHandler): + """Counts every request, and how many are open at once. A slow page waits before it answers.""" + + def do_GET(self): + with LOCK: + HITS[self.path] = HITS.get(self.path, 0) + 1 + COUNT[0] += 1 + COUNT[1] = max(COUNT[1], COUNT[0]) + if self.path.startswith("/slow/"): + time.sleep(HOLD) + with LOCK: + # Counted out before the answer: a client that comes back at once is never two. + COUNT[0] -= 1 + status, body = (404, b"gone") if self.path == "/dead" else (200, PAGE) + self.send_response(status) + self.send_header("Content-Type", "text/html") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + +def pages(): + server = ThreadingHTTPServer(("127.0.0.1", 0), Pages) + threading.Thread(target=server.serve_forever, daemon=True).start() + return server, "http://127.0.0.1:%d" % server.server_address[1] + + +def hits(path): + return HITS.get(path, 0) + + +def drive(binary, data, base): + sock_path, control, calls = (os.path.join(data, name) for name in ("chat.sock", "messages.ctl", "messages.calls")) + dead = "See " + base + "/dead" + good = "Look at " + base + "/good" + read = empty = 0 + + def with_chatd(run, what, act): + """chatd on the profile for `act` to steer through its socket, and stopped after.""" + process, logs = start(binary, data, run) + chat = running(process, sock_path, what) + try: + if chat is not None: + act(chat) + finally: + if chat: + chat.close() + stop(process) + for handle in logs: + handle.close() + + def first(chat): + nonlocal read, empty + # The first run reads Grace's chat back to its first line. + if wait("Messages is connected", chat, lambda: connected(chat)) is None: + return + if wait("the phone's hundred lines are read back to the first", chat, lambda: (len(lines(chat)) == 100) or None) is None: + return + if wait("the chat with no message is read too", chat, lambda: (asked(calls, "history " + CLUB) >= 1) or None) is None: + return + read, empty = asked(calls, "history " + GRACE), asked(calls, "history " + CLUB) + step("the hundred lines came in %d pages" % read, read >= 3) + + # Links are looked up first asked first answered, so the one with no page is done + # once the other shows its preview. + step("Grace sends a link to a page with no preview", steer(control, "incoming grace " + dead)) + step("Grace sends a link to a page with a preview", steer(control, "incoming grace " + good)) + kept = wait("the page's preview is kept on its message", chat, lambda: preview(chat, "/good")) + if kept is not None: + step("the preview is the page's own", kept.get("title") == "Kept page" and kept.get("site") == "Club News") + step("the link with no page was looked up once", hits("/dead") == 1) + step("the page with a preview was looked up once", hits("/good") == 1) + + def shown(chat): + return all(preview(chat, "/slow/%d" % n) for n in range(SLOW)) or None + + def second(chat): + # The chat with no message is asked for on every connection. That ask says the + # background read has had its turn over the chats, Grace's included. + if wait("Messages is connected again", chat, lambda: connected(chat)) is None: + return + if wait("the background read has had its turn", chat, lambda: (asked(calls, "history " + CLUB) > empty) or None) is None: + return + time.sleep(1.0) + step("an unchanged chat is not asked for a page again", asked(calls, "history " + GRACE) == read) + + step("Grace sends the message with the kept link again", steer(control, "incoming grace " + good)) + time.sleep(1.0) + still = preview(chat, "/good") + step("the kept preview is still on its message after the restart", + still is not None and still.get("title") == "Kept page") + step("a kept preview is not fetched again after a restart", hits("/good") == 1) + + step("Grace sends the message with the other link again", steer(control, "incoming grace " + dead)) + time.sleep(1.0) + step("a link that had no preview is not fetched again after a restart", hits("/dead") == 1) + + # Six lines of different lengths: the scripted phone names a message after its length. + for n in range(SLOW): + steer(control, "incoming grace %s%d %s/slow/%d" % ("#" * (n + 1), n, base, n)) + if wait("six slow pages each show their preview", chat, lambda: shown(chat), 20) is None: + return + step("six links are looked up one at a time, not a thread each", COUNT[1] == 1) + step("each slow page was looked up once", all(hits("/slow/%d" % n) == 1 for n in range(SLOW))) + + with_chatd(1, "chatd opens its socket", first) + if not read: + # Nothing was read, so there is nothing to compare a restart with. + return + # The second run finds everything the first one stored. + with_chatd(2, "chatd opens its socket again", second) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/e2e/scenarios/messages-restart-asks-nothing-again/drive.windows.ps1 b/e2e/scenarios/messages-restart-asks-nothing-again/drive.windows.ps1 new file mode 100644 index 00000000..aeae7165 --- /dev/null +++ b/e2e/scenarios/messages-restart-asks-nothing-again/drive.windows.ps1 @@ -0,0 +1,17 @@ +# messages-restart-asks-nothing-again on Windows. The lab runs this in the console session it is already filming. +$ErrorActionPreference = 'Stop' +$drive = Join-Path $PSScriptRoot 'drive.py' +if (Get-Command py -ErrorAction SilentlyContinue) { + & py -3 $drive + exit $LASTEXITCODE +} +if (Get-Command python -ErrorAction SilentlyContinue) { + & python $drive + exit $LASTEXITCODE +} +if (Get-Command python3 -ErrorAction SilentlyContinue) { + & python3 $drive + exit $LASTEXITCODE +} +Write-Host 'python is not on PATH (tried py -3, python, python3)' +exit 1 diff --git a/e2e/scenarios/messages-restart-asks-nothing-again/scenario.json b/e2e/scenarios/messages-restart-asks-nothing-again/scenario.json new file mode 100644 index 00000000..f4883dd3 --- /dev/null +++ b/e2e/scenarios/messages-restart-asks-nothing-again/scenario.json @@ -0,0 +1,12 @@ +{ + "id": "messages-restart-asks-nothing-again", + "title": "After a restart chatd asks neither the phone nor the pages again for what a Messages chat already has", + "platforms": ["windows", "macos", "linux"], + "not_applicable": { + "android": "The phone proof build does not run desktop chatd. The background read of a chat and its link previews are chatd's.", + "ios": "The phone proof build does not run desktop chatd. The background read of a chat and its link previews are chatd's." + }, + "needs": [], + "release": false, + "max_still_seconds": 90 +}