Skip to main content

weirdnet_backends/
engine.rs

1//! How each engine is launched and probed.
2
3use std::path::{Path, PathBuf};
4use std::time::Duration;
5
6use serde::{Deserialize, Serialize};
7use tokio::process::Command;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
10#[serde(rename_all = "lowercase")]
11#[non_exhaustive]
12pub enum EngineKind {
13    /// llama.cpp `llama-server`.
14    Llamacpp,
15    /// `vllm serve` (Linux, NVIDIA sm_80+ or supported ROCm).
16    Vllm,
17}
18
19impl EngineKind {
20    pub fn name(self) -> &'static str {
21        match self {
22            EngineKind::Llamacpp => "llamacpp",
23            EngineKind::Vllm => "vllm",
24        }
25    }
26}
27
28/// One engine binary and how long it may take to come up.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct EngineConfig {
31    pub kind: EngineKind,
32    pub program: PathBuf,
33    /// Arguments added to every launch of this engine.
34    pub extra_args: Vec<String>,
35    pub ready_timeout: Duration,
36}
37
38impl EngineConfig {
39    pub fn llamacpp(program: impl Into<PathBuf>) -> Self {
40        Self { kind: EngineKind::Llamacpp, program: program.into(), extra_args: Vec::new(), ready_timeout: Duration::from_secs(300) }
41    }
42
43    pub fn vllm(program: impl Into<PathBuf>) -> Self {
44        Self { kind: EngineKind::Vllm, program: program.into(), extra_args: Vec::new(), ready_timeout: Duration::from_secs(1200) }
45    }
46
47    /// The command for `model` on `127.0.0.1:port`. The API key goes in the environment, not the
48    /// command line, so other local users can't read it from the process list.
49    pub fn command(&self, model: &ModelLaunch, port: u16, api_key: &str) -> Command {
50        let mut cmd = Command::new(&self.program);
51        match self.kind {
52            EngineKind::Llamacpp => {
53                cmd.args(["--model", &model.source, "--host", "127.0.0.1", "--port", &port.to_string(), "--alias", &model.id, "--no-webui"]);
54                if let Some(ctx) = model.context {
55                    cmd.args(["--ctx-size", &ctx.to_string()]);
56                }
57                if let Some(slots) = model.slots {
58                    cmd.args(["--parallel", &slots.to_string()]);
59                }
60                if let Some(ngl) = model.gpu_layers {
61                    cmd.args(["--n-gpu-layers", &ngl.to_string()]);
62                }
63                if model.embedding {
64                    cmd.arg("--embedding");
65                }
66                cmd.env("LLAMA_API_KEY", api_key);
67            }
68            EngineKind::Vllm => {
69                cmd.args(["serve", &model.source, "--host", "127.0.0.1", "--port", &port.to_string(), "--served-model-name", &model.id]);
70                if let Some(ctx) = model.context {
71                    cmd.args(["--max-model-len", &ctx.to_string()]);
72                }
73                if let Some(slots) = model.slots {
74                    cmd.args(["--max-num-seqs", &slots.to_string()]);
75                }
76                cmd.env("VLLM_API_KEY", api_key);
77            }
78        }
79        cmd.args(&self.extra_args).args(&model.extra_args);
80        cmd
81    }
82}
83
84/// A model this node may be told to load.
85#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
86pub struct ModelLaunch {
87    /// Pool id; also the engine's served model name.
88    pub id: String,
89    pub engine: EngineKind,
90    /// A GGUF path for llama.cpp; a path or Hub id for vLLM.
91    pub source: String,
92    pub context: Option<u32>,
93    /// Concurrent requests (llama.cpp slots, vLLM max sequences).
94    pub slots: Option<u32>,
95    /// llama.cpp `--n-gpu-layers`; `None` keeps the engine's default (all that fit).
96    pub gpu_layers: Option<i32>,
97    /// Models in the same group are never resident together.
98    pub swap_group: Option<String>,
99    pub embedding: bool,
100    pub extra_args: Vec<String>,
101    /// Unload after this long without requests; `None` keeps it loaded.
102    #[serde(default, with = "opt_secs")]
103    pub idle_ttl: Option<Duration>,
104    /// Wrap a stock server already running on loopback (such as `vllm serve` or `llama-server`
105    /// started by hand) instead of starting an engine: the node only probes, advertises and forwards.
106    #[serde(default)]
107    pub wrap: Option<Wrap>,
108}
109
110/// A stock OpenAI-compatible server the node forwards to but doesn't own.
111#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
112pub struct Wrap {
113    /// Base URL without `/v1`, such as `http://127.0.0.1:8000`. Must be loopback.
114    pub url: String,
115    /// The server's API key, if it wants one (read from the environment or a file by the caller).
116    #[serde(default, skip_serializing)]
117    pub api_key: Option<String>,
118}
119
120impl std::fmt::Debug for Wrap {
121    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
122        f.debug_struct("Wrap").field("url", &self.url).field("api_key", &self.api_key.as_ref().map(|_| "<redacted>")).finish()
123    }
124}
125
126impl Wrap {
127    /// Only loopback URLs: the wrapped server is on this machine, reached without TLS.
128    pub fn check(&self) -> Result<(), String> {
129        let rest = self.url.strip_prefix("http://").ok_or_else(|| format!("wrap url {} must start with http:// (loopback only)", self.url))?;
130        let host = match rest.strip_prefix('[') {
131            Some(v6) => v6.split(']').next().unwrap_or(""),
132            None => rest.split(['/', ':']).next().unwrap_or(""),
133        };
134        if matches!(host, "127.0.0.1" | "localhost" | "::1") { Ok(()) } else { Err(format!("wrap url {} is not loopback", self.url)) }
135    }
136
137    pub fn base(&self) -> String {
138        self.url.trim_end_matches('/').trim_end_matches("/v1").to_string()
139    }
140}
141
142mod opt_secs {
143    use std::time::Duration;
144
145    use serde::{Deserialize, Deserializer, Serializer};
146
147    pub fn serialize<S: Serializer>(d: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
148        match d {
149            Some(d) => s.serialize_some(&d.as_secs()),
150            None => s.serialize_none(),
151        }
152    }
153
154    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
155        Ok(Option::<u64>::deserialize(d)?.map(Duration::from_secs))
156    }
157}
158
159impl ModelLaunch {
160    pub fn new(id: impl Into<String>, engine: EngineKind, source: impl Into<String>) -> Self {
161        Self {
162            id: id.into(),
163            engine,
164            source: source.into(),
165            context: None,
166            slots: None,
167            gpu_layers: None,
168            swap_group: None,
169            embedding: false,
170            extra_args: Vec::new(),
171            idle_ttl: None,
172            wrap: None,
173        }
174    }
175}
176
177/// The first executable called `name` on `PATH`.
178pub fn find_in_path(name: &str) -> Option<PathBuf> {
179    let path = std::env::var_os("PATH")?;
180    std::env::split_paths(&path).map(|d| d.join(name)).find(|p| is_executable(p))
181}
182
183fn is_executable(p: &Path) -> bool {
184    #[cfg(unix)]
185    {
186        use std::os::unix::fs::PermissionsExt;
187        std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
188    }
189    #[cfg(not(unix))]
190    {
191        p.is_file()
192    }
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198
199    fn args(cmd: &Command) -> Vec<String> {
200        cmd.as_std().get_args().map(|a| a.to_string_lossy().into_owned()).collect()
201    }
202
203    #[test]
204    fn llama_args() {
205        let mut m = ModelLaunch::new("qwen3-8b", EngineKind::Llamacpp, "/m/q.gguf");
206        m.context = Some(8192);
207        m.slots = Some(2);
208        let cmd = EngineConfig::llamacpp("/bin/llama-server").command(&m, 4321, "k");
209        let a = args(&cmd);
210        assert!(a.windows(2).any(|w| w == ["--host", "127.0.0.1"]));
211        assert!(a.windows(2).any(|w| w == ["--port", "4321"]));
212        assert!(a.windows(2).any(|w| w == ["--alias", "qwen3-8b"]));
213        assert!(a.windows(2).any(|w| w == ["--parallel", "2"]));
214        assert!(!a.iter().any(|x| x == "k"), "the key stays out of argv");
215    }
216
217    #[test]
218    fn wrap_is_loopback_only() {
219        let w = |u: &str| Wrap { url: u.into(), api_key: None }.check();
220        assert!(w("http://127.0.0.1:8000").is_ok());
221        assert!(w("http://localhost:8000/").is_ok());
222        assert!(w("http://[::1]:8000").is_ok());
223        assert!(w("https://127.0.0.1:8000").is_err());
224        assert!(w("http://10.0.0.2:8000").is_err());
225        assert!(w("http://127.0.0.1.evil:8000").is_err());
226        assert_eq!(Wrap { url: "http://127.0.0.1:8000/v1/".into(), api_key: None }.base(), "http://127.0.0.1:8000");
227    }
228
229    #[test]
230    fn vllm_args() {
231        let m = ModelLaunch::new("big", EngineKind::Vllm, "Qwen/Qwen3-8B");
232        let a = args(&EngineConfig::vllm("vllm").command(&m, 9000, "k"));
233        assert_eq!(&a[..2], ["serve", "Qwen/Qwen3-8B"]);
234        assert!(a.windows(2).any(|w| w == ["--served-model-name", "big"]));
235    }
236}