//! `feedback.send` and `feedback.flush` over a scripted Worker: what the core //! gathers and posts, who the report says sent it, and that a report nothing //! took stays on the phone until something does. Every sentence, number and //! byte is invented. use std::path::Path; use std::sync::Arc; use base64::{engine::general_purpose::STANDARD, Engine}; use cotton_client::transport::object::ObjectAddress; use cotton_client::transport::scripted::{Reply, ScriptedExchange, Seen}; use serde_json::{json, Value}; use super::{over, Facts, OUTBOX, PATH, PLATFORM}; use crate::handle::CottonHandle; use crate::phone::passwords::tests::phone; use crate::phone::personal_object::ObjectDoor; const CREDENTIAL: &str = "ctd_11111111-1111-4111-8111-111111111111_test-credential"; const OPEN: &str = "https://cottondb.example.test"; const PNG: [u8; 12] = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3, 4]; fn facts() -> Facts { Facts { app: "notes".into(), build: "1.4 (212)".into(), core_log: vec!["2026-11-13T10:00:00Z info core: opened".into()] } } fn signed_in(handle: &CottonHandle, replies: impl IntoIterator) -> Arc { let exchange = ScriptedExchange::new(replies); let door = ObjectDoor { address: ObjectAddress::open(OPEN).expect("an address"), exchange: exchange.clone(), credential: CREDENTIAL.to_string() }; handle.client().set_object_door(Some(Arc::new(door))); exchange } fn call(handle: &CottonHandle, outbox: &Path, exchange: Arc, method: &str, request: Value) -> Result { over(&handle.client(), outbox, &facts(), exchange, method, &request) } fn body(seen: &Seen) -> Value { serde_json::from_slice(&seen.body).expect("a JSON body") } fn kept(outbox: &Path) -> usize { std::fs::read_dir(outbox).map(|dir| dir.filter_map(Result::ok).filter(|e| e.path().extension().and_then(|x| x.to_str()) == Some("json")).count()).unwrap_or(0) } fn taken(sender: &str) -> Reply { Reply::json(201, &json!({ "id": "x", "status": "new", "sender": sender, "pushed": true }).to_string()) } #[test] fn a_signed_in_report_goes_with_the_device_credential_and_what_the_core_knows() { let (dir, handle) = phone(); let outbox = dir.path().join(OUTBOX); let exchange = signed_in(&handle, [taken("signed_in")]); let shot = dir.path().join("shake.png"); std::fs::write(&shot, PNG).unwrap(); let answer = call(&handle, &outbox, ScriptedExchange::new([]), "feedback.send", json!({ "sentence": " The fan does not open ", "screenshotPath": shot.to_str().unwrap(), "route": "/notes", "device": "iPhone16,1", "os": "iOS 26.1", "log": ["shell: shake"] })).expect("sent"); assert_eq!(answer["state"], "sent"); assert_eq!(answer["sender"], "signed_in"); assert_eq!(answer["pushed"], true); let seen = exchange.only(); assert_eq!((seen.method.as_str(), seen.path.as_str()), ("POST", PATH)); assert_eq!(seen.header("authorization"), Some(format!("Bearer {CREDENTIAL}").as_str())); let sent = body(&seen); assert_eq!(sent["id"], answer["id"]); assert_eq!(sent["sentence"], "The fan does not open"); assert_eq!((sent["app"].as_str(), sent["build"].as_str(), sent["platform"].as_str()), (Some("notes"), Some("1.4 (212)"), Some(PLATFORM))); assert_eq!((sent["route"].as_str(), sent["device"].as_str(), sent["os"].as_str()), (Some("/notes"), Some("iPhone16,1"), Some("iOS 26.1"))); assert_eq!(sent["screenshot"], json!({ "type": "image/png", "base64": STANDARD.encode(PNG) })); assert_eq!(sent["log"], json!(["2026-11-13T10:00:00Z info core: opened", "shell: shake"]), "the core's tail, then the shell's"); assert!(sent.get("sender_number").is_none() && sent.get("number").is_none(), "the body never names a sender"); assert_eq!(kept(&outbox), 0, "a report taken leaves the outbox"); } #[test] fn a_signed_out_report_goes_anonymous_to_the_server_the_shell_names() { let (dir, handle) = phone(); let outbox = dir.path().join(OUTBOX); let exchange = ScriptedExchange::new([taken("anonymous")]); let answer = call(&handle, &outbox, exchange.clone(), "feedback.send", json!({ "sentence": "Books shows a blank shelf", "server": OPEN })).expect("sent"); assert_eq!((answer["state"].as_str(), answer["sender"].as_str()), (Some("sent"), Some("anonymous"))); let seen = exchange.only(); assert_eq!(seen.origin, OPEN); assert_eq!(seen.path, PATH); assert!(seen.header("authorization").is_none(), "no bearer: anonymous"); } #[test] fn a_report_nothing_took_is_kept_and_sent_by_a_later_flush() { let (dir, handle) = phone(); let outbox = dir.path().join(OUTBOX); // Offline: the script has no answer, as a phone with no network has none. let answer = call(&handle, &outbox, ScriptedExchange::new([]), "feedback.send", json!({ "sentence": "Money froze", "server": OPEN })).expect("kept, not refused"); assert_eq!(answer["state"], "kept"); assert_eq!(answer["code"], "offline"); assert_eq!(kept(&outbox), 1, "kept on the phone"); // Too many: still kept. let busy = ScriptedExchange::new([Reply::json(429, r#"{"code":"too_many_reports","message":"later"}"#)]); assert_eq!(call(&handle, &outbox, busy, "feedback.flush", json!({})).unwrap(), json!({ "sent": 0, "kept": 1, "refused": 0 })); // Back online: the same report, the same id, sent once. let online = ScriptedExchange::new([taken("anonymous")]); assert_eq!(call(&handle, &outbox, online.clone(), "feedback.flush", json!({})).unwrap(), json!({ "sent": 1, "kept": 0, "refused": 0 })); assert_eq!(body(&online.only())["id"], answer["id"], "a retry is the same report"); assert_eq!(kept(&outbox), 0); } #[test] fn a_refusal_in_words_is_said_and_the_report_goes() { let (dir, handle) = phone(); let outbox = dir.path().join(OUTBOX); let exchange = ScriptedExchange::new([Reply::json(400, r#"{"code":"bad_app","message":"app: the app's slug"}"#)]); let refused = call(&handle, &outbox, exchange, "feedback.send", json!({ "sentence": "x", "server": OPEN })).expect_err("refused"); assert_eq!(refused.code, "bad_app"); assert_eq!(kept(&outbox), 0, "a report the Worker can never take is not kept to be refused again"); } #[test] fn a_credential_the_worker_no_longer_takes_sends_the_report_without_it() { let (dir, handle) = phone(); let outbox = dir.path().join(OUTBOX); let exchange = signed_in(&handle, [Reply::json(401, r#"{"code":"invalid_credential","message":"sign in again"}"#), taken("anonymous")]); let answer = call(&handle, &outbox, ScriptedExchange::new([]), "feedback.send", json!({ "sentence": "Calendar is empty" })).expect("sent"); assert_eq!((answer["state"].as_str(), answer["sender"].as_str()), (Some("sent"), Some("anonymous"))); let (first, second) = (exchange.nth(0), exchange.nth(1)); assert!(first.header("authorization").is_some()); assert!(second.header("authorization").is_none()); assert_eq!(body(&first)["id"], body(&second)["id"]); } #[test] fn a_report_made_signed_out_stays_anonymous_after_a_sign_in() { let (dir, handle) = phone(); let outbox = dir.path().join(OUTBOX); call(&handle, &outbox, ScriptedExchange::new([]), "feedback.send", json!({ "sentence": "Photos is slow", "server": OPEN })).expect("kept"); let exchange = signed_in(&handle, [taken("anonymous")]); call(&handle, &outbox, ScriptedExchange::new([]), "feedback.flush", json!({})).unwrap(); assert!(exchange.only().header("authorization").is_none(), "it never claims the number signed in since"); } #[test] fn what_could_never_arrive_is_refused_before_it_is_kept() { let (dir, handle) = phone(); let outbox = dir.path().join(OUTBOX); let none = || ScriptedExchange::new([]); assert_eq!(call(&handle, &outbox, none(), "feedback.send", json!({ "sentence": " " })).unwrap_err().code, "bad_request"); assert_eq!(call(&handle, &outbox, none(), "feedback.send", json!({ "sentence": "x".repeat(super::SENTENCE_MAX + 1) })).unwrap_err().code, "bad_request"); assert_eq!(call(&handle, &outbox, none(), "feedback.send", json!({ "sentence": "x", "screenshot": "AAAA" })).unwrap_err().code, "bad_request"); let gif = dir.path().join("shake.gif"); std::fs::write(&gif, b"GIF89a").unwrap(); assert_eq!(call(&handle, &outbox, none(), "feedback.send", json!({ "sentence": "x", "screenshotPath": gif.to_str().unwrap() })).unwrap_err().code, "bad_request"); assert_eq!(call(&handle, &outbox, none(), "feedback.send", json!({ "sentence": "x", "screenshotPath": dir.path().join("gone.png").to_str().unwrap() })).unwrap_err().code, "unreadable"); assert_eq!(kept(&outbox), 0); } #[test] fn the_log_is_cut_from_its_oldest_end_to_the_workers_cap() { let core: Vec = (0..300).map(|n| format!("core {n} {}", "c".repeat(400))).collect(); let shell: Vec = (0..300).map(|n| json!(format!("shell {n} {}", "s".repeat(1000)))).collect(); let log = super::log_of(&core, Some(&Value::Array(shell))); assert!(log.iter().map(|line| line.len() + 1).sum::() <= super::LOG_MAX_BYTES); assert_eq!(log.last().map(|line| line.starts_with("shell 299 ")), Some(true), "the newest line stays"); assert!(log.iter().all(|line| line.chars().count() <= 500), "a line is cut at 500"); } #[test] fn both_methods_are_on_the_phones_list() { for method in super::METHODS { assert!(crate::methods::CLIENT_METHODS.contains(&method), "{method}"); assert!(crate::methods::ALL_METHODS.contains(&method), "{method}"); } } /// One HTTP answer on `listener`: the whole request read (headers, then /// `content-length` bytes), then a 201 the way the Worker takes a report. /// Answers the request's body. fn take_one(listener: std::net::TcpListener) -> Value { use std::io::{Read, Write}; let (mut stream, _) = listener.accept().expect("a connection"); let mut seen = Vec::new(); let mut chunk = [0u8; 65536]; let header_end = loop { let n = stream.read(&mut chunk).expect("the request"); assert!(n > 0, "the connection closed before the headers ended"); seen.extend_from_slice(&chunk[..n]); if let Some(at) = seen.windows(4).position(|w| w == b"\r\n\r\n") { break at + 4; } }; let head = String::from_utf8_lossy(&seen[..header_end]).to_ascii_lowercase(); let length: usize = head.lines().find_map(|line| line.strip_prefix("content-length:")).map(|v| v.trim().parse().unwrap()).unwrap_or(0); while seen.len() < header_end + length { let n = stream.read(&mut chunk).expect("the body"); assert!(n > 0, "the connection closed before the body ended"); seen.extend_from_slice(&chunk[..n]); } let body: Value = serde_json::from_slice(&seen[header_end..header_end + length]).expect("a JSON body"); let answer = json!({ "id": body["id"], "status": "new", "sender": "anonymous", "pushed": false }).to_string(); write!(stream, "HTTP/1.1 201 Created\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{answer}", answer.len()).unwrap(); body } /// RULE: over the real socket, a report to a server nobody answers (a dead port: the phone with no connection) is kept, and the next flush, once the server answers, sends that same report and empties the outbox (the Mac feedback walk, 13 Nov 2026). #[test] fn a_report_to_a_dead_port_is_kept_and_a_flush_sends_it_once_the_server_answers() { let (dir, handle) = phone(); let outbox = dir.path().join(OUTBOX); let port = { let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("a port"); listener.local_addr().unwrap().port() }; let server = format!("http://127.0.0.1:{port}"); let socket: Arc = Arc::new(cotton_client::transport::SocketExchange); let answer = over(&handle.client(), &outbox, &facts(), socket.clone(), "feedback.send", &json!({ "sentence": "Books lost its shelf offline", "server": server })).expect("kept, not refused"); assert_eq!(answer["state"], "kept", "{answer}"); assert_eq!(kept(&outbox), 1, "on the phone until something takes it"); let listener = std::net::TcpListener::bind(("127.0.0.1", port)).expect("the same port, answering now"); let worker = std::thread::spawn(move || take_one(listener)); let tally = over(&handle.client(), &outbox, &facts(), socket, "feedback.flush", &json!({})).expect("flushed"); assert_eq!(tally, json!({ "sent": 1, "kept": 0, "refused": 0 })); let posted = worker.join().expect("the server's thread"); assert_eq!(posted["id"], answer["id"], "the kept report, by its own id"); assert_eq!(posted["sentence"], "Books lost its shelf offline"); assert_eq!(kept(&outbox), 0); }