Skip to main content

kitchen_tools/plugin/
client.rs

1//! A plugin in server mode (from lumen's client): `<program> serve`, kept alive so what it loaded
2//! stays loaded (a model, SAM's image embedding between clicks). Blocking: the app calls it off
3//! the UI thread.
4
5use 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
12/// A running plugin server.
13pub struct PluginProcess {
14    /// The program it runs.
15    pub program: String,
16    child: Child,
17    stdin: ChildStdin,
18    stdout: BufReader<ChildStdout>,
19}
20
21impl PluginProcess {
22    /// Starts `program serve`.
23    pub fn start(program: &str) -> Result<Self, String> {
24        Self::start_command(program, &["serve"])
25    }
26
27    /// Starts `program args…` as a server speaking this protocol: a program whose `serve` means
28    /// something else (`dspk tool serve`), or one started through another (`podman run … dspk
29    /// tool serve`).
30    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    /// Whether the program is still running.
44    pub fn alive(&mut self) -> bool {
45        matches!(self.child.try_wait(), Ok(None))
46    }
47
48    /// Sends a request (any type with a `"request"` tag) and reads events until its answer;
49    /// `progress` sees the progress events. A line that is not an event is skipped.
50    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        // A server busy with a long request is not waited for
80        let _ = self.child.kill();
81        let _ = self.child.wait();
82    }
83}