forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

main.rs281 lines, 12.4 KiBHistoryRawDownload
1#![forbid(unsafe_code)]
2mod help;
3mod parse;
4mod rpc;
5mod server;
6#[cfg(test)]
7mod testutil;
8mod tools;
9
10use std::io::{self, BufRead, Write};
11use std::os::fd::AsFd;
12use std::sync::atomic::{AtomicI32, Ordering};
13use std::sync::mpsc::{self, RecvTimeoutError};
14use std::thread;
15use std::time::{Duration, Instant};
16
17use signal_hook::consts::{SIGINT, SIGTERM};
18
19/// The signal that asked this server to stop, or 0. Only the signal thread writes it.
20static STOP_SIGNAL: AtomicI32 = AtomicI32::new(0);
21
22fn stop_signal() -> i32 {
23 STOP_SIGNAL.load(Ordering::SeqCst)
24}
25
26/// SIGTERM and SIGINT are a deliberate stop: running exports are cancelled (each deletes its
27/// `.part`), then the process exits with 128 + the signal. The handler only sets the flag.
28fn install_stop_handlers() {
29 // A thread waits for the signals and records them; no signal handler runs
30 // any code of ours, so the whole path stays safe Rust.
31 let mut signals = signal_hook::iterator::Signals::new([SIGTERM, SIGINT])
32 .expect("stop signal handlers");
33 thread::spawn(move || {
34 for sig in signals.forever() {
35 STOP_SIGNAL.store(sig, Ordering::SeqCst);
36 }
37 });
38}
39
40fn main() {
41 engine::ao::set_silent_output();
42 // Stdout carries JSON-RPC lines and nothing else. The writer below gets its own copy of
43 // the real stdout; fd 1 itself is pointed at stderr, so a C library or child process that
44 // writes to fd 1 lands in the log instead of the protocol. Before any thread starts.
45 let rpc_out = io::stdout()
46 .as_fd()
47 .try_clone_to_owned()
48 .expect("dup of stdout failed");
49 rustix::stdio::dup2_stdout(io::stderr()).expect("redirect stdout to stderr");
50 tools::see::sweep_stale_scratch();
51 let mut server = server::Server::new();
52 let mut out = io::BufWriter::new(std::fs::File::from(rpc_out));
53 install_stop_handlers();
54 // stdin is read on its own thread, so a stop signal is seen while the client is quiet.
55 let (lines_tx, lines_rx) = mpsc::channel();
56 thread::Builder::new()
57 .name("stdin".into())
58 .spawn(move || {
59 for line in io::stdin().lock().lines() {
60 if lines_tx.send(line).is_err() {
61 break;
62 }
63 }
64 })
65 .expect("start the stdin reader");
66 loop {
67 if stop_signal() != 0 {
68 break;
69 }
70 // A queued export starts the moment the one before it ends, polled or not.
71 tools::export::advance(&mut server);
72 tools::media::poll_proxies(&mut server);
73 let line = match lines_rx.recv_timeout(Duration::from_millis(100)) {
74 Ok(Ok(line)) => line,
75 Ok(Err(_)) | Err(RecvTimeoutError::Disconnected) => break,
76 Err(RecvTimeoutError::Timeout) => continue,
77 };
78 if line.trim().is_empty() {
79 continue;
80 }
81 let reply = match serde_json::from_str(&line) {
82 Ok(msg) => rpc::handle(&mut server, msg),
83 Err(e) => Some(rpc::error(serde_json::Value::Null, -32700, &format!("parse error: {e}"))),
84 };
85 if let Some(v) = reply
86 && write_reply(&mut out, &v).is_err()
87 {
88 break;
89 }
90 }
91 // Stdout is not written past this point: the protocol ends with the last reply.
92 drop(out);
93 // Unsaved work is written aside before anything else can go wrong: an autosave
94 // next to the project, never over it (see `project_open`, which offers it).
95 tools::project::autosave_at_eof(&server);
96 wait_for_exports(&mut server);
97 tools::see::remove_scratch();
98 let sig = stop_signal();
99 if sig != 0 {
100 std::process::exit(128 + sig);
101 }
102}
103
104/// Writes one reply as one line and flushes it. The stderr lock is held across the write, so no
105/// `eprintln!` from an engine or export thread can land inside the line, even when a client
106/// merges the two streams into one pipe.
107fn write_reply(out: &mut impl Write, reply: &serde_json::Value) -> io::Result<()> {
108 let mut line = reply.to_string();
109 line.push('\n');
110 let _stderr = io::stderr().lock();
111 out.write_all(line.as_bytes())?;
112 out.flush()
113}
114
115/// Keeps polling the export jobs after stdin closes, so a client that disconnects
116/// does not lose a running export. Returns once no job is still writing. A stop signal
117/// cancels the jobs still writing instead, and they delete their `.part`s.
118fn wait_for_exports(server: &mut server::Server) {
119 let mut last_log: Option<Instant> = None;
120 let debug = std::env::var_os("EDITH_DEBUG").is_some();
121 // The jobs still writing when the client left: their outcomes are the ones to report.
122 let left: Vec<usize> = server
123 .jobs
124 .iter()
125 .enumerate()
126 .filter(|(_, j)| tools::export::job_running(j))
127 .map(|(i, _)| i)
128 .collect();
129 let mut cancelled = false;
130 loop {
131 if stop_signal() != 0 && !cancelled {
132 cancelled = true;
133 let running = server.jobs.iter().filter(|j| tools::export::job_running(j)).count();
134 eprintln!("stop signal {}: cancelling {running} export job(s); their .part files are deleted", stop_signal());
135 for job in server.jobs.iter_mut().filter(|j| tools::export::job_running(j)) {
136 job.cancel();
137 }
138 }
139 tools::export::advance(server);
140 let running: Vec<(usize, f32)> = server
141 .jobs
142 .iter()
143 .enumerate()
144 .filter(|(_, j)| tools::export::job_running(j))
145 .map(|(i, j)| (i + 1, j.progress()))
146 .collect();
147 // A paused queue starts nothing, so once only held exports remain the wait is over.
148 let held = server.queue_paused && server.jobs.iter().all(|j| !tools::export::job_running(j) || j.waiting());
149 if running.is_empty() || held {
150 // Nothing else can read this outcome back, so it goes to stderr once: a failure
151 // always (the client is gone and a missing file would otherwise be silent), a
152 // success only under EDITH_DEBUG.
153 for &i in &left {
154 let job = &server.jobs[i];
155 match &job.outcome {
156 Some(Ok(())) if debug => eprintln!("export job:{} finished: {} ({:.0?} after start)", i + 1, job.out.display(), job.started.elapsed()),
157 Some(Ok(())) => {}
158 Some(Err(e)) => eprintln!("export job:{} failed: {}: {e}", i + 1, job.out.display()),
159 None if job.waiting() => eprintln!("export job:{} was queued and never started (the queue was paused): {}", i + 1, job.out.display()),
160 None => eprintln!("export job:{} ended without a result: {}", i + 1, job.out.display()),
161 }
162 }
163 return;
164 }
165 if debug && last_log.is_none_or(|t| t.elapsed() >= Duration::from_secs(5)) {
166 for (n, p) in &running {
167 eprintln!("stdin closed; export job:{n} still running: {:.0}%", p * 100.0);
168 }
169 last_log = Some(Instant::now());
170 }
171 std::thread::sleep(Duration::from_millis(200));
172 }
173}
174
175#[cfg(test)]
176mod tests {
177 use super::*;
178 use serde_json::json;
179
180 /// A reply bigger than the writer's buffer still goes out as one JSON line, and nothing else is
181 /// written with it: the line ends the reply and the next one starts on a line of its own.
182 #[test]
183 fn a_big_reply_is_one_json_line() {
184 let big = json!({"jsonrpc": "2.0", "id": 7, "result": {"text": "x\n".repeat(20_000)}});
185 let mut out = io::BufWriter::new(Vec::new());
186 write_reply(&mut out, &big).expect("write the reply");
187 write_reply(&mut out, &json!({"jsonrpc": "2.0", "id": 8, "result": {}})).expect("write the next reply");
188 let bytes = out.into_inner().expect("flush the buffer");
189 let text = String::from_utf8(bytes).expect("utf-8");
190 let lines: Vec<&str> = text.split_terminator('\n').collect();
191 assert_eq!(lines.len(), 2, "one line per reply");
192 assert_eq!(serde_json::from_str::<serde_json::Value>(lines[0]).expect("first line")["id"], 7);
193 assert_eq!(serde_json::from_str::<serde_json::Value>(lines[1]).expect("second line")["id"], 8);
194 }
195
196 #[test]
197 fn no_jobs_means_no_wait() {
198 let mut server = server::Server::new();
199 wait_for_exports(&mut server);
200 assert!(server.jobs.is_empty());
201 }
202
203 /// A job still writing when stdin closes is waited for, and its outcome recorded.
204 #[test]
205 fn a_running_export_is_waited_for_after_eof() {
206 engine::ao::set_silent_output();
207 let src = format!("{}/../../assets/test_av.mp4", env!("CARGO_MANIFEST_DIR"));
208 let session = engine::PlaybackSession::open(&src).expect("open assets/test_av.mp4");
209 let mut server = server::Server::new();
210 server.session = Some(session);
211 let dir = crate::testutil::TestDir::new("main-eof");
212 let out = dir.join("eof.mp4");
213 let started = tools::export::tools()
214 .into_iter()
215 .find(|t| t.name == "export_start")
216 .map(|t| (t.run)(&mut server, &json!({"out": out.display().to_string(), "range": {"from": 0, "to": 1}})))
217 .expect("export_start is registered");
218 assert!(!started.is_error, "{}", started.text);
219
220 wait_for_exports(&mut server);
221 assert!(server.jobs.iter().all(|j| j.outcome.is_some()), "every job settled");
222 assert!(matches!(server.jobs[0].outcome, Some(Ok(()))), "{:?}", server.jobs[0].outcome);
223 assert!(std::fs::metadata(&out).is_ok_and(|m| m.len() > 0));
224 }
225
226 /// A `.part` a killed process left beside the output is named by the next export to it, and
227 /// cleared before that export writes its own.
228 #[test]
229 fn a_stale_part_is_named_and_cleared_by_the_next_export() {
230 engine::ao::set_silent_output();
231 let src = format!("{}/../../assets/test_av.mp4", env!("CARGO_MANIFEST_DIR"));
232 let session = engine::PlaybackSession::open(&src).expect("open assets/test_av.mp4");
233 let mut server = server::Server::new();
234 server.session = Some(session);
235 let dir = crate::testutil::TestDir::new("main-stale-part");
236 let out = dir.join("c.mp4");
237 let part = dir.join("c.mp4.part");
238 std::fs::write(&part, b"left by a killed process").expect("write the stale part");
239 let start = tools::export::tools()
240 .into_iter()
241 .find(|t| t.name == "export_start")
242 .expect("export_start is registered");
243 let r = (start.run)(&mut server, &json!({"out": out.display().to_string(), "range": {"from": 0, "to": 1}}));
244 assert!(!r.is_error, "{}", r.text);
245 assert!(r.text.contains("did not finish") && r.text.contains("left behind — deleted"), "{}", r.text);
246 wait_for_exports(&mut server);
247 assert!(matches!(server.jobs[0].outcome, Some(Ok(()))), "{:?}", server.jobs[0].outcome);
248 assert!(!part.exists(), "the export wrote its own part and renamed it away");
249 assert!(std::fs::metadata(&out).is_ok_and(|m| m.len() > 0));
250 }
251
252 /// Two exports still running when stdin closes are both waited for: each finishes, leaves no
253 /// `.part`, and its outcome is recorded.
254 #[test]
255 fn two_running_exports_are_both_waited_for_after_eof() {
256 engine::ao::set_silent_output();
257 let src = format!("{}/../../assets/test_av.mp4", env!("CARGO_MANIFEST_DIR"));
258 let session = engine::PlaybackSession::open(&src).expect("open assets/test_av.mp4");
259 let mut server = server::Server::new();
260 server.session = Some(session);
261 let dir = crate::testutil::TestDir::new("main-eof-two");
262 let start = tools::export::tools()
263 .into_iter()
264 .find(|t| t.name == "export_start")
265 .expect("export_start is registered");
266 let outs = [dir.join("a.mp4"), dir.join("b.mp4")];
267 for out in &outs {
268 let r = (start.run)(&mut server, &json!({"out": out.display().to_string(), "range": {"from": 0, "to": 1}}));
269 assert!(!r.is_error, "{}", r.text);
270 }
271 assert_eq!(server.jobs.len(), 2);
272
273 wait_for_exports(&mut server);
274 assert!(server.jobs.iter().all(|j| matches!(j.outcome, Some(Ok(())))), "every job finished");
275 for out in &outs {
276 assert!(std::fs::metadata(out).is_ok_and(|m| m.len() > 0), "{} written", out.display());
277 let part = out.with_extension("mp4.part");
278 assert!(!part.exists(), "{} left behind", part.display());
279 }
280 }
281}