Skip to main content

rigspark_runtime/
command.rs

1use std::{collections::BTreeMap, path::Path, process::Stdio, time::Duration};
2use tokio::io::AsyncReadExt;
3use tokio_util::sync::CancellationToken;
4
5pub struct OllamaCommandContext {
6    environment: BTreeMap<String, String>,
7}
8impl OllamaCommandContext {
9    pub fn new(endpoint: &str, models: &Path) -> Result<Self, String> {
10        let endpoint = crate::state::loopback(endpoint).map_err(|error| error.to_string())?;
11        if endpoint.path() != "/" || endpoint.query().is_some() || endpoint.fragment().is_some() {
12            return Err("Ollama endpoint must be a loopback origin".into());
13        }
14        let models = models
15            .to_str()
16            .filter(|value| !value.is_empty() && !value.contains('\0'))
17            .ok_or("invalid Ollama model store")?;
18        if !Path::new(models).is_absolute() {
19            return Err("Ollama model store must be absolute".into());
20        }
21        Ok(Self {
22            environment: BTreeMap::from([
23                ("OLLAMA_HOST".into(), endpoint.to_string()),
24                ("OLLAMA_MODELS".into(), models.into()),
25            ]),
26        })
27    }
28    pub fn environment(&self) -> &BTreeMap<String, String> {
29        &self.environment
30    }
31}
32
33#[async_trait::async_trait]
34pub trait CommandRunner: Send + Sync {
35    async fn run(
36        &self,
37        binary: &Path,
38        args: &[String],
39        cancel: &CancellationToken,
40        timeout: Duration,
41    ) -> Result<String, String>;
42    async fn run_ollama(
43        &self,
44        _binary: &Path,
45        _args: &[String],
46        _context: &OllamaCommandContext,
47        _cancel: &CancellationToken,
48        _timeout: Duration,
49    ) -> Result<String, String> {
50        Err("explicit Ollama command context is unsupported".into())
51    }
52}
53pub struct NativeCommandRunner;
54#[async_trait::async_trait]
55impl CommandRunner for NativeCommandRunner {
56    async fn run(
57        &self,
58        binary: &Path,
59        args: &[String],
60        cancel: &CancellationToken,
61        timeout: Duration,
62    ) -> Result<String, String> {
63        run_command(binary, args, None, cancel, timeout).await
64    }
65    async fn run_ollama(
66        &self,
67        binary: &Path,
68        args: &[String],
69        context: &OllamaCommandContext,
70        cancel: &CancellationToken,
71        timeout: Duration,
72    ) -> Result<String, String> {
73        run_command(binary, args, Some(context), cancel, timeout).await
74    }
75}
76async fn run_command(
77    binary: &Path,
78    args: &[String],
79    context: Option<&OllamaCommandContext>,
80    cancel: &CancellationToken,
81    timeout: Duration,
82) -> Result<String, String> {
83    if cancel.is_cancelled() || timeout.is_zero() {
84        return Err("command cancelled or deadline elapsed".into());
85    }
86    if !binary.is_absolute() || args.iter().any(|arg| arg.contains('\0')) {
87        return Err("invalid command".into());
88    }
89    let mut environment = crate::process_control::minimal_env();
90    if let Some(context) = context {
91        environment.extend(context.environment().clone());
92    }
93    let mut child = tokio::process::Command::new(binary)
94        .args(args)
95        .env_clear()
96        .envs(environment)
97        .stdin(Stdio::null())
98        .stdout(Stdio::piped())
99        .stderr(Stdio::null())
100        .kill_on_drop(true)
101        .spawn()
102        .map_err(|_| "runtime command failed to start")?;
103    let output = child.stdout.take().ok_or("missing command output")?;
104    let operation = async {
105        let mut bytes = Vec::new();
106        output
107            .take(1048577)
108            .read_to_end(&mut bytes)
109            .await
110            .map_err(|_| "runtime command output failed")?;
111        if bytes.len() > 1048576 {
112            return Err("runtime command output exceeds limit".into());
113        }
114        if !child
115            .wait()
116            .await
117            .map_err(|_| "runtime command wait failed")?
118            .success()
119        {
120            return Err("runtime command failed".into());
121        }
122        String::from_utf8(bytes).map_err(|_| "runtime command output is not UTF-8".into())
123    };
124    let result = tokio::select! {biased;_=cancel.cancelled()=>Err("command cancelled".into()),result=tokio::time::timeout(timeout,operation)=>result.map_err(|_|"command timed out".to_owned()).and_then(|result|result)};
125    if result.is_err() {
126        let _ = tokio::time::timeout(Duration::from_secs(5), child.kill()).await;
127    }
128    result
129}