Skip to main content

waratah_notebook/
state.rs

1//! Live sidecar status shared by the supervisor, proxy, and HTTP surface.
2
3use std::net::SocketAddr;
4use std::sync::atomic::{AtomicBool, Ordering};
5
6use tokio::sync::RwLock;
7
8/// Atomically-updated view of the jupyter sidecar.
9///
10/// The supervisor owns writes; the proxy and the `/waratah/notebooks` +
11/// `/waratah/cluster` handlers only read. `ready` flips as sidecar
12/// instances die and come back; `addr` changes when a restart picks a fresh
13/// port (the old value could point at a reused port, so readers must always
14/// go through [`NotebookState::sidecar_addr`], never cache it).
15#[derive(Debug)]
16pub struct NotebookState {
17    token: String,
18    repo: String,
19    ready: AtomicBool,
20    addr: RwLock<SocketAddr>,
21}
22
23impl NotebookState {
24    /// New state for a sidecar not yet started at `addr`.
25    pub fn new(token: String, repo: String, addr: SocketAddr) -> Self {
26        Self {
27            token,
28            repo,
29            ready: AtomicBool::new(false),
30            addr: RwLock::new(addr),
31        }
32    }
33
34    /// The startup-minted jupyter token (`Authorization: token …`).
35    pub fn token(&self) -> &str {
36        &self.token
37    }
38
39    /// The repository this compute serves — the only legal
40    /// `env.WARATAH_REPO` value (the engine writes exactly one kernelspec).
41    pub fn repo(&self) -> &str {
42        &self.repo
43    }
44
45    /// Whether the sidecar currently answers (`GET /api` 200 at last poll).
46    pub fn is_ready(&self) -> bool {
47        self.ready.load(Ordering::Relaxed)
48    }
49
50    /// Supervisor writes readiness; also `false` while a restart is in progress.
51    pub fn set_ready(&self, ready: bool) {
52        self.ready.store(ready, Ordering::Relaxed);
53    }
54
55    /// Loopback address of the current sidecar instance.
56    pub async fn sidecar_addr(&self) -> SocketAddr {
57        *self.addr.read().await
58    }
59
60    /// Supervisor records the address of each (re)started instance.
61    pub async fn set_sidecar_addr(&self, addr: SocketAddr) {
62        *self.addr.write().await = addr;
63    }
64}