Skip to main content

waratah_notebook/
python_env.rs

1//! Pinned Python environment for the sidecar (auto-provisioned venv).
2//!
3//! First `--with-notebooks` start creates a venv at
4//! `NotebookOptions::venv_dir` and `pip install`s the committed
5//! [`REQUIREMENTS`] lock; a hash marker skips re-installs until the lock
6//! changes. An explicit `--notebooks-python` skips provisioning entirely.
7
8use std::path::{Path, PathBuf};
9
10use crate::error::NotebookError;
11use crate::options::NotebookOptions;
12
13/// The committed pin list (`python/requirements.lock`).
14pub const REQUIREMENTS: &str = include_str!("../python/requirements.lock");
15
16/// Minimum interpreter version (work order: Python 3.11+).
17const MIN_VERSION: (u8, u8) = (3, 11);
18
19/// Fast inline validation (no provisioning, no network).
20///
21/// Runs before the engine starts serving so a missing or too-old
22/// interpreter fails the command itself, not the first notebook click.
23/// The slow part — venv creation and `pip install` — stays in the
24/// background supervisor task.
25pub fn validate(options: &NotebookOptions) -> Result<(), NotebookError> {
26    let program: &Path = options
27        .python
28        .as_deref()
29        .unwrap_or_else(|| Path::new("python3"));
30    if let Err(error) = check_version(program) {
31        return Err(NotebookError::PythonUnavailable(format!(
32            "the notebook sidecar needs Python {}.{} or newer; point \
33             --notebooks-python at one: {error}",
34            MIN_VERSION.0, MIN_VERSION.1,
35        )));
36    }
37    Ok(())
38}
39
40/// Resolve the sidecar interpreter, provisioning the venv if needed.
41pub async fn ensure(options: &NotebookOptions) -> Result<PathBuf, NotebookError> {
42    if let Some(python) = &options.python {
43        return Ok(python.clone());
44    }
45    let interpreter = options.venv_dir.join("bin").join("python");
46    let marker = options.venv_dir.join(".waratah-requirements-hash");
47    let hash = lock_hash();
48    if interpreter.is_file()
49        && std::fs::read_to_string(&marker).ok().as_deref() == Some(hash.as_str())
50    {
51        return Ok(interpreter);
52    }
53
54    let system = PathBuf::from("python3");
55    check_version(&system)?;
56    println!(
57        "notebooks: provisioning pinned Python venv at {} (first start, or the lock changed)",
58        options.venv_dir.display()
59    );
60    run(
61        &system,
62        &["-m", "venv", &options.venv_dir.display().to_string()],
63    )
64    .await?;
65
66    // pip reads the lock from the runtime dir so the venv is reproducible
67    // from exactly what this binary embedded.
68    std::fs::create_dir_all(&options.runtime_dir)?;
69    let lock_path = options.runtime_dir.join("requirements.lock");
70    std::fs::write(&lock_path, REQUIREMENTS)?;
71    run(
72        &interpreter,
73        &[
74            "-m",
75            "pip",
76            "install",
77            "--no-input",
78            "--disable-pip-version-check",
79            "-r",
80            &lock_path.display().to_string(),
81        ],
82    )
83    .await?;
84    std::fs::write(&marker, hash)?;
85    println!("notebooks: pinned venv ready ({})", interpreter.display());
86    Ok(interpreter)
87}
88
89/// `pip`'s view of "is this lock installed": hash of the embedded lockfile.
90fn lock_hash() -> String {
91    use std::hash::{Hash, Hasher};
92    let mut hasher = std::collections::hash_map::DefaultHasher::new();
93    REQUIREMENTS.hash(&mut hasher);
94    format!("{:016x}", hasher.finish())
95}
96
97/// Run `program --version` and parse its `Python 3.Y.Z` banner.
98fn check_version(program: &Path) -> Result<(u8, u8), NotebookError> {
99    let output = std::process::Command::new(program)
100        .arg("--version")
101        .output()
102        .map_err(|source| {
103            NotebookError::PythonUnavailable(format!(
104                "could not run {}: {source}",
105                program.display()
106            ))
107        })?;
108    // `python --version` prints to stdout (3.4+); keep stderr in the search
109    // for wrappers that put the banner there.
110    let text = format!(
111        "{}{}",
112        String::from_utf8_lossy(&output.stdout),
113        String::from_utf8_lossy(&output.stderr)
114    );
115    let mut words = text.split_whitespace();
116    let (Some("Python"), Some(version)) = (words.next(), words.next()) else {
117        return Err(NotebookError::PythonUnavailable(format!(
118            "no Python version banner from {} (got {text:?})",
119            program.display()
120        )));
121    };
122    let mut numbers = version.split('.');
123    let (Some(major), Some(minor)) = (numbers.next(), numbers.next()) else {
124        return Err(NotebookError::PythonUnavailable(format!(
125            "unrecognized Python version {version:?} from {}",
126            program.display()
127        )));
128    };
129    let (Ok(major), Ok(minor)) = (major.parse::<u8>(), minor.parse::<u8>()) else {
130        return Err(NotebookError::PythonUnavailable(format!(
131            "unrecognized Python version {version:?} from {}",
132            program.display()
133        )));
134    };
135    if (major, minor) < MIN_VERSION {
136        return Err(NotebookError::PythonUnavailable(format!(
137            "{} is Python {major}.{minor}, the sidecar needs {}.{} or newer",
138            program.display(),
139            MIN_VERSION.0,
140            MIN_VERSION.1,
141        )));
142    }
143    Ok((major, minor))
144}
145
146/// Run a provisioning step, inheriting stdio so `pip` progress is visible.
147async fn run(program: &Path, args: &[&str]) -> Result<(), NotebookError> {
148    let status = tokio::process::Command::new(program)
149        .args(args)
150        .status()
151        .await
152        .map_err(|source| NotebookError::Spawn {
153            program: program.to_owned(),
154            source,
155        })?;
156    if status.success() {
157        Ok(())
158    } else {
159        Err(NotebookError::Provisioning(format!(
160            "`{} {}` exited with {status}",
161            program.display(),
162            args.join(" ")
163        )))
164    }
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170    use crate::options::DEFAULT_CULL_IDLE_SECS;
171
172    fn options(python: Option<PathBuf>, venv: &Path, runtime: &Path) -> NotebookOptions {
173        NotebookOptions {
174            dir: runtime.join("books"),
175            runtime_dir: runtime.to_path_buf(),
176            venv_dir: venv.to_path_buf(),
177            python,
178            bind: "127.0.0.1:0".parse().unwrap(),
179            token: "t".to_owned(),
180            cull_idle_secs: DEFAULT_CULL_IDLE_SECS,
181            repo: "main".to_owned(),
182            engine_http: "127.0.0.1:8080".parse().unwrap(),
183        }
184    }
185
186    #[test]
187    fn lock_hash_tracks_the_embedded_lock() {
188        assert_eq!(lock_hash().len(), 16);
189        assert!(!REQUIREMENTS.is_empty());
190    }
191
192    #[test]
193    fn missing_interpreter_is_a_typed_python_error() {
194        let tmp = tempfile::tempdir().unwrap();
195        let error = validate(&options(
196            Some(PathBuf::from("/no/such/python-xyz")),
197            &tmp.path().join("venv"),
198            tmp.path(),
199        ))
200        .unwrap_err();
201        assert!(matches!(error, NotebookError::PythonUnavailable(_)));
202        assert!(error.to_string().contains("--notebooks-python"));
203    }
204}