Skip to main content

rullst_studio/
lib.rs

1#![cfg_attr(mutants, mutants::skip)]
2extern crate rullst_core as rullst;
3use axum::Router;
4use rullst_core::Queue;
5use std::sync::Arc;
6use utoipa::openapi::OpenApi;
7
8pub mod access;
9pub mod ai_playground;
10pub mod api_playground;
11pub use access::{LocalStudioAccess, StudioBuildError};
12mod assets;
13pub mod cache_inspector;
14pub mod data_browser;
15pub use data_browser::run_studio;
16pub mod distributed_traces;
17pub mod env_viewer;
18pub mod er_diagram;
19pub mod feature_flags;
20pub mod jobs_monitor;
21pub mod logger;
22pub mod migration_manager;
23pub mod radar_visualizer;
24pub mod revenue_dashboard;
25pub mod security_radar;
26pub mod traces_visualizer;
27
28pub struct Studio {
29    openapi: Option<OpenApi>,
30    queue: Option<Queue>,
31    cache: Option<rullst_core::Cache>,
32    distributed_traces: distributed_traces::DistributedTraceStore,
33}
34
35impl Default for Studio {
36    fn default() -> Self {
37        Self::new()
38    }
39}
40
41impl Studio {
42    pub fn new() -> Self {
43        Self {
44            openapi: None,
45            queue: None,
46            cache: None,
47            distributed_traces: distributed_traces::DistributedTraceStore::default(),
48        }
49    }
50
51    pub fn with_openapi(mut self, openapi: OpenApi) -> Self {
52        self.openapi = Some(openapi);
53        self
54    }
55
56    pub fn with_horizon(mut self, queue: Queue) -> Self {
57        self.queue = Some(queue);
58        self
59    }
60
61    /// Supplies a cache for metadata-only inspection and individual local
62    /// invalidation. Cached values and bulk flush are never exposed by Studio.
63    pub fn with_cache(mut self, cache: rullst_core::Cache) -> Self {
64        self.cache = Some(cache);
65        self
66    }
67
68    /// Supplies the bounded store shared with a separately mounted,
69    /// authenticated distributed trace ingestion endpoint.
70    pub fn with_distributed_traces(
71        mut self,
72        store: distributed_traces::DistributedTraceStore,
73    ) -> Self {
74        self.distributed_traces = store;
75        self
76    }
77
78    /// Builds Studio behind an explicit debug-only loopback access capability.
79    /// Routes already include `/studio`; mount this router at the listener root.
80    pub fn into_router(self, access: LocalStudioAccess) -> Result<Router, StudioBuildError> {
81        let logger_state = Arc::new(logger::LoggerState::new());
82        let cache_router = cache_inspector::router(self.cache)?;
83        let mut router = data_browser::router_with_cache(self.distributed_traces, cache_router)
84            .nest("/studio/requests", logger::router(logger_state.clone()))
85            .nest("/studio/env", env_viewer::router())
86            .nest("/studio/features", feature_flags::router())
87            .nest("/studio/er", er_diagram::router())
88            .merge(security_radar::stats_router());
89
90        if let Some(openapi) = self.openapi {
91            router = router.merge(api_playground::router(openapi));
92        }
93
94        if let Some(queue) = self.queue {
95            router = router.nest("/studio/jobs", jobs_monitor::router(queue));
96        }
97
98        router = router.layer(axum::middleware::from_fn_with_state(
99            logger_state,
100            logger::logger_middleware,
101        ));
102        access.protect_router(router)
103    }
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109    #[cfg(debug_assertions)]
110    use axum::{body::Body, http::Request};
111    #[cfg(debug_assertions)]
112    use tower::ServiceExt;
113
114    #[cfg(debug_assertions)]
115    #[tokio::test]
116    async fn test_studio_builder_and_routes() {
117        let studio = Studio::new();
118        let router = studio
119            .into_router(LocalStudioAccess::loopback_only())
120            .expect("debug Studio router");
121        let request = |uri: &'static str| {
122            let mut request = Request::builder()
123                .uri(uri)
124                .header(axum::http::header::HOST, "127.0.0.1:5555")
125                .body(Body::empty())
126                .expect("valid request");
127            request.extensions_mut().insert(axum::extract::ConnectInfo(
128                "127.0.0.1:42000"
129                    .parse::<std::net::SocketAddr>()
130                    .expect("loopback peer"),
131            ));
132            request
133        };
134        let security_page = router
135            .clone()
136            .oneshot(request("/studio/security"))
137            .await
138            .expect("security page response");
139        assert_eq!(security_page.status(), axum::http::StatusCode::OK);
140
141        let security_stats = router
142            .oneshot(request("/studio/security/stats"))
143            .await
144            .expect("security stats response");
145        assert_eq!(security_stats.status(), axum::http::StatusCode::OK);
146
147        let queue = Queue::sqlite("sqlite::memory:").await.unwrap();
148        let openapi = OpenApi::default();
149
150        let full_studio = Studio::default().with_openapi(openapi).with_horizon(queue);
151        let _ = full_studio
152            .into_router(LocalStudioAccess::loopback_only())
153            .expect("debug full Studio router");
154    }
155
156    #[cfg(debug_assertions)]
157    #[tokio::test]
158    async fn configured_cache_and_trace_routes_render_real_bounded_state() {
159        let cache = rullst_core::Cache::memory();
160        cache
161            .put("private:learner:7", "sensitive-value", Some(60))
162            .await
163            .expect("cache fixture");
164        let trace_store =
165            distributed_traces::DistributedTraceStore::new(8).expect("bounded trace store");
166        trace_store
167            .insert_batch(
168                "lms-api",
169                1_800_000_000,
170                vec![distributed_traces::DistributedTraceSpanV1 {
171                    trace_id: "0123456789abcdef0123456789abcdef".to_string(),
172                    span_id: "0123456789abcdef".to_string(),
173                    parent_span_id: None,
174                    operation: "lessons.list".to_string(),
175                    kind: distributed_traces::DistributedTraceKind::Sql,
176                    started_at_unix_us: 1_800_000_000_000_000,
177                    duration_us: 700,
178                    status: distributed_traces::DistributedTraceStatus::Ok,
179                }],
180            )
181            .expect("trace fixture");
182        let router = Studio::new()
183            .with_cache(cache)
184            .with_distributed_traces(trace_store)
185            .into_router(LocalStudioAccess::loopback_only())
186            .expect("debug Studio router");
187        let request = |uri: &'static str| {
188            let mut request = Request::builder()
189                .uri(uri)
190                .header(axum::http::header::HOST, "127.0.0.1:5555")
191                .body(Body::empty())
192                .expect("valid request");
193            request.extensions_mut().insert(axum::extract::ConnectInfo(
194                "127.0.0.1:42000"
195                    .parse::<std::net::SocketAddr>()
196                    .expect("loopback peer"),
197            ));
198            request
199        };
200
201        let cache_response = router
202            .clone()
203            .oneshot(request("/studio/cache"))
204            .await
205            .expect("cache response");
206        assert_eq!(cache_response.status(), axum::http::StatusCode::OK);
207        let cache_body = axum::body::to_bytes(cache_response.into_body(), 512 * 1024)
208            .await
209            .expect("cache body");
210        let cache_body = String::from_utf8(cache_body.to_vec()).expect("UTF-8 cache body");
211        assert!(cache_body.contains("Cache Inspector"));
212        assert!(cache_body.contains("15 bytes"));
213        assert!(!cache_body.contains("private:learner:7"));
214        assert!(!cache_body.contains("sensitive-value"));
215
216        let trace_response = router
217            .oneshot(request("/studio/traces"))
218            .await
219            .expect("trace response");
220        assert_eq!(trace_response.status(), axum::http::StatusCode::OK);
221        let trace_body = axum::body::to_bytes(trace_response.into_body(), 512 * 1024)
222            .await
223            .expect("trace body");
224        let trace_body = String::from_utf8(trace_body.to_vec()).expect("UTF-8 trace body");
225        assert!(trace_body.contains("Trace Inspector"));
226        assert!(trace_body.contains("lms-api"));
227        assert!(trace_body.contains("lessons.list"));
228        assert!(trace_body.contains("1 retained"));
229    }
230
231    #[cfg(not(debug_assertions))]
232    #[test]
233    fn studio_builder_fails_closed_in_release() {
234        assert!(matches!(
235            Studio::new().into_router(LocalStudioAccess::loopback_only()),
236            Err(StudioBuildError::LocalAccessRequiresDebugBuild)
237        ));
238        assert!(matches!(
239            Studio::default()
240                .with_openapi(OpenApi::default())
241                .into_router(LocalStudioAccess::loopback_only()),
242            Err(StudioBuildError::LocalAccessRequiresDebugBuild)
243        ));
244    }
245}