| 1 | |
| 2 | |
| 3 | |
| 4 | use std::fs; |
| 5 | use std::io::{BufRead, BufReader, Read, Write}; |
| 6 | use std::path::{Path, PathBuf}; |
| 7 | use std::process::{Child, ChildStdin, ChildStdout, Command, ExitStatus, Stdio}; |
| 8 | use std::thread::sleep; |
| 9 | use std::time::{Duration, Instant}; |
| 10 | |
| 11 | use serde_json::{json, Value}; |
| 12 | |
| 13 | struct Client { |
| 14 | child: Child, |
| 15 | stdin: ChildStdin, |
| 16 | stdout: BufReader<ChildStdout>, |
| 17 | next_id: u64, |
| 18 | } |
| 19 | |
| 20 | impl Client { |
| 21 | |
| 22 | |
| 23 | fn spawn(log: &Path) -> Self { |
| 24 | let stderr = fs::File::create(log).expect("make the server log"); |
| 25 | let mut child = Command::new(env!("CARGO_BIN_EXE_edith_mcp")) |
| 26 | |
| 27 | .env("XDG_DATA_HOME", std::env::temp_dir().join(format!("edith_mcp-xdg-{}", std::process::id()))) |
| 28 | .stdin(Stdio::piped()) |
| 29 | .stdout(Stdio::piped()) |
| 30 | .stderr(Stdio::from(stderr)) |
| 31 | .spawn() |
| 32 | .expect("spawn edith_mcp"); |
| 33 | let stdin = child.stdin.take().expect("server stdin"); |
| 34 | let stdout = BufReader::new(child.stdout.take().expect("server stdout")); |
| 35 | Self { child, stdin, stdout, next_id: 1 } |
| 36 | } |
| 37 | |
| 38 | fn call(&mut self, method: &str, params: Value) -> Value { |
| 39 | let id = self.next_id; |
| 40 | self.next_id += 1; |
| 41 | let mut line = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}).to_string(); |
| 42 | line.push('\n'); |
| 43 | self.stdin.write_all(line.as_bytes()).expect("write request"); |
| 44 | self.stdin.flush().expect("flush request"); |
| 45 | let mut reply = String::new(); |
| 46 | let n = self.stdout.read_line(&mut reply).expect("read response"); |
| 47 | assert!(n > 0, "server closed stdout during {method}"); |
| 48 | let v: Value = serde_json::from_str(&reply).expect("JSON reply"); |
| 49 | assert_eq!(v["id"], json!(id), "response id mismatch for {method}"); |
| 50 | v |
| 51 | } |
| 52 | |
| 53 | fn tool(&mut self, name: &str, args: Value) -> String { |
| 54 | let r = self.call("tools/call", json!({"name": name, "arguments": args})); |
| 55 | let result = &r["result"]; |
| 56 | assert!(result["isError"] != json!(true), "{name} failed: {result}"); |
| 57 | result["content"][0]["text"].as_str().unwrap_or_default().to_string() |
| 58 | } |
| 59 | |
| 60 | |
| 61 | |
| 62 | |
| 63 | fn start_export(&mut self, dir: &Path, out: &Path, length: &str) { |
| 64 | self.call("initialize", json!({"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "exit-paths", "version": "1"}})); |
| 65 | let mut line = json!({"jsonrpc": "2.0", "method": "notifications/initialized"}).to_string(); |
| 66 | line.push('\n'); |
| 67 | self.stdin.write_all(line.as_bytes()).expect("write initialized"); |
| 68 | self.tool( |
| 69 | "project_new", |
| 70 | json!({"path": dir.join("p.edith").display().to_string(), "resolution": "320x180"}), |
| 71 | ); |
| 72 | self.tool("media_import", json!({"paths": [still().display().to_string()]})); |
| 73 | self.tool("edit", json!({"ops": [{"op": "place", "source": "src:0", "lane": "V1", "at": "0s", "length": length}]})); |
| 74 | let started = self.tool("export_start", json!({"out": out.display().to_string(), "seat": "software"})); |
| 75 | assert!(started.contains("job:1 started"), "{started}"); |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | fn still() -> PathBuf { |
| 80 | PathBuf::from(format!("{}/../../assets/test_still.png", env!("CARGO_MANIFEST_DIR"))) |
| 81 | } |
| 82 | |
| 83 | fn fresh_dir(name: &str) -> PathBuf { |
| 84 | let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!("{name}-{}", std::process::id())); |
| 85 | let _ = fs::remove_dir_all(&dir); |
| 86 | fs::create_dir_all(&dir).expect("make test dir"); |
| 87 | dir |
| 88 | } |
| 89 | |
| 90 | |
| 91 | fn server_log(log: &Path) -> String { |
| 92 | fs::read_to_string(log).unwrap_or_else(|e| format!("(no server log: {e})")) |
| 93 | } |
| 94 | |
| 95 | |
| 96 | fn probe_seconds(path: &Path) -> f64 { |
| 97 | let out = Command::new("ffprobe") |
| 98 | .args(["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0"]) |
| 99 | .arg(path) |
| 100 | .output() |
| 101 | .expect("run ffprobe"); |
| 102 | assert!(out.status.success(), "ffprobe failed on {}", path.display()); |
| 103 | String::from_utf8_lossy(&out.stdout) |
| 104 | .trim() |
| 105 | .parse() |
| 106 | .unwrap_or_else(|_| panic!("no duration for {}", path.display())) |
| 107 | } |
| 108 | |
| 109 | |
| 110 | fn wait_exit(child: &mut Child, limit: Duration) -> ExitStatus { |
| 111 | let started = Instant::now(); |
| 112 | loop { |
| 113 | if let Some(status) = child.try_wait().expect("poll child") { |
| 114 | return status; |
| 115 | } |
| 116 | if started.elapsed() > limit { |
| 117 | let _ = child.kill(); |
| 118 | panic!("edith_mcp still running after {limit:?}"); |
| 119 | } |
| 120 | sleep(Duration::from_millis(200)); |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | |
| 125 | |
| 126 | #[test] |
| 127 | fn an_export_outlives_stdin_closing() { |
| 128 | let dir = fresh_dir("exit-eof"); |
| 129 | let out = dir.join("eof.mp4"); |
| 130 | let log = dir.join("eof.log"); |
| 131 | let mut client = Client::spawn(&log); |
| 132 | client.start_export(&dir, &out, "3s"); |
| 133 | |
| 134 | let Client { mut child, stdin, mut stdout, .. } = client; |
| 135 | drop(stdin); |
| 136 | let mut rest = Vec::new(); |
| 137 | stdout.read_to_end(&mut rest).expect("read stdout to its end"); |
| 138 | assert!(rest.is_empty(), "stdout after EOF: {:?}", String::from_utf8_lossy(&rest)); |
| 139 | let status = wait_exit(&mut child, Duration::from_secs(300)); |
| 140 | let said = server_log(&log); |
| 141 | assert!(status.success(), "exit {status:?}; server said:\n{said}"); |
| 142 | assert!( |
| 143 | fs::metadata(&out).is_ok_and(|m| m.len() > 0), |
| 144 | "export not written after EOF; server said:\n{said}" |
| 145 | ); |
| 146 | let seconds = probe_seconds(&out); |
| 147 | assert!((2.5..=3.5).contains(&seconds), "a 3 s export ran {seconds} s; server said:\n{said}"); |
| 148 | assert!(!dir.join("eof.mp4.part").exists(), "no .part left behind"); |
| 149 | } |
| 150 | |
| 151 | |
| 152 | |
| 153 | #[test] |
| 154 | fn sigterm_cancels_a_running_export_and_removes_its_part() { |
| 155 | let dir = fresh_dir("exit-sigterm"); |
| 156 | let out = dir.join("term.mp4"); |
| 157 | let log = dir.join("term.log"); |
| 158 | let mut client = Client::spawn(&log); |
| 159 | |
| 160 | |
| 161 | client.start_export(&dir, &out, "300s"); |
| 162 | let part = dir.join("term.mp4.part"); |
| 163 | let wait = Instant::now(); |
| 164 | while !part.exists() && wait.elapsed() < Duration::from_secs(120) { |
| 165 | sleep(Duration::from_millis(100)); |
| 166 | } |
| 167 | assert!(part.exists(), "the export started writing its .part; server said:\n{}", server_log(&log)); |
| 168 | |
| 169 | let pid = client.child.id() as libc::pid_t; |
| 170 | assert_eq!(unsafe { libc::kill(pid, libc::SIGTERM) }, 0, "send SIGTERM"); |
| 171 | let status = wait_exit(&mut client.child, Duration::from_secs(300)); |
| 172 | let said = server_log(&log); |
| 173 | assert_eq!(status.code(), Some(128 + libc::SIGTERM), "exit {status:?}; server said:\n{said}"); |
| 174 | assert!(!part.exists(), "the cancelled export deleted its .part"); |
| 175 | assert!(!out.exists(), "no output published by a cancelled export; server said:\n{said}"); |
| 176 | } |
| 177 | |
| 178 | |
| 179 | |
| 180 | #[test] |
| 181 | fn a_failed_export_after_stdin_closes_is_named_on_stderr() { |
| 182 | let dir = fresh_dir("exit-failed"); |
| 183 | let sub = dir.join("sub"); |
| 184 | fs::create_dir_all(&sub).expect("make the output folder"); |
| 185 | let out = sub.join("gone.mp4"); |
| 186 | let log = dir.join("failed.log"); |
| 187 | let mut client = Client::spawn(&log); |
| 188 | client.start_export(&dir, &out, "30s"); |
| 189 | let part = sub.join("gone.mp4.part"); |
| 190 | let wait = Instant::now(); |
| 191 | while !part.exists() && wait.elapsed() < Duration::from_secs(120) { |
| 192 | sleep(Duration::from_millis(50)); |
| 193 | } |
| 194 | assert!(part.exists(), "the export started writing its .part"); |
| 195 | fs::remove_dir_all(&sub).expect("remove the output folder under the export"); |
| 196 | |
| 197 | let Client { mut child, stdin, mut stdout, .. } = client; |
| 198 | drop(stdin); |
| 199 | let mut rest = Vec::new(); |
| 200 | stdout.read_to_end(&mut rest).expect("read stdout to its end"); |
| 201 | let status = wait_exit(&mut child, Duration::from_secs(300)); |
| 202 | let said = server_log(&log); |
| 203 | assert!(status.success(), "exit {status:?}; server said:\n{said}"); |
| 204 | assert!(said.contains("export job:1 failed"), "the failure is named on stderr; server said:\n{said}"); |
| 205 | assert!(said.contains("gone.mp4"), "the failure names the file; server said:\n{said}"); |
| 206 | } |