//! The four names, the two event kinds, and the arguments a view sends. //! //! What is NOT here is a dial: opening a terminal needs either a helper //! process or a server, and both are proved where they live — the Mac's end by //! `cotton-session-host`'s own socket suite, the phone's by `cotton-server`'s //! attach route. What this module decides is the vocabulary and the //! validation, and those are pure. use serde_json::json; use super::*; use crate::events::EventKind; use crate::handle::{CottonHandle, OpenConfig, OpenMode}; use crate::methods::{ALL_METHODS, CLIENT_METHODS}; /// A core with a container and nothing else — no server, no join, no helper. /// Every case below is about what this build ANSWERS, not about a dial. fn core() -> (tempfile::TempDir, CottonHandle) { let root = tempfile::tempdir().expect("a temp container"); let handle = CottonHandle::open(OpenConfig { mode: OpenMode::Phone { container_path: root.path().to_string_lossy().to_string(), previous_container_path: None, }, app_version: Some("0.1.0".to_string()), time_zone: Some("Asia/Kolkata".to_string()), device_secret: None, vault_secret: None, flavor: cotton_core::flavor::Flavor::Real, manifest: None, }) .expect("an open core"); (root, handle) } #[test] fn every_method_this_module_names_is_one_the_core_answers() { for method in METHODS { assert!( ALL_METHODS.contains(&method), "{method} is dispatched but not declared" ); } } #[test] fn the_terminal_is_on_the_client_half_because_a_phone_is_what_it_is_for() { for method in METHODS { assert!( CLIENT_METHODS.contains(&method), "{method} should be answered by every build" ); } } #[test] fn there_are_four_verbs_and_they_are_the_ones_the_design_fixed() { assert_eq!( METHODS, [ "terminal.attach", "terminal.detach", "terminal.resize", "terminal.write", ] ); } #[test] fn the_two_event_kinds_are_spelled_the_way_the_design_fixed_them() { // Dotted, where every other kind is one word — the contract phase 4 builds // its terminal view against. assert_eq!( serde_json::to_value(EventKind::TerminalData).expect("a kind"), json!("terminal.data") ); assert_eq!( serde_json::to_value(EventKind::TerminalState).expect("a kind"), json!("terminal.state") ); } #[test] fn a_call_with_no_session_is_a_named_refusal_on_every_verb() { let (_root, handle) = core(); for method in METHODS { let refusal = call(&handle, method, &json!({})).expect_err("a refusal"); assert_eq!(refusal.code, "bad_request", "{method}"); assert!(refusal.message.contains("session"), "{method}: {}", refusal.message); } } #[test] fn a_size_outside_the_band_is_refused_rather_than_clamped() { let (_root, handle) = core(); for (cols, rows) in [(0, 24), (24, 0), (5_000, 24), (80, -1)] { let refusal = call( &handle, "terminal.resize", &json!({ "session": "s1", "cols": cols, "rows": rows }), ) .expect_err("a refusal"); assert_eq!(refusal.code, "bad_request", "{cols}x{rows}"); } } #[test] fn bytes_that_are_not_base64_are_refused_by_name() { let (_root, handle) = core(); let refusal = call( &handle, "terminal.write", &json!({ "session": "s1", "bytes": "not base64!!" }), ) .expect_err("a refusal"); assert_eq!(refusal.code, "bad_request"); assert!(refusal.message.contains("base64"), "{}", refusal.message); } #[test] fn writing_or_resizing_a_terminal_nobody_attached_says_so_rather_than_pretending() { let (_root, handle) = core(); let refusal = call( &handle, "terminal.write", &json!({ "session": "s1", "bytes": "aGk=" }), ) .expect_err("a refusal"); assert_eq!(refusal.code, "terminal_unavailable"); assert!(refusal.message.contains("s1"), "{}", refusal.message); } #[test] fn detaching_something_that_was_never_attached_is_still_detached() { // A screen going away is not a refusal worth drawing. let (_root, handle) = core(); let answer = call(&handle, "terminal.detach", &json!({ "session": "s1" })) .expect("a detach"); assert_eq!(answer, json!({ "session": "s1", "state": "closed" })); } #[test] fn a_device_with_no_server_has_no_mac_to_ask_and_says_which_it_is() { let (_root, handle) = core(); let refusal = call( &handle, "terminal.attach", &json!({ "session": "s1", "cols": 80, "rows": 24 }), ) .expect_err("a refusal"); // On a fixture handle nothing is served and nothing has joined, so the // honest answer names the state rather than dialling nowhere. assert!( matches!(refusal.code.as_str(), "no_server_yet" | "terminal_unavailable"), "{}: {}", refusal.code, refusal.message ); } // ── the wire, held by both halves ─────────────────────────────────────────── // // **The two halves of this method were written from the design page separately // and never met.** The core decoded `{session, bytes, cols, rows}`; the pane // sent `{sessionId, data}` with no size at all. Both sides had tests and // neither could see the other, so every `terminal.attach` answered // `bad_request` and the phone drew "No terminal for this session" about a // session that was running fine. // // `src/phone/terminal-wire.json` is the wire written down once. This half feeds // every `request` to the core and every `refused` shape too; the app's // `TerminalWireTests` builds the same requests out of `CottonKit`'s boundary // types and reads the same events. Rename a field on either side and one of the // two goes red. /// Where the fixture lives. fn wire_fixture_path() -> std::path::PathBuf { cotton_store::manifest::manifest_dir().join("src/phone/terminal-wire.json") } fn wire_fixture() -> serde_json::Value { let path = wire_fixture_path(); let text = std::fs::read_to_string(&path).unwrap_or_else(|error| { panic!( "could not read {} — it is the wire the app's TerminalWireTests reads too; \ grep the path repo-wide before moving it ({error})", path.display() ) }); serde_json::from_str(&text).expect("the wire fixture is JSON") } fn cases<'a>(fixture: &'a serde_json::Value, key: &str) -> &'a Vec { fixture .get(key) .and_then(serde_json::Value::as_array) .unwrap_or_else(|| panic!("the wire fixture has no `{key}` array")) } #[test] fn every_request_the_app_sends_is_one_this_core_decodes() { let fixture = wire_fixture(); let listed = cases(&fixture, "calls"); // Anti-vacuity: a loop over an empty array passes on nothing. assert!(listed.len() >= 7, "the fixture read as {} calls", listed.len()); let (_root, handle) = core(); for case in listed { let name = case["case"].as_str().expect("a case name"); let method = case["method"].as_str().expect("a method"); assert!(METHODS.contains(&method), "{name}: {method} is not one of the four verbs"); let request = &case["request"]; // What is proved here is the DECODE, not the dial: this handle has // joined no server and serves no file, so an attach or a write can only // refuse — but it must refuse for a reason about the terminal, never // because it could not read the arguments. if let Err(refusal) = call(&handle, method, request) { assert_ne!( refusal.code, "bad_request", "{name}: the core could not read {request} — {}", refusal.message ); } } } #[test] fn the_shapes_the_pane_used_to_send_are_refused_by_name() { // The fixture's discriminating half. Without it the case above would pass // on a core that accepted anything — and a `bad_request` here is exactly // what the phone drew as "No terminal for this session". let fixture = wire_fixture(); let listed = cases(&fixture, "refused"); assert!(listed.len() >= 5, "the fixture read as {} refusals", listed.len()); let (_root, handle) = core(); for case in listed { let name = case["case"].as_str().expect("a case name"); let method = case["method"].as_str().expect("a method"); let refusal = call(&handle, method, &case["request"]) .err() .unwrap_or_else(|| panic!("{name}: the core accepted a shape it cannot read")); assert_eq!( refusal.code, "bad_request", "{name}: refused as {} rather than as a shape the core cannot read", refusal.code ); } } /// The lines the collector below was handed, in order. /// /// A C function pointer carries no captures, so the record is a static — which /// means the one test that uses it must be the only one using it. static WIRE_SEEN: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); extern "C" fn collect_wire(_ctx: *mut std::ffi::c_void, line: *const std::ffi::c_char) { let text = unsafe { std::ffi::CStr::from_ptr(line) } .to_string_lossy() .to_string(); WIRE_SEEN.lock().expect("the record").push(text); } fn drain_wire() -> Vec { std::mem::take(&mut *WIRE_SEEN.lock().expect("the record")) } #[test] fn every_event_the_app_reads_is_one_this_core_emits() { let fixture = wire_fixture(); let listed = cases(&fixture, "events"); assert!(listed.len() >= 4, "the fixture read as {} events", listed.len()); let (_root, handle) = core(); handle.events().subscribe(std::ptr::null_mut(), Some(collect_wire)); // Whatever `open` emitted is not this test's. let _ = drain_wire(); let sink = EventSink { events: Arc::clone(handle.events()), }; for case in listed { let name = case["case"].as_str().expect("a case name"); let kind = case["kind"].as_str().expect("a kind"); let session = case["given"]["session"].as_str().expect("a session"); match kind { "terminal.data" => { let bytes: Vec = case["given"]["bytes"] .as_array() .expect("the bytes") .iter() .map(|byte| byte.as_u64().expect("a byte") as u8) .collect(); sink.data(session, &bytes); } "terminal.state" => { let state = match case["given"]["state"].as_str().expect("a state") { "attached" => TerminalState::Attached, "catchingUp" => TerminalState::CatchingUp, "closed" => TerminalState::Closed, other => panic!("{name}: `{other}` is not a state this build has"), }; sink.state(session, state); } other => panic!("{name}: `{other}` is not one of the two event kinds"), } // The handle's own background work logs onto the same bus, so the // terminal's two kinds are picked out rather than the stream counted. let emitted: Vec = drain_wire() .iter() .map(|text| serde_json::from_str(text).expect("the event is JSON")) .filter(|line: &serde_json::Value| { line["kind"] .as_str() .is_some_and(|kind| kind.starts_with("terminal.")) }) .collect(); assert_eq!(emitted.len(), 1, "{name}: {emitted:?}"); let line = &emitted[0]; assert_eq!(line["kind"], json!(kind), "{name}"); assert_eq!( line["payload"], case["payload"], "{name}: the app reads this payload by its field names" ); } handle.events().subscribe(std::ptr::null_mut(), None); } #[test] fn the_ceiling_the_app_clamps_to_is_this_cores_own() { // The fixture's clamped case asks for exactly `MAX_DIMENSION`, so the // Swift side's ceiling and this constant cannot drift apart without the // case above refusing. let fixture = wire_fixture(); let clamped = cases(&fixture, "calls") .iter() .find(|case| case["request"]["cols"] == json!(MAX_DIMENSION)) .expect("the fixture no longer asks for the ceiling"); assert_eq!(clamped["request"]["rows"], json!(MAX_DIMENSION)); assert!( clamped["given"]["measuredCols"].as_i64().expect("a measurement") > MAX_DIMENSION, "the clamped case no longer measures anything the core would refuse" ); }