Skip to main content

waratah_notebook/
options.rs

1//! Resolved notebook-service options and the `notebooks.toml` document.
2//!
3//! `notebooks.toml` is its own config file under the CLI config dir
4//! (`waratah_bin/src/config_dir.rs` resolves *where* that is) — deliberately
5//! not a table inside the cluster address file, so the two configs can be
6//! owned and edited independently. Merge order is CLI flag >
7//! `notebooks.toml` value > built-in default ([`NotebookOptions::resolve`]).
8//! `waratah_bin` owns the flags and the data-dir-derived defaults; this
9//! crate only defines the file schema and the merge so both are testable
10//! in one place.
11
12use std::net::SocketAddr;
13use std::path::PathBuf;
14
15use serde::Deserialize;
16
17use crate::error::NotebookError;
18use crate::token::mint_token;
19
20/// Path prefix the proxy and the sidecar's `base_url` agree on.
21pub const JUPYTER_PATH: &str = "/jupyter";
22
23/// Default kernel idle culling timeout, seconds (~1h, work-order v1 value).
24pub const DEFAULT_CULL_IDLE_SECS: u64 = 3600;
25
26/// Per-field CLI overrides from `waratah start` flags.
27///
28/// Every field is "not passed"; the merge fills from TOML or defaults.
29#[derive(Debug, Clone, Default)]
30pub struct NotebookCli {
31    /// `--notebooks-dir`
32    pub dir: Option<PathBuf>,
33    /// `--notebooks-python`
34    pub python: Option<PathBuf>,
35    /// `--notebooks-bind`
36    pub bind: Option<SocketAddr>,
37    /// `--notebooks-token`
38    pub token: Option<String>,
39    /// `--notebooks-cull-idle-secs`
40    pub cull_idle_secs: Option<u64>,
41}
42
43/// The `{config-dir}/notebooks.toml` document.
44///
45/// The document *is* the notebooks table — no wrapper section — since the
46/// file has this one concern. Unknown keys are ignored so future knobs
47/// don't break older engines.
48#[derive(Debug, Clone, Default, Deserialize)]
49pub struct NotebooksToml {
50    /// Enable the notebook service (same as `--with-notebooks`).
51    pub enabled: Option<bool>,
52    /// Contents-API root.
53    pub dir: Option<PathBuf>,
54    /// Python interpreter for the sidecar (skips auto-provisioning).
55    pub python: Option<PathBuf>,
56    /// Loopback bind for the sidecar (`"127.0.0.1:0"` = engine-assigned).
57    pub bind: Option<String>,
58    /// Jupyter auth token (auto-minted when absent).
59    pub token: Option<String>,
60    /// Kernel idle culling timeout, seconds.
61    pub cull_idle_secs: Option<u64>,
62}
63
64impl NotebooksToml {
65    /// Parse a `notebooks.toml` document.
66    pub fn from_toml_str(text: &str) -> Result<Self, NotebookError> {
67        Ok(toml::from_str(text)?)
68    }
69}
70
71/// Data-dir-derived defaults; `waratah_bin` fills these from
72/// `waratah_storage::layout` exactly like `--ingest-dir` / `--spill-dir`.
73#[derive(Debug, Clone)]
74pub struct NotebookDefaults {
75    /// Contents-API root (`{data_dir}/notebooks`, else `./notebooks`).
76    pub dir: PathBuf,
77    /// Sidecar runtime dir: generated config + jupyter runtime files
78    /// (`{data_dir}/notebooks-runtime`, else `./notebooks-runtime`).
79    pub runtime_dir: PathBuf,
80    /// Auto-provisioned venv root (`{data_dir}/notebooks-venv`, else
81    /// `./notebooks-venv`).
82    pub venv_dir: PathBuf,
83    /// Loopback bind address of THIS compute's HTTP server.
84    pub engine_http: SocketAddr,
85}
86
87/// Fully resolved notebook-service options.
88#[derive(Debug, Clone)]
89pub struct NotebookOptions {
90    /// Contents-API root (`c.ServerApp.root_dir`).
91    pub dir: PathBuf,
92    /// Sidecar runtime dir (generated config carrying the token + jupyter
93    /// runtime files). Deliberately not under `dir`: the Contents API must
94    /// not serve the token.
95    pub runtime_dir: PathBuf,
96    /// Auto-provisioned venv root.
97    pub venv_dir: PathBuf,
98    /// Explicit interpreter (`--notebooks-python`); `None` = auto-provision
99    /// the pinned venv at startup.
100    pub python: Option<PathBuf>,
101    /// Loopback bind for the sidecar. Port 0 = engine-assigned per attempt.
102    pub bind: SocketAddr,
103    /// Jupyter auth token (minted during resolve when not configured).
104    pub token: String,
105    /// Kernel idle culling timeout, seconds.
106    pub cull_idle_secs: u64,
107    /// Default repository advertised to kernels (`WARATAH_REPO`).
108    pub repo: String,
109    /// Loopback address of THIS compute's HTTP server (`WARATAH_URL`).
110    pub engine_http: SocketAddr,
111}
112
113impl NotebookOptions {
114    /// Merge CLI flags over the `notebooks.toml` values over the defaults.
115    pub fn resolve(
116        cli: NotebookCli,
117        toml: Option<NotebooksToml>,
118        defaults: NotebookDefaults,
119        repo: String,
120    ) -> Result<Self, NotebookError> {
121        let toml = toml.unwrap_or_default();
122        let bind = match cli.bind {
123            Some(bind) => bind,
124            None => match toml.bind.as_deref() {
125                Some(text) => {
126                    text.parse::<SocketAddr>()
127                        .map_err(|source| NotebookError::InvalidBind {
128                            addr: text.to_owned(),
129                            source,
130                        })?
131                }
132                None => SocketAddr::from(([127, 0, 0, 1], 0)),
133            },
134        };
135        Ok(Self {
136            dir: cli.dir.or(toml.dir).unwrap_or(defaults.dir),
137            runtime_dir: defaults.runtime_dir,
138            venv_dir: defaults.venv_dir,
139            python: cli.python.or(toml.python),
140            bind,
141            token: cli.token.or(toml.token).unwrap_or_else(mint_token),
142            cull_idle_secs: cli
143                .cull_idle_secs
144                .or(toml.cull_idle_secs)
145                .unwrap_or(DEFAULT_CULL_IDLE_SECS),
146            repo,
147            engine_http: defaults.engine_http,
148        })
149    }
150
151    /// `WARATAH_URL`: loopback root of this compute's HTTP server.
152    ///
153    /// An unspecified bind (`0.0.0.0`, `::`) is normalized to `127.0.0.1` —
154    /// kernels must dial the co-located engine over loopback, never the
155    /// externally advertised wildcard.
156    pub fn waratah_url(&self) -> String {
157        let mut addr = self.engine_http;
158        if addr.ip().is_unspecified() {
159            addr.set_ip(std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST));
160        }
161        format!("http://{addr}")
162    }
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168    use pretty_assertions::assert_eq;
169
170    fn defaults() -> NotebookDefaults {
171        NotebookDefaults {
172            dir: PathBuf::from("/data/notebooks"),
173            runtime_dir: PathBuf::from("/data/notebooks-runtime"),
174            venv_dir: PathBuf::from("/data/notebooks-venv"),
175            engine_http: "127.0.0.1:8080".parse().unwrap(),
176        }
177    }
178
179    fn resolved(cli: NotebookCli, toml: Option<&str>) -> NotebookOptions {
180        let toml = toml.map(|text| NotebooksToml::from_toml_str(text).unwrap());
181        NotebookOptions::resolve(cli, toml, defaults(), "main".to_owned()).unwrap()
182    }
183
184    #[test]
185    fn defaults_apply_with_no_cli_and_no_toml() {
186        let options = resolved(NotebookCli::default(), None);
187        assert_eq!(options.dir, PathBuf::from("/data/notebooks"));
188        assert_eq!(options.bind, SocketAddr::from(([127, 0, 0, 1], 0)));
189        assert_eq!(options.cull_idle_secs, DEFAULT_CULL_IDLE_SECS);
190        assert_eq!(options.repo, "main");
191        assert_eq!(options.waratah_url(), "http://127.0.0.1:8080");
192        assert_eq!(options.token.len(), 64);
193        assert!(options.token.chars().all(|c| c.is_ascii_hexdigit()));
194    }
195
196    #[test]
197    fn toml_overrides_defaults_but_not_flags() {
198        let cli = NotebookCli {
199            dir: Some(PathBuf::from("/flag/dir")),
200            ..NotebookCli::default()
201        };
202        let options = resolved(
203            cli,
204            Some(
205                r#"
206dir = "/toml/dir"
207cull_idle_secs = 60
208bind = "127.0.0.1:9100"
209"#,
210            ),
211        );
212        // CLI wins over TOML for dir.
213        assert_eq!(options.dir, PathBuf::from("/flag/dir"));
214        // TOML wins over built-in defaults.
215        assert_eq!(options.cull_idle_secs, 60);
216        assert_eq!(
217            options.bind,
218            "127.0.0.1:9100".parse::<SocketAddr>().unwrap()
219        );
220    }
221
222    #[test]
223    fn unknown_keys_are_ignored() {
224        // A stale or forward-compatible knob must not break startup; the
225        // document is flat (no [notebooks] wrapper section).
226        let toml =
227            NotebooksToml::from_toml_str("cull_idle_secs = 90\nsomething_new = true\n").unwrap();
228        assert_eq!(toml.cull_idle_secs, Some(90));
229    }
230
231    #[test]
232    fn invalid_toml_bind_is_a_typed_error() {
233        let error = NotebooksToml::from_toml_str("bind = \"not an addr\"\n").unwrap();
234        let error = NotebookOptions::resolve(
235            NotebookCli::default(),
236            Some(error),
237            defaults(),
238            "main".to_owned(),
239        )
240        .unwrap_err();
241        assert!(matches!(error, NotebookError::InvalidBind { .. }));
242    }
243
244    #[test]
245    fn explicit_token_is_kept_and_unspecified_engine_http_normalizes() {
246        let cli = NotebookCli {
247            token: Some("fixed-token".to_owned()),
248            ..NotebookCli::default()
249        };
250        let mut defaults = defaults();
251        defaults.engine_http = "0.0.0.0:8080".parse().unwrap();
252        let toml = None;
253        let options = NotebookOptions::resolve(cli, toml, defaults, "main".to_owned()).unwrap();
254        assert_eq!(options.token, "fixed-token");
255        assert_eq!(options.waratah_url(), "http://127.0.0.1:8080");
256    }
257}