1#![forbid(unsafe_code)]
12
13mod listener;
14mod render;
15mod status;
16
17use std::{future::Future, sync::Arc, time::Duration};
18
19use axum::{
20 Router,
21 body::{Body, Bytes, HttpBody as _},
22 extract::{Path, Request, State},
23 http::{HeaderName, HeaderValue, StatusCode, header},
24 middleware::Next,
25 response::{Html, IntoResponse, Redirect, Response},
26 routing::get,
27};
28use dekopon_broker_host::{BrokerHostMetrics, LoadedProviderMetadata};
29use thiserror::Error;
30use tokio::net::TcpListener;
31
32use crate::listener::BoundedListener;
33
34pub use status::{ServiceStatus, TokenTotals};
35
36pub const DEFAULT_MAX_CONNECTIONS: usize = 16;
38pub const DEFAULT_CONNECTION_TIMEOUT: Duration = Duration::from_secs(30);
40
41#[derive(Clone, Debug, Eq, PartialEq)]
43pub struct OtelSummary {
44 pub endpoint: String,
46 pub transport: String,
48 pub service_name: String,
50 pub export_timeout_ms: u64,
52 pub telemetry_payloads: bool,
54 pub headers_configured: bool,
58 pub resource_attributes_configured: bool,
60}
61
62#[derive(Clone, Copy, Debug, Eq, PartialEq)]
69pub struct WebUiLimits {
70 pub max_connections: usize,
72 pub connection_timeout: Duration,
74}
75
76impl Default for WebUiLimits {
77 fn default() -> Self {
78 Self {
79 max_connections: DEFAULT_MAX_CONNECTIONS,
80 connection_timeout: DEFAULT_CONNECTION_TIMEOUT,
81 }
82 }
83}
84
85#[derive(Clone, Debug)]
87pub(crate) struct ProviderPage {
88 metadata: LoadedProviderMetadata,
89 page: Bytes,
90}
91
92impl ProviderPage {
93 pub(crate) const fn metadata(&self) -> &LoadedProviderMetadata {
94 &self.metadata
95 }
96}
97
98#[derive(Clone, Debug)]
100pub struct Dashboard {
101 pub(crate) version: String,
102 pub(crate) providers: Arc<[ProviderPage]>,
103 pub(crate) host_metrics: BrokerHostMetrics,
104 pub(crate) service_status: ServiceStatus,
105 pub(crate) otel: Option<OtelSummary>,
106}
107
108impl Dashboard {
109 #[must_use]
115 pub fn new(
116 version: impl Into<String>,
117 mut providers: Vec<LoadedProviderMetadata>,
118 host_metrics: BrokerHostMetrics,
119 service_status: ServiceStatus,
120 otel: Option<OtelSummary>,
121 ) -> Self {
122 let version = version.into();
123 providers.sort_by(|left, right| left.manifest.id.cmp(&right.manifest.id));
124 let providers = providers
125 .into_iter()
126 .map(|metadata| ProviderPage {
127 page: Bytes::from(render::provider_page(&version, &metadata)),
128 metadata,
129 })
130 .collect();
131 Self {
132 version,
133 providers,
134 host_metrics,
135 service_status,
136 otel,
137 }
138 }
139
140 fn provider(&self, id: &str) -> Option<&ProviderPage> {
141 self.providers
142 .iter()
143 .find(|provider| provider.metadata.manifest.id.as_str() == id)
144 }
145}
146
147pub fn router(dashboard: Dashboard) -> Router {
149 Router::new()
150 .route("/", get(root))
151 .route("/ui", get(index))
152 .route("/ui/", get(ui_slash))
153 .route("/ui/providers/{provider}", get(provider))
154 .fallback(not_found)
155 .layer(axum::middleware::map_response(apply_secure_headers))
158 .layer(axum::middleware::from_fn(trace_request))
159 .with_state(dashboard)
160}
161
162pub async fn serve<F>(
166 listener: TcpListener,
167 dashboard: Dashboard,
168 shutdown: F,
169) -> Result<(), WebUiError>
170where
171 F: Future<Output = ()> + Send + 'static,
172{
173 serve_with_limits(listener, dashboard, WebUiLimits::default(), shutdown).await
174}
175
176pub async fn serve_with_limits<F>(
178 listener: TcpListener,
179 dashboard: Dashboard,
180 limits: WebUiLimits,
181 shutdown: F,
182) -> Result<(), WebUiError>
183where
184 F: Future<Output = ()> + Send + 'static,
185{
186 if limits.max_connections == 0 || limits.connection_timeout.is_zero() {
187 return Err(WebUiError::InvalidLimits);
188 }
189 axum::serve(BoundedListener::new(listener, limits), router(dashboard))
190 .with_graceful_shutdown(shutdown)
191 .await
192 .map_err(WebUiError::Serve)
193}
194
195async fn root() -> Response {
196 redirect("/ui")
197}
198
199async fn ui_slash() -> Response {
200 redirect("/ui")
201}
202
203async fn index(State(dashboard): State<Dashboard>) -> Response {
204 html(StatusCode::OK, render::dashboard(&dashboard))
205}
206
207async fn provider(State(dashboard): State<Dashboard>, Path(provider): Path<String>) -> Response {
208 match dashboard.provider(&provider) {
209 Some(provider) => rendered(StatusCode::OK, provider.page.clone()),
210 None => html(
211 StatusCode::NOT_FOUND,
212 render::not_found(&dashboard, "Provider not found"),
213 ),
214 }
215}
216
217async fn not_found(State(dashboard): State<Dashboard>) -> Response {
218 html(
219 StatusCode::NOT_FOUND,
220 render::not_found(&dashboard, "Page not found"),
221 )
222}
223
224fn redirect(location: &'static str) -> Response {
225 Redirect::permanent(location).into_response()
226}
227
228fn html(status: StatusCode, body: String) -> Response {
229 (status, Html(body)).into_response()
230}
231
232fn rendered(status: StatusCode, body: Bytes) -> Response {
233 (
234 status,
235 [(
236 header::CONTENT_TYPE,
237 HeaderValue::from_static("text/html; charset=utf-8"),
238 )],
239 Body::from(body),
240 )
241 .into_response()
242}
243
244async fn apply_secure_headers(mut response: Response) -> Response {
245 let headers = response.headers_mut();
246 headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
247 headers.insert(
248 header::X_CONTENT_TYPE_OPTIONS,
249 HeaderValue::from_static("nosniff"),
250 );
251 headers.insert(
252 header::REFERRER_POLICY,
253 HeaderValue::from_static("no-referrer"),
254 );
255 headers.insert(
256 HeaderName::from_static("content-security-policy"),
257 HeaderValue::from_static(
258 "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'",
259 ),
260 );
261 response
262}
263
264async fn trace_request(request: Request, next: Next) -> Response {
269 let method = request.method().clone();
270 let path = request.uri().path().to_owned();
271 let response = next.run(request).await;
272 tracing::debug!(
273 event = "webui_request",
274 http.method = %method,
275 http.path = %path,
276 http.status = response.status().as_u16(),
277 http.response_bytes = response.body().size_hint().exact().unwrap_or_default()
278 );
279 response
280}
281
282#[derive(Debug, Error)]
284pub enum WebUiError {
285 #[error("Dekopon web UI server failed")]
287 Serve(#[source] std::io::Error),
288 #[error("Dekopon web UI connection limits are invalid")]
290 InvalidLimits,
291}