Skip to main content

standard_plugin/testing/
machine.rs

1//! The daemon world of the in-process host: children a plugin spawns
2//! (recorded with their argv, environment and directory, answered from a
3//! script) and file watches (checked with the host's own path rules).
4
5use alloc::collections::VecDeque;
6use alloc::string::{String, ToString};
7use alloc::vec::Vec;
8use std::path::Path;
9
10use standard_plugin_manifest::paths::{Excludes, PathGrants, real};
11
12use super::MockHost;
13use crate::daemon::process::{Command, Stdio};
14use crate::error::{Error, Result};
15use crate::ui_runtime::Event;
16
17/// What a scripted program does when the plugin spawns it: the output
18/// it writes (delivered as `Event::ProcessOutput` for a piped stream) and
19/// its exit status (`Event::ProcessExited`, and what `wait` answers).
20#[derive(Clone, Debug, Default, PartialEq, Eq)]
21pub struct ProcessScript {
22    pub stdout: Vec<u8>,
23    pub stderr: Vec<u8>,
24    pub status: i32,
25}
26
27impl ProcessScript {
28    /// Exits with `status` and writes nothing.
29    pub fn exit(status: i32) -> Self {
30        Self {
31            status,
32            ..Self::default()
33        }
34    }
35
36    pub fn stdout(mut self, bytes: impl AsRef<[u8]>) -> Self {
37        self.stdout = bytes.as_ref().to_vec();
38        self
39    }
40
41    pub fn stderr(mut self, bytes: impl AsRef<[u8]>) -> Self {
42        self.stderr = bytes.as_ref().to_vec();
43        self
44    }
45}
46
47/// One child the plugin spawned, as the host saw it.
48#[derive(Clone, Debug, PartialEq, Eq)]
49pub struct MockProcess {
50    /// Distinct per child, from 1000.
51    pub pid: u32,
52    pub program: String,
53    pub args: Vec<String>,
54    /// The environment the child got: the plugin's
55    /// ([`MockHost::env`]), less `env_remove`, plus `env` (or only `env`
56    /// with `clear_env`), sorted.
57    pub env: Vec<(String, String)>,
58    /// The directory it ran in: the command's, else the plugin's `HOME`.
59    pub cwd: Option<String>,
60    pub stdin: Vec<u8>,
61    pub stdin_closed: bool,
62    /// Its exit status once it exited (a script, [`DaemonHarness::exit`],
63    /// or a kill: `-9`).
64    ///
65    /// [`DaemonHarness::exit`]: super::DaemonHarness::exit
66    pub status: Option<i32>,
67    pub killed: bool,
68    /// Whether it has a message channel (`Command::spawn_with_channel`),
69    /// and the messages the plugin sent on it.
70    pub channel: bool,
71    pub sent: Vec<String>,
72    stdout: Stdio,
73    stderr: Stdio,
74}
75
76impl MockProcess {
77    /// One variable of the child's environment.
78    pub fn var(&self, name: &str) -> Option<&str> {
79        self.env
80            .iter()
81            .find(|(key, _)| key == name)
82            .map(|(_, value)| value.as_str())
83    }
84}
85
86/// One watch the plugin holds.
87#[derive(Clone, Debug, PartialEq, Eq)]
88pub struct MockWatch {
89    pub handle: u32,
90    pub path: String,
91    pub recursive: bool,
92    pub exclude: Vec<String>,
93}
94
95/// One pane the plugin opened (`daemon::panes::create`), as the host saw
96/// it.
97#[derive(Clone, Debug, PartialEq, Eq)]
98pub struct MockPaneLaunch {
99    /// The pane's id, `pane-1` onwards; its generation is 1.
100    pub id: String,
101    /// The project whose root holds `cwd`.
102    pub project: String,
103    pub cwd: String,
104    pub command: Option<String>,
105    pub env: Vec<(String, String)>,
106    /// The title it asked for (`NewPane::title`); the plugin's id shows when
107    /// none.
108    pub title: Option<String>,
109}
110
111/// The daemon-world state of a [`MockHost`].
112#[derive(Clone, Debug, Default)]
113pub(crate) struct Machine {
114    pub processes: Vec<MockProcess>,
115    pub pane_launches: Vec<MockPaneLaunch>,
116    pub scripts: Vec<(String, Option<Vec<String>>, ProcessScript)>,
117    pub watches: Vec<MockWatch>,
118    /// WebSockets the plugin opened (`daemon-net`), by handle.
119    pub websockets: Vec<MockWebSocket>,
120    next_pid: u32,
121    next_watch: u32,
122    /// Machine events for the plugin, delivered before the next drive.
123    pub pending: VecDeque<Event>,
124}
125
126/// A WebSocket the plugin opened on the test host.
127#[derive(Clone, Debug, PartialEq, Eq)]
128pub struct MockWebSocket {
129    pub socket: u32,
130    pub url: String,
131    pub headers: Vec<(String, String)>,
132    /// The text frames it sent.
133    pub sent: Vec<String>,
134    pub closed: bool,
135}
136
137/// Watches one plugin may hold, as the host allows.
138const MAX_WATCHES: usize = 256;
139
140impl MockHost {
141    /// The WebSockets the plugin opened, in order.
142    pub fn websockets(&self) -> &[MockWebSocket] {
143        &self.machine.websockets
144    }
145
146    /// Delivers a socket's news to the plugin as the host would
147    /// (`system.net.websocket`): `kind` `open`, `message` (with `text`) or
148    /// `closed` (with `text` as the reason).
149    pub fn websocket_event(&mut self, socket: u32, kind: &str, text: &str) {
150        let payload = match kind {
151            "message" => serde_json::json!({"socket": socket, "kind": kind, "text": text}),
152            "closed" => serde_json::json!({"socket": socket, "kind": kind, "reason": text}),
153            _ => serde_json::json!({"socket": socket, "kind": kind}),
154        };
155        self.machine.pending.push_back(Event::Plugin {
156            name: String::from(crate::daemon::net::WEBSOCKET_EVENT),
157            payload: crate::Json(payload.to_string()),
158        });
159    }
160
161    /// A program in a pane connects to the plugin's endpoint `endpoint`,
162    /// from `machine` when it runs on another: delivers `accepted` and
163    /// returns the socket, which [`MockHost::websockets`] then lists with
164    /// the endpoint as its URL (`endpoint:<id>`).
165    pub fn endpoint_accept(&mut self, endpoint: &str, machine: Option<&str>) -> u32 {
166        self.endpoint_accept_from(endpoint, machine, None)
167    }
168
169    /// [`MockHost::endpoint_accept`] from the pane `pane`, as a pane started
170    /// with its own endpoint URL connects.
171    pub fn endpoint_accept_from(
172        &mut self,
173        endpoint: &str,
174        machine: Option<&str>,
175        pane: Option<&str>,
176    ) -> u32 {
177        let socket = (1 << 31) | (self.machine.websockets.len() as u32 + 1);
178        self.machine.websockets.push(MockWebSocket {
179            socket,
180            url: alloc::format!("endpoint:{endpoint}"),
181            headers: Vec::new(),
182            sent: Vec::new(),
183            closed: false,
184        });
185        let payload = serde_json::json!({
186            "socket": socket,
187            "kind": "accepted",
188            "endpoint": endpoint,
189            "path": "/",
190            "machine": machine,
191            "pane": pane,
192        });
193        self.machine.pending.push_back(Event::Plugin {
194            name: String::from(crate::daemon::net::WEBSOCKET_EVENT),
195            payload: crate::Json(payload.to_string()),
196        });
197        socket
198    }
199
200    pub(crate) fn websocket_open(
201        &mut self,
202        url: &str,
203        headers: &[(String, String)],
204    ) -> Result<u32> {
205        let (target, secure) = match (url.strip_prefix("wss://"), url.strip_prefix("ws://")) {
206            (Some(rest), _) => (rest, true),
207            (None, Some(rest)) => (rest, false),
208            _ => {
209                return Err(Error::Invalid(alloc::format!(
210                    "{url:?} is not a wss:// URL"
211                )));
212            }
213        };
214        let target = target.split('/').next().unwrap_or_default();
215        let (host, port) = match target.rsplit_once(':') {
216            Some((host, port)) => (host, port.parse::<u16>().unwrap_or(0)),
217            None => (target, if secure { 443 } else { 80 }),
218        };
219        if !secure {
220            // Plain sockets reach only this machine's loopback, with a grant
221            // that reaches any address already.
222            if !matches!(host, "127.0.0.1" | "localhost" | "[::1]") {
223                return Err(Error::Invalid(alloc::format!(
224                    "{url:?} is not on this machine's loopback"
225                )));
226            }
227            if !self.grants.allows("machine.full") && !self.grants.allows("network.full") {
228                return Err(self.deny(standard_plugin_manifest::GrantDenied {
229                    grant: "network.full".into(),
230                }));
231            }
232        } else if !self.grants.socket_ports(host).contains(&port) {
233            return Err(self.deny(standard_plugin_manifest::GrantDenied {
234                grant: alloc::format!("socket.connect:{host}:{port}"),
235            }));
236        }
237        let socket = self.machine.websockets.len() as u32 + 1;
238        self.machine.websockets.push(MockWebSocket {
239            socket,
240            url: url.to_string(),
241            headers: headers.to_vec(),
242            sent: Vec::new(),
243            closed: false,
244        });
245        Ok(socket)
246    }
247
248    pub(crate) fn websocket_send(&mut self, socket: u32, text: &str) -> Result<()> {
249        let open = self
250            .machine
251            .websockets
252            .iter_mut()
253            .find(|open| open.socket == socket && !open.closed)
254            .ok_or_else(|| Error::Invalid(alloc::format!("socket {socket} is not open")))?;
255        open.sent.push(text.to_string());
256        Ok(())
257    }
258
259    pub(crate) fn websocket_close(&mut self, socket: u32) {
260        if let Some(open) = self
261            .machine
262            .websockets
263            .iter_mut()
264            .find(|open| open.socket == socket)
265        {
266            open.closed = true;
267        }
268    }
269
270    /// Answers every spawn of `program` (as spawned, any arguments) with
271    /// `script`. A later script for the same program wins.
272    pub fn script(mut self, program: &str, script: ProcessScript) -> Self {
273        self.machine
274            .scripts
275            .insert(0, (program.to_string(), None, script));
276        self
277    }
278
279    /// Answers spawns of `program` whose arguments start with `args`.
280    pub fn script_args(mut self, program: &str, args: &[&str], script: ProcessScript) -> Self {
281        let args = args.iter().map(|arg| arg.to_string()).collect();
282        self.machine
283            .scripts
284            .insert(0, (program.to_string(), Some(args), script));
285        self
286    }
287
288    /// Every child the plugin spawned, in order.
289    pub fn processes(&self) -> &[MockProcess] {
290        &self.machine.processes
291    }
292
293    /// The watches the plugin holds.
294    /// The panes the plugin opened, in order.
295    pub fn pane_launches(&self) -> &[MockPaneLaunch] {
296        &self.machine.pane_launches
297    }
298
299    /// Opens a pane as `standardd` does: in a directory inside a project
300    /// root of this machine (`account.projects`, by whole components after
301    /// symlinks; any machine's while [`MockHost::machine`] is unset), with
302    /// the command and variables recorded, listed in `panes` at
303    /// generation 1.
304    pub(crate) fn create_pane(
305        &mut self,
306        cwd: &str,
307        command: Option<&str>,
308        env: &[(String, String)],
309        title: Option<&str>,
310    ) -> Result<(String, u64)> {
311        if title.is_some_and(|title| {
312            title.trim().is_empty()
313                || title.chars().count() > 128
314                || title.chars().any(char::is_control)
315        }) {
316            return Err(Error::Invalid(
317                "a pane title is 1 to 128 characters with no control characters".to_string(),
318            ));
319        }
320        if env.len() > 64
321            || env.iter().any(|(name, value)| {
322                name.is_empty() || name.contains(['=', '\0']) || value.contains('\0')
323            })
324        {
325            return Err(Error::Invalid(
326                "variables a pane cannot be given".to_string(),
327            ));
328        }
329        let path = Path::new(cwd);
330        if !path.is_absolute() {
331            return Err(Error::Invalid(alloc::format!(
332                "{cwd} is not an absolute path"
333            )));
334        }
335        let resolved = real(path);
336        let machine = self.machine_id.clone();
337        let project = self
338            .account
339            .projects
340            .iter()
341            .filter(|project| machine.as_ref().is_none_or(|id| &project.machine == id))
342            .filter(|project| resolved.starts_with(real(Path::new(&project.path))))
343            .max_by_key(|project| real(Path::new(&project.path)).components().count())
344            .ok_or_else(|| {
345                Error::Invalid(alloc::format!(
346                    "{cwd} is not inside a project root on this machine"
347                ))
348            })?
349            .id
350            .clone();
351        let id = alloc::format!("pane-{}", self.machine.pane_launches.len() + 1);
352        self.panes.push(crate::api::account::Pane {
353            id: id.clone(),
354            generation: 1,
355            machine: machine.unwrap_or_default(),
356            project: Some(project.clone()),
357            title: title.map_or_else(|| self.plugin_id.clone(), str::to_string),
358            cwd: cwd.to_string(),
359            cols: 80,
360            rows: 24,
361            ..Default::default()
362        });
363        self.machine.pane_launches.push(MockPaneLaunch {
364            id: id.clone(),
365            project,
366            cwd: cwd.to_string(),
367            command: command.map(str::to_string),
368            env: env.to_vec(),
369            title: title.map(str::to_string),
370        });
371        Ok((id, 1))
372    }
373
374    pub fn watches(&self) -> &[MockWatch] {
375        &self.machine.watches
376    }
377
378    pub(crate) fn spawn(&mut self, command: &Command) -> Result<u32> {
379        if command.program.is_empty() {
380            return Err(Error::Invalid("no program".into()));
381        }
382        if !self.grants.allows("machine.full") {
383            self.check(&alloc::format!("process.exec:{}", command.program))?;
384        }
385        let mut env: Vec<(String, String)> = if command.clear_env {
386            Vec::new()
387        } else {
388            self.environment
389                .iter()
390                .filter(|(name, _)| !command.env_remove.contains(name))
391                .cloned()
392                .collect()
393        };
394        for (name, value) in &command.env {
395            env.retain(|(key, _)| key != name);
396            env.push((name.clone(), value.clone()));
397        }
398        env.sort();
399        let cwd = command.cwd.clone().or_else(|| {
400            self.environment
401                .iter()
402                .find(|(name, _)| name == "HOME")
403                .map(|(_, home)| home.clone())
404        });
405        let pid = 1000 + self.machine.next_pid;
406        self.machine.next_pid += 1;
407        let script = self
408            .machine
409            .scripts
410            .iter()
411            .find(|(program, args, _)| {
412                *program == command.program
413                    && args
414                        .as_ref()
415                        .is_none_or(|args| command.args.starts_with(args))
416            })
417            .map(|(_, _, script)| script.clone());
418        self.machine.processes.push(MockProcess {
419            pid,
420            program: command.program.clone(),
421            args: command.args.clone(),
422            env,
423            cwd,
424            stdin: Vec::new(),
425            stdin_closed: false,
426            status: None,
427            killed: false,
428            channel: false,
429            sent: Vec::new(),
430            stdout: command.stdout,
431            stderr: command.stderr,
432        });
433        if let Some(script) = script {
434            self.output(pid, false, &script.stdout);
435            self.output(pid, true, &script.stderr);
436            self.exited(pid, script.status);
437        }
438        Ok(pid)
439    }
440
441    fn process(&mut self, pid: u32) -> Result<&mut MockProcess> {
442        self.machine
443            .processes
444            .iter_mut()
445            .find(|process| process.pid == pid)
446            .ok_or_else(|| Error::Invalid(alloc::format!("no child {pid} of this plugin")))
447    }
448
449    /// Queues output of `pid` for the plugin, when that stream is piped.
450    pub(crate) fn output(&mut self, pid: u32, stderr: bool, bytes: &[u8]) {
451        let Ok(process) = self.process(pid) else {
452            return;
453        };
454        let piped = if stderr {
455            process.stderr == Stdio::Piped
456        } else {
457            process.stdout == Stdio::Piped
458        };
459        if piped && !bytes.is_empty() {
460            self.machine.pending.push_back(Event::ProcessOutput {
461                pid,
462                stderr,
463                bytes: bytes.to_vec(),
464            });
465        }
466    }
467
468    /// `pid` exits with `status`: the plugin hears it after its output.
469    pub(crate) fn exited(&mut self, pid: u32, status: i32) {
470        let Ok(process) = self.process(pid) else {
471            return;
472        };
473        if process.status.is_some() {
474            return;
475        }
476        process.status = Some(status);
477        self.machine
478            .pending
479            .push_back(Event::ProcessExited { pid, status });
480    }
481
482    pub(crate) fn wait(&mut self, pid: u32) -> Result<i32> {
483        let process = self.process(pid)?;
484        process.status.ok_or_else(|| {
485            Error::Unavailable(alloc::format!(
486                "child {pid} ({}) has no script and would block forever: script it \
487                 (MockHost::script) or end it (DaemonHarness::exit) first",
488                process.program
489            ))
490        })
491    }
492
493    /// A scripted child has exited by the time anyone waits; one with no
494    /// script and no exit still runs, so a bounded wait times out.
495    pub(crate) fn wait_timeout(&mut self, pid: u32) -> Result<Option<i32>> {
496        Ok(self.process(pid)?.status)
497    }
498
499    pub(crate) fn try_wait(&mut self, pid: u32) -> Result<Option<i32>> {
500        Ok(self.process(pid)?.status)
501    }
502
503    pub(crate) fn write(&mut self, pid: u32, bytes: &[u8]) -> Result<()> {
504        let process = self.process(pid)?;
505        if process.stdin_closed {
506            return Err(Error::Invalid(alloc::format!(
507                "child {pid}'s stdin is closed"
508            )));
509        }
510        process.stdin.extend_from_slice(bytes);
511        Ok(())
512    }
513
514    /// As `spawn`, with a message channel.
515    pub(crate) fn spawn_with_channel(&mut self, command: &Command) -> Result<u32> {
516        let pid = self.spawn(command)?;
517        self.process(pid)?.channel = true;
518        Ok(pid)
519    }
520
521    pub(crate) fn send(&mut self, pid: u32, message: &str) -> Result<()> {
522        let process = self.process(pid)?;
523        if !process.channel {
524            return Err(Error::Invalid(alloc::format!("child {pid} has no channel")));
525        }
526        process.sent.push(message.to_string());
527        Ok(())
528    }
529
530    /// Delivers a message from a child's channel to the plugin, as the
531    /// host would (`system.process.channel`).
532    pub fn channel_message(&mut self, pid: u32, message: &str) {
533        let message = serde_json::from_str::<serde_json::Value>(message)
534            .unwrap_or_else(|_| serde_json::Value::String(message.to_string()));
535        self.machine.pending.push_back(Event::Plugin {
536            name: String::from(crate::daemon::process::CHANNEL_EVENT),
537            payload: crate::Json(serde_json::json!({ "pid": pid, "message": message }).to_string()),
538        });
539    }
540
541    pub(crate) fn close_stdin(&mut self, pid: u32) -> Result<()> {
542        self.process(pid)?.stdin_closed = true;
543        Ok(())
544    }
545
546    pub(crate) fn kill(&mut self, pid: u32) -> Result<()> {
547        let process = self.process(pid)?;
548        if process.status.is_none() {
549            process.killed = true;
550            self.exited(pid, -9);
551        }
552        Ok(())
553    }
554
555    /// `daemon-watch.watch` with the host's own rules: an absolute path a
556    /// read grant covers after resolving symlinks (or `machine.full`), and
557    /// exclude globs the host accepts.
558    pub(crate) fn watch(&mut self, path: &str, recursive: bool, exclude: &[String]) -> Result<u32> {
559        let named = Path::new(path);
560        if !named.is_absolute() {
561            return Err(Error::Invalid(alloc::format!(
562                "{path} is not an absolute path"
563            )));
564        }
565        if !PathGrants::from_grants(&self.grants).allows(&real(named), false) {
566            return Err(self.deny(standard_plugin_manifest::GrantDenied {
567                grant: alloc::format!("fs.read:{path}"),
568            }));
569        }
570        Excludes::new(exclude).map_err(|error| Error::Invalid(error.to_string()))?;
571        if self.machine.watches.len() >= MAX_WATCHES {
572            return Err(Error::RateLimited);
573        }
574        self.machine.next_watch += 1;
575        let handle = self.machine.next_watch;
576        self.machine.watches.push(MockWatch {
577            handle,
578            path: path.to_string(),
579            recursive,
580            exclude: exclude.to_vec(),
581        });
582        Ok(handle)
583    }
584
585    pub(crate) fn unwatch(&mut self, handle: u32) -> Result<()> {
586        let before = self.machine.watches.len();
587        self.machine.watches.retain(|watch| watch.handle != handle);
588        if self.machine.watches.len() == before {
589            return Err(Error::Invalid(alloc::format!("no watch {handle}")));
590        }
591        Ok(())
592    }
593
594    /// Queues `Event::FileChanged` for every watch that hears a change at
595    /// `path`, as the host decides it (depth and exclude globs). Returns
596    /// how many watches hear it.
597    pub(crate) fn changed(&mut self, path: &str) -> usize {
598        let path = Path::new(path);
599        let mut heard = 0;
600        for watch in &self.machine.watches {
601            let Ok(rest) = path.strip_prefix(&watch.path) else {
602                continue;
603            };
604            if !watch.recursive && rest.components().count() > 1 {
605                continue;
606            }
607            let excluded = Excludes::new(&watch.exclude).is_ok_and(|globs| globs.excludes(rest));
608            if excluded {
609                continue;
610            }
611            heard += 1;
612            self.machine.pending.push_back(Event::FileChanged {
613                watch: watch.handle,
614                paths: alloc::vec![path.to_string_lossy().into_owned()],
615            });
616        }
617        heard
618    }
619}