Skip to main content

mouser_mode_api/
host.rs

1//! The host side: start a plugin, run the handshake, pump its messages, and
2//! restart it after a crash with back-off ([`crate::supervisor`]). Mouser
3//! owns one [`Supervisor`] per enabled plugin. Nothing here touches a shell:
4//! shells live in the session server, so a plugin crash never affects them.
5
6use crate::codec::{self, Wire};
7use crate::mode::Context;
8use crate::protocol::{Accepted, ApiRange, Hello, In, Out, Welcome, negotiate};
9use crate::shm::Ring;
10use crate::supervisor::{Decision, Restarts};
11use std::io::{BufReader, BufWriter};
12use std::path::PathBuf;
13use std::process::{Child, ChildStdin, Command, Stdio};
14use std::sync::Arc;
15use std::sync::mpsc::{Receiver, TryRecvError, channel};
16use std::time::{Duration, Instant};
17
18/// How to start a plugin.
19#[derive(Debug, Clone)]
20pub struct Spec {
21    pub name: String,
22    pub program: PathBuf,
23    pub args: Vec<String>,
24    pub env: Vec<(String, String)>,
25    /// Shared-memory ring: slots and bytes per slot (`None`: inline images).
26    pub shm: Option<(u32, usize)>,
27    /// What the host offers ([`crate::protocol::Accepted::features`]).
28    pub features: Vec<String>,
29}
30
31/// What Mouser grants a plugin after reading its `Hello`.
32#[derive(Debug, Clone, Default)]
33pub struct Grants {
34    pub granted: Vec<String>,
35    pub denied: Vec<(String, String)>,
36}
37
38/// A running, handshaken plugin.
39pub struct Connection {
40    child: Child,
41    tx: BufWriter<ChildStdin>,
42    rx: Receiver<Out>,
43    pub hello: Hello,
44    pub api: u32,
45    pub ring: Option<Ring>,
46}
47
48/// Called from the reader thread when a message arrives (wake the UI).
49pub type Notify = Arc<dyn Fn() + Send + Sync>;
50
51/// How long the plugin may take to say hello.
52pub const HELLO_TIMEOUT: Duration = Duration::from_secs(5);
53
54/// Start `spec`, read its `Hello`, negotiate and answer. `grant` decides
55/// permissions; `restore` is the state it saved before a crash.
56pub fn connect(
57    spec: &Spec,
58    ctx: Context,
59    restore: Option<Vec<u8>>,
60    grant: &mut dyn FnMut(&Hello) -> Grants,
61    notify: Option<Notify>,
62) -> Result<Connection, String> {
63    let mut cmd = Command::new(&spec.program);
64    cmd.args(&spec.args).envs(spec.env.iter().map(|(k, v)| (k, v))).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::inherit());
65    let mut child = cmd.spawn().map_err(|e| format!("can't start {}: {e}", spec.program.display()))?;
66    let mut tx = BufWriter::new(child.stdin.take().ok_or("no stdin")?);
67    let mut out = BufReader::with_capacity(1 << 20, child.stdout.take().ok_or("no stdout")?);
68    let (send, rx) = channel();
69    std::thread::Builder::new()
70        .name(format!("plugin-{}", spec.name))
71        .spawn(move || {
72            let mut buf = Vec::new();
73            while let Ok(Some(m)) = codec::read::<Out>(&mut out, Wire::MsgPack, &mut buf) {
74                if send.send(m).is_err() {
75                    break;
76                }
77                if let Some(n) = &notify {
78                    n();
79                }
80            }
81            // The plugin is gone: let the UI notice now.
82            drop(send);
83            if let Some(n) = &notify {
84                n();
85            }
86        })
87        .map_err(|e| e.to_string())?;
88    let fail = |mut child: Child, why: String| {
89        let _ = child.kill();
90        let _ = child.wait();
91        Err(why)
92    };
93    let hello = match rx.recv_timeout(HELLO_TIMEOUT) {
94        Ok(Out::Hello(h)) => h,
95        Ok(_) => return fail(child, "plugin spoke before saying hello".into()),
96        Err(_) => return fail(child, format!("{} sent no hello", spec.name)),
97    };
98    let api = match negotiate(ApiRange::CURRENT, hello.api) {
99        Ok(a) => a,
100        Err(reason) => {
101            let _ = codec::write_named(&mut tx, Wire::MsgPack, &Welcome::Rejected { reason: reason.clone() });
102            return fail(child, reason);
103        }
104    };
105    let g = grant(&hello);
106    let ring = match (spec.shm, hello.shm) {
107        (Some((slots, bytes)), true) => Ring::create(&spec.name, slots, bytes).ok(),
108        _ => None,
109    };
110    let accepted = Accepted {
111        api,
112        session: format!("{}-{}", spec.name, child.id()),
113        ctx,
114        granted: g.granted,
115        denied: g.denied,
116        shm: ring.as_ref().map(Ring::spec),
117        mcp: None,
118        restore,
119        features: spec.features.clone(),
120    };
121    if let Err(e) = codec::write_named(&mut tx, Wire::MsgPack, &Welcome::Accepted(Box::new(accepted))) {
122        return fail(child, e.to_string());
123    }
124    Ok(Connection { child, tx, rx, hello, api, ring })
125}
126
127impl Connection {
128    pub fn send(&mut self, m: &In) -> std::io::Result<()> {
129        codec::write_named(&mut self.tx, Wire::MsgPack, m)
130    }
131
132    /// Ask it to stop, then make sure it has.
133    pub fn stop(mut self, reason: &str, grace: Duration) {
134        let _ = self.send(&In::Stopping { reason: reason.into() });
135        let end = Instant::now() + grace;
136        while Instant::now() < end {
137            if let Ok(Some(_)) = self.child.try_wait() {
138                return;
139            }
140            std::thread::sleep(Duration::from_millis(10));
141        }
142        let _ = self.child.kill();
143        let _ = self.child.wait();
144    }
145}
146
147impl Drop for Connection {
148    fn drop(&mut self) {
149        if let Ok(None) = self.child.try_wait() {
150            let _ = self.child.kill();
151        }
152        let _ = self.child.wait();
153    }
154}
155
156/// Where a supervised plugin is.
157#[derive(Debug, Clone, PartialEq, Eq)]
158pub enum State {
159    Running,
160    /// Crashed; starting again at this time.
161    Waiting {
162        until: Instant,
163        crashes: u32,
164    },
165    /// Gave up after too many crashes (or it was incompatible): stays off
166    /// until the user restarts it.
167    Disabled {
168        reason: String,
169    },
170}
171
172/// One plugin, kept running.
173pub struct Supervisor {
174    pub spec: Spec,
175    ctx: Context,
176    grant: Box<dyn FnMut(&Hello) -> Grants + Send>,
177    restarts: Restarts,
178    conn: Option<Connection>,
179    state: State,
180    saved: Option<Vec<u8>>,
181    crashes: u32,
182    notify: Option<Notify>,
183}
184
185impl Supervisor {
186    /// `max_restarts` is the `plugins.max_restarts` preference.
187    pub fn new(spec: Spec, ctx: Context, max_restarts: u32, grant: impl FnMut(&Hello) -> Grants + Send + 'static) -> Self {
188        Self::with_restarts(spec, ctx, Restarts::new(max_restarts), grant)
189    }
190
191    pub fn with_restarts(spec: Spec, ctx: Context, restarts: Restarts, grant: impl FnMut(&Hello) -> Grants + Send + 'static) -> Self {
192        let mut s = Self {
193            spec,
194            ctx,
195            grant: Box::new(grant),
196            restarts,
197            conn: None,
198            state: State::Waiting { until: Instant::now(), crashes: 0 },
199            saved: None,
200            crashes: 0,
201            notify: None,
202        };
203        s.start(Instant::now());
204        s
205    }
206
207    /// Like [`Supervisor::new`], with a callback for arriving messages; it is
208    /// set before the first start.
209    pub fn with_notify(spec: Spec, ctx: Context, restarts: Restarts, notify: Notify, grant: impl FnMut(&Hello) -> Grants + Send + 'static) -> Self {
210        let mut s = Self {
211            spec,
212            ctx,
213            grant: Box::new(grant),
214            restarts,
215            conn: None,
216            state: State::Waiting { until: Instant::now(), crashes: 0 },
217            saved: None,
218            crashes: 0,
219            notify: Some(notify),
220        };
221        s.start(Instant::now());
222        s
223    }
224
225    /// Send the new drawing area to later restarts too.
226    pub fn set_ctx(&mut self, ctx: Context) {
227        self.ctx = ctx;
228    }
229
230    pub fn state(&self) -> &State {
231        &self.state
232    }
233
234    pub fn connection(&self) -> Option<&Connection> {
235        self.conn.as_ref()
236    }
237
238    fn start(&mut self, now: Instant) {
239        match connect(&self.spec, self.ctx, self.saved.clone(), &mut *self.grant, self.notify.clone()) {
240            Ok(c) => {
241                self.conn = Some(c);
242                self.state = State::Running;
243            }
244            Err(e) if e.contains("update") => self.state = State::Disabled { reason: e },
245            Err(_) => self.crashed(now),
246        }
247    }
248
249    fn crashed(&mut self, now: Instant) {
250        self.conn = None;
251        self.crashes += 1;
252        self.state = match self.restarts.crashed(now) {
253            Decision::Restart(wait) => State::Waiting { until: now + wait, crashes: self.crashes },
254            Decision::GiveUp => State::Disabled { reason: format!("{} stopped after {} crashes", self.spec.name, self.crashes) },
255        };
256    }
257
258    /// Send a message; a broken pipe counts as a crash.
259    pub fn send(&mut self, m: &In, now: Instant) -> bool {
260        let ok = self.conn.as_mut().is_some_and(|c| c.send(m).is_ok());
261        if !ok && self.state == State::Running {
262            self.crashed(now);
263        }
264        ok
265    }
266
267    /// Drain the plugin's messages and handle crashes and restarts. Call it
268    /// every frame or when woken. `StateSave` is kept here for the restart.
269    pub fn poll(&mut self, now: Instant) -> Vec<Out> {
270        let mut out = Vec::new();
271        if let State::Waiting { until, .. } = self.state
272            && now >= until
273        {
274            self.start(now);
275        }
276        let mut dead = false;
277        if let Some(c) = &mut self.conn {
278            loop {
279                match c.rx.try_recv() {
280                    Ok(Out::StateSave(b)) => self.saved = Some(b),
281                    Ok(m) => out.push(m),
282                    Err(TryRecvError::Empty) => break,
283                    Err(TryRecvError::Disconnected) => {
284                        dead = true;
285                        break;
286                    }
287                }
288            }
289        }
290        if dead {
291            self.crashed(now);
292        }
293        out
294    }
295
296    /// The status bar's restart action: count again from zero and start now.
297    pub fn restart(&mut self, now: Instant) {
298        if let Some(c) = self.conn.take() {
299            c.stop("restart", Duration::from_millis(500));
300        }
301        self.restarts.reset();
302        self.crashes = 0;
303        self.start(now);
304    }
305
306    /// Stop for good (quit, disable, upgrade).
307    pub fn stop(&mut self, reason: &str) {
308        if let Some(c) = self.conn.take() {
309            c.stop(reason, Duration::from_millis(500));
310        }
311        self.state = State::Disabled { reason: reason.into() };
312    }
313
314    /// A status-bar line, or `None` while it runs normally.
315    pub fn status(&self, now: Instant) -> Option<String> {
316        match &self.state {
317            State::Running => None,
318            State::Waiting { until, .. } => {
319                Some(format!("{} crashed, restarting in {} s", self.spec.name, until.saturating_duration_since(now).as_secs_f32().ceil() as u64))
320            }
321            State::Disabled { reason } => Some(format!("{reason} (restart)")),
322        }
323    }
324}