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 = url
206            .strip_prefix("wss://")
207            .map(|rest| rest.split('/').next().unwrap_or_default())
208            .ok_or_else(|| Error::Invalid(alloc::format!("{url:?} is not a wss:// URL")))?;
209        let (host, port) = match target.rsplit_once(':') {
210            Some((host, port)) => (host, port.parse::<u16>().unwrap_or(0)),
211            None => (target, 443),
212        };
213        if !self.grants.socket_ports(host).contains(&port) {
214            return Err(self.deny(standard_plugin_manifest::GrantDenied {
215                grant: alloc::format!("socket.connect:{host}:{port}"),
216            }));
217        }
218        let socket = self.machine.websockets.len() as u32 + 1;
219        self.machine.websockets.push(MockWebSocket {
220            socket,
221            url: url.to_string(),
222            headers: headers.to_vec(),
223            sent: Vec::new(),
224            closed: false,
225        });
226        Ok(socket)
227    }
228
229    pub(crate) fn websocket_send(&mut self, socket: u32, text: &str) -> Result<()> {
230        let open = self
231            .machine
232            .websockets
233            .iter_mut()
234            .find(|open| open.socket == socket && !open.closed)
235            .ok_or_else(|| Error::Invalid(alloc::format!("socket {socket} is not open")))?;
236        open.sent.push(text.to_string());
237        Ok(())
238    }
239
240    pub(crate) fn websocket_close(&mut self, socket: u32) {
241        if let Some(open) = self
242            .machine
243            .websockets
244            .iter_mut()
245            .find(|open| open.socket == socket)
246        {
247            open.closed = true;
248        }
249    }
250
251    /// Answers every spawn of `program` (as spawned, any arguments) with
252    /// `script`. A later script for the same program wins.
253    pub fn script(mut self, program: &str, script: ProcessScript) -> Self {
254        self.machine
255            .scripts
256            .insert(0, (program.to_string(), None, script));
257        self
258    }
259
260    /// Answers spawns of `program` whose arguments start with `args`.
261    pub fn script_args(mut self, program: &str, args: &[&str], script: ProcessScript) -> Self {
262        let args = args.iter().map(|arg| arg.to_string()).collect();
263        self.machine
264            .scripts
265            .insert(0, (program.to_string(), Some(args), script));
266        self
267    }
268
269    /// Every child the plugin spawned, in order.
270    pub fn processes(&self) -> &[MockProcess] {
271        &self.machine.processes
272    }
273
274    /// The watches the plugin holds.
275    /// The panes the plugin opened, in order.
276    pub fn pane_launches(&self) -> &[MockPaneLaunch] {
277        &self.machine.pane_launches
278    }
279
280    /// Opens a pane as `standardd` does: in a directory inside a project
281    /// root of this machine (`account.projects`, by whole components after
282    /// symlinks; any machine's while [`MockHost::machine`] is unset), with
283    /// the command and variables recorded, listed in `panes` at
284    /// generation 1.
285    pub(crate) fn create_pane(
286        &mut self,
287        cwd: &str,
288        command: Option<&str>,
289        env: &[(String, String)],
290        title: Option<&str>,
291    ) -> Result<(String, u64)> {
292        if title.is_some_and(|title| {
293            title.trim().is_empty()
294                || title.chars().count() > 128
295                || title.chars().any(char::is_control)
296        }) {
297            return Err(Error::Invalid(
298                "a pane title is 1 to 128 characters with no control characters".to_string(),
299            ));
300        }
301        if env.len() > 64
302            || env.iter().any(|(name, value)| {
303                name.is_empty() || name.contains(['=', '\0']) || value.contains('\0')
304            })
305        {
306            return Err(Error::Invalid(
307                "variables a pane cannot be given".to_string(),
308            ));
309        }
310        let path = Path::new(cwd);
311        if !path.is_absolute() {
312            return Err(Error::Invalid(alloc::format!(
313                "{cwd} is not an absolute path"
314            )));
315        }
316        let resolved = real(path);
317        let machine = self.machine_id.clone();
318        let project = self
319            .account
320            .projects
321            .iter()
322            .filter(|project| machine.as_ref().is_none_or(|id| &project.machine == id))
323            .filter(|project| resolved.starts_with(real(Path::new(&project.path))))
324            .max_by_key(|project| real(Path::new(&project.path)).components().count())
325            .ok_or_else(|| {
326                Error::Invalid(alloc::format!(
327                    "{cwd} is not inside a project root on this machine"
328                ))
329            })?
330            .id
331            .clone();
332        let id = alloc::format!("pane-{}", self.machine.pane_launches.len() + 1);
333        self.panes.push(crate::api::account::Pane {
334            id: id.clone(),
335            generation: 1,
336            machine: machine.unwrap_or_default(),
337            project: Some(project.clone()),
338            title: title.map_or_else(|| self.plugin_id.clone(), str::to_string),
339            cwd: cwd.to_string(),
340            cols: 80,
341            rows: 24,
342            ..Default::default()
343        });
344        self.machine.pane_launches.push(MockPaneLaunch {
345            id: id.clone(),
346            project,
347            cwd: cwd.to_string(),
348            command: command.map(str::to_string),
349            env: env.to_vec(),
350            title: title.map(str::to_string),
351        });
352        Ok((id, 1))
353    }
354
355    pub fn watches(&self) -> &[MockWatch] {
356        &self.machine.watches
357    }
358
359    pub(crate) fn spawn(&mut self, command: &Command) -> Result<u32> {
360        if command.program.is_empty() {
361            return Err(Error::Invalid("no program".into()));
362        }
363        if !self.grants.allows("machine.full") {
364            self.check(&alloc::format!("process.exec:{}", command.program))?;
365        }
366        let mut env: Vec<(String, String)> = if command.clear_env {
367            Vec::new()
368        } else {
369            self.environment
370                .iter()
371                .filter(|(name, _)| !command.env_remove.contains(name))
372                .cloned()
373                .collect()
374        };
375        for (name, value) in &command.env {
376            env.retain(|(key, _)| key != name);
377            env.push((name.clone(), value.clone()));
378        }
379        env.sort();
380        let cwd = command.cwd.clone().or_else(|| {
381            self.environment
382                .iter()
383                .find(|(name, _)| name == "HOME")
384                .map(|(_, home)| home.clone())
385        });
386        let pid = 1000 + self.machine.next_pid;
387        self.machine.next_pid += 1;
388        let script = self
389            .machine
390            .scripts
391            .iter()
392            .find(|(program, args, _)| {
393                *program == command.program
394                    && args
395                        .as_ref()
396                        .is_none_or(|args| command.args.starts_with(args))
397            })
398            .map(|(_, _, script)| script.clone());
399        self.machine.processes.push(MockProcess {
400            pid,
401            program: command.program.clone(),
402            args: command.args.clone(),
403            env,
404            cwd,
405            stdin: Vec::new(),
406            stdin_closed: false,
407            status: None,
408            killed: false,
409            channel: false,
410            sent: Vec::new(),
411            stdout: command.stdout,
412            stderr: command.stderr,
413        });
414        if let Some(script) = script {
415            self.output(pid, false, &script.stdout);
416            self.output(pid, true, &script.stderr);
417            self.exited(pid, script.status);
418        }
419        Ok(pid)
420    }
421
422    fn process(&mut self, pid: u32) -> Result<&mut MockProcess> {
423        self.machine
424            .processes
425            .iter_mut()
426            .find(|process| process.pid == pid)
427            .ok_or_else(|| Error::Invalid(alloc::format!("no child {pid} of this plugin")))
428    }
429
430    /// Queues output of `pid` for the plugin, when that stream is piped.
431    pub(crate) fn output(&mut self, pid: u32, stderr: bool, bytes: &[u8]) {
432        let Ok(process) = self.process(pid) else {
433            return;
434        };
435        let piped = if stderr {
436            process.stderr == Stdio::Piped
437        } else {
438            process.stdout == Stdio::Piped
439        };
440        if piped && !bytes.is_empty() {
441            self.machine.pending.push_back(Event::ProcessOutput {
442                pid,
443                stderr,
444                bytes: bytes.to_vec(),
445            });
446        }
447    }
448
449    /// `pid` exits with `status`: the plugin hears it after its output.
450    pub(crate) fn exited(&mut self, pid: u32, status: i32) {
451        let Ok(process) = self.process(pid) else {
452            return;
453        };
454        if process.status.is_some() {
455            return;
456        }
457        process.status = Some(status);
458        self.machine
459            .pending
460            .push_back(Event::ProcessExited { pid, status });
461    }
462
463    pub(crate) fn wait(&mut self, pid: u32) -> Result<i32> {
464        let process = self.process(pid)?;
465        process.status.ok_or_else(|| {
466            Error::Unavailable(alloc::format!(
467                "child {pid} ({}) has no script and would block forever: script it \
468                 (MockHost::script) or end it (DaemonHarness::exit) first",
469                process.program
470            ))
471        })
472    }
473
474    /// A scripted child has exited by the time anyone waits; one with no
475    /// script and no exit still runs, so a bounded wait times out.
476    pub(crate) fn wait_timeout(&mut self, pid: u32) -> Result<Option<i32>> {
477        Ok(self.process(pid)?.status)
478    }
479
480    pub(crate) fn try_wait(&mut self, pid: u32) -> Result<Option<i32>> {
481        Ok(self.process(pid)?.status)
482    }
483
484    pub(crate) fn write(&mut self, pid: u32, bytes: &[u8]) -> Result<()> {
485        let process = self.process(pid)?;
486        if process.stdin_closed {
487            return Err(Error::Invalid(alloc::format!(
488                "child {pid}'s stdin is closed"
489            )));
490        }
491        process.stdin.extend_from_slice(bytes);
492        Ok(())
493    }
494
495    /// As `spawn`, with a message channel.
496    pub(crate) fn spawn_with_channel(&mut self, command: &Command) -> Result<u32> {
497        let pid = self.spawn(command)?;
498        self.process(pid)?.channel = true;
499        Ok(pid)
500    }
501
502    pub(crate) fn send(&mut self, pid: u32, message: &str) -> Result<()> {
503        let process = self.process(pid)?;
504        if !process.channel {
505            return Err(Error::Invalid(alloc::format!("child {pid} has no channel")));
506        }
507        process.sent.push(message.to_string());
508        Ok(())
509    }
510
511    /// Delivers a message from a child's channel to the plugin, as the
512    /// host would (`system.process.channel`).
513    pub fn channel_message(&mut self, pid: u32, message: &str) {
514        let message = serde_json::from_str::<serde_json::Value>(message)
515            .unwrap_or_else(|_| serde_json::Value::String(message.to_string()));
516        self.machine.pending.push_back(Event::Plugin {
517            name: String::from(crate::daemon::process::CHANNEL_EVENT),
518            payload: crate::Json(serde_json::json!({ "pid": pid, "message": message }).to_string()),
519        });
520    }
521
522    pub(crate) fn close_stdin(&mut self, pid: u32) -> Result<()> {
523        self.process(pid)?.stdin_closed = true;
524        Ok(())
525    }
526
527    pub(crate) fn kill(&mut self, pid: u32) -> Result<()> {
528        let process = self.process(pid)?;
529        if process.status.is_none() {
530            process.killed = true;
531            self.exited(pid, -9);
532        }
533        Ok(())
534    }
535
536    /// `daemon-watch.watch` with the host's own rules: an absolute path a
537    /// read grant covers after resolving symlinks (or `machine.full`), and
538    /// exclude globs the host accepts.
539    pub(crate) fn watch(&mut self, path: &str, recursive: bool, exclude: &[String]) -> Result<u32> {
540        let named = Path::new(path);
541        if !named.is_absolute() {
542            return Err(Error::Invalid(alloc::format!(
543                "{path} is not an absolute path"
544            )));
545        }
546        if !PathGrants::from_grants(&self.grants).allows(&real(named), false) {
547            return Err(self.deny(standard_plugin_manifest::GrantDenied {
548                grant: alloc::format!("fs.read:{path}"),
549            }));
550        }
551        Excludes::new(exclude).map_err(|error| Error::Invalid(error.to_string()))?;
552        if self.machine.watches.len() >= MAX_WATCHES {
553            return Err(Error::RateLimited);
554        }
555        self.machine.next_watch += 1;
556        let handle = self.machine.next_watch;
557        self.machine.watches.push(MockWatch {
558            handle,
559            path: path.to_string(),
560            recursive,
561            exclude: exclude.to_vec(),
562        });
563        Ok(handle)
564    }
565
566    pub(crate) fn unwatch(&mut self, handle: u32) -> Result<()> {
567        let before = self.machine.watches.len();
568        self.machine.watches.retain(|watch| watch.handle != handle);
569        if self.machine.watches.len() == before {
570            return Err(Error::Invalid(alloc::format!("no watch {handle}")));
571        }
572        Ok(())
573    }
574
575    /// Queues `Event::FileChanged` for every watch that hears a change at
576    /// `path`, as the host decides it (depth and exclude globs). Returns
577    /// how many watches hear it.
578    pub(crate) fn changed(&mut self, path: &str) -> usize {
579        let path = Path::new(path);
580        let mut heard = 0;
581        for watch in &self.machine.watches {
582            let Ok(rest) = path.strip_prefix(&watch.path) else {
583                continue;
584            };
585            if !watch.recursive && rest.components().count() > 1 {
586                continue;
587            }
588            let excluded = Excludes::new(&watch.exclude).is_ok_and(|globs| globs.excludes(rest));
589            if excluded {
590                continue;
591            }
592            heard += 1;
593            self.machine.pending.push_back(Event::FileChanged {
594                watch: watch.handle,
595                paths: alloc::vec![path.to_string_lossy().into_owned()],
596            });
597        }
598        heard
599    }
600}