Skip to main content

schedr_api/
lib.rs

1//! The schedr webserver: REST API and web UI.
2//!
3//! So far the REST API subset the CLI needs (`/api/v1`: DAGs, runs, tasks, attempts and their
4//! logs, commands, workers), with version headers, a generated OpenAPI description and Swagger UI
5//! over it at `/api/v1/docs` (see archive/PROJECT.md, Web UI and CLI). Reads come straight from the
6//! database; actions are command rows the master applies.
7
8use axum::Router;
9use axum::routing::{get, post};
10use utoipa::openapi::security::{Http, HttpAuthScheme, SecurityRequirement, SecurityScheme};
11use utoipa::{Modify, OpenApi};
12
13pub mod attempt_memory;
14pub mod auth;
15pub mod docs;
16pub mod error;
17pub mod events;
18pub mod logs;
19pub mod metrics;
20pub mod named_events;
21pub mod routes;
22pub mod series;
23pub mod state;
24pub mod task_flow;
25pub mod version;
26pub mod views;
27
28#[cfg(test)]
29mod tests;
30
31pub use error::ApiError;
32pub use state::ApiState;
33
34/// The OpenAPI description of `/api/v1`, generated from the handlers and views.
35#[derive(OpenApi)]
36#[openapi(
37    info(title = "schedr", description = "The schedr REST API."),
38    paths(
39        routes::list_dags,
40        routes::get_dag,
41        routes::pause_dag,
42        routes::unpause_dag,
43        routes::list_run_resources,
44        routes::get_run_resource,
45        routes::list_switched_off_sensors,
46        routes::switch_on_sensor,
47        routes::list_triggers,
48        routes::dag_trigger,
49        routes::trigger_events,
50        routes::restart_trigger,
51        routes::skip_trigger_run,
52        routes::switch_on_trigger,
53        routes::list_runs,
54        routes::trigger_run,
55        routes::create_backfill,
56        routes::list_dag_backfills,
57        routes::get_backfill,
58        routes::cancel_backfill,
59        routes::list_all_runs,
60        routes::get_run,
61        routes::get_run_dag,
62        routes::list_run_commands,
63        routes::cancel_run,
64        routes::list_attempts,
65        routes::get_log,
66        routes::get_output,
67        routes::cancel_task,
68        routes::retry_task,
69        routes::get_command,
70        routes::list_workers,
71        routes::get_deployment,
72        series::list_samples,
73        series::memory_totals,
74        task_flow::task_flow,
75        attempt_memory::task_memory,
76        attempt_memory::dag_memory,
77        routes::list_import_errors,
78        events::events,
79        named_events::post_event,
80        named_events::list_events,
81        routes::drain_worker,
82        routes::resume_worker,
83        routes::list_connections,
84        routes::check_connections,
85        routes::test_connection,
86    ),
87    tags(
88        (name = "dags", description = "DAGs and pausing"),
89        (name = "runs", description = "Runs, their tasks and attempts"),
90        (name = "commands", description = "Actions and the master's decisions"),
91        (name = "workers", description = "The worker registry"),
92        (name = "connections", description = "Checking and testing connections on a worker"),
93        (name = "events", description = "Events posted by outside systems, for `EventNamed`"),
94    ),
95    modifiers(&BearerToken)
96)]
97pub struct ApiDoc;
98
99/// Where Swagger UI is served (always: it shows only what `openapi.json` already does).
100pub const DOCS_PATH: &str = "/api/v1/docs";
101
102/// Where the OpenAPI description is served.
103pub const OPENAPI_PATH: &str = "/api/v1/openapi.json";
104
105/// An optional bearer token on every operation: schedr checks none itself (until the UI's
106/// auth modes, milestone M3), but a mesh or proxy in front may require one (e.g. Istio with a
107/// Keycloak token), and Swagger UI's "Authorize" sends it.
108struct BearerToken;
109
110impl Modify for BearerToken {
111    fn modify(&self, openapi: &mut utoipa::openapi::OpenApi) {
112        let mut http = Http::new(HttpAuthScheme::Bearer);
113        http.description = Some(
114            "A token for a mesh or proxy in front of schedr that requires one; schedr itself \
115             checks none."
116                .to_owned(),
117        );
118        openapi
119            .components
120            .get_or_insert_with(Default::default)
121            .add_security_scheme("bearer", SecurityScheme::Http(http));
122        // The empty requirement first: no token is also accepted.
123        openapi.security = Some(vec![
124            SecurityRequirement::default(),
125            SecurityRequirement::new("bearer", Vec::<String>::new()),
126        ]);
127    }
128}
129
130/// The OpenAPI description as committed under `schema/` (pretty JSON).
131///
132/// # Panics
133///
134/// Never in practice: the generated description always serializes.
135#[must_use]
136pub fn openapi_json() -> serde_json::Value {
137    serde_json::to_value(ApiDoc::openapi()).expect("the OpenAPI description serializes")
138}
139
140/// The routes cancelling runs and creating backfills (`schedr runs cancel`, `schedr runs
141/// backfill`).
142fn run_control_routes() -> Router<ApiState> {
143    Router::new()
144        .route("/api/v1/runs/{run_id}/cancel", post(routes::cancel_run))
145        .route(
146            "/api/v1/dags/{dag_id}/backfills",
147            get(routes::list_dag_backfills).post(routes::create_backfill),
148        )
149        .route("/api/v1/backfills/{backfill_id}", get(routes::get_backfill))
150        .route(
151            "/api/v1/backfills/{backfill_id}/cancel",
152            post(routes::cancel_backfill),
153        )
154}
155
156/// The routes of `schedr connections`.
157fn connection_routes() -> Router<ApiState> {
158    Router::new()
159        .route("/api/v1/connections", get(routes::list_connections))
160        .route("/api/v1/connections/check", post(routes::check_connections))
161        .route(
162            "/api/v1/connections/{name}/test",
163            post(routes::test_connection),
164        )
165}
166
167/// The Metrics page's (decisions 464, 465).
168fn metrics_routes() -> Router<ApiState> {
169    Router::new()
170        .route("/api/v1/metrics/samples", get(series::list_samples))
171        .route("/api/v1/metrics/memory", get(series::memory_totals))
172        .route("/api/v1/metrics/tasks", get(task_flow::task_flow))
173        .route(
174            "/api/v1/dags/{dag_id}/memory",
175            get(attempt_memory::dag_memory),
176        )
177        .route(
178            "/api/v1/dags/{dag_id}/tasks/{task_id}/memory",
179            get(attempt_memory::task_memory),
180        )
181}
182
183/// The routes of `schedr triggers`.
184fn trigger_routes() -> Router<ApiState> {
185    Router::new()
186        .route("/api/v1/triggers", get(routes::list_triggers))
187        .route("/api/v1/dags/{dag_id}/trigger", get(routes::dag_trigger))
188        .route(
189            "/api/v1/dags/{dag_id}/trigger/events",
190            get(routes::trigger_events),
191        )
192        .route(
193            "/api/v1/dags/{dag_id}/trigger/restart",
194            post(routes::restart_trigger),
195        )
196        .route(
197            "/api/v1/dags/{dag_id}/trigger/skip",
198            post(routes::skip_trigger_run),
199        )
200        .route(
201            "/api/v1/dags/{dag_id}/trigger/switch-on",
202            post(routes::switch_on_trigger),
203        )
204}
205
206/// The API's routes over `state`.
207pub fn router(state: ApiState) -> Router {
208    // An event's data may be up to `[events] max_size`, over axum's 2 MiB default (Codex's
209    // review); the name, key and JSON around it get some room.
210    let event_body = state
211        .max_event_size
212        .saturating_add(named_events::EVENT_BODY_ROOM);
213    Router::new()
214        .route("/api/v1/dags", get(routes::list_dags))
215        .route("/api/v1/dags/{dag_id}", get(routes::get_dag))
216        .route("/api/v1/dags/{dag_id}/pause", post(routes::pause_dag))
217        .route("/api/v1/dags/{dag_id}/unpause", post(routes::unpause_dag))
218        .route(
219            "/api/v1/dags/{dag_id}/runs",
220            get(routes::list_runs).post(routes::trigger_run),
221        )
222        .route("/api/v1/runs", get(routes::list_all_runs))
223        .route("/api/v1/changes", get(events::events))
224        .route(
225            "/api/v1/events",
226            get(named_events::list_events)
227                .post(named_events::post_event)
228                .layer(axum::extract::DefaultBodyLimit::max(event_body)),
229        )
230        .route("/api/v1/runs/{run_id}", get(routes::get_run))
231        .route("/api/v1/runs/{run_id}/dag", get(routes::get_run_dag))
232        .route(
233            "/api/v1/runs/{run_id}/commands",
234            get(routes::list_run_commands),
235        )
236        .route(
237            "/api/v1/runs/{run_id}/tasks/{task_id}/output",
238            get(routes::get_output),
239        )
240        .route(
241            "/api/v1/runs/{run_id}/resources",
242            get(routes::list_run_resources),
243        )
244        .route(
245            "/api/v1/runs/{run_id}/resources/{resource}",
246            get(routes::get_run_resource),
247        )
248        .merge(trigger_routes())
249        .merge(metrics_routes())
250        .merge(run_control_routes())
251        .route(
252            "/api/v1/sensors/switched-off",
253            get(routes::list_switched_off_sensors),
254        )
255        .route(
256            "/api/v1/dags/{dag_id}/sensors/{sensor}/switch-on",
257            post(routes::switch_on_sensor),
258        )
259        .route(
260            "/api/v1/runs/{run_id}/tasks/{task_id}/attempts",
261            get(routes::list_attempts),
262        )
263        .route(
264            "/api/v1/runs/{run_id}/tasks/{task_id}/attempts/{try_number}/log",
265            get(routes::get_log),
266        )
267        .route(
268            "/api/v1/runs/{run_id}/tasks/{task_id}/cancel",
269            post(routes::cancel_task),
270        )
271        .route(
272            "/api/v1/runs/{run_id}/tasks/{task_id}/retry",
273            post(routes::retry_task),
274        )
275        .route("/api/v1/commands/{command_id}", get(routes::get_command))
276        .route("/api/v1/workers", get(routes::list_workers))
277        .route("/api/v1/deployment", get(routes::get_deployment))
278        .route("/api/v1/import-errors", get(routes::list_import_errors))
279        .route(
280            "/api/v1/workers/{worker_id}/drain",
281            post(routes::drain_worker),
282        )
283        .route(
284            "/api/v1/workers/{worker_id}/resume",
285            post(routes::resume_worker),
286        )
287        .merge(connection_routes())
288        .route(OPENAPI_PATH, get(docs::description))
289        .route(DOCS_PATH, get(docs::redirect))
290        .route("/api/v1/docs/", get(docs::file))
291        .route("/api/v1/docs/{*path}", get(docs::file))
292        .layer(axum::middleware::from_fn_with_state(
293            state.clone(),
294            auth::require,
295        ))
296        .layer(axum::middleware::from_fn(auth::refuse_cross_site))
297        .layer(axum::middleware::from_fn_with_state(
298            state.clone(),
299            version::versions,
300        ))
301        // Outside the version check, so the requests it refuses are counted too.
302        .layer(axum::middleware::from_fn_with_state(
303            state.clone(),
304            metrics::count_requests,
305        ))
306        .with_state(state)
307}