Skip to main content

schedr_ui/
lib.rs

1//! The web UI: server-rendered HTML pages over webservers' REST APIs (see archive/PROJECT.md, Web
2//! UI).
3//!
4//! It is `schedr ui`, a role of its own talking only to webservers' JSON APIs (decision 21B),
5//! one per deployment in its list (one the common case); `schedr standalone` serves it too,
6//! calling its own API in process. Pages are askama templates (checked at compile time) with
7//! one stylesheet of our own, light and dark (decision 26A and the user's style); times show
8//! in UTC and in the browser's zone (a cookie its inline script sets); links follow
9//! `X-Forwarded-Prefix`; the documentation is served at `/docs` from the image (28A).
10
11use std::path::PathBuf;
12use std::sync::Arc;
13
14use axum::Router;
15use axum::routing::{get, post};
16use schedr_client::{Client, Transport};
17
18mod actions;
19mod ansi;
20mod assets;
21pub mod chart;
22mod connections;
23mod dag_filters;
24pub mod deployments;
25mod docs;
26pub mod graph;
27mod imports;
28pub mod live;
29mod metrics;
30pub mod page;
31mod pages;
32mod params_form;
33mod runs;
34mod task_memory;
35mod workers;
36
37#[cfg(test)]
38mod tests;
39
40/// One deployment the UI shows: a webserver's API, by the name the UI gives it.
41#[derive(Debug)]
42pub struct Deployment<T> {
43    /// Its name in the UI and in URLs (`/d/<name>/...`).
44    pub name: String,
45    /// Its webserver's API.
46    pub client: Client<T>,
47    /// How the UI proves itself to that webserver, as the UI's panel says it: `none`,
48    /// `token`, `mTLS`, `token and mTLS`, or `in process` (standalone's own API).
49    pub proof: &'static str,
50}
51
52/// What the UI serves.
53#[derive(Debug)]
54pub struct Ui<T> {
55    /// The deployments it shows, in the order given (one the common case).
56    pub deployments: Vec<Deployment<T>>,
57    /// Where the documentation site is (`[ui] docs_dir`); none: no `/docs`.
58    pub docs_dir: Option<PathBuf>,
59    /// Who the person using it is (`[ui.auth]`; standalone's: `[webserver.auth]`, one port).
60    pub auth: schedr_api::auth::Auth,
61    /// How its live pages are paced.
62    pub timings: live::UiTimings,
63    /// Its own configuration, masked (its node's panel on the Deployments page; standalone's:
64    /// the process's).
65    pub config: serde_json::Value,
66    /// Its process's ID (empty: not known): in standalone the webserver's, which draws the UI
67    /// inside that process.
68    pub process_id: String,
69    /// Its host (empty: not known).
70    pub host: String,
71}
72
73/// The actions' routes (POSTs, see `actions`).
74fn action_routes<T: Transport + Send + Sync + 'static>() -> Router<Arc<Ui<T>>> {
75    Router::new()
76        .route(
77            "/d/{deployment}/dags/{dag}/trigger/restart",
78            post(actions::restart_trigger::<T>),
79        )
80        .route(
81            "/d/{deployment}/dags/{dag}/trigger/skip",
82            post(actions::skip_trigger_run::<T>),
83        )
84        .route(
85            "/d/{deployment}/dags/{dag}/trigger/run-event",
86            post(actions::run_event::<T>),
87        )
88        .route(
89            "/d/{deployment}/dags/{dag}/sensors/{sensor}/switch-on",
90            post(actions::switch_on::<T>),
91        )
92        .route(
93            "/d/{deployment}/dags/{dag}/pause",
94            post(actions::pause::<T>),
95        )
96        .route(
97            "/d/{deployment}/dags/{dag}/unpause",
98            post(actions::unpause::<T>),
99        )
100        .route(
101            "/d/{deployment}/dags/{dag}/trigger",
102            post(actions::trigger::<T>),
103        )
104        .route(
105            "/d/{deployment}/runs/{run}/cancel",
106            post(actions::cancel_run::<T>),
107        )
108        .route(
109            "/d/{deployment}/dags/{dag}/backfill",
110            post(actions::backfill::<T>),
111        )
112        .route(
113            "/d/{deployment}/backfills/{backfill}/cancel",
114            post(actions::cancel_backfill::<T>),
115        )
116        .route(
117            "/d/{deployment}/runs/{run}/tasks/{task}/{action}",
118            post(actions::task::<T>),
119        )
120        .route(
121            "/d/{deployment}/workers/{worker}/{action}",
122            post(actions::worker::<T>),
123        )
124}
125
126/// The UI's routes: `/` (the DAGs), `/d/<deployment>/dags/<dag>`, `/runs`,
127/// `/d/<deployment>/runs/<run>` (and its tasks' panels and log tails), `/deployments`,
128/// `/metrics`, `/workers`, `/connections` (and its checks and tests), the
129/// actions (POSTs, see `actions`), `/events`, `/time`, `/assets/...`, `/docs/...`.
130/// Every answer varies with `X-Forwarded-Prefix` (its links do), so a cache keeps them apart.
131pub fn router<T: Transport + Send + Sync + 'static>(ui: Ui<T>) -> Router {
132    let relays = Arc::new(live::Relays::new(ui.deployments.len()));
133    let state = Arc::new(ui);
134    Router::new()
135        .route("/", get(pages::dags::<T>))
136        .route("/d/{deployment}/dags/{dag}", get(pages::dag::<T>))
137        .route("/runs", get(runs::list::<T>))
138        .route("/d/{deployment}/runs/{run}", get(runs::run::<T>))
139        .route(
140            "/d/{deployment}/runs/{run}/tasks/{task}",
141            get(runs::panel::<T>),
142        )
143        .route(
144            "/d/{deployment}/runs/{run}/tasks/{task}/output.json",
145            get(runs::output_download::<T>),
146        )
147        .route("/deployments", get(deployments::list::<T>))
148        .route("/metrics", get(metrics::page::<T>))
149        .route("/metrics/chart", get(metrics::node_chart::<T>))
150        .route("/workers", get(workers::list::<T>))
151        .route("/connections", get(connections::list::<T>))
152        .route(
153            "/d/{deployment}/connections/check",
154            post(connections::check::<T>),
155        )
156        .route(
157            "/d/{deployment}/connections/{name}/test",
158            post(connections::test::<T>),
159        )
160        .route(
161            "/d/{deployment}/connections/commands/{command}",
162            get(connections::poll::<T>),
163        )
164        .route("/import-errors", get(imports::list::<T>))
165        .route("/import-errors/count", get(imports::nav_count::<T>))
166        .route("/import-errors/notice", get(imports::notice::<T>))
167        .route("/time", get(actions::time))
168        .merge(action_routes::<T>())
169        .route(
170            "/d/{deployment}/commands/{command}",
171            get(actions::command::<T>),
172        )
173        .route("/events", get(live::events::<T>))
174        .route(
175            "/d/{deployment}/runs/{run}/tasks/{task}/tail",
176            get(live::tail::<T>),
177        )
178        .route("/assets/style.css", get(assets::style))
179        .route("/assets/live.js", get(assets::live))
180        .route(assets::HTMX_PATH, get(assets::htmx))
181        .route("/docs", get(docs::to_index))
182        .route("/docs/", get(docs::index::<T>))
183        .route("/docs/{*path}", get(docs::file::<T>))
184        .fallback(pages::not_found::<T>)
185        .layer(axum::Extension(relays))
186        .layer(axum::middleware::from_fn_with_state(
187            Arc::clone(&state),
188            signed_in::<T>,
189        ))
190        .layer(axum::middleware::from_fn(actions::guard))
191        .layer(axum::middleware::map_response(vary_on_prefix))
192        .with_state(state)
193}
194
195/// Who the person is, by the UI's `auth` (refused: 401, a sign-in prompt in `basic` mode),
196/// their name carried to the webservers with every call made for this request
197/// ([`schedr_client::USER`]). The stylesheet and scripts are served to anyone (the sign-in
198/// page needs them).
199async fn signed_in<T: Transport>(
200    axum::extract::State(ui): axum::extract::State<Arc<Ui<T>>>,
201    request: axum::extract::Request,
202    next: axum::middleware::Next,
203) -> axum::response::Response {
204    use axum::response::IntoResponse as _;
205    if request.uri().path().starts_with("/assets/") {
206        return next.run(request).await;
207    }
208    match ui.auth.user(request.headers(), false).await {
209        Ok(user) => schedr_client::USER.scope(user, next.run(request)).await,
210        Err(refused) => {
211            let page = page::Page::new(request.headers(), ui.docs_dir.is_some());
212            let htmx = request.headers().contains_key("hx-request");
213            ui.auth.refusal(&refused, |message| {
214                if htmx {
215                    axum::response::Html(format!(
216                        "<div class=\"banner warning\"><strong>Not signed in</strong>: {}</div>",
217                        ansi::to_html(message)
218                    ))
219                    .into_response()
220                } else {
221                    pages::error_page(
222                        &page,
223                        "Not signed in",
224                        message,
225                        axum::http::StatusCode::UNAUTHORIZED,
226                    )
227                }
228            })
229        }
230    }
231}
232
233/// Every answer varies with the prefix, and may not be shown in another site's frame (its
234/// buttons can't be clicked through one: clickjacking).
235async fn vary_on_prefix(mut response: axum::response::Response) -> axum::response::Response {
236    use axum::http::{HeaderValue, header};
237    let headers = response.headers_mut();
238    headers.append(header::VARY, HeaderValue::from_static(page::PREFIX_HEADER));
239    headers.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));
240    headers.insert(
241        header::CONTENT_SECURITY_POLICY,
242        HeaderValue::from_static("frame-ancestors 'none'"),
243    );
244    response
245}