Skip to main content

waratah_api/
state.rs

1//! Shared axum application state.
2
3use std::ops::Deref;
4use std::path::PathBuf;
5use std::sync::Arc;
6
7use waratah_storage::WarmState;
8
9use crate::backend::ComputeBackend;
10use crate::debug::QueryDebug;
11use crate::query_library::{QueryLibrary, ServerQuery};
12use crate::repos::RepositoryCatalog;
13
14/// State cloned into every RDF4J / Waratah HTTP handler.
15///
16/// Cloning an [`AppState`] must stay O(1): axum clones it once per request, and
17/// a deep clone here puts dozens of allocations on the hot path (the compute
18/// node, router rings, repository catalog, warning list). That churn was
19/// measurable — enough allocator warm-up to make a fresh process's first query
20/// executions visibly slower than the same process's steady state — so every
21/// process-lifetime service lives once behind the single [`Arc`], and requests
22/// borrow through it. Add fields to [`AppStateInner`], never to [`AppState`].
23/// The builders clone-on-write via [`Arc::make_mut`]: calling one on a state
24/// that was already cloned (and shared with a router) forks the inner state,
25/// so build configuration before the state is shared.
26#[derive(Debug, Clone)]
27pub struct AppState<C> {
28    inner: Arc<AppStateInner<C>>,
29}
30
31/// The shared application state one [`Arc`] behind every [`AppState`] clone.
32#[derive(Debug, Clone)]
33pub struct AppStateInner<C> {
34    /// Compute backend (live [`waratah_compute::ComputeNode`] or a test mock).
35    pub compute: C,
36    /// Repository catalog (MVP: `"main"` only).
37    pub repos: RepositoryCatalog,
38    /// SPARQL request tracing (`waratah start --debug`).
39    pub debug: QueryDebug,
40    /// Staging parent for `/waratah/.../ingest`. Handlers join `{ingest_dir}/{repository_id}`.
41    /// `None` disables ingest routes.
42    pub ingest_dir: Option<PathBuf>,
43    /// Live notebook-sidecar status. `Some` mounts the `/jupyter` proxy and
44    /// advertises the capability on `/waratah/notebooks` + the cluster view.
45    pub notebooks: Option<Arc<waratah_notebook::NotebookState>>,
46    /// AI services state (`ai.toml` / `--with-ai`). `Some` enables the
47    /// `/waratah/ai` discovery, the egress proxy, and the ai-context
48    /// endpoint; `None` answers `501` on all three.
49    pub ai: Option<Arc<crate::ai::AiService>>,
50    /// Published query library for `GET /waratah/.../queries`
51    /// (`--queries-dir`, or the inline `--load-demo` samples). `None`
52    /// disables the endpoint: every request answers `501`.
53    pub query_library: Option<QueryLibrary>,
54    /// Startup cache-warm tracker (standalone mode). `Some` gates `/health`:
55    /// 503 with the pending walk names until every walk finishes, so first
56    /// queries never race a still-running warm pass.
57    pub warm: Option<Arc<WarmState>>,
58    /// Orchestrator warnings surfaced verbatim in the `/health` body (RPC
59    /// mode: e.g. a child cache-walk that outlived the readiness wait).
60    pub startup_warnings: Vec<String>,
61}
62
63impl<C> Deref for AppState<C> {
64    type Target = AppStateInner<C>;
65
66    fn deref(&self) -> &Self::Target {
67        &self.inner
68    }
69}
70
71impl<C> AppState<C> {
72    /// Build state over `compute` with the default `"main"` catalog.
73    pub fn new(compute: C) -> Self
74    where
75        C: ComputeBackend,
76    {
77        Self::with_catalog(compute, RepositoryCatalog::main_only())
78    }
79
80    /// Build state with an explicit catalog (tests / future multi-repo).
81    pub fn with_catalog(compute: C, repos: RepositoryCatalog) -> Self {
82        Self {
83            inner: Arc::new(AppStateInner {
84                compute,
85                repos,
86                debug: QueryDebug::off(),
87                ingest_dir: None,
88                notebooks: None,
89                ai: None,
90                query_library: None,
91                warm: None,
92                startup_warnings: Vec::new(),
93            }),
94        }
95    }
96}
97
98/// Builders clone-on-write the inner state (`Arc::make_mut`), so they must
99/// run while the state is unshared — at startup, before the router clones it.
100/// This is the same `C: Clone` requirement the deep-clone `AppState` had.
101impl<C: Clone> AppState<C> {
102    /// Gate `/health` on the startup cache-warm tracker.
103    pub fn with_warm_state(mut self, warm: Option<Arc<WarmState>>) -> Self {
104        Arc::make_mut(&mut self.inner).warm = warm;
105        self
106    }
107
108    /// Surface orchestrator warnings in the `/health` body.
109    pub fn with_startup_warnings(mut self, warnings: Vec<String>) -> Self {
110        Arc::make_mut(&mut self.inner).startup_warnings = warnings;
111        self
112    }
113
114    /// Enable the `/waratah/.../ingest` API over `dir`.
115    pub fn with_ingest_dir(mut self, dir: PathBuf) -> Self {
116        Arc::make_mut(&mut self.inner).ingest_dir = Some(dir);
117        self
118    }
119
120    /// Serve `GET /waratah/.../queries` from `{dir}/{repository}/*.rq`.
121    pub fn with_queries_dir(mut self, dir: PathBuf) -> Self {
122        Arc::make_mut(&mut self.inner).query_library = Some(QueryLibrary::Directory(dir));
123        self
124    }
125
126    /// Publish fixed inline queries (the `--load-demo` samples) for every
127    /// known repository, in the given order.
128    pub fn with_inline_queries(mut self, queries: Vec<ServerQuery>) -> Self {
129        Arc::make_mut(&mut self.inner).query_library = Some(QueryLibrary::Inline(queries.into()));
130        self
131    }
132
133    /// Mount the `/jupyter` reverse proxy and the notebook capability
134    /// endpoints over `state`.
135    pub fn with_notebooks(mut self, state: Arc<waratah_notebook::NotebookState>) -> Self {
136        Arc::make_mut(&mut self.inner).notebooks = Some(state);
137        self
138    }
139
140    /// Enable the AI routes (discovery, egress proxy, ai-context) over the
141    /// resolved service state.
142    pub fn with_ai(mut self, service: Arc<crate::ai::AiService>) -> Self {
143        Arc::make_mut(&mut self.inner).ai = Some(service);
144        self
145    }
146
147    /// Enable or disable SPARQL debug logging on stderr.
148    pub fn with_debug(self, enabled: bool) -> Self {
149        self.with_query_debug(QueryDebug::from_enabled(enabled))
150    }
151
152    /// Install an explicit SPARQL debug logger (shared query-id sequence).
153    pub fn with_query_debug(mut self, debug: QueryDebug) -> Self {
154        Arc::make_mut(&mut self.inner).debug = debug;
155        self
156    }
157}