//! Crash recovery over the control channel, headless: type into a file, //! drop the backend without saving, start a new one on the same directories, //! get `recoveryAvailable` after `project.open`, restore and check the text. #![allow( clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing, clippy::panic )] use std::io::{BufRead, BufReader, Write}; use std::net::TcpStream; use std::sync::Arc; use std::time::{Duration, Instant}; use lutra_testkit::{EngineBackend, engine_config}; use serde_json::{Value, json}; /// A control client that keeps event lines apart from responses. struct Client { reader: BufReader, writer: TcpStream, events: Vec, } impl Client { fn connect(addr: std::net::SocketAddr) -> Self { let stream = TcpStream::connect(addr).unwrap(); stream .set_read_timeout(Some(Duration::from_secs(5))) .unwrap(); Self { writer: stream.try_clone().unwrap(), reader: BufReader::new(stream), events: Vec::new(), } } fn call(&mut self, request: Value) -> Value { self.writer .write_all(format!("{request}\n").as_bytes()) .unwrap(); loop { let mut line = String::new(); self.reader.read_line(&mut line).expect("line within 5 s"); let line: Value = serde_json::from_str(&line).unwrap(); if line.get("event").is_some() { self.events.push(line["event"].clone()); } else { return line; } } } /// Waits until an event of `kind` has arrived and returns it. fn event(&mut self, kind: &str) -> Value { let deadline = Instant::now() + Duration::from_secs(5); loop { if let Some(at) = self.events.iter().position(|e| e["kind"] == kind) { return self.events.remove(at); } assert!( Instant::now() < deadline, "no {kind} event; got {:?}", self.events ); let mut line = String::new(); self.reader.read_line(&mut line).expect("line within 5 s"); let line: Value = serde_json::from_str(&line).unwrap(); if line.get("event").is_some() { self.events.push(line["event"].clone()); } } } fn execute(&mut self, command: &str, params: Value) -> Value { let r = self.call(json!({"id": command, "method": "engine.execute", "params": {"command": command, "params": params}})); assert!(r.get("error").is_none(), "{command}: {r}"); r["result"].clone() } } #[test] fn typed_text_survives_a_crash_and_is_restored() { let dir = tempfile::tempdir().unwrap(); let project = dir.path().join("project"); std::fs::create_dir(&project).unwrap(); std::fs::write(project.join("a.php"), b"\xEF\xBB\xBF