Skip to main content

byob_plugins/
pyenv.rs

1//! The Python a plugin's scripts and backend run with.
2//!
3//! Every plugin gets byob's helper module (`byob_plugin.py`, [`HELPER`]) on `PYTHONPATH`.
4//! A plugin that lists `python.requirements` gets its own virtual environment, cached under
5//! byob's data folder and keyed by a hash of the interpreter and the requirements (so two
6//! plugins with the same list share one, and changing the list makes a new one). It is
7//! built the first time something needs it, never on the engine thread: with `uv` when it
8//! is on `PATH` (`uv venv` + `uv pip install`), else `python -m venv` + `pip install`. A
9//! failure is kept (with the installer's output) until the plugin is reloaded, and shows
10//! as one of the plugin's problems. A build can be called off (the tool call stopped, the
11//! backend stopped); it isn't kept as a failure then.
12//!
13//! Two byob processes may share the data folder: a build holds a lock file next to the
14//! environment (`<venv>.lock`), and the other waits for it and uses what it built. A lock
15//! whose holder stopped refreshing it (a byob that died mid-build) is taken over.
16
17use byob_types::process::NoWindow as _;
18use std::collections::BTreeMap;
19use std::ffi::OsString;
20use std::fs;
21use std::hash::Hasher;
22use std::path::{Path, PathBuf};
23use std::process::Command;
24use std::sync::{Arc, Mutex, OnceLock, PoisonError, TryLockError};
25use std::time::{Duration, Instant, SystemTime};
26
27use byob_sandbox::RunOptions;
28
29use crate::authoring::Fnv;
30
31/// byob's Python helper for plugins (`import byob_plugin`).
32pub const HELPER: &str = include_str!("byob_plugin.py");
33/// Its file name.
34pub const HELPER_FILE: &str = "byob_plugin.py";
35/// Longest an environment may take to build (downloads included).
36const BUILD_TIMEOUT: Duration = Duration::from_secs(15 * 60);
37/// Installer output kept per stream.
38const MAX_BUILD_OUTPUT: usize = 64 * 1024;
39/// Characters of the installer's output in a problem message.
40const PROBLEM_OUTPUT: usize = 3000;
41/// The file that says an environment is complete.
42const READY: &str = ".byob-ready";
43/// What a build that was called off says.
44pub const BUILD_CALLED_OFF: &str = "the Python environment wasn't built: stopped";
45/// How often a build refreshes its lock file.
46const LOCK_BEAT: Duration = Duration::from_secs(20);
47/// A lock file not refreshed for this long is left over from a byob that died.
48const LOCK_STALE: Duration = Duration::from_secs(120);
49/// How often a waiting build looks at the lock again.
50const LOCK_POLL: Duration = Duration::from_millis(100);
51
52/// How to start Python for one plugin.
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct Python {
55    /// Interpreter and leading arguments.
56    pub program: Vec<OsString>,
57    /// Folders a sandbox must let it read (the venv, the helper).
58    pub read: Vec<PathBuf>,
59    /// Variables to set (`PYTHONPATH`).
60    pub env: BTreeMap<String, String>,
61}
62
63/// Every plugin environment of one engine.
64pub struct PyEnvs {
65    root: PathBuf,
66    base: Vec<OsString>,
67    /// `None`: look for `uv` on `PATH`; `Some(None)`: never use it.
68    uv: Option<Option<PathBuf>>,
69    offline: bool,
70    helper: OnceLock<Result<PathBuf, String>>,
71    envs: Mutex<BTreeMap<String, Arc<PyEnv>>>,
72}
73
74impl PyEnvs {
75    /// Environments go under `root` (e.g. `<data>/plugin-python`); `base` is the
76    /// interpreter they are made from (and the one plugins without requirements use).
77    pub fn new(root: impl Into<PathBuf>, base: Vec<OsString>) -> Self {
78        Self { root: root.into(), base, uv: None, offline: false, helper: OnceLock::new(), envs: Mutex::new(BTreeMap::new()) }
79    }
80
81    /// Use this `uv` (`None`: pip only) instead of looking for one.
82    pub fn with_uv(mut self, uv: Option<PathBuf>) -> Self {
83        self.uv = Some(uv);
84        self
85    }
86
87    /// Install without a package index (local wheels and folders only; tests).
88    pub fn offline(mut self) -> Self {
89        self.offline = true;
90        self
91    }
92
93    pub fn base(&self) -> &[OsString] {
94        &self.base
95    }
96
97    /// The folder holding `byob_plugin.py`, written there the first time it is asked for.
98    pub fn helper_dir(&self) -> Result<PathBuf, String> {
99        self.helper
100            .get_or_init(|| {
101                let dir = self.root.join("lib");
102                let file = dir.join(HELPER_FILE);
103                if fs::read_to_string(&file).ok().as_deref() != Some(HELPER) {
104                    fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
105                    let tmp = dir.join(format!(".{HELPER_FILE}.{}", std::process::id()));
106                    fs::write(&tmp, HELPER).and_then(|()| fs::rename(&tmp, &file)).map_err(|e| format!("{}: {e}", file.display()))?;
107                }
108                Ok(dir)
109            })
110            .clone()
111    }
112
113    /// The environment for a plugin in `dir` that needs `requirements` (relative paths,
114    /// like `./wheels/x.whl`, are taken from the plugin folder).
115    pub fn for_plugin(&self, requirements: &[String], dir: &Path) -> Arc<PyEnv> {
116        let reqs: Vec<String> =
117            requirements.iter().map(|r| if r.starts_with("./") || r.starts_with("../") { dir.join(r).display().to_string() } else { r.clone() }).collect();
118        let mut h = Fnv::default();
119        for p in &self.base {
120            h.write(p.as_encoded_bytes());
121            h.write_u8(0);
122        }
123        let mut sorted = reqs.clone();
124        sorted.sort();
125        for r in &sorted {
126            h.write(r.as_bytes());
127            h.write_u8(1);
128        }
129        let key = format!("{:016x}", h.finish());
130        let mut envs = self.envs.lock().unwrap_or_else(PoisonError::into_inner);
131        let env = envs.entry(key.clone()).or_insert_with(|| {
132            let uv = match &self.uv {
133                Some(u) => u.clone(),
134                None => byob_sandbox::which(std::ffi::OsStr::new("uv")),
135            };
136            Arc::new(PyEnv {
137                dir: self.root.join("venvs").join(&key),
138                reqs,
139                base: self.base.clone(),
140                uv,
141                offline: self.offline,
142                state: Mutex::new(State::Unknown),
143                build: Mutex::new(()),
144            })
145        });
146        Arc::clone(env)
147    }
148
149    /// Forget failed builds so they are tried again (a reload).
150    pub fn forget_failed(&self) {
151        self.envs.lock().unwrap_or_else(PoisonError::into_inner).retain(|_, e| e.failure().is_none());
152    }
153
154    /// How to start Python for a plugin with this environment (`None`: no requirements).
155    /// Builds the environment if needed, until `cancelled()`: call it off the engine thread.
156    pub fn python(&self, env: Option<&PyEnv>, cancelled: &dyn Fn() -> bool) -> Result<Python, String> {
157        let helper = self.helper_dir();
158        let mut read = Vec::new();
159        let mut vars = BTreeMap::new();
160        match &helper {
161            Ok(dir) => {
162                let mut path = dir.display().to_string();
163                if let Some(old) = std::env::var_os("PYTHONPATH").filter(|p| !p.is_empty()) {
164                    path.push(if cfg!(windows) { ';' } else { ':' });
165                    path.push_str(&old.to_string_lossy());
166                }
167                vars.insert("PYTHONPATH".to_owned(), path);
168                read.push(dir.clone());
169            }
170            Err(e) => log::warn!("the byob_plugin helper isn't available: {e}"),
171        }
172        vars.insert("PYTHONUNBUFFERED".to_owned(), "1".to_owned());
173        // UTF-8 on stdin/stdout and in files even where the locale says otherwise (Windows)
174        vars.insert("PYTHONUTF8".to_owned(), "1".to_owned());
175        vars.insert("PYTHONIOENCODING".to_owned(), "utf-8".to_owned());
176        let program = match env {
177            None => self.base.clone(),
178            Some(env) => {
179                let python = env.ensure(cancelled)?;
180                read.push(env.dir.clone());
181                vec![python.into_os_string()]
182            }
183        };
184        Ok(Python { program, read, env: vars })
185    }
186}
187
188/// One plugin's Python: byob's helper, and its own environment if it has requirements.
189#[derive(Clone)]
190pub struct PluginPython {
191    pub envs: Arc<PyEnvs>,
192    pub env: Option<Arc<PyEnv>>,
193}
194
195impl PluginPython {
196    /// For a plugin in `dir` with these requirements.
197    pub fn new(envs: &Arc<PyEnvs>, requirements: &[String], dir: &Path) -> Self {
198        let env = (!requirements.is_empty()).then(|| envs.for_plugin(requirements, dir));
199        Self { envs: Arc::clone(envs), env }
200    }
201
202    /// See [`PyEnvs::python`] (may build the environment: not on the engine thread).
203    pub fn python(&self) -> Result<Python, String> {
204        self.python_until(&|| false)
205    }
206
207    /// [`Self::python`] whose build gives up once `cancelled()`.
208    pub fn python_until(&self, cancelled: &dyn Fn() -> bool) -> Result<Python, String> {
209        self.envs.python(self.env.as_deref(), cancelled)
210    }
211
212    /// Why its environment couldn't be built (never blocks).
213    pub fn failure(&self) -> Option<String> {
214        self.env.as_ref().and_then(|e| e.failure())
215    }
216}
217
218#[derive(Debug, Clone)]
219enum State {
220    Unknown,
221    Ready(PathBuf),
222    Failed(String),
223}
224
225/// One virtual environment.
226pub struct PyEnv {
227    dir: PathBuf,
228    reqs: Vec<String>,
229    base: Vec<OsString>,
230    uv: Option<PathBuf>,
231    offline: bool,
232    state: Mutex<State>,
233    /// Held while building, so one build runs at a time (in this process; the lock file
234    /// covers others).
235    build: Mutex<()>,
236}
237
238impl PyEnv {
239    pub fn dir(&self) -> &Path {
240        &self.dir
241    }
242
243    pub fn requirements(&self) -> &[String] {
244        &self.reqs
245    }
246
247    /// Why the last build failed (never blocks).
248    pub fn failure(&self) -> Option<String> {
249        match &*self.state.lock().unwrap_or_else(PoisonError::into_inner) {
250            State::Failed(e) => Some(e.clone()),
251            _ => None,
252        }
253    }
254
255    /// It is built (never blocks).
256    pub fn ready(&self) -> bool {
257        matches!(&*self.state.lock().unwrap_or_else(PoisonError::into_inner), State::Ready(_)) || self.dir.join(READY).is_file()
258    }
259
260    fn set(&self, s: State) {
261        *self.state.lock().unwrap_or_else(PoisonError::into_inner) = s;
262    }
263
264    fn get(&self) -> State {
265        self.state.lock().unwrap_or_else(PoisonError::into_inner).clone()
266    }
267
268    /// The environment's interpreter, building it first if needed (blocks while it builds,
269    /// or another byob does, until `cancelled()`: then [`BUILD_CALLED_OFF`]).
270    pub fn ensure(&self, cancelled: &dyn Fn() -> bool) -> Result<PathBuf, String> {
271        match self.get() {
272            State::Ready(p) => return Ok(p),
273            State::Failed(e) => return Err(e),
274            State::Unknown => {}
275        }
276        let _building = loop {
277            match self.build.try_lock() {
278                Ok(g) => break g,
279                Err(TryLockError::Poisoned(p)) => break p.into_inner(),
280                Err(TryLockError::WouldBlock) if cancelled() => return Err(BUILD_CALLED_OFF.into()),
281                Err(TryLockError::WouldBlock) => std::thread::sleep(LOCK_POLL),
282            }
283        };
284        // Someone else may have finished while we waited.
285        match self.get() {
286            State::Ready(p) => return Ok(p),
287            State::Failed(e) => return Err(e),
288            State::Unknown => {}
289        }
290        let python = venv_python(&self.dir);
291        if self.built(&python) {
292            self.set(State::Ready(python.clone()));
293            return Ok(python);
294        }
295        if let Some(parent) = self.dir.parent() {
296            fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
297        }
298        let lock = BuildLock::take(&self.dir.with_extension("lock"), cancelled)?;
299        // Another byob may have built it while we waited.
300        if self.built(&python) {
301            self.set(State::Ready(python.clone()));
302            return Ok(python);
303        }
304        log::info!("building a Python environment for {} in {}", self.reqs.join(" "), self.dir.display());
305        let called_off = || {
306            lock.beat();
307            cancelled()
308        };
309        match self.build_now(&python, &called_off) {
310            Ok(()) => {
311                self.set(State::Ready(python.clone()));
312                Ok(python)
313            }
314            Err(e) => {
315                let _ = fs::remove_dir_all(&self.dir);
316                if cancelled() {
317                    // not a failure: the next use builds it again
318                    return Err(BUILD_CALLED_OFF.into());
319                }
320                let e = format!("python.requirements couldn't be installed: {e}");
321                self.set(State::Failed(e.clone()));
322                Err(e)
323            }
324        }
325    }
326
327    fn built(&self, python: &Path) -> bool {
328        self.dir.join(READY).is_file() && python.exists()
329    }
330
331    fn build_now(&self, python: &Path, cancelled: &dyn Fn() -> bool) -> Result<(), String> {
332        let _ = fs::remove_dir_all(&self.dir);
333        let Some((base, lead)) = self.base.split_first() else { return Err("no Python interpreter configured".into()) };
334        match &self.uv {
335            Some(uv) => {
336                let mut c = Command::new(uv);
337                c.no_window();
338                c.arg("venv").arg("--quiet").arg("--python").arg(base).arg(&self.dir);
339                run(c, "uv venv", cancelled)?;
340                let mut c = Command::new(uv);
341                c.no_window();
342                c.args(["pip", "install", "--python"]).arg(python).args(self.offline.then_some("--offline")).args(&self.reqs);
343                run(c, "uv pip install", cancelled)?;
344            }
345            None => {
346                let mut c = Command::new(base);
347                c.no_window();
348                c.args(lead).args(["-m", "venv"]).arg(&self.dir);
349                run(c, "python -m venv", cancelled)?;
350                let mut c = Command::new(python);
351                c.no_window();
352                c.args(["-m", "pip", "install", "--disable-pip-version-check", "--no-input"]).args(self.offline.then_some("--no-index")).args(&self.reqs);
353                run(c, "pip install", cancelled)?;
354            }
355        }
356        fs::write(self.dir.join(READY), self.reqs.join("\n")).map_err(|e| format!("{}: {e}", self.dir.display()))
357    }
358}
359
360/// The lock file of one environment's build, shared by every byob using the data folder:
361/// created (exclusively) to build, refreshed while building, removed when done.
362struct BuildLock {
363    path: PathBuf,
364    file: Option<fs::File>,
365    beat: std::cell::Cell<Instant>,
366}
367
368impl BuildLock {
369    /// Take the lock at `path`, waiting while another build holds it (until `cancelled()`).
370    fn take(path: &Path, cancelled: &dyn Fn() -> bool) -> Result<Self, String> {
371        let mut waited = false;
372        loop {
373            match fs::OpenOptions::new().write(true).create_new(true).open(path) {
374                Ok(mut file) => {
375                    let _ = std::io::Write::write_all(&mut file, format!("{}\n", std::process::id()).as_bytes());
376                    return Ok(Self { path: path.to_path_buf(), file: Some(file), beat: std::cell::Cell::new(Instant::now()) });
377                }
378                Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
379                    let age = fs::metadata(path).and_then(|m| m.modified()).ok().and_then(|t| SystemTime::now().duration_since(t).ok());
380                    if age.is_some_and(|a| a > LOCK_STALE) {
381                        log::warn!("{} is left over from a build that stopped; taking it over", path.display());
382                        let _ = fs::remove_file(path);
383                        continue;
384                    }
385                    if !waited {
386                        log::info!("waiting for another byob to build the Python environment ({})", path.display());
387                        waited = true;
388                    }
389                }
390                Err(e) => return Err(format!("{}: {e}", path.display())),
391            }
392            if cancelled() {
393                return Err(BUILD_CALLED_OFF.into());
394            }
395            std::thread::sleep(LOCK_POLL);
396        }
397    }
398
399    /// Say the build is still going (at most every [`LOCK_BEAT`]).
400    fn beat(&self) {
401        if self.beat.get().elapsed() >= LOCK_BEAT {
402            if let Some(f) = &self.file {
403                let _ = f.set_modified(SystemTime::now());
404            }
405            self.beat.set(Instant::now());
406        }
407    }
408}
409
410impl Drop for BuildLock {
411    fn drop(&mut self) {
412        drop(self.file.take());
413        let _ = fs::remove_file(&self.path);
414    }
415}
416
417fn venv_python(dir: &Path) -> PathBuf {
418    if cfg!(windows) { dir.join("Scripts").join("python.exe") } else { dir.join("bin").join("python") }
419}
420
421fn run(cmd: Command, what: &str, cancelled: &dyn Fn() -> bool) -> Result<(), String> {
422    let opts = RunOptions { stdin: Vec::new(), timeout: BUILD_TIMEOUT, max_output: MAX_BUILD_OUTPUT };
423    let o = byob_sandbox::run(cmd, &opts, cancelled).map_err(|e| format!("{what}: {e}"))?;
424    if o.success() {
425        return Ok(());
426    }
427    if o.cancelled {
428        return Err(BUILD_CALLED_OFF.into());
429    }
430    let out = format!("{}\n{}", o.stdout.text().trim(), o.stderr.text().trim());
431    let out = out.trim();
432    let start = out.char_indices().rev().nth(PROBLEM_OUTPUT).map_or(0, |(i, _)| i);
433    let why = if o.timed_out { "took too long".to_owned() } else { format!("exit code {}", o.exit_code.map_or_else(|| "none".into(), |c| c.to_string())) };
434    Err(format!("{what} failed ({why}):\n{}", out.get(start..).unwrap_or(out)))
435}
436
437#[cfg(test)]
438mod tests {
439    use super::*;
440
441    #[test]
442    fn same_requirements_share_an_environment() {
443        let root = tempfile::tempdir().unwrap();
444        let envs = PyEnvs::new(root.path(), crate::default_python()).with_uv(None);
445        let a = envs.for_plugin(&["x==1".into(), "y".into()], Path::new("/p/a"));
446        let b = envs.for_plugin(&["y".into(), "x==1".into()], Path::new("/p/b"));
447        let c = envs.for_plugin(&["x==2".into()], Path::new("/p/a"));
448        assert_eq!(a.dir(), b.dir());
449        assert_ne!(a.dir(), c.dir());
450        let w = envs.for_plugin(&["./wheels/w.whl".into()], Path::new("/p/a"));
451        assert_eq!(w.requirements(), [Path::new("/p/a").join("./wheels/w.whl").display().to_string()]);
452    }
453
454    #[test]
455    fn helper_is_written_once_and_on_the_path() {
456        let root = tempfile::tempdir().unwrap();
457        let envs = PyEnvs::new(root.path(), crate::default_python());
458        let py = envs.python(None, &|| false).unwrap();
459        let dir = envs.helper_dir().unwrap();
460        assert_eq!(fs::read_to_string(dir.join(HELPER_FILE)).unwrap(), HELPER);
461        assert!(py.env["PYTHONPATH"].starts_with(&dir.display().to_string()));
462        assert_eq!(py.program, crate::default_python());
463    }
464
465    #[test]
466    fn python_speaks_utf8_whatever_the_locale() {
467        let root = tempfile::tempdir().unwrap();
468        let py = PyEnvs::new(root.path(), crate::default_python()).python(None, &|| false).unwrap();
469        assert_eq!(py.env.get("PYTHONUTF8").map(String::as_str), Some("1"));
470        assert_eq!(py.env.get("PYTHONIOENCODING").map(String::as_str), Some("utf-8"));
471    }
472
473    /// An environment whose interpreter doesn't exist: a build fails at once.
474    fn broken(root: &Path) -> Arc<PyEnv> {
475        PyEnvs::new(root, vec!["/definitely/not/python".into()]).with_uv(None).for_plugin(&["x".into()], Path::new("/p"))
476    }
477
478    #[test]
479    fn another_byobs_build_is_waited_for_and_used_not_clobbered() {
480        let root = tempfile::tempdir().unwrap();
481        let env = broken(root.path());
482        let lock = env.dir().with_extension("lock");
483        fs::create_dir_all(env.dir()).unwrap();
484        fs::write(&lock, "4242\n").unwrap();
485        // the other byob finishes its build, then lets go of the lock
486        let dir = env.dir().to_path_buf();
487        let other = std::thread::spawn(move || {
488            std::thread::sleep(Duration::from_millis(300));
489            let python = venv_python(&dir);
490            fs::create_dir_all(python.parent().unwrap()).unwrap();
491            fs::write(&python, "").unwrap();
492            fs::write(dir.join(READY), "x").unwrap();
493            fs::remove_file(dir.with_extension("lock")).unwrap();
494        });
495        assert_eq!(env.ensure(&|| false), Ok(venv_python(env.dir())));
496        other.join().unwrap();
497        assert!(env.dir().join(READY).is_file(), "its build was left alone");
498    }
499
500    #[test]
501    fn waiting_for_another_build_can_be_called_off() {
502        let root = tempfile::tempdir().unwrap();
503        let env = broken(root.path());
504        fs::create_dir_all(env.dir()).unwrap();
505        fs::write(env.dir().join("theirs"), "").unwrap();
506        fs::write(env.dir().with_extension("lock"), "4242\n").unwrap();
507        let t = Instant::now();
508        assert_eq!(env.ensure(&|| t.elapsed() > Duration::from_millis(200)), Err(BUILD_CALLED_OFF.to_owned()));
509        assert!(env.dir().join("theirs").exists(), "their half-built environment was left alone");
510        assert!(env.failure().is_none(), "not a failure: tried again next time");
511    }
512
513    #[test]
514    fn a_lock_left_by_a_byob_that_died_is_taken_over() {
515        let root = tempfile::tempdir().unwrap();
516        let env = broken(root.path());
517        let lock = env.dir().with_extension("lock");
518        fs::create_dir_all(env.dir()).unwrap();
519        let f = fs::File::create(&lock).unwrap();
520        f.set_modified(SystemTime::now() - Duration::from_secs(3600)).unwrap();
521        drop(f);
522        let e = env.ensure(&|| false).unwrap_err();
523        assert!(e.starts_with("python.requirements couldn't be installed"), "{e}");
524        assert!(!lock.exists(), "the lock goes with the build");
525    }
526
527    #[cfg(unix)]
528    #[test]
529    fn a_build_can_be_called_off() {
530        let root = tempfile::tempdir().unwrap();
531        // an "interpreter" whose `-m venv` takes half a minute
532        let base: Vec<OsString> = vec!["sh".into(), "-c".into(), "sleep 30".into(), "sh".into()];
533        let env = PyEnvs::new(root.path(), base).with_uv(None).for_plugin(&["x".into()], Path::new("/p"));
534        let t = Instant::now();
535        assert_eq!(env.ensure(&|| t.elapsed() > Duration::from_millis(300)), Err(BUILD_CALLED_OFF.to_owned()));
536        assert!(t.elapsed() < Duration::from_secs(10), "{:?}", t.elapsed());
537        assert!(env.failure().is_none());
538        assert!(!env.dir().exists());
539        assert!(!env.dir().with_extension("lock").exists());
540    }
541}