Skip to main content

waratah_notebook/
kernelspec.rs

1//! Per-repository kernelspecs: the only stock-jupyter channel for a
2//! per-kernel `WARATAH_REPO`.
3//!
4//! jupyter-server 2.21 (see `python/requirements.lock`) has **no kernel env
5//! allowlist** โ€” request-supplied `env` is dropped by the API handlers and
6//! no trait re-enables it (that is a jupyter-enterprise-gateway feature the
7//! work order assumed existed; verified absent against the pin). What stock
8//! jupyter *does* support:
9//!
10//! * kernels inherit the sidecar process environment (covers `WARATAH_URL`
11//!   and the default `WARATAH_REPO`), and
12//! * a kernelspec's `env` stanza is applied over the inherited environment
13//!   at kernel launch (`jupyter_client` `pre_launch`:
14//!   `env.update(...)`).
15//!
16//! So the engine writes one spec per repository โ€”
17//! `{runtime_dir}/kernels/python3-{repo}/kernel.json` with
18//! `"env": {"WARATAH_REPO": repo}` โ€” and discovers them by putting
19//! `{runtime_dir}` on the sidecar's `JUPYTER_PATH`. The proxy turns the
20//! UI's per-request `env.WARATAH_REPO` into that kernelspec name
21//! (`waratah_notebook::proxy`), keeping the documented UI contract
22//! working on a stack without request-env support.
23
24use std::io;
25use std::path::Path;
26
27/// Kernelspec name for one Waratah repository.
28pub fn kernel_spec_name(repo: &str) -> String {
29    format!("python3-{repo}")
30}
31
32/// Repository ids are the engine's `MAIN_REPOSITORY_ID`-style ids; keep them
33/// filesystem-safe because they become kernelspec directory names.
34pub fn valid_repo_id(repo: &str) -> bool {
35    !repo.is_empty()
36        && repo.len() <= 64
37        && repo
38            .chars()
39            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
40}
41
42/// Write the kernelspec for `repo` under `{runtime_dir}/kernels/`.
43///
44/// `argv[0]` is `"python"` on purpose: `jupyter_client` rewrites that token
45/// to `sys.executable`, so kernels run on the sidecar's pinned venv even
46/// though the spec itself is engine-generated.
47pub fn write_spec(runtime_dir: &Path, repo: &str) -> io::Result<()> {
48    let dir = runtime_dir.join("kernels").join(kernel_spec_name(repo));
49    std::fs::create_dir_all(&dir)?;
50    let spec = serde_json::json!({
51        "argv": ["python", "-m", "ipykernel_launcher", "-f", "{connection_file}"],
52        "display_name": format!("Python 3 (waratah: {repo})"),
53        "language": "python",
54        "env": {"WARATAH_REPO": repo},
55    });
56    std::fs::write(
57        dir.join("kernel.json"),
58        serde_json::to_string_pretty(&spec).expect("kernelspec json serializes"),
59    )
60}
61
62#[cfg(test)]
63mod tests {
64    use super::*;
65
66    #[test]
67    fn repo_ids_must_be_filesystem_safe() {
68        assert!(valid_repo_id("main"));
69        assert!(valid_repo_id("repo-2_x"));
70        assert!(!valid_repo_id(""));
71        assert!(!valid_repo_id("a/b"));
72        assert!(!valid_repo_id(".."));
73        assert!(!valid_repo_id("has space"));
74        assert!(!valid_repo_id("unicode-ยต"));
75    }
76
77    #[test]
78    fn spec_names_embed_the_repo() {
79        assert_eq!(kernel_spec_name("main"), "python3-main");
80    }
81
82    #[test]
83    fn written_specs_carry_the_repo_env() {
84        let runtime = tempfile::tempdir().unwrap();
85        write_spec(runtime.path(), "main").unwrap();
86        let text = std::fs::read_to_string(
87            runtime
88                .path()
89                .join("kernels")
90                .join("python3-main")
91                .join("kernel.json"),
92        )
93        .unwrap();
94        let json: serde_json::Value = serde_json::from_str(&text).unwrap();
95        assert_eq!(json["env"]["WARATAH_REPO"], "main");
96        assert_eq!(json["argv"][0], "python");
97    }
98}