Skip to main content

notedthat_api_http/
state.rs

1//! Shared application state for the axum router.
2
3use notedthat_core::{
4    AccessPolicy, Authenticator, EventPublisher, EventSource, KbDetails, KbSlug, Storage,
5};
6use notedthat_indexer::{IndexHealth, Searcher};
7
8use crate::readiness::ReadinessReceiver;
9use std::collections::BTreeMap;
10use std::sync::Arc;
11
12/// Application state shared across all axum handlers.
13///
14/// This is cloned cheaply for each request (all fields are behind [`Arc`]).
15#[derive(Clone)]
16pub struct AppState {
17    /// The backing storage implementation (injected at startup).
18    pub storage: Arc<dyn Storage>,
19    /// Canonical map of slug string → [`KbSlug`] for declared knowledge bases.
20    pub declared_kbs: Arc<BTreeMap<String, KbSlug>>,
21    /// Startup snapshot of manifest access policies, keyed by KB slug.
22    ///
23    /// One `Arc` per policy so a request-scoped authorization handle can hold
24    /// its knowledge base's policy cheaply instead of borrowing the whole map.
25    pub access_policies: Arc<BTreeMap<String, Arc<AccessPolicy>>>,
26    /// Startup snapshot of each manifest's display name and description,
27    /// keyed by KB slug: what `GET /api/v1/knowledgebases` shows (#98).
28    pub kb_details: Arc<BTreeMap<String, KbDetails>>,
29    /// The credential rules every request's principal is resolved through.
30    pub authenticator: Arc<Authenticator>,
31    /// Maximum accepted PUT body size in bytes (16 MiB in M2).
32    pub max_body_size: u64,
33    /// Maximum object size eligible for patch operations, in bytes.
34    pub max_patchable_size: u64,
35    /// Sender half of the async indexing queue.
36    pub indexer_tx: tokio::sync::mpsc::Sender<notedthat_indexer::IndexEvent>,
37    /// The search implementation (injected at startup).
38    pub searcher: Arc<dyn Searcher>,
39    /// The object change event log, when `NOTEDTHAT_EVENTS_BACKEND` selects one.
40    /// `None` is the default: writes are not announced and the events route
41    /// answers 404.
42    pub events: Option<Arc<dyn EventPublisher>>,
43    /// The per-knowledge-base index health record, shared with the indexer
44    /// worker and every write path (#97).
45    pub index_health: Arc<IndexHealth>,
46    /// The latest background probe of the storage and vector backends.
47    /// `/readyz` reads it and never probes inline.
48    pub readiness: ReadinessReceiver,
49}
50
51impl AppState {
52    /// Where a write made through this surface is reported, attributed to
53    /// `source` — the HTTP API itself, or MCP when the request says so.
54    pub(crate) fn sinks(&self, source: EventSource) -> notedthat_write::WriteSinks<'_> {
55        notedthat_write::WriteSinks::new(
56            &self.indexer_tx,
57            self.events.as_deref(),
58            &self.index_health,
59            source,
60        )
61    }
62}
63
64#[cfg(test)]
65mod tests {
66    use super::*;
67    use crate::testing::InMemoryStorage;
68    use std::collections::BTreeMap;
69    use std::sync::Arc;
70
71    fn minimal_state(tx: tokio::sync::mpsc::Sender<notedthat_indexer::IndexEvent>) -> AppState {
72        AppState {
73            storage: Arc::new(InMemoryStorage::default()),
74            declared_kbs: Arc::new(BTreeMap::new()),
75            access_policies: Arc::new(BTreeMap::new()),
76            kb_details: Arc::new(BTreeMap::new()),
77            authenticator: Arc::new(Authenticator::new("token")),
78            max_body_size: 1024,
79            max_patchable_size: 1024,
80            indexer_tx: tx,
81            searcher: Arc::new(crate::testing::NoopSearcher),
82            events: None,
83            index_health: Arc::new(notedthat_indexer::IndexHealth::new()),
84            readiness: crate::testing::ready_receiver(),
85        }
86    }
87
88    #[tokio::test]
89    async fn clone_shares_same_channel() {
90        let (tx, mut rx) = tokio::sync::mpsc::channel(10);
91        let state = minimal_state(tx);
92        let cloned = state.clone();
93
94        let event = notedthat_indexer::IndexEvent::Tombstone {
95            kb: notedthat_core::KbSlug::try_new("test").expect("valid kb slug"),
96            object_key: notedthat_core::ObjectPath::try_from("a.md").expect("valid path"),
97        };
98        cloned
99            .indexer_tx
100            .send(event.clone())
101            .await
102            .expect("send on cloned tx");
103
104        let received = rx.recv().await.expect("receive on original rx");
105        assert_eq!(
106            received, event,
107            "cloned Sender must share the same underlying channel"
108        );
109    }
110}