Skip to main content

schedr_api/
routes.rs

1//! The `/api/v1` endpoints: reads straight from the database, actions as command rows.
2//!
3//! A handler's errors are its OpenAPI responses (`ErrorBody` with 400 / 404 / 503 / 500); the doc
4//! comments are the endpoints' descriptions in the OpenAPI document, so they carry no
5//! `# Errors` sections.
6#![expect(
7    clippy::missing_errors_doc,
8    reason = "handler docs become OpenAPI descriptions; errors are listed as responses"
9)]
10
11use std::collections::{BTreeSet, HashMap};
12
13use axum::body::Bytes;
14use axum::extract::rejection::QueryRejection;
15use axum::extract::{Path, Query, State};
16use axum::http::StatusCode;
17use axum::{Extension, Json};
18use jiff::Timestamp;
19use schedr_db::commands::Submitted;
20use schedr_db::reads::RunFilter;
21use schedr_db::runs::Held;
22use schedr_model::commands::{AskedEvent, Command};
23use schedr_model::logs::{MASK_CONTEXT, MAX_CHUNK, MIN_CHUNK};
24use schedr_model::{DagId, ResourceState, TaskId, TaskInstanceState, WorkerState};
25
26use crate::auth::User;
27use crate::error::ApiError;
28use crate::logs::{LogFetchError, masked_lines};
29use crate::state::ApiState;
30use crate::views::{
31    AllRunsQuery, AttemptList, BackfillList, BackfillRequest, BackfillView,
32    CheckConnectionsRequest, CommandList, CommandView, ConnectionList, DagList, DagView,
33    DeploymentView, ErrorBody, EventList, EventView, ImportErrorList, ImportErrorView,
34    InstanceQuery, LimitView, LogChunk, LogQuery, MasterView, NodeView, OutputView, ParamFieldView,
35    PauseRequest, ProblemView, ResourceList, ResourceView, RunDetail, RunList, RunView, RunsQuery,
36    SensorList, SensorView, TaskView, TestConnectionRequest, TriggerList, TriggerRequest,
37    TriggerView, WorkerList, WorkerNodeView, WorkerUsageView, WorkerView,
38};
39
40#[cfg(test)]
41mod tests;
42
43/// How many runs a list returns when the client doesn't say.
44pub const DEFAULT_RUNS: u32 = 50;
45
46pub(crate) type ApiResult<T> = Result<Json<T>, ApiError>;
47type Accepted = Result<(StatusCode, Json<CommandView>), ApiError>;
48
49/// Every DAG not removed.
50#[utoipa::path(get, path = "/api/v1/dags", tag = "dags",
51    responses((status = 200, body = DagList)))]
52pub async fn list_dags(State(state): State<ApiState>) -> ApiResult<DagList> {
53    let dags = state.db.stored_dags().await?;
54    let held = Held::by_file(&state.db.current_import_errors().await?);
55    Ok(Json(DagList {
56        dags: dags
57            .iter()
58            .filter(|d| !d.removed)
59            .map(|d| DagView::of(d, &held))
60            .collect(),
61    }))
62}
63
64/// The files of each DAG root's current code that failed to import (decision 66). A DAG
65/// defined in such a file keeps its last good version (still listed) but is held: no run is
66/// created and manual triggers are refused until the file is fixed (decision 72). A timeout or
67/// a runner that died holds nothing: the file is parsed again (72.2). Fixing the file and
68/// syncing the root makes the entry go.
69#[utoipa::path(get, path = "/api/v1/import-errors", tag = "dags",
70    responses((status = 200, body = ImportErrorList)))]
71pub async fn list_import_errors(State(state): State<ApiState>) -> ApiResult<ImportErrorList> {
72    let errors = state.db.current_import_errors().await?;
73    Ok(Json(ImportErrorList {
74        errors: errors.iter().map(ImportErrorView::from).collect(),
75    }))
76}
77
78/// Every worker the master has seen, gone ones included.
79#[utoipa::path(get, path = "/api/v1/workers", tag = "workers",
80    responses((status = 200, body = WorkerList)))]
81pub async fn list_workers(State(state): State<ApiState>) -> ApiResult<WorkerList> {
82    let workers = state.db.workers().await?;
83    let mut nodes: HashMap<String, schedr_db::nodes::WorkerNode> = state
84        .db
85        .worker_nodes()
86        .await?
87        .into_iter()
88        .map(|node| (node.worker_id.clone(), node))
89        .collect();
90    Ok(Json(WorkerList {
91        workers: workers
92            .iter()
93            .map(|worker| {
94                let node = nodes.remove(&worker.id);
95                WorkerView {
96                    master_id: node.as_ref().and_then(|n| n.master_id.clone()),
97                    memory: node
98                        .as_ref()
99                        .and_then(|n| n.usage.as_ref())
100                        .map(crate::views::WorkerMemoryView::from),
101                    ..WorkerView::from(worker)
102                }
103            })
104            .collect(),
105    }))
106}
107
108/// The deployment this webserver serves, as nodes (decisions 121-123): this webserver, the
109/// masters heard from in the last 30 s (the leader first; standbys too), and every worker,
110/// each with its effective configuration as the node masked it (secrets never in clear).
111#[utoipa::path(get, path = "/api/v1/deployment", tag = "workers",
112    responses((status = 200, body = DeploymentView)))]
113pub async fn get_deployment(
114    State(state): State<ApiState>,
115    Extension(user): Extension<User>,
116) -> ApiResult<DeploymentView> {
117    let since = (state.clock)()
118        .checked_sub(state.limits.masters_heard_within)
119        .unwrap_or(Timestamp::UNIX_EPOCH);
120    let masters = state.db.masters(since).await?;
121    // The import errors of files each worker parsed: a warning on its node.
122    let mut import_errors: HashMap<String, usize> = HashMap::new();
123    for error in state.db.current_import_errors().await? {
124        *import_errors.entry(error.worker_id).or_default() += 1;
125    }
126    let mut nodes: HashMap<String, schedr_db::nodes::WorkerNode> = state
127        .db
128        .worker_nodes()
129        .await?
130        .into_iter()
131        .map(|node| (node.worker_id.clone(), node))
132        .collect();
133    let workers = state
134        .db
135        .workers()
136        .await?
137        .into_iter()
138        .map(|worker| {
139            let node = nodes.remove(&worker.id);
140            let problems = worker_problems(&worker, import_errors.get(&worker.id).copied());
141            WorkerNodeView {
142                problems,
143                queues: worker.queues.clone(),
144                slots: worker.slots,
145                running: worker.running,
146                state: worker.state.to_string(),
147                schedr_version: worker.schedr_version,
148                master_id: node.as_ref().and_then(|n| n.master_id.clone()),
149                process_id: node.as_ref().and_then(|n| n.process_id.clone()),
150                usage: node
151                    .as_ref()
152                    .and_then(|n| n.usage.clone())
153                    .map(WorkerUsageView::from),
154                config: node.and_then(|n| n.config),
155                worker_id: worker.id,
156            }
157        })
158        .collect();
159    Ok(Json(DeploymentView {
160        // What it uses now (decision 463), read for each answer.
161        webserver: NodeView {
162            usage: (state.usage)().map(crate::views::NodeUsageView::from),
163            ..NodeView::clone(&state.node)
164        },
165        masters: masters.into_iter().map(MasterView::from).collect(),
166        workers,
167        user: user.0,
168    }))
169}
170
171/// A worker's problems now (decision 129): lost (an error), disconnected, what it reports wrong
172/// and the import errors of the files it parsed (warnings). One offline deregistered on purpose
173/// (a restart, a scale-down) and has none: kept for good, it would stay coloured (decision 130).
174fn worker_problems(
175    worker: &schedr_db::workers::WorkerRecord,
176    import_errors: Option<usize>,
177) -> Vec<ProblemView> {
178    let mut problems = Vec::new();
179    if worker.state == WorkerState::Offline {
180        return problems;
181    }
182    match worker.state {
183        WorkerState::Lost => problems.push(ProblemView {
184            error: true,
185            message: "lost: it stopped answering, its attempts were given up".to_owned(),
186        }),
187        WorkerState::Disconnected => problems.push(ProblemView {
188            error: false,
189            message: "disconnected: lost unless it comes back within its lease".to_owned(),
190        }),
191        WorkerState::Active | WorkerState::Draining | WorkerState::Offline => {}
192    }
193    problems.extend(worker.warnings.iter().map(|warning| ProblemView {
194        error: false,
195        message: schedr_config::masked::mask_text(&warning.message),
196    }));
197    if let Some(count) = import_errors {
198        problems.push(ProblemView {
199            error: false,
200            message: format!(
201                "{count} file{} it parsed failed to import",
202                if count == 1 { "" } else { "s" }
203            ),
204        });
205    }
206    problems
207}
208
209/// How lately a master must have written its row to be shown by default: three of its node
210/// heartbeats of 10 s (the webserver passes its own, from `node_heartbeat`).
211pub const MASTERS_HEARD_WITHIN: jiff::SignedDuration = jiff::SignedDuration::from_secs(30);
212
213/// A process with no sample this long before the samples are asked for has ended: three of the
214/// master's sample intervals of a minute (the webserver passes its own, from
215/// `sample_interval`).
216pub const SAMPLED_WITHIN: jiff::SignedDuration = jiff::SignedDuration::from_mins(3);
217
218/// How many sample intervals a running process may go unsampled.
219pub const SAMPLED_INTERVALS: u32 = 3;
220
221/// Drain a worker for maintenance (`schedr workers drain`): no new tasks, its running ones
222/// finish; kept across restarts until resumed. Applied by the master; poll the command for
223/// the decision.
224#[utoipa::path(post, path = "/api/v1/workers/{worker_id}/drain", tag = "workers",
225    params(("Idempotency-Key" = Option<String>, Header, description = "A key of the client's for this request: sent again with it, it is the command stored the first time (B140)"),
226        ("worker_id" = String, Path, description = "The worker's ID")),
227    responses((status = 202, body = CommandView), (status = 400, body = ErrorBody)))]
228pub async fn drain_worker(
229    State(state): State<ApiState>,
230    Path(worker_id): Path<String>,
231    Extension(user): Extension<User>,
232    key: RequestKey,
233) -> Accepted {
234    submit(&state, &user, key, Command::DrainWorker { worker_id }).await
235}
236
237/// Each DAG root's connections in its current code (decision 211): name, type, the file
238/// defining it, why one can't be used, and the DAGs and tasks declaring it; never a value.
239/// A task declaring a connection no file defines lists it too, refused.
240#[utoipa::path(get, path = "/api/v1/connections", tag = "connections",
241    responses((status = 200, body = ConnectionList)))]
242pub async fn list_connections(State(state): State<ApiState>) -> ApiResult<ConnectionList> {
243    let mut registries = std::collections::BTreeMap::new();
244    for root in state.db.current_parses().await?.into_keys() {
245        let registry = state.db.current_connections(&root).await?;
246        registries.insert(root, registry);
247    }
248    let dags = state.db.stored_dags().await?;
249    Ok(Json(ConnectionList::of(&registries, &dags)))
250}
251
252/// The default time a connection test may take (decision 200), unless `[webserver]
253/// connection_test_timeout` says.
254pub const CONNECTION_TEST_TIMEOUT: std::time::Duration = std::time::Duration::from_mins(1);
255
256/// Render connections on a worker (`schedr connections check`, decision 174): each secret
257/// they name present or missing, never a value. The command's result fills in as the
258/// workers answer: poll it until no job is `running`.
259#[utoipa::path(post, path = "/api/v1/connections/check", tag = "connections",
260    params(("Idempotency-Key" = Option<String>, Header, description = "A key of the client's for this request: sent again with it, it is the command stored the first time (B140)")),
261    request_body(content = CheckConnectionsRequest, description = "Optional; every root's connections by default"),
262    responses((status = 202, body = CommandView), (status = 400, body = ErrorBody)))]
263pub async fn check_connections(
264    State(state): State<ApiState>,
265    Extension(user): Extension<User>,
266    key: RequestKey,
267    body: Bytes,
268) -> Accepted {
269    let request: CheckConnectionsRequest = optional_body(&body)?;
270    let command = Command::CheckConnections {
271        root: request.root,
272        name: request.name,
273        worker: request.worker,
274    };
275    submit(&state, &user, key, command).await
276}
277
278/// Open a connection on a worker and run its check (`schedr connections test`, decisions
279/// 198-200), beside the tasks. The command's result fills in when the worker answers.
280#[utoipa::path(post, path = "/api/v1/connections/{name}/test", tag = "connections",
281    params(("Idempotency-Key" = Option<String>, Header, description = "A key of the client's for this request: sent again with it, it is the command stored the first time (B140)"),
282        ("name" = String, Path, description = "The connection's name")),
283    request_body(content = TestConnectionRequest, description = "Optional"),
284    responses((status = 202, body = CommandView), (status = 400, body = ErrorBody)))]
285pub async fn test_connection(
286    State(state): State<ApiState>,
287    Path(name): Path<String>,
288    Extension(user): Extension<User>,
289    key: RequestKey,
290    body: Bytes,
291) -> Accepted {
292    let request: TestConnectionRequest = optional_body(&body)?;
293    let default_ms = u64::try_from(state.connection_test_timeout.as_millis()).unwrap_or(u64::MAX);
294    let timeout_ms = request.timeout_ms.unwrap_or(default_ms);
295    if timeout_ms == 0 || timeout_ms > schedr_model::commands::MAX_CONNECTION_TEST_MS {
296        return Err(ApiError::BadRequest(format!(
297            "timeout_ms: 1 to {}",
298            schedr_model::commands::MAX_CONNECTION_TEST_MS
299        )));
300    }
301    let command = Command::TestConnection {
302        name,
303        root: request.root,
304        worker: request.worker,
305        timeout_ms,
306    };
307    submit(&state, &user, key, command).await
308}
309
310/// Let a drained worker take tasks again (`schedr workers resume`). Applied by the master;
311/// poll the command for the decision.
312#[utoipa::path(post, path = "/api/v1/workers/{worker_id}/resume", tag = "workers",
313    params(("Idempotency-Key" = Option<String>, Header, description = "A key of the client's for this request: sent again with it, it is the command stored the first time (B140)"),
314        ("worker_id" = String, Path, description = "The worker's ID")),
315    responses((status = 202, body = CommandView), (status = 400, body = ErrorBody)))]
316pub async fn resume_worker(
317    State(state): State<ApiState>,
318    Path(worker_id): Path<String>,
319    Extension(user): Extension<User>,
320    key: RequestKey,
321) -> Accepted {
322    submit(&state, &user, key, Command::ResumeWorker { worker_id }).await
323}
324
325/// One DAG.
326#[utoipa::path(get, path = "/api/v1/dags/{dag_id}", tag = "dags",
327    params(("dag_id" = String, Path, description = "The DAG's ID")),
328    responses((status = 200, body = DagView), (status = 404, body = ErrorBody)))]
329pub async fn get_dag(
330    State(state): State<ApiState>,
331    Path(dag_id): Path<String>,
332) -> ApiResult<DagView> {
333    let dag_id = parse_dag_id(&dag_id)?;
334    let dag = known_dag(&state, &dag_id).await?;
335    let held = Held::by_file(&state.db.current_import_errors().await?);
336    let mut view = DagView::of(&dag, &held);
337    if let Some(current) = &dag.current {
338        if let Some(params) = &current.dag.params {
339            view.params = ParamFieldView::of(params);
340        }
341        if current.dag.tasks.iter().any(|t| !t.connections.is_empty()) {
342            let root = &current.dag.location.root;
343            view.warnings = state
344                .db
345                .current_connections(root)
346                .await?
347                .problems(&current.dag);
348        }
349        let limited = current.dag.max_active_tasks.is_some()
350            || current.dag.tasks.iter().any(|t| {
351                t.settings.max_active.is_some() || t.settings.max_active_per_run.is_some()
352            });
353        if limited {
354            let counts = state.db.active_counts(&dag_id).await?;
355            view.limits = LimitView::of(&current.dag, &counts);
356        }
357    }
358    Ok(Json(view))
359}
360
361/// Pause a DAG: the scheduler creates no runs of it (optionally cancelling those in
362/// progress). Applied by the master; poll the command for the decision.
363#[utoipa::path(post, path = "/api/v1/dags/{dag_id}/pause", tag = "dags",
364    params(("Idempotency-Key" = Option<String>, Header, description = "A key of the client's for this request: sent again with it, it is the command stored the first time (B140)"),
365        ("dag_id" = String, Path, description = "The DAG's ID")),
366    request_body(content = PauseRequest, description = "Optional; `{}` by default"),
367    responses((status = 202, body = CommandView), (status = 400, body = ErrorBody)))]
368pub async fn pause_dag(
369    State(state): State<ApiState>,
370    Path(dag_id): Path<String>,
371    Extension(user): Extension<User>,
372    key: RequestKey,
373    body: Bytes,
374) -> Accepted {
375    let dag_id = parse_dag_id(&dag_id)?;
376    let request: PauseRequest = optional_body(&body)?;
377    submit(
378        &state,
379        &user,
380        key,
381        Command::PauseDag {
382            dag_id,
383            cancel_runs: request.cancel_runs,
384        },
385    )
386    .await
387}
388
389/// Unpause a DAG. Applied by the master; poll the command for the decision.
390#[utoipa::path(post, path = "/api/v1/dags/{dag_id}/unpause", tag = "dags",
391    params(("Idempotency-Key" = Option<String>, Header, description = "A key of the client's for this request: sent again with it, it is the command stored the first time (B140)"),
392        ("dag_id" = String, Path, description = "The DAG's ID")),
393    responses((status = 202, body = CommandView), (status = 400, body = ErrorBody)))]
394pub async fn unpause_dag(
395    State(state): State<ApiState>,
396    Path(dag_id): Path<String>,
397    Extension(user): Extension<User>,
398    key: RequestKey,
399) -> Accepted {
400    let dag_id = parse_dag_id(&dag_id)?;
401    submit(&state, &user, key, Command::UnpauseDag { dag_id }).await
402}
403
404/// A DAG's runs, newest first.
405#[utoipa::path(get, path = "/api/v1/dags/{dag_id}/runs", tag = "runs",
406    params(("dag_id" = String, Path, description = "The DAG's ID"), RunsQuery),
407    responses((status = 200, body = RunList), (status = 404, body = ErrorBody)))]
408pub async fn list_runs(
409    State(state): State<ApiState>,
410    Path(dag_id): Path<String>,
411    query: Result<Query<RunsQuery>, QueryRejection>,
412) -> ApiResult<RunList> {
413    let dag_id = parse_dag_id(&dag_id)?;
414    let Query(query) = query.map_err(|e| ApiError::BadRequest(e.body_text()))?;
415    known_dag(&state, &dag_id).await?;
416    let runs = state
417        .db
418        .dag_runs(
419            &dag_id,
420            query.planned_for,
421            query.limit.unwrap_or(DEFAULT_RUNS),
422        )
423        .await?;
424    Ok(Json(RunList {
425        runs: runs.iter().map(RunView::from).collect(),
426    }))
427}
428
429/// Start a manual run (`schedr runs trigger`). Applied by the master; poll the command for the
430/// decision and the run's ID.
431#[utoipa::path(post, path = "/api/v1/dags/{dag_id}/runs", tag = "runs",
432    params(("Idempotency-Key" = Option<String>, Header, description = "A key of the client's for this request: sent again with it, it is the command stored the first time (B140)"),
433        ("dag_id" = String, Path, description = "The DAG's ID")),
434    request_body(content = TriggerRequest, description = "Optional; now by default"),
435    responses((status = 202, body = CommandView), (status = 400, body = ErrorBody)))]
436pub async fn trigger_run(
437    State(state): State<ApiState>,
438    Path(dag_id): Path<String>,
439    Extension(user): Extension<User>,
440    key: RequestKey,
441    body: Bytes,
442) -> Accepted {
443    let dag_id = parse_dag_id(&dag_id)?;
444    let request: TriggerRequest = optional_body(&body)?;
445    refuse_nul(request.params.as_ref())?;
446    let event = asked_event(&request)?;
447    submit(
448        &state,
449        &user,
450        key,
451        Command::TriggerRun {
452            dag_id,
453            planned_for: request.planned_for,
454            params: request.params,
455            event,
456        },
457    )
458    .await
459}
460
461/// Create a backfill (`schedr runs backfill`, decisions 363, 364, 400-404): a run per fire time
462/// of the range with no successful, queued or running run (every one with `all`), oldest first,
463/// behind the other kinds of runs. Applied by the master; the command's result has the counts
464/// and the backfill's ID (its own).
465#[utoipa::path(post, path = "/api/v1/dags/{dag_id}/backfills", tag = "runs",
466    params(("Idempotency-Key" = Option<String>, Header, description = "A key of the client's for this request: sent again with it, it is the command stored the first time (B140)"),
467        ("dag_id" = String, Path, description = "The DAG's ID")),
468    request_body(content = BackfillRequest),
469    responses((status = 202, body = CommandView), (status = 400, body = ErrorBody)))]
470pub async fn create_backfill(
471    State(state): State<ApiState>,
472    Path(dag_id): Path<String>,
473    Extension(user): Extension<User>,
474    key: RequestKey,
475    body: Bytes,
476) -> Accepted {
477    let dag_id = parse_dag_id(&dag_id)?;
478    let request: BackfillRequest =
479        read_body(&body).map_err(|why| ApiError::BadRequest(format!("invalid body: {why}")))?;
480    refuse_nul(request.params.as_ref())?;
481    submit(
482        &state,
483        &user,
484        key,
485        Command::Backfill(schedr_model::commands::BackfillRequest {
486            dag_id,
487            from: request.from,
488            to: request.to,
489            all: request.all,
490            params: request.params,
491            dry_run: request.dry_run,
492        }),
493    )
494    .await
495}
496
497/// How many backfills a DAG's list shows: its newest.
498const DAG_BACKFILLS: u32 = 50;
499
500/// A DAG's backfills, newest first (the 50 newest), with their runs by state (decision 403).
501#[utoipa::path(get, path = "/api/v1/dags/{dag_id}/backfills", tag = "runs",
502    params(("dag_id" = String, Path, description = "The DAG's ID")),
503    responses((status = 200, body = BackfillList), (status = 404, body = ErrorBody)))]
504pub async fn list_dag_backfills(
505    State(state): State<ApiState>,
506    Path(dag_id): Path<String>,
507) -> ApiResult<BackfillList> {
508    let dag_id = parse_dag_id(&dag_id)?;
509    known_dag(&state, &dag_id).await?;
510    let backfills = state.db.dag_backfills(&dag_id, DAG_BACKFILLS).await?;
511    Ok(Json(BackfillList {
512        backfills: backfills.iter().map(BackfillView::from).collect(),
513    }))
514}
515
516/// A backfill, with its runs by state (`schedr runs backfill` prints its ID).
517#[utoipa::path(get, path = "/api/v1/backfills/{backfill_id}", tag = "runs",
518    params(("backfill_id" = String, Path, description = "The backfill's ID")),
519    responses((status = 200, body = BackfillView), (status = 400, body = ErrorBody),
520        (status = 404, body = ErrorBody)))]
521pub async fn get_backfill(
522    State(state): State<ApiState>,
523    Path(backfill_id): Path<String>,
524) -> ApiResult<BackfillView> {
525    let backfill_id = parse_uuid(&backfill_id, "backfill")?;
526    let backfill = state
527        .db
528        .backfill(&backfill_id)
529        .await?
530        .ok_or_else(|| ApiError::NotFound(format!("no backfill `{backfill_id}`")))?;
531    Ok(Json(BackfillView::from(&backfill)))
532}
533
534/// Cancel a backfill (`schedr runs cancel --backfill`, decision 402): its queued and running
535/// runs; the finished ones stay as they are. Applied by the master; poll the command.
536#[utoipa::path(post, path = "/api/v1/backfills/{backfill_id}/cancel", tag = "runs",
537    params(("Idempotency-Key" = Option<String>, Header, description = "A key of the client's for this request: sent again with it, it is the command stored the first time (B140)"),
538        ("backfill_id" = String, Path, description = "The backfill's ID")),
539    responses((status = 202, body = CommandView), (status = 400, body = ErrorBody)))]
540pub async fn cancel_backfill(
541    State(state): State<ApiState>,
542    Path(backfill_id): Path<String>,
543    Extension(user): Extension<User>,
544    key: RequestKey,
545) -> Accepted {
546    let backfill_id = parse_uuid(&backfill_id, "backfill")?;
547    submit(&state, &user, key, Command::CancelBackfill { backfill_id }).await
548}
549
550/// Parameters with a NUL in some text, refused here: the command's storage would replace it
551/// (decision 114), and the master would see other values than those given.
552fn refuse_nul(params: Option<&serde_json::Map<String, serde_json::Value>>) -> Result<(), ApiError> {
553    if let Some(params) = params
554        && schedr_model::params::nul_at(&serde_json::Value::Object(params.clone())).is_some()
555    {
556        return Err(ApiError::BadRequest(
557            "params: text containing NUL (\\u0000) can't be stored".to_owned(),
558        ));
559    }
560    Ok(())
561}
562
563/// The event a manual run asks for; what can't be stored is refused here, as params are.
564fn asked_event(request: &TriggerRequest) -> Result<Option<AskedEvent>, ApiError> {
565    let bad = |why: &str| Err(ApiError::BadRequest(why.to_owned()));
566    if request.event_at.is_some() && request.event_key.is_none() {
567        return bad("event_at needs an event_key");
568    }
569    match (&request.event, &request.event_key, &request.event_data) {
570        (None, None, None) => Ok(None),
571        (Some(key), None, None) => Ok(Some(AskedEvent::Stored { key: key.clone() })),
572        (None, Some(key), data) => {
573            let data = data.clone().unwrap_or(serde_json::Value::Null);
574            if schedr_model::params::nul_at(&data).is_some() {
575                return bad("event_data: text containing NUL (\\u0000) can't be stored");
576            }
577            schedr_model::trigger::check_event_key(key).map_err(ApiError::BadRequest)?;
578            Ok(Some(AskedEvent::Given {
579                key: key.clone(),
580                data,
581                at: request.event_at,
582            }))
583        }
584        (None, None, Some(_)) => bad("event_data needs an event_key"),
585        (Some(_), _, _) => bad("event is the key of a stored event: give it or an event_key"),
586    }
587}
588
589/// A trigger's view from its stored row.
590fn trigger_view(
591    active: &schedr_db::runs::ActiveDag,
592    record: Option<&schedr_db::triggers::TriggerRecord>,
593    switched_off: bool,
594    heartbeat: std::time::Duration,
595    now: Timestamp,
596) -> Option<TriggerView> {
597    let schedr_model::Trigger::Event {
598        task, start, end, ..
599    } = &active.dag.trigger
600    else {
601        return None;
602    };
603    let outside = start.is_some_and(|start| now < start) || end.is_some_and(|end| end < now);
604    let state = if active.paused || active.held.is_some() || outside {
605        "paused"
606    } else if switched_off {
607        "switched_off"
608    } else if record.is_some_and(|r| r.instance_id.is_some()) {
609        "running"
610    } else if record.is_some_and(|r| r.stopped_why.is_some()) {
611        "stopped"
612    } else {
613        "waiting"
614    };
615    let empty = schedr_db::triggers::TriggerRecord::default();
616    let record = record.unwrap_or(&empty);
617    let stuck = state == "running" && poke_stuck(task, record, heartbeat, now);
618    Some(TriggerView {
619        dag_id: active.dag.id.to_string(),
620        trigger: task.id.to_string(),
621        state: state.to_owned(),
622        worker: record.worker_id.clone(),
623        // Masked when read, as an output is: what a run reads is the stored one.
624        bookmark: record
625            .bookmark
626            .as_deref()
627            .map(schedr_config::masked::mask_text),
628        stopped_why: record.stopped_why.clone(),
629        failures: record.failures,
630        last_error: record
631            .last_error
632            .as_deref()
633            .map(schedr_config::masked::mask_text),
634        not_before: record.not_before,
635        started_at: record.started_at,
636        last_event_at: record.last_event_at,
637        last_poked_at: record.last_poked_at,
638        last_restart_at: record.last_restart_at,
639        stuck,
640        called_for: None,
641    })
642}
643
644/// Whether a poke trigger has had no call end for over three times its `every` plus a heartbeat,
645/// counted from its start when none has yet (decision 461): a call past `every` is cancelled as
646/// an error, and the end reported within a heartbeat, so its worker may hang. (One that never
647/// yields is cut at the block limit, 30 s, which a short `every` may not cover: Restart is then
648/// offered early, and harmless.) The time is the worker's own clock: one more than the window
649/// off (it reports `clock_skew` past 2 s) may be shown stuck wrongly, or not. A long-running
650/// trigger can't be told: quiet is normal for it, and `restart_if_idle` restarts it.
651fn poke_stuck(
652    task: &schedr_model::Task,
653    record: &schedr_db::triggers::TriggerRecord,
654    heartbeat: std::time::Duration,
655    now: Timestamp,
656) -> bool {
657    let schedr_model::TaskKind::Sensor {
658        mode: schedr_model::SensorMode::Poke,
659        every_ms: Some(every),
660        ..
661    } = &task.kind
662    else {
663        return false;
664    };
665    let Some(since) = record.last_poked_at.max(record.started_at) else {
666        return false;
667    };
668    let limit = std::time::Duration::from_millis(every.saturating_mul(3)).saturating_add(heartbeat);
669    jiff::SignedDuration::try_from(limit)
670        .ok()
671        .and_then(|limit| since.checked_add(limit).ok())
672        .is_some_and(|at| at < now)
673}
674
675/// The run an `@trigger(wait_for=...)` is called for (decision 353), on its view.
676async fn add_called_for(
677    db: &schedr_db::Database,
678    active: &schedr_db::runs::ActiveDag,
679    view: &mut TriggerView,
680) -> Result<(), ApiError> {
681    if let schedr_model::Trigger::Event { task, .. } = &active.dag.trigger
682        && matches!(
683            task.kind,
684            schedr_model::TaskKind::Sensor {
685                wait_for: Some(_),
686                ..
687            }
688        )
689    {
690        view.called_for = db
691            .trigger_run_handed(active.dag.id.as_str())
692            .await?
693            .map(|handed| handed.run);
694    }
695    Ok(())
696}
697
698/// Every DAG's trigger.
699#[utoipa::path(get, path = "/api/v1/triggers", tag = "triggers",
700    responses((status = 200, body = TriggerList)))]
701pub async fn list_triggers(State(state): State<ApiState>) -> ApiResult<TriggerList> {
702    let records = state.db.triggers().await?;
703    let off = state.db.switched_off_wait_steps().await?;
704    let now = Timestamp::now();
705    let mut triggers = Vec::new();
706    for active in &state.db.active_dags().await? {
707        let dag = active.dag.id.as_str();
708        let function = match &active.dag.trigger {
709            schedr_model::Trigger::Event { task, .. } => task.id.as_str(),
710            _ => continue,
711        };
712        let Some(mut view) = trigger_view(
713            active,
714            records.iter().find(|r| r.dag_id == dag),
715            off.iter().any(|s| s.dag_id == dag && s.task_id == function),
716            state.heartbeat_interval,
717            now,
718        ) else {
719            continue;
720        };
721        add_called_for(&state.db, active, &mut view).await?;
722        triggers.push(view);
723    }
724    Ok(Json(TriggerList { triggers }))
725}
726
727/// A DAG's trigger: `404` for a DAG without one.
728#[utoipa::path(get, path = "/api/v1/dags/{dag_id}/trigger", tag = "triggers",
729    params(("dag_id" = String, Path, description = "The DAG's ID")),
730    responses((status = 200, body = TriggerView), (status = 404, body = ErrorBody)))]
731pub async fn dag_trigger(
732    State(state): State<ApiState>,
733    Path(dag_id): Path<String>,
734) -> ApiResult<TriggerView> {
735    let id = parse_dag_id(&dag_id)?;
736    let active = state.db.active_dags_of(&[&id]).await?;
737    let none = || ApiError::NotFound(format!("no DAG `{dag_id}` with an event trigger"));
738    let active = active.first().ok_or_else(none)?;
739    let function = match &active.dag.trigger {
740        schedr_model::Trigger::Event { task, .. } => task.id.as_str(),
741        _ => return Err(none()),
742    };
743    let off = state
744        .db
745        .wait_step_strikes(&dag_id, function)
746        .await?
747        .is_some_and(|strikes| strikes.off_at.is_some());
748    let record = state.db.trigger(&dag_id).await?;
749    let mut view = trigger_view(
750        active,
751        record.as_ref(),
752        off,
753        state.heartbeat_interval,
754        Timestamp::now(),
755    )
756    .ok_or_else(none)?;
757    add_called_for(&state.db, active, &mut view).await?;
758    Ok(Json(view))
759}
760
761/// How many events one call gives at most, by default and at most.
762const DEFAULT_EVENTS: u32 = 50;
763const MAX_EVENTS: u32 = 500;
764
765/// Which of a trigger's events.
766#[derive(Debug, serde::Deserialize, utoipa::IntoParams)]
767#[into_params(parameter_in = Query)]
768pub struct EventsQuery {
769    /// How many, 50 by default and 500 at most.
770    pub limit: Option<u32>,
771    /// Those after the one last listed: its `received_at`.
772    pub before: Option<Timestamp>,
773    /// And its `key`, for those received at the same moment.
774    pub before_key: Option<String>,
775}
776
777/// What a DAG's trigger found, newest received first.
778#[utoipa::path(get, path = "/api/v1/dags/{dag_id}/trigger/events", tag = "triggers",
779    params(("dag_id" = String, Path, description = "The DAG's ID"), EventsQuery),
780    responses((status = 200, body = EventList), (status = 400, body = ErrorBody)))]
781pub async fn trigger_events(
782    State(state): State<ApiState>,
783    Path(dag_id): Path<String>,
784    query: Result<Query<EventsQuery>, QueryRejection>,
785) -> ApiResult<EventList> {
786    let Query(query) = query.map_err(|e| ApiError::BadRequest(e.body_text()))?;
787    let limit = query.limit.unwrap_or(DEFAULT_EVENTS).min(MAX_EVENTS);
788    if query.before_key.is_some() && query.before.is_none() {
789        return Err(ApiError::BadRequest(
790            "`before_key` needs `before` (the event's `received_at`)".to_owned(),
791        ));
792    }
793    let after = query
794        .before
795        .map(|at| (at, query.before_key.as_deref().unwrap_or_default()));
796    let events = state
797        .db
798        .events(&dag_id, limit, after)
799        .await?
800        .into_iter()
801        .map(|mut stored| {
802            // Masked when read, as an output is: what a run reads is the stored one.
803            schedr_config::masked::mask_data(&mut stored.event.data);
804            EventView {
805                key: schedr_config::masked::mask_text(&stored.event.key),
806                data: stored.event.data,
807                at: stored.event.at,
808                received_at: stored.received_at,
809            }
810        })
811        .collect();
812    Ok(Json(EventList { events }))
813}
814
815/// Start a DAG's trigger again from its bookmark, whatever stopped it. Applied by the master;
816/// poll the command for the decision.
817#[utoipa::path(post, path = "/api/v1/dags/{dag_id}/trigger/restart", tag = "triggers",
818    params(("Idempotency-Key" = Option<String>, Header, description = "A key of the client's"),
819        ("dag_id" = String, Path, description = "The DAG's ID")),
820    responses((status = 202, body = CommandView), (status = 400, body = ErrorBody)))]
821pub async fn restart_trigger(
822    State(state): State<ApiState>,
823    Path(dag_id): Path<String>,
824    Extension(user): Extension<User>,
825    key: RequestKey,
826) -> Accepted {
827    let dag_id = parse_dag_id(&dag_id)?;
828    submit(&state, &user, key, Command::RestartTrigger { dag_id }).await
829}
830
831/// Pass the run an `@trigger(wait_for=...)` is called for and keeps failing on, so its next call
832/// gets the next run (decision 353); refused while a call of it runs. Applied by the master; poll
833/// the command for the decision.
834#[utoipa::path(post, path = "/api/v1/dags/{dag_id}/trigger/skip", tag = "triggers",
835    params(("Idempotency-Key" = Option<String>, Header, description = "A key of the client's"),
836        ("dag_id" = String, Path, description = "The DAG's ID")),
837    responses((status = 202, body = CommandView), (status = 400, body = ErrorBody)))]
838pub async fn skip_trigger_run(
839    State(state): State<ApiState>,
840    Path(dag_id): Path<String>,
841    Extension(user): Extension<User>,
842    key: RequestKey,
843) -> Accepted {
844    let dag_id = parse_dag_id(&dag_id)?;
845    submit(&state, &user, key, Command::SkipTriggerRun { dag_id }).await
846}
847
848/// Switch a DAG's trigger back on, forgetting its strikes. Applied by the master; poll the
849/// command for the decision.
850#[utoipa::path(post, path = "/api/v1/dags/{dag_id}/trigger/switch-on", tag = "triggers",
851    params(("Idempotency-Key" = Option<String>, Header, description = "A key of the client's"),
852        ("dag_id" = String, Path, description = "The DAG's ID")),
853    responses((status = 202, body = CommandView), (status = 400, body = ErrorBody),
854        (status = 404, body = ErrorBody)))]
855pub async fn switch_on_trigger(
856    State(state): State<ApiState>,
857    Path(dag_id): Path<String>,
858    Extension(user): Extension<User>,
859    key: RequestKey,
860) -> Accepted {
861    let id = parse_dag_id(&dag_id)?;
862    let active = state.db.active_dags_of(&[&id]).await?;
863    let sensor = active.first().and_then(|active| match &active.dag.trigger {
864        schedr_model::Trigger::Event { task, .. } => Some(task.id.clone()),
865        _ => None,
866    });
867    let Some(sensor) = sensor else {
868        return Err(ApiError::NotFound(format!(
869            "no DAG `{dag_id}` with an event trigger"
870        )));
871    };
872    submit(
873        &state,
874        &user,
875        key,
876        Command::SwitchOnSensor { dag_id: id, sensor },
877    )
878    .await
879}
880
881/// Runs of every DAG, newest triggered first (then by ID); filtered by DAG and state, paged
882/// with `before` and `before_run` (the last listed run's `triggered_at` and ID).
883#[utoipa::path(get, path = "/api/v1/runs", tag = "runs",
884    params(AllRunsQuery),
885    responses((status = 200, body = RunList), (status = 400, body = ErrorBody)))]
886pub async fn list_all_runs(
887    State(state): State<ApiState>,
888    query: Result<Query<AllRunsQuery>, QueryRejection>,
889) -> ApiResult<RunList> {
890    let Query(query) = query.map_err(|e| ApiError::BadRequest(e.body_text()))?;
891    if query.before_run.is_some() && query.before.is_none() {
892        return Err(ApiError::BadRequest(
893            "`before_run` needs `before` (the run's `triggered_at`)".to_owned(),
894        ));
895    }
896    let before_run = query
897        .before_run
898        .as_deref()
899        .map(|id| parse_uuid(id, "run"))
900        .transpose()?;
901    let runs = state
902        .db
903        .runs(&RunFilter {
904            dag_id: query.dag,
905            dag_contains: query.dag_contains.filter(|part| !part.is_empty()),
906            state: query.state,
907            before: query.before,
908            before_run,
909            limit: query.limit.unwrap_or(DEFAULT_RUNS),
910        })
911        .await?;
912    Ok(Json(RunList {
913        runs: runs.iter().map(RunView::from).collect(),
914    }))
915}
916
917/// The DAG a run ran with: its version's DAG JSON (tasks, dependencies, settings), for its
918/// graph.
919#[utoipa::path(get, path = "/api/v1/runs/{run_id}/dag", tag = "runs",
920    params(("run_id" = String, Path, description = "The run's ID")),
921    responses((status = 200, body = Object), (status = 404, body = ErrorBody)))]
922pub async fn get_run_dag(
923    State(state): State<ApiState>,
924    Path(run_id): Path<String>,
925) -> ApiResult<serde_json::Value> {
926    let run_id = known_run(&state, &run_id).await?.id;
927    let mut dag = state
928        .db
929        .run_dag_json(&run_id)
930        .await?
931        .ok_or_else(|| ApiError::NotFound(format!("no run `{run_id}`")))?;
932    // Its params hold values (the defaults, and the schema's and type's copies of them, such
933    // as a `Literal`'s): only the defaults are shown, masked (decision 134).
934    if let Some(params) = dag
935        .get_mut("params")
936        .and_then(serde_json::Value::as_object_mut)
937    {
938        params.retain(|key, _| key == "defaults");
939        if let Some(defaults) = params.get_mut("defaults") {
940            schedr_config::masked::mask_data(defaults);
941        }
942    }
943    Ok(Json(dag))
944}
945
946/// A task's stored output in a run, with its outcome; 404 while it has none.
947#[utoipa::path(get, path = "/api/v1/runs/{run_id}/tasks/{task_id}/output", tag = "runs",
948    params(
949        ("run_id" = String, Path, description = "The run's ID"),
950        ("task_id" = String, Path, description = "The task's ID"),
951        InstanceQuery
952    ),
953    responses(
954        (status = 200, body = OutputView),
955        (status = 400, body = ErrorBody),
956        (status = 404, body = ErrorBody),
957        (status = 410, body = ErrorBody, description = "Deleted by retention ([retention] outputs)")
958    ))]
959pub async fn get_output(
960    State(state): State<ApiState>,
961    Path((run_id, task_id)): Path<(String, String)>,
962    query: Result<Query<InstanceQuery>, QueryRejection>,
963) -> ApiResult<OutputView> {
964    let task_id = TaskId::new(task_id).map_err(|e| ApiError::BadRequest(e.to_string()))?;
965    let Query(query) = query.map_err(|e| ApiError::BadRequest(e.body_text()))?;
966    let run_id = known_run(&state, &run_id).await?.id;
967    let none = || ApiError::NotFound(format!("no output of `{task_id}` in run `{run_id}`"));
968    // A successful task's output that retention deleted (decision 435), not one never stored:
969    // asked after the outputs are read, so a deletion between the two isn't missed (Codex's
970    // review of M4.14).
971    let gone = || {
972        ApiError::Gone(format!(
973            "the output of `{task_id}` in run `{run_id}` was deleted by retention"
974        ))
975    };
976    let mapped = mapped_count(&state, &run_id, &task_id).await?;
977    if let (Some(_), None | Some(-1)) = (mapped, query.map_index) {
978        // The mapped task's whole output: the list a downstream task gets (decision 81).
979        let whole = state
980            .db
981            .run_instances(&run_id)
982            .await?
983            .into_iter()
984            .find(|i| i.task_id == task_id && i.map_index == -1)
985            .filter(|i| i.state == schedr_model::TaskInstanceState::Success)
986            .ok_or_else(none)?;
987        let results = state.db.instance_results(&run_id, &task_id).await?;
988        if state.db.outputs_deleted(&run_id).await? {
989            return Err(gone());
990        }
991        let list = results
992            .into_iter()
993            .map(|r| {
994                if r.state == schedr_model::TaskInstanceState::Success {
995                    r.output.unwrap_or(serde_json::Value::Null)
996                } else {
997                    serde_json::Value::Null
998                }
999            })
1000            .collect();
1001        return Ok(Json(OutputView {
1002            outcome: whole.outcome.unwrap_or_else(|| "SUCCESS".to_owned()),
1003            value: shown(serde_json::Value::Array(list)),
1004        }));
1005    }
1006    let map_index = instance_of(mapped, &task_id, query.map_index, false)?;
1007    let Some((outcome, value)) = state
1008        .db
1009        .instance_output(&run_id, &task_id, map_index)
1010        .await?
1011    else {
1012        let succeeded = state.db.outputs_deleted(&run_id).await?
1013            && state.db.run_instances(&run_id).await?.iter().any(|i| {
1014                i.task_id == task_id
1015                    && i.map_index == map_index
1016                    && i.state == schedr_model::TaskInstanceState::Success
1017            });
1018        return Err(if succeeded { gone() } else { none() });
1019    };
1020    Ok(Json(OutputView {
1021        outcome,
1022        value: shown(value),
1023    }))
1024}
1025
1026/// A task's output as shown: masked as a task's own data is (decision 131: its texts, and a
1027/// field whose name has a word naming a secret, `partition_key` shown). Downstream tasks get
1028/// it as stored.
1029fn shown(mut value: serde_json::Value) -> serde_json::Value {
1030    schedr_config::masked::mask_data(&mut value);
1031    value
1032}
1033
1034/// How many instances `task_id` has in the run when it is mapped (decision 80); `None` for
1035/// an unmapped task; a 404 for a task the run doesn't have.
1036async fn mapped_count(
1037    state: &ApiState,
1038    run_id: &str,
1039    task_id: &TaskId,
1040) -> Result<Option<usize>, ApiError> {
1041    let Some((tasks, mapped)) = run_tasks(state, run_id).await? else {
1042        return Ok(None);
1043    };
1044    if !tasks.contains(task_id) {
1045        return Err(ApiError::NotFound(format!(
1046            "no task `{task_id}` in run `{run_id}`"
1047        )));
1048    }
1049    if !mapped.contains(task_id) {
1050        return Ok(None);
1051    }
1052    // Counted, not every instance of the run read (B137).
1053    Ok(Some(state.db.mapped_instances(run_id, task_id).await?))
1054}
1055
1056/// The run's tasks and, of those, its mapped ones, from the DAG version it runs (`None` for no
1057/// such run).
1058async fn run_tasks(
1059    state: &ApiState,
1060    run_id: &str,
1061) -> Result<Option<(BTreeSet<TaskId>, BTreeSet<TaskId>)>, ApiError> {
1062    // Parsed once per version (B137). One that doesn't read is the request's error: as an
1063    // unmapped DAG, a missing task would look known and a mapped one plain (B89).
1064    let dag = match state.db.run_dag(run_id).await {
1065        Ok(dag) => dag,
1066        Err(schedr_db::DbError::InvalidData { reason, .. }) => {
1067            // Why, in the log only: serde's message can quote a stored value (Grok's review).
1068            tracing::error!(run_id, reason, "a run's DAG version doesn't read");
1069            return Err(ApiError::Unreadable(format!(
1070                "run `{run_id}`: its DAG version doesn't read (the webserver's log says why); \
1071                 a schedr upgrade should have kept it readable"
1072            )));
1073        }
1074        Err(error) => return Err(error.into()),
1075    };
1076    Ok(dag.map(|dag| {
1077        let mapped = dag
1078            .tasks
1079            .iter()
1080            .filter(|t| t.expand.is_some())
1081            .map(|t| t.id.clone())
1082            .collect();
1083        (dag.tasks.iter().map(|t| t.id.clone()).collect(), mapped)
1084    }))
1085}
1086
1087/// The `map_index` a request about `task_id` means: the instance asked for of a mapped task
1088/// (`required`: a mapped task needs one, decision 82), -1 for an unmapped one.
1089fn instance_of(
1090    mapped: Option<usize>,
1091    task_id: &TaskId,
1092    asked: Option<i32>,
1093    required: bool,
1094) -> Result<i32, ApiError> {
1095    // -1 is the whole task, as listed: the same as naming no instance.
1096    match (mapped, asked.filter(|index| *index != -1)) {
1097        (Some(count), None) if required => Err(ApiError::BadRequest(format!(
1098            "task `{task_id}` is mapped ({count} instances): give ?map_index=N, from 0 to {}",
1099            count.saturating_sub(1)
1100        ))),
1101        (Some(_) | None, None) => Ok(-1),
1102        (Some(count), Some(index)) if usize::try_from(index).is_ok_and(|i| i < count) => Ok(index),
1103        (Some(0), Some(index)) => Err(ApiError::BadRequest(format!(
1104            "task `{task_id}` has no instances (yet): no instance {index}"
1105        ))),
1106        (Some(count), Some(index)) => Err(ApiError::BadRequest(format!(
1107            "task `{task_id}` has {count} instances, from 0 to {}: no instance {index}",
1108            count - 1
1109        ))),
1110        (None, Some(index)) => Err(ApiError::BadRequest(format!(
1111            "task `{task_id}` isn't mapped: it has no instance {index}"
1112        ))),
1113    }
1114}
1115
1116/// The commands about a run, oldest first: the trigger that made it, and cancelling it or
1117/// cancelling or retrying its tasks, with the master's decisions.
1118#[utoipa::path(get, path = "/api/v1/runs/{run_id}/commands", tag = "runs",
1119    params(("run_id" = String, Path, description = "The run's ID")),
1120    responses((status = 200, body = CommandList), (status = 404, body = ErrorBody)))]
1121pub async fn list_run_commands(
1122    State(state): State<ApiState>,
1123    Path(run_id): Path<String>,
1124) -> ApiResult<CommandList> {
1125    let run_id = known_run(&state, &run_id).await?.id;
1126    let commands = state.db.run_commands(&run_id).await?;
1127    Ok(Json(CommandList {
1128        commands: commands.iter().map(CommandView::from).collect(),
1129    }))
1130}
1131
1132/// A run with its tasks.
1133#[utoipa::path(get, path = "/api/v1/runs/{run_id}", tag = "runs",
1134    params(("run_id" = String, Path, description = "The run's ID")),
1135    responses((status = 200, body = RunDetail), (status = 404, body = ErrorBody)))]
1136pub async fn get_run(
1137    State(state): State<ApiState>,
1138    Path(run_id): Path<String>,
1139) -> ApiResult<RunDetail> {
1140    let run = known_run(&state, &run_id).await?;
1141    let run_id = &run.id;
1142    let tasks = state.db.run_instances(run_id).await?;
1143    let dag = match state.db.run_dag(run_id).await {
1144        Ok(dag) => dag,
1145        Err(schedr_db::DbError::InvalidData { .. }) => None,
1146        Err(error) => return Err(error.into()),
1147    };
1148    let mapped: BTreeSet<&TaskId> = dag
1149        .iter()
1150        .flat_map(|dag| dag.tasks.iter().filter(|t| t.expand.is_some()))
1151        .map(|t| &t.id)
1152        .collect();
1153    let state_of = |task: &TaskId| {
1154        tasks
1155            .iter()
1156            .find(|i| &i.task_id == task && i.map_index == -1)
1157            .map_or(TaskInstanceState::Scheduled, |i| i.state)
1158    };
1159    let resources = dag
1160        .iter()
1161        .flat_map(|dag| &dag.resources)
1162        .map(|r| resource_view(r, &state_of))
1163        .collect();
1164    let count = |task: &TaskId| {
1165        tasks
1166            .iter()
1167            .filter(|i| &i.task_id == task && i.map_index >= 0)
1168            .count()
1169    };
1170    Ok(Json(RunDetail {
1171        run: RunView::from(&run),
1172        tasks: tasks
1173            .iter()
1174            .map(|i| {
1175                let whole = i.map_index == -1 && mapped.contains(&&i.task_id);
1176                let mut view = TaskView::of(i, whole.then(|| count(&i.task_id)));
1177                if whole && view.cleanup.is_none() {
1178                    view.cleanup = worst_cleanup(&tasks, &i.task_id);
1179                }
1180                view
1181            })
1182            .collect(),
1183        code_hashes: state.db.run_code_hashes(run_id).await?,
1184        params: shown(schedr_model::params::shown(
1185            &state
1186                .db
1187                .run_params(run_id)
1188                .await?
1189                .unwrap_or_else(|| serde_json::json!({})),
1190        )),
1191        resources,
1192    }))
1193}
1194
1195/// A mapped task's cleanup as a whole: the worst of its instances' (`failed`, then
1196/// `worker_lost`, `ok`, `not_needed`), so a failed one shows on the task's row.
1197fn worst_cleanup(tasks: &[schedr_db::reads::InstanceRecord], task: &TaskId) -> Option<String> {
1198    use schedr_model::CleanupResult as R;
1199    let rank = |r: R| match r {
1200        R::Failed => 3,
1201        R::WorkerLost => 2,
1202        R::Ok => 1,
1203        R::NotNeeded => 0,
1204    };
1205    tasks
1206        .iter()
1207        .filter(|i| &i.task_id == task && i.map_index >= 0)
1208        .filter_map(|i| i.cleanup_result)
1209        .max_by_key(|r| rank(*r))
1210        .map(|r| r.to_string())
1211}
1212
1213fn resource_view(
1214    resource: &schedr_model::Resource,
1215    state_of: &impl Fn(&TaskId) -> TaskInstanceState,
1216) -> ResourceView {
1217    ResourceView {
1218        setup: resource.setup.to_string(),
1219        cleanup: resource.cleanup.to_string(),
1220        users: resource.users.iter().map(ToString::to_string).collect(),
1221        blocking: resource.blocking,
1222        state: name_of(ResourceState::of(
1223            state_of(&resource.setup),
1224            state_of(&resource.cleanup),
1225        )),
1226    }
1227}
1228
1229/// A run's resources, each with its setup, cleanup, users and state (decision 340).
1230#[utoipa::path(get, path = "/api/v1/runs/{run_id}/resources", tag = "resources",
1231    params(("run_id" = String, Path, description = "The run's ID")),
1232    responses((status = 200, body = ResourceList), (status = 404, body = ErrorBody)))]
1233pub async fn list_run_resources(
1234    State(state): State<ApiState>,
1235    Path(run_id): Path<String>,
1236) -> ApiResult<ResourceList> {
1237    let run = known_run(&state, &run_id).await?;
1238    let resources = get_run(State(state), Path(run.id)).await?.0.resources;
1239    Ok(Json(ResourceList { resources }))
1240}
1241
1242/// One resource of a run, by its name (decision 340).
1243#[utoipa::path(get, path = "/api/v1/runs/{run_id}/resources/{resource}", tag = "resources",
1244    params(("run_id" = String, Path, description = "The run's ID"),
1245        ("resource" = String, Path, description = "The resource: its setup's task ID")),
1246    responses((status = 200, body = ResourceView), (status = 404, body = ErrorBody)))]
1247pub async fn get_run_resource(
1248    State(state): State<ApiState>,
1249    Path((run_id, resource)): Path<(String, String)>,
1250) -> ApiResult<ResourceView> {
1251    let run = known_run(&state, &run_id).await?;
1252    let resources = get_run(State(state), Path(run.id)).await?.0.resources;
1253    resources
1254        .into_iter()
1255        .find(|found| found.setup == resource)
1256        .map(Json)
1257        .ok_or_else(|| ApiError::NotFound(format!("no resource `{resource}` in run `{run_id}`")))
1258}
1259
1260/// The wait steps switched off for getting their host killed too many times in a row
1261/// (decision 338).
1262#[utoipa::path(get, path = "/api/v1/sensors/switched-off", tag = "sensors",
1263    responses((status = 200, body = SensorList)))]
1264pub async fn list_switched_off_sensors(State(state): State<ApiState>) -> ApiResult<SensorList> {
1265    let sensors = state
1266        .db
1267        .switched_off_wait_steps()
1268        .await?
1269        .into_iter()
1270        .map(|strikes| SensorView {
1271            dag_id: strikes.dag_id,
1272            sensor: strikes.task_id,
1273            strikes: strikes.strikes,
1274            switched_off_at: strikes.off_at.map(|at| at.to_string()).unwrap_or_default(),
1275        })
1276        .collect();
1277    Ok(Json(SensorList { sensors }))
1278}
1279
1280/// Switch a wait step back on, forgetting its strikes. Applied by the master; poll the command
1281/// for the decision.
1282#[utoipa::path(post, path = "/api/v1/dags/{dag_id}/sensors/{sensor}/switch-on", tag = "sensors",
1283    params(("Idempotency-Key" = Option<String>, Header, description = "A key of the client's for this request"),
1284        ("dag_id" = String, Path, description = "The DAG's ID"),
1285        ("sensor" = String, Path, description = "The wait step's task ID")),
1286    responses((status = 202, body = CommandView), (status = 400, body = ErrorBody)))]
1287pub async fn switch_on_sensor(
1288    State(state): State<ApiState>,
1289    Path((dag_id, sensor)): Path<(String, String)>,
1290    Extension(user): Extension<User>,
1291    key: RequestKey,
1292) -> Accepted {
1293    let dag_id = parse_dag_id(&dag_id)?;
1294    let sensor = TaskId::new(sensor).map_err(|e| ApiError::BadRequest(e.to_string()))?;
1295    submit(
1296        &state,
1297        &user,
1298        key,
1299        Command::SwitchOnSensor { dag_id, sensor },
1300    )
1301    .await
1302}
1303
1304/// A resource's state as the API names it (`waiting_for_users`).
1305fn name_of(state: ResourceState) -> String {
1306    serde_json::to_value(state)
1307        .ok()
1308        .and_then(|v| v.as_str().map(str::to_owned))
1309        .unwrap_or_default()
1310}
1311
1312/// Cancel a run (`schedr runs cancel`). Applied by the master; poll the command for the
1313/// decision.
1314#[utoipa::path(post, path = "/api/v1/runs/{run_id}/cancel", tag = "runs",
1315    params(("Idempotency-Key" = Option<String>, Header, description = "A key of the client's for this request: sent again with it, it is the command stored the first time (B140)"),
1316        ("run_id" = String, Path, description = "The run's ID")),
1317    responses((status = 202, body = CommandView), (status = 400, body = ErrorBody)))]
1318pub async fn cancel_run(
1319    State(state): State<ApiState>,
1320    Path(run_id): Path<String>,
1321    Extension(user): Extension<User>,
1322    key: RequestKey,
1323) -> Accepted {
1324    let run_id = parse_uuid(&run_id, "run")?;
1325    submit(&state, &user, key, Command::CancelRun { run_id }).await
1326}
1327
1328/// Cancel one task of a run (`schedr tasks cancel`): stopped if it runs, cancelled at once if
1329/// it hasn't started; the tasks downstream of it are cancelled. Applied by the master; poll
1330/// the command for the decision.
1331#[utoipa::path(post, path = "/api/v1/runs/{run_id}/tasks/{task_id}/cancel", tag = "runs",
1332    params(("Idempotency-Key" = Option<String>, Header, description = "A key of the client's for this request: sent again with it, it is the command stored the first time (B140)"),
1333        ("run_id" = String, Path, description = "The run's ID"),
1334        ("task_id" = String, Path, description = "The task's ID"),
1335        InstanceQuery
1336    ),
1337    responses(
1338        (status = 202, body = CommandView),
1339        (status = 400, body = ErrorBody),
1340        (status = 404, body = ErrorBody)
1341    ))]
1342pub async fn cancel_task(
1343    State(state): State<ApiState>,
1344    Path((run_id, task_id)): Path<(String, String)>,
1345    query: Result<Query<InstanceQuery>, QueryRejection>,
1346    Extension(user): Extension<User>,
1347    key: RequestKey,
1348) -> Accepted {
1349    let run_id = parse_uuid(&run_id, "run")?;
1350    let task_id = TaskId::new(task_id).map_err(|e| ApiError::BadRequest(e.to_string()))?;
1351    let Query(query) = query.map_err(|e| ApiError::BadRequest(e.body_text()))?;
1352    // An instance must be one the task has; checked when the run is known.
1353    let mut map_index = query.map_index.filter(|index| *index != -1);
1354    if let Some(found) = state.db.run_record(&run_id).await? {
1355        let mapped = mapped_count(&state, &found.id, &task_id).await?;
1356        map_index = Some(instance_of(mapped, &task_id, query.map_index, false)?)
1357            .filter(|index| *index >= 0);
1358    }
1359    let command = Command::CancelTask {
1360        run_id,
1361        task_id,
1362        map_index,
1363    };
1364    submit(&state, &user, key, command).await
1365}
1366
1367/// Retry an `unschedulable` task of an unfinished run (`schedr tasks retry`). Applied by the
1368/// master; poll the command for the decision.
1369#[utoipa::path(post, path = "/api/v1/runs/{run_id}/tasks/{task_id}/retry", tag = "runs",
1370    params(("Idempotency-Key" = Option<String>, Header, description = "A key of the client's for this request: sent again with it, it is the command stored the first time (B140)"),
1371        ("run_id" = String, Path, description = "The run's ID"),
1372        ("task_id" = String, Path, description = "The task's ID"),
1373        InstanceQuery
1374    ),
1375    responses(
1376        (status = 202, body = CommandView),
1377        (status = 400, body = ErrorBody),
1378        (status = 404, body = ErrorBody)
1379    ))]
1380pub async fn retry_task(
1381    State(state): State<ApiState>,
1382    Path((run_id, task_id)): Path<(String, String)>,
1383    query: Result<Query<InstanceQuery>, QueryRejection>,
1384    Extension(user): Extension<User>,
1385    key: RequestKey,
1386) -> Accepted {
1387    let run_id = parse_uuid(&run_id, "run")?;
1388    let task_id = TaskId::new(task_id).map_err(|e| ApiError::BadRequest(e.to_string()))?;
1389    let Query(query) = query.map_err(|e| ApiError::BadRequest(e.body_text()))?;
1390    // A mapped task's instance must be named (decision 82); checked when the run is known.
1391    let mut map_index = query.map_index.filter(|index| *index != -1);
1392    if let Some(found) = state.db.run_record(&run_id).await? {
1393        let mapped = mapped_count(&state, &found.id, &task_id).await?;
1394        map_index =
1395            Some(instance_of(mapped, &task_id, query.map_index, true)?).filter(|index| *index >= 0);
1396    }
1397    let command = Command::RetryTask {
1398        run_id,
1399        task_id,
1400        map_index,
1401    };
1402    submit(&state, &user, key, command).await
1403}
1404
1405/// The attempts of a run's task, oldest first.
1406#[utoipa::path(get, path = "/api/v1/runs/{run_id}/tasks/{task_id}/attempts", tag = "runs",
1407    params(
1408        ("run_id" = String, Path, description = "The run's ID"),
1409        ("task_id" = String, Path, description = "The task's ID"),
1410        InstanceQuery
1411    ),
1412    responses(
1413        (status = 200, body = AttemptList),
1414        (status = 400, body = ErrorBody),
1415        (status = 404, body = ErrorBody)
1416    ))]
1417pub async fn list_attempts(
1418    State(state): State<ApiState>,
1419    Path((run_id, task_id)): Path<(String, String)>,
1420    query: Result<Query<InstanceQuery>, QueryRejection>,
1421) -> ApiResult<AttemptList> {
1422    let task_id = TaskId::new(task_id).map_err(|e| ApiError::BadRequest(e.to_string()))?;
1423    let Query(query) = query.map_err(|e| ApiError::BadRequest(e.body_text()))?;
1424    let run_id = known_run(&state, &run_id).await?.id;
1425    let mapped = mapped_count(&state, &run_id, &task_id).await?;
1426    let map_index = instance_of(mapped, &task_id, query.map_index, true)?;
1427    let attempts = state
1428        .db
1429        .instance_attempts(&run_id, &task_id, map_index)
1430        .await?;
1431    Ok(Json(AttemptList {
1432        attempts: attempts.iter().map(Into::into).collect(),
1433    }))
1434}
1435
1436/// A part of an attempt's log, read from the worker that ran it; read on from `next` to follow
1437/// a running task. 404 when the attempt has no log (yet), or the worker no longer has it; 503
1438/// when the worker is gone or can't be reached.
1439#[utoipa::path(get, path = "/api/v1/runs/{run_id}/tasks/{task_id}/attempts/{try_number}/log",
1440    tag = "runs",
1441    params(
1442        ("run_id" = String, Path, description = "The run's ID"),
1443        ("task_id" = String, Path, description = "The task's ID"),
1444        ("try_number" = u32, Path, description = "The attempt's try number"),
1445        LogQuery
1446    ),
1447    responses(
1448        (status = 200, body = LogChunk),
1449        (status = 404, body = ErrorBody),
1450        (status = 503, body = ErrorBody)
1451    ))]
1452pub async fn get_log(
1453    State(state): State<ApiState>,
1454    Path((run_id, task_id, try_number)): Path<(String, String, u32)>,
1455    query: Result<Query<LogQuery>, QueryRejection>,
1456) -> ApiResult<LogChunk> {
1457    let task_id = TaskId::new(task_id).map_err(|e| ApiError::BadRequest(e.to_string()))?;
1458    let Query(query) = query.map_err(|e| ApiError::BadRequest(e.body_text()))?;
1459    let run_id = known_run(&state, &run_id).await?.id;
1460    let mapped = mapped_count(&state, &run_id, &task_id).await?;
1461    let map_index = instance_of(mapped, &task_id, query.map_index, true)?;
1462    let attempt = state
1463        .db
1464        .instance_attempts(&run_id, &task_id, map_index)
1465        .await?
1466        .into_iter()
1467        .find(|a| a.try_number == try_number)
1468        .ok_or_else(|| {
1469            ApiError::NotFound(format!(
1470                "task `{task_id}` of run `{run_id}` has no try {try_number}"
1471            ))
1472        })?;
1473    let attempt_id = attempt.id;
1474    let worker_id = match (attempt.worker_id, attempt.started_at, attempt.status) {
1475        (Some(worker_id), Some(_), _) => worker_id,
1476        (_, _, None) => {
1477            return Err(ApiError::NotFound(format!(
1478                "try {try_number} of task `{task_id}` hasn't started yet: no log so far"
1479            )));
1480        }
1481        (_, _, Some(_)) => {
1482            return Err(ApiError::NotFound(format!(
1483                "try {try_number} of task `{task_id}` never started, so it has no log"
1484            )));
1485        }
1486    };
1487    let endpoint = match state.db.worker_log_endpoint(&worker_id).await? {
1488        Some((worker_state, _)) if worker_state.is_gone() => {
1489            state.metrics.log_error("worker_gone");
1490            return Err(ApiError::Unavailable(format!(
1491                "worker `{worker_id}` is {worker_state}: the log of try {try_number} is \
1492                 unavailable"
1493            )));
1494        }
1495        Some((_, endpoint)) if !endpoint.is_empty() => endpoint,
1496        _ => {
1497            state.metrics.log_error("no_endpoint");
1498            return Err(ApiError::Unavailable(format!(
1499                "worker `{worker_id}` has no log endpoint: the log of try {try_number} is \
1500                 unavailable"
1501            )));
1502        }
1503    };
1504    let from = query.from.unwrap_or(0);
1505    let limit = query.limit.unwrap_or(MAX_CHUNK).clamp(MIN_CHUNK, MAX_CHUNK);
1506    let answered = |answered: Option<&String>| match answered {
1507        Some(other) if *other != worker_id => Err({
1508            state.metrics.log_error("stale_address");
1509            ApiError::Unavailable(format!(
1510                "reached worker `{other}` instead of `{worker_id}` at {endpoint}: its address \
1511                 is stale; try again shortly"
1512            ))
1513        }),
1514        _ => Ok(()),
1515    };
1516    // One byte before `from` too: whether the part starts at a line (see `masked_lines`).
1517    // Some bytes before `from` too, masked with the part (see `shown_part`).
1518    let asked = from.saturating_sub(MASK_CONTEXT);
1519    let fetched = limit + (from - asked);
1520    let log = match state
1521        .logs
1522        .fetch(&endpoint, &attempt_id, asked, fetched)
1523        .await
1524    {
1525        Ok(log) => log,
1526        Err(LogFetchError::Missing { worker_id: other }) => {
1527            answered(other.as_ref())?;
1528            state.metrics.log_error("missing");
1529            return Err(ApiError::NotFound(format!(
1530                "the log file is unavailable at worker `{worker_id}` (it may have been deleted)"
1531            )));
1532        }
1533        Err(LogFetchError::Unreachable(reason)) => {
1534            state.metrics.log_error("unreachable");
1535            return Err(ApiError::Unavailable(format!(
1536                "worker `{worker_id}` can't be reached at {endpoint}: {reason}"
1537            )));
1538        }
1539    };
1540    answered(log.worker_id.as_ref())?;
1541    let (from, content, next) = shown_part(&log, asked, from, fetched);
1542    Ok(Json(LogChunk {
1543        attempt_id,
1544        try_number,
1545        worker_id,
1546        from,
1547        content,
1548        next,
1549        size: log.size,
1550        running: log.running,
1551    }))
1552}
1553
1554/// The part of `log` (read from `asked`, `fetched` bytes asked for) shown from `from`: where
1555/// its content starts, its masked content, and where the next part starts.
1556fn shown_part(
1557    log: &crate::logs::WorkerLog,
1558    asked: u64,
1559    from: u64,
1560    fetched: u64,
1561) -> (u64, String, u64) {
1562    let from = from.min(log.size);
1563    let before = usize::try_from(from.saturating_sub(asked))
1564        .unwrap_or(usize::MAX)
1565        .min(log.bytes.len());
1566    let (context, bytes) = log.bytes.split_at(before);
1567    // `from` starts a line: the log's start, or a newline before it.
1568    let at_line = from == 0 || context.last() == Some(&b'\n');
1569    let read = u64::try_from(bytes.len()).unwrap_or(u64::MAX);
1570    let more = log.running || from + read < log.size;
1571    // As long as asked: a line with no end in it would never end in a part this long.
1572    let full = u64::try_from(log.bytes.len()).unwrap_or(u64::MAX) >= fetched;
1573    let part = masked_lines(context, bytes, at_line, more, full);
1574    let from = from + u64::try_from(part.skipped).unwrap_or(u64::MAX);
1575    let next = from + u64::try_from(part.used).unwrap_or(u64::MAX);
1576    (from, part.content, next)
1577}
1578
1579/// A command and the master's decision about it.
1580#[utoipa::path(get, path = "/api/v1/commands/{command_id}", tag = "commands",
1581    params(("command_id" = String, Path, description = "The command's ID")),
1582    responses((status = 200, body = CommandView), (status = 404, body = ErrorBody)))]
1583pub async fn get_command(
1584    State(state): State<ApiState>,
1585    Path(command_id): Path<String>,
1586) -> ApiResult<CommandView> {
1587    let command_id = parse_uuid(&command_id, "command")?;
1588    let command = state
1589        .db
1590        .command(&command_id)
1591        .await?
1592        .ok_or_else(|| ApiError::NotFound(format!("no command `{command_id}`")))?;
1593    Ok(Json(CommandView::from(&command)))
1594}
1595
1596async fn submit(state: &ApiState, user: &User, key: RequestKey, command: Command) -> Accepted {
1597    let submitted = state
1598        .db
1599        .submit_command(&command, &user.0, key.0.as_deref(), (state.clock)())
1600        .await?;
1601    let id = match submitted {
1602        Submitted::New(id) | Submitted::Again(id) => id,
1603        Submitted::KeyTaken => {
1604            return Err(ApiError::Unprocessable(
1605                "this `Idempotency-Key` was sent before with another command: use a new key \
1606                 for each command"
1607                    .to_owned(),
1608            ));
1609        }
1610    };
1611    let record = state
1612        .db
1613        .command(&id)
1614        .await?
1615        .ok_or_else(|| ApiError::NotFound(format!("no command `{id}`")))?;
1616    Ok((StatusCode::ACCEPTED, Json(CommandView::from(&record))))
1617}
1618
1619/// The longest `Idempotency-Key` taken.
1620pub const MAX_REQUEST_KEY: usize = 128;
1621
1622/// A command request's `Idempotency-Key` header, if sent (B140): the client's key for this
1623/// request, so one sent again after its answer was lost is stored once. 1 to
1624/// [`MAX_REQUEST_KEY`] visible ASCII characters (a UUID, say).
1625#[derive(Debug, Clone, PartialEq, Eq)]
1626pub struct RequestKey(pub Option<String>);
1627
1628impl<S: Send + Sync> axum::extract::FromRequestParts<S> for RequestKey {
1629    type Rejection = ApiError;
1630
1631    fn from_request_parts(
1632        parts: &mut axum::http::request::Parts,
1633        _state: &S,
1634    ) -> impl Future<Output = Result<Self, Self::Rejection>> + Send {
1635        std::future::ready(Self::read(parts))
1636    }
1637}
1638
1639impl RequestKey {
1640    /// The key in `parts`' headers, if any, or why it isn't one.
1641    fn read(parts: &axum::http::request::Parts) -> Result<Self, ApiError> {
1642        let Some(value) = parts.headers.get("idempotency-key") else {
1643            return Ok(Self(None));
1644        };
1645        let key = value
1646            .to_str()
1647            .ok()
1648            .filter(|k| {
1649                (1..=MAX_REQUEST_KEY).contains(&k.len()) && k.bytes().all(|b| b.is_ascii_graphic())
1650            })
1651            .ok_or_else(|| {
1652                ApiError::BadRequest(format!(
1653                    "`Idempotency-Key` must be 1 to {MAX_REQUEST_KEY} visible ASCII characters"
1654                ))
1655            })?;
1656        Ok(Self(Some(key.to_owned())))
1657    }
1658}
1659
1660pub(crate) async fn known_dag(
1661    state: &ApiState,
1662    dag_id: &DagId,
1663) -> Result<schedr_db::dags::StoredDag, ApiError> {
1664    state
1665        .db
1666        .stored_dag(dag_id)
1667        .await?
1668        .filter(|d| !d.removed)
1669        .ok_or_else(|| ApiError::NotFound(format!("no DAG `{dag_id}`")))
1670}
1671
1672async fn known_run(
1673    state: &ApiState,
1674    run_id: &str,
1675) -> Result<schedr_db::reads::RunRecord, ApiError> {
1676    let run_id = parse_uuid(run_id, "run")?;
1677    state
1678        .db
1679        .run_record(&run_id)
1680        .await?
1681        .ok_or_else(|| ApiError::NotFound(format!("no run `{run_id}`")))
1682}
1683
1684pub(crate) fn parse_dag_id(text: &str) -> Result<DagId, ApiError> {
1685    DagId::new(text).map_err(|e| ApiError::BadRequest(e.to_string()))
1686}
1687
1688/// Run and command IDs are UUIDs, `8-4-4-4-12` hex digits; anything else can't exist (and
1689/// Postgres would refuse it). Lowercased, as schedr writes them: Postgres compares UUIDs
1690/// whatever their case, SQLite compares the text, and commands name runs in JSON (text on both).
1691fn parse_uuid(text: &str, what: &str) -> Result<String, ApiError> {
1692    let canonical = text.len() == 36
1693        && text.bytes().enumerate().all(|(i, b)| {
1694            if matches!(i, 8 | 13 | 18 | 23) {
1695                b == b'-'
1696            } else {
1697                b.is_ascii_hexdigit()
1698            }
1699        });
1700    if canonical {
1701        Ok(text.to_ascii_lowercase())
1702    } else {
1703        Err(ApiError::BadRequest(format!("`{text}` isn't a {what} ID")))
1704    }
1705}
1706
1707/// A JSON body that may be left out (then the request's defaults apply).
1708fn optional_body<T: Default + serde::de::DeserializeOwned>(body: &[u8]) -> Result<T, ApiError> {
1709    if body.iter().all(u8::is_ascii_whitespace) {
1710        return Ok(T::default());
1711    }
1712    read_body(body).map_err(|why| ApiError::BadRequest(format!("invalid body: {why}")))
1713}
1714
1715/// A JSON body read as `T`, or why it can't be, without any value from it ([`body_error`]).
1716pub(crate) fn read_body<T: serde::de::DeserializeOwned>(body: &[u8]) -> Result<T, String> {
1717    let mut reader = serde_json::Deserializer::from_slice(body);
1718    let value = serde_path_to_error::deserialize(&mut reader)
1719        .map_err(|error| body_error(error.inner(), Some(error.path())))?;
1720    reader.end().map_err(|error| body_error(&error, None))?;
1721    Ok(value)
1722}
1723
1724/// Why a JSON body can't be read, without any value from it (decision 134): serde's message
1725/// with the quoted and backticked values taken out, then masked as text. A message of a
1726/// type's own (a timestamp's parser quoting the input, B220) is replaced: only serde's own
1727/// forms are known not to hold more of the value. A data error names the field (`path`): a
1728/// typed one, as only `params` holds keys of the client's, and its values (any JSON) fail as
1729/// syntax, never as data.
1730fn body_error(error: &serde_json::Error, path: Option<&serde_path_to_error::Path>) -> String {
1731    let text = error.to_string();
1732    let at =
1733        (error.line() != 0).then(|| format!(" at line {} column {}", error.line(), error.column()));
1734    let message = at
1735        .as_deref()
1736        .and_then(|at| text.strip_suffix(at))
1737        .unwrap_or(&text);
1738    let data = error.classify() == serde_json::error::Category::Data;
1739    let own = data && !serde_form(message);
1740    let message = if own {
1741        "a value isn't valid here"
1742    } else {
1743        message
1744    };
1745    let field = path
1746        .filter(|path| data && path.iter().next().is_some())
1747        .map(|path| format!("`{path}`: "))
1748        .unwrap_or_default();
1749    let shown = format!("{field}{message}{}", at.unwrap_or_default());
1750    // The backticked values first: one may hold a `"` (an unknown variant's, unescaped).
1751    schedr_config::masked::mask_text(&without_quoted(&without_values(&shown)))
1752}
1753
1754/// Whether `message` has the whole form of one of serde's own data errors, not just its
1755/// start (B224: a type's own `invalid value: {value}` would pass a check of the start). An
1756/// invalid type or value names the kind of value found the way serde does (`Unexpected`), a
1757/// value of it in backticks or, a string, in quotes, which are hidden after.
1758fn serde_form(message: &str) -> bool {
1759    /// `Unexpected`'s forms holding no value.
1760    const WORDS: [&str; 12] = [
1761        "byte array",
1762        "unit value",
1763        "Option value",
1764        "newtype struct",
1765        "sequence",
1766        "map",
1767        "enum",
1768        "unit variant",
1769        "newtype variant",
1770        "tuple variant",
1771        "struct variant",
1772        "null",
1773    ];
1774    /// Those holding one, in backticks.
1775    const VALUES: [&str; 4] = ["integer `", "floating point `", "boolean `", "character `"];
1776    // What follows a value: serde's `, expected `, then what the type says it expects, its
1777    // author's text (`u8`, `a map`), not the client's: the rest of such a message can't be
1778    // told from a type's own more exactly than that.
1779    let expected = |rest: &str| rest.starts_with(", expected ");
1780    let found = message
1781        .strip_prefix("invalid type: ")
1782        .or_else(|| message.strip_prefix("invalid value: "));
1783    if let Some(found) = found {
1784        if WORDS
1785            .iter()
1786            .any(|word| found.strip_prefix(word).is_some_and(expected))
1787        {
1788            return true;
1789        }
1790        // A string, as Rust's `Debug` quotes it (`"` and `\` escaped).
1791        if let Some(quoted) = found.strip_prefix("string \"") {
1792            return closing_quote(quoted).is_some_and(|end| expected(&quoted[end + 1..]));
1793        }
1794        return VALUES.iter().any(|kind| {
1795            found
1796                .strip_prefix(kind)
1797                .is_some_and(|rest| rest.find('`').is_some_and(|end| expected(&rest[end + 1..])))
1798        });
1799    }
1800    if let Some(length) = message.strip_prefix("invalid length ") {
1801        let digits = length.bytes().take_while(u8::is_ascii_digit).count();
1802        return digits > 0 && expected(&length[digits..]);
1803    }
1804    // `missing field`, `duplicate field`: the name, and the end. `unknown field`, `unknown
1805    // variant`: the name (or the value, which may hold a backtick), then serde's list of what
1806    // it knows, backticked names only, or that there are none.
1807    for known in ["missing field `", "duplicate field `"] {
1808        if let Some(rest) = message.strip_prefix(known) {
1809            return rest.find('`').is_some_and(|end| end + 1 == rest.len());
1810        }
1811    }
1812    let unknown = message
1813        .strip_prefix("unknown field `")
1814        .map(|rest| (rest, rest.find('`')))
1815        .or_else(|| {
1816            message.strip_prefix(UNKNOWN_VARIANT).map(|rest| {
1817                let end = [UNKNOWN_VARIANT_END, "`, there are no variants"]
1818                    .iter()
1819                    .filter_map(|after| rest.rfind(after))
1820                    .max();
1821                (rest, end)
1822            })
1823        });
1824    unknown.is_some_and(|(rest, end)| end.is_some_and(|end| serde_list(&rest[end + 1..])))
1825}
1826
1827/// Whether `rest` is serde's list of the fields or variants a type knows, after a name:
1828/// "expected" and one backticked name, two joined by "or", or "one of" and three or more
1829/// separated by commas; or that there are none.
1830fn serde_list(rest: &str) -> bool {
1831    if matches!(rest, ", there are no fields" | ", there are no variants") {
1832        return true;
1833    }
1834    let Some(names) = rest
1835        .strip_prefix(", expected one of ")
1836        .or_else(|| rest.strip_prefix(", expected "))
1837    else {
1838        return false;
1839    };
1840    let one = |name: &str| {
1841        name.len() >= 2
1842            && name.starts_with('`')
1843            && name.ends_with('`')
1844            && !name[1..name.len() - 1].contains('`')
1845    };
1846    // serde's two names are `a` or `b`; three or more, a list.
1847    names
1848        .split_once(" or ")
1849        .map_or_else(|| names.split(", ").all(one), |(a, b)| one(a) && one(b))
1850}
1851
1852/// Where a string Rust's `Debug` quoted ends: its closing `"`, after `\` escapes.
1853fn closing_quote(quoted: &str) -> Option<usize> {
1854    let mut escaped = false;
1855    for (at, c) in quoted.char_indices() {
1856        match c {
1857            _ if escaped => escaped = false,
1858            '\\' => escaped = true,
1859            '"' => return Some(at),
1860            _ => {}
1861        }
1862    }
1863    None
1864}
1865
1866/// What follows an unknown variant's value: serde's list of the type's variants.
1867const UNKNOWN_VARIANT_END: &str = "`, expected";
1868
1869/// The kinds serde shows a value of in backticks (``integer `5` ``, decision 134, B194; an
1870/// unknown variant's, B196); names it puts in backticks (``unknown field `x` ``) stay.
1871const BACKTICKED_VALUES: [&str; 5] = [
1872    "integer `",
1873    "floating point `",
1874    "boolean `",
1875    "character `",
1876    UNKNOWN_VARIANT,
1877];
1878
1879/// How serde names an enum's value it doesn't know.
1880const UNKNOWN_VARIANT: &str = "unknown variant `";
1881
1882/// `text` with each value serde shows in backticks as `` `…` ``.
1883fn without_values(text: &str) -> String {
1884    let mut out = text.to_owned();
1885    for kind in BACKTICKED_VALUES {
1886        let mut from = 0;
1887        while let Some(at) = out[from..].find(kind) {
1888            let start = from + at + kind.len();
1889            // An unknown variant's value may hold a backtick (serde doesn't escape it): to the
1890            // last of serde's own words after it, which name only the type's variants.
1891            let end = if kind == UNKNOWN_VARIANT {
1892                [UNKNOWN_VARIANT_END, "`, there are no variants"]
1893                    .iter()
1894                    .filter_map(|after| out[start..].rfind(after))
1895                    .max()
1896            } else {
1897                out[start..].find('`')
1898            };
1899            let Some(length) = end else {
1900                break;
1901            };
1902            out.replace_range(start..start + length, "…");
1903            from = start + '…'.len_utf8() + 1;
1904        }
1905    }
1906    out
1907}
1908
1909/// `text` with each double-quoted part (a value from the body, which may be a secret) as
1910/// `"…"`; names stay (serde quotes them in backticks), to be masked as texts.
1911fn without_quoted(text: &str) -> String {
1912    let mut out = String::with_capacity(text.len());
1913    let mut chars = text.chars();
1914    while let Some(c) = chars.next() {
1915        if c != '"' {
1916            out.push(c);
1917            continue;
1918        }
1919        out.push_str("\"…\"");
1920        let mut escaped = false;
1921        for c in chars.by_ref() {
1922            match c {
1923                _ if escaped => escaped = false,
1924                '\\' => escaped = true,
1925                '"' => break,
1926                _ => {}
1927            }
1928        }
1929    }
1930    out
1931}