Skip to main content

toolblox_lib/
widget_process.rs

1//! Lifecycle ownership for declared widget sidecar processes.
2
3use std::collections::{HashMap, VecDeque};
4use std::io::{BufRead, BufReader, Write};
5use std::path::{Path, PathBuf};
6use std::process::{Child, ChildStdin, Command, Stdio};
7use std::sync::mpsc::{self, Receiver, SyncSender};
8use std::thread;
9use std::time::{Duration, Instant};
10
11use serde::Serialize;
12
13use crate::widgets::WidgetProcess;
14
15/// Longest line read from or sent to a widget process, in bytes. Longer output lines are cut.
16const MAX_LINE_BYTES: usize = 64 * 1024;
17/// How long a process may take to exit after its input closes before it's killed.
18const EXIT_GRACE: Duration = Duration::from_secs(2);
19/// Error output lines logged per process start. Later lines still reach the widget.
20const MAX_LOGGED_STDERR_LINES: usize = 200;
21
22/// One line of output from a widget process.
23#[derive(Clone, Debug, Serialize)]
24#[serde(rename_all = "camelCase")]
25pub struct WidgetProcessEvent {
26    pub widget_id: String,
27    pub process_id: String,
28    pub stream: ProcessStream,
29    pub line: String,
30}
31
32/// The output stream a line came from.
33#[derive(Clone, Copy, Debug, Serialize)]
34#[serde(rename_all = "lowercase")]
35pub enum ProcessStream {
36    Stdout,
37    Stderr,
38}
39
40/// A running widget process and its input pipe.
41struct ManagedProcess {
42    child: Child,
43    stdin: ChildStdin,
44}
45
46/// Starts, feeds, and stops the processes widgets declare, and buffers their output.
47///
48/// Processes are keyed by widget ID and process ID. Dropping the manager stops them all.
49pub struct WidgetProcessManager {
50    processes: HashMap<(String, String), ManagedProcess>,
51    events_tx: SyncSender<WidgetProcessEvent>,
52    events_rx: Receiver<WidgetProcessEvent>,
53    /// Events read from the channel but not yet taken by their widget.
54    pending_events: VecDeque<WidgetProcessEvent>,
55}
56
57impl Default for WidgetProcessManager {
58    fn default() -> Self {
59        let (events_tx, events_rx) = mpsc::sync_channel(1_024);
60        Self {
61            processes: HashMap::new(),
62            events_tx,
63            events_rx,
64            pending_events: VecDeque::new(),
65        }
66    }
67}
68
69impl WidgetProcessManager {
70    /// Starts a declared process with arguments from its allow list.
71    ///
72    /// The executable must resolve inside the widget folder. Fails when the process is already
73    /// running; an exited process is replaced.
74    pub fn start(
75        &mut self,
76        widget_id: &str,
77        widget_root: &Path,
78        declaration: &WidgetProcess,
79        arguments: &[String],
80    ) -> Result<(), String> {
81        validate_arguments(declaration, arguments)?;
82        let key = (widget_id.to_owned(), declaration.id.clone());
83        if let Some(process) = self.processes.get_mut(&key) {
84            match process.child.try_wait() {
85                Ok(None) => return Err("The widget process is already running.".into()),
86                Ok(Some(_)) => {
87                    self.processes.remove(&key);
88                }
89                Err(_) => return Err("The widget process state couldn't be read.".into()),
90            }
91        }
92        let root = widget_root
93            .canonicalize()
94            .map_err(|_| "Couldn't resolve the widget directory.".to_string())?;
95        let executable = canonical_child(&root, &declaration.executable)?;
96        let mut child = Command::new(executable)
97            .args(arguments)
98            .current_dir(&root)
99            .stdin(Stdio::piped())
100            .stdout(Stdio::piped())
101            .stderr(Stdio::piped())
102            .spawn()
103            .map_err(|_| {
104                "Couldn't start the widget process. Is the package complete?".to_string()
105            })?;
106        let stdin = child
107            .stdin
108            .take()
109            .ok_or_else(|| "Couldn't open the widget process input.".to_string())?;
110        let stdout = child
111            .stdout
112            .take()
113            .ok_or_else(|| "Couldn't open the widget process output.".to_string())?;
114        let stderr = child
115            .stderr
116            .take()
117            .ok_or_else(|| "Couldn't open the widget process error stream.".to_string())?;
118
119        spawn_reader(
120            self.events_tx.clone(),
121            widget_id.to_owned(),
122            declaration.id.clone(),
123            ProcessStream::Stdout,
124            stdout,
125        );
126        spawn_reader(
127            self.events_tx.clone(),
128            widget_id.to_owned(),
129            declaration.id.clone(),
130            ProcessStream::Stderr,
131            stderr,
132        );
133        log::info!(
134            target: &format!("widget:{widget_id}"),
135            "Started process {} (pid {})",
136            declaration.id,
137            child.id()
138        );
139        self.processes.insert(key, ManagedProcess { child, stdin });
140        Ok(())
141    }
142
143    /// Writes one line of JSON to the process's input.
144    pub fn send(&mut self, widget_id: &str, process_id: &str, message: &str) -> Result<(), String> {
145        if message.len() > MAX_LINE_BYTES || message.contains(['\n', '\r']) {
146            return Err("Widget process messages must be one line under 64 KB.".into());
147        }
148        serde_json::from_str::<serde_json::Value>(message)
149            .map_err(|_| "Widget process messages must be valid JSON.".to_string())?;
150        let process = self
151            .processes
152            .get_mut(&(widget_id.to_owned(), process_id.to_owned()))
153            .ok_or_else(|| "The widget process isn't running.".to_string())?;
154        process
155            .stdin
156            .write_all(message.as_bytes())
157            .and_then(|_| process.stdin.write_all(b"\n"))
158            .and_then(|_| process.stdin.flush())
159            .map_err(|_| "Couldn't send data to the widget process.".to_string())
160    }
161
162    /// Closes the process's input so it can clean up and exit, and kills it after `EXIT_GRACE`. Stopping a missing or exited process succeeds.
163    pub fn stop(&mut self, widget_id: &str, process_id: &str) -> Result<(), String> {
164        let Some(ManagedProcess { mut child, stdin }) = self
165            .processes
166            .remove(&(widget_id.to_owned(), process_id.to_owned()))
167        else {
168            return Ok(());
169        };
170        drop(stdin);
171        finish(&mut child, Instant::now() + EXIT_GRACE)?;
172        log::info!(target: &format!("widget:{widget_id}"), "Stopped process {process_id}");
173        Ok(())
174    }
175
176    /// Stops every process a widget started.
177    pub fn stop_widget(&mut self, widget_id: &str) {
178        let ids: Vec<_> = self
179            .processes
180            .keys()
181            .filter(|(owner, _)| owner == widget_id)
182            .cloned()
183            .collect();
184        for (owner, process_id) in ids {
185            let _ = self.stop(&owner, &process_id);
186        }
187    }
188
189    /// Stops every process, sharing one `EXIT_GRACE` between them.
190    pub fn stop_all(&mut self) {
191        let children: Vec<_> = self
192            .processes
193            .drain()
194            .map(|(_, process)| process.child)
195            .collect();
196        let deadline = Instant::now() + EXIT_GRACE;
197        for mut child in children {
198            let _ = finish(&mut child, deadline);
199        }
200    }
201
202    /// Returns and removes the widget's buffered output, keeping other widgets' output.
203    pub fn drain_events(&mut self, widget_id: &str) -> Vec<WidgetProcessEvent> {
204        self.pending_events.extend(self.events_rx.try_iter());
205        let mut matching = Vec::new();
206        let mut remaining = VecDeque::new();
207        while let Some(event) = self.pending_events.pop_front() {
208            if event.widget_id == widget_id {
209                matching.push(event);
210            } else {
211                remaining.push_back(event);
212            }
213        }
214        self.pending_events = remaining;
215        matching
216    }
217}
218
219impl Drop for WidgetProcessManager {
220    fn drop(&mut self) {
221        self.stop_all();
222    }
223}
224
225/// Waits for a process whose input is closed, and kills it at `deadline`.
226fn finish(child: &mut Child, deadline: Instant) -> Result<(), String> {
227    while Instant::now() < deadline {
228        match child.try_wait() {
229            Ok(Some(_)) => return Ok(()),
230            Ok(None) => thread::sleep(Duration::from_millis(20)),
231            Err(_) => break,
232        }
233    }
234    child
235        .kill()
236        .map_err(|_| "Couldn't stop the widget process.".to_string())?;
237    child
238        .wait()
239        .map_err(|_| "Couldn't finish stopping the widget process.".to_string())?;
240    Ok(())
241}
242
243/// Resolves `relative` inside `root`, rejecting paths that escape it or aren't files.
244fn canonical_child(root: &Path, relative: &str) -> Result<PathBuf, String> {
245    let candidate = root.join(relative);
246    let resolved = candidate
247        .canonicalize()
248        .map_err(|_| "Couldn't resolve the widget process executable.".to_string())?;
249    if !resolved.starts_with(root) || !resolved.is_file() {
250        return Err("The widget process executable is outside its package.".into());
251    }
252    Ok(resolved)
253}
254
255/// Allows at most 32 arguments of up to 1 KB, each from the declaration's allow list.
256fn validate_arguments(declaration: &WidgetProcess, arguments: &[String]) -> Result<(), String> {
257    if arguments.len() > 32
258        || arguments.iter().any(|argument| {
259            argument.len() > 1_024 || !declaration.allowed_arguments.contains(argument)
260        })
261    {
262        return Err("The widget requested unsupported process arguments.".into());
263    }
264    Ok(())
265}
266
267/// Reads a stream line by line on a background thread and sends each line as an event until
268/// the stream closes or the manager is dropped.
269fn spawn_reader<R: std::io::Read + Send + 'static>(
270    sender: SyncSender<WidgetProcessEvent>,
271    widget_id: String,
272    process_id: String,
273    stream: ProcessStream,
274    reader: R,
275) {
276    thread::spawn(move || {
277        let target = format!("widget:{widget_id}");
278        let mut logged_errors = 0;
279        let mut reader = BufReader::new(reader);
280        loop {
281            let mut bytes = Vec::new();
282            loop {
283                let Ok(buffer) = reader.fill_buf() else {
284                    return;
285                };
286                if buffer.is_empty() {
287                    if matches!(stream, ProcessStream::Stdout) {
288                        log::info!(target: &target, "Process {process_id} closed its output");
289                    }
290                    return;
291                }
292                let consumed = buffer
293                    .iter()
294                    .position(|byte| *byte == b'\n')
295                    .map_or(buffer.len(), |position| position + 1);
296                let remaining = MAX_LINE_BYTES.saturating_sub(bytes.len());
297                bytes.extend_from_slice(&buffer[..consumed.min(remaining)]);
298                let complete = buffer[..consumed].ends_with(b"\n");
299                reader.consume(consumed);
300                if complete {
301                    break;
302                }
303            }
304            while bytes
305                .last()
306                .is_some_and(|byte| matches!(byte, b'\n' | b'\r'))
307            {
308                bytes.pop();
309            }
310            let line = String::from_utf8_lossy(&bytes).into_owned();
311            if matches!(stream, ProcessStream::Stderr) {
312                logged_errors += 1;
313                if logged_errors <= MAX_LOGGED_STDERR_LINES {
314                    log::warn!(target: &target, "{process_id}: {line}");
315                } else if logged_errors == MAX_LOGGED_STDERR_LINES + 1 {
316                    log::warn!(target: &target, "{process_id}: further error output isn't logged");
317                }
318            }
319            if sender
320                .send(WidgetProcessEvent {
321                    widget_id: widget_id.clone(),
322                    process_id: process_id.clone(),
323                    stream,
324                    line,
325                })
326                .is_err()
327            {
328                break;
329            }
330        }
331    });
332}
333
334#[cfg(test)]
335mod tests {
336    use super::*;
337
338    #[test]
339    fn only_manifest_arguments_are_allowed() {
340        let declaration = WidgetProcess {
341            id: "worker".into(),
342            executable: "optional-bin/worker".into(),
343            allowed_arguments: vec!["--quiet".into()],
344        };
345        assert!(validate_arguments(&declaration, &["--quiet".into()]).is_ok());
346        assert!(validate_arguments(&declaration, &["--shell".into()]).is_err());
347    }
348
349    #[test]
350    fn process_messages_must_be_single_line_json() {
351        let mut manager = WidgetProcessManager::default();
352        assert!(manager.send("sample", "worker", "not-json").is_err());
353        assert!(manager.send("sample", "worker", "{}\n{}").is_err());
354    }
355
356    /// `sort` reads its input to the end on Windows and macOS, so it exits only once that closes.
357    #[test]
358    fn stopping_lets_a_process_exit_before_killing_it() {
359        let spawn = || {
360            Command::new("sort")
361                .stdin(Stdio::piped())
362                .stdout(Stdio::null())
363                .spawn()
364                .unwrap()
365        };
366        let mut child = spawn();
367        drop(child.stdin.take());
368        finish(&mut child, Instant::now() + Duration::from_secs(10)).unwrap();
369        assert!(child.wait().unwrap().success());
370
371        let mut held = spawn();
372        let _stdin = held.stdin.take();
373        finish(&mut held, Instant::now()).unwrap();
374        assert!(!held.wait().unwrap().success());
375    }
376
377    #[test]
378    fn process_events_stay_scoped_to_their_widget() {
379        let mut manager = WidgetProcessManager::default();
380        for widget_id in ["first", "second"] {
381            manager
382                .events_tx
383                .send(WidgetProcessEvent {
384                    widget_id: widget_id.into(),
385                    process_id: "worker".into(),
386                    stream: ProcessStream::Stdout,
387                    line: widget_id.into(),
388                })
389                .unwrap();
390        }
391        assert_eq!(manager.drain_events("first").len(), 1);
392        let second = manager.drain_events("second");
393        assert_eq!(second.len(), 1);
394        assert_eq!(second[0].widget_id, "second");
395    }
396}