kitchen_tools/plugin/
client.rs1use std::io::{BufRead, BufReader, Write};
6use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
7
8use serde::Serialize;
9
10use crate::plugin::protocol::{CoreRequest, Event};
11
12pub struct PluginProcess {
14 pub program: String,
16 child: Child,
17 stdin: ChildStdin,
18 stdout: BufReader<ChildStdout>,
19}
20
21impl PluginProcess {
22 pub fn start(program: &str) -> Result<Self, String> {
24 Self::start_command(program, &["serve"])
25 }
26
27 pub fn start_command(program: &str, args: &[&str]) -> Result<Self, String> {
31 let mut child = Command::new(program)
32 .args(args)
33 .stdin(Stdio::piped())
34 .stdout(Stdio::piped())
35 .stderr(Stdio::inherit())
36 .spawn()
37 .map_err(|e| format!("{program}: {e}"))?;
38 let stdin = child.stdin.take().ok_or("no stdin")?;
39 let stdout = BufReader::new(child.stdout.take().ok_or("no stdout")?);
40 Ok(Self { program: program.to_string(), child, stdin, stdout })
41 }
42
43 pub fn alive(&mut self) -> bool {
45 matches!(self.child.try_wait(), Ok(None))
46 }
47
48 pub fn request<R: Serialize>(
51 &mut self,
52 req: &R,
53 progress: &mut dyn FnMut(&str, Option<f32>),
54 ) -> Result<serde_json::Value, String> {
55 let line = serde_json::to_string(req).map_err(|e| e.to_string())?;
56 writeln!(self.stdin, "{line}")
57 .and_then(|_| self.stdin.flush())
58 .map_err(|e| format!("{}: {e}", self.program))?;
59 loop {
60 let mut buf = String::new();
61 let n = self.stdout.read_line(&mut buf).map_err(|e| e.to_string())?;
62 if n == 0 {
63 return Err(format!("{} stopped (see its messages in the terminal)", self.program));
64 }
65 let Ok(event) = serde_json::from_str::<Event>(buf.trim()) else { continue };
66 match event {
67 Event::Progress { stage, fraction } => progress(&stage, fraction),
68 Event::Done { result } => return Ok(result),
69 Event::Error { message } => return Err(message),
70 }
71 }
72 }
73}
74
75impl Drop for PluginProcess {
76 fn drop(&mut self) {
77 let _ = writeln!(self.stdin, "{}", serde_json::to_string(&CoreRequest::Quit).unwrap_or_default());
78 let _ = self.stdin.flush();
79 let _ = self.child.kill();
81 let _ = self.child.wait();
82 }
83}